diff --git a/.claude-config/backup/daily-sync.sh b/.claude-config/backup/daily-sync.sh index 46f27e6..70a8677 100755 --- a/.claude-config/backup/daily-sync.sh +++ b/.claude-config/backup/daily-sync.sh @@ -1,7 +1,9 @@ #!/usr/bin/env bash # Daily sync: (1) back up the OPS repo to GitHub, (2) pull every project # repo under PROJECTS/ so all clones stay current across machines, (3) -# garbage-collect local branches and worktrees whose PRs merged (branch-gc). +# garbage-collect local branches and worktrees whose PRs merged (branch-gc), +# (4) lapse setup rulings past their review date (desk lapse), then refresh the +# desk check's cache (bin/desk), the one line the session briefing shows. # Runs via Linux cron / Windows Task Scheduler ("OPS Daily Backup", 09:00). # # Design: @@ -286,8 +288,80 @@ gc_branches() { fi } +# --- Stage 4a: setup rulings that lapse (desk lapse) -------------------------------- +# A ruling written at setup as a temporary measure (Kind `setup`, with a `review by` date 14 +# days out) moves out of force after its review date unless its owner says keep. `desk lapse` +# moves each such row to CONTEXT/standing-orders-archive.md in one commit of those two files and +# leaves a one-time notice for the session briefing. Before the check, so the check reads the +# table the lapse left. desk itself decides what applies: a table with no Kind column (not +# migrated), no table, or the owner's own layout is "nothing to do" and nothing is touched, +# because only desk's parser can read the table. Non-fatal, matching the stages above: a refusal +# (an uncommitted edit to a due ruling's file, a git operation in progress, the sync's lock, an +# executable commit hook, since desk commits with plumbing, which runs none, and hooks are never +# bypassed) leaves the row in force and the check then shows it as past its review date. 120 s +# covers desk's 30 s flock and 10 s index waits. +run_lapse() { + local script="$OPS_DIR/.claude-config/bin/desk" + local lib="$OPS_DIR/.claude-config/hooks/hooklib.sh" py to rc out line + if [ ! -r "$script" ]; then + log "LAPSE: WARN desk unreadable at $script, skipping" + return 0 + fi + if [ ! -r "$lib" ] || ! . "$lib" || ! py="$(hook_python)"; then + log "LAPSE: WARN Python 3 resolver unavailable, skipping" + return 0 + fi + to="$(hook_timeout)" || to="" + if [ -n "$to" ]; then + out="$("$to" -k 5 120 "$py" "$script" lapse --root "$OPS_DIR" 2>&1)"; rc=$? + else + out="$("$py" "$script" lapse --root "$OPS_DIR" 2>&1)"; rc=$? + fi + while IFS= read -r line; do [ -n "$line" ] && log "LAPSE: $line"; done <<< "$out" + [ "$rc" -eq 0 ] || log "LAPSE: WARN desk lapse exited $rc (see output above for the outcome)" + return 0 +} + +# --- Stage 4b: the desk check ------------------------------------------------------- +# desk (bin/desk) is a read-only check of the AI context on this box: stale core files, dead +# references in the always-loaded files, ruling rows, duplicate memory pools. One scan a day +# refreshes desk-last.json in ${OPS_STATE_DIR:-~/.local/state/ops}, the cache the session +# briefing reads; the briefing never scans. Last, so it reads the tree the pull, the cleanup and +# the lapse left. Non-fatal: a check that errors must not fail the sync. Not silent either: the +# outcome is one line in sync.log, and a failed scan leaves the last good cache untouched (desk +# never replaces a cache on error), so the briefing ages it out at 8 days instead of showing a +# false clean. The 300 s cap stops a hung git read from holding the sync. +run_desk() { + local script="$OPS_DIR/.claude-config/bin/desk" + local lib="$OPS_DIR/.claude-config/hooks/hooklib.sh" py to line rc + if [ ! -r "$script" ]; then + log "DESK: WARN desk unreadable at $script, skipping" + return 0 + fi + if [ ! -r "$lib" ] || ! . "$lib" || ! py="$(hook_python)"; then + log "DESK: WARN Python 3 resolver unavailable, skipping" + return 0 + fi + to="$(hook_timeout)" || to="" + log "DESK: running desk" + if [ -n "$to" ]; then + "$to" -k 5 300 "$py" "$script" --root "$OPS_DIR" >/dev/null 2>> "$LOG_FILE"; rc=$? + else + "$py" "$script" --root "$OPS_DIR" >/dev/null 2>> "$LOG_FILE"; rc=$? + fi + if [ "$rc" -ne 0 ]; then + log "DESK: WARN desk exited $rc (the previous cache is kept; see output above)" + return 0 + fi + line="$("$py" "$script" --root "$OPS_DIR" --line 2>/dev/null)" || line="" + log "DESK: ${line:-nothing to show}" + return 0 +} + log "===== daily-sync start =====" backup_ops sync_projects gc_branches +run_lapse +run_desk log "===== daily-sync complete =====" diff --git a/.claude-config/bin/README.md b/.claude-config/bin/README.md index 780a802..9db013f 100644 --- a/.claude-config/bin/README.md +++ b/.claude-config/bin/README.md @@ -87,8 +87,10 @@ pool directory is gone (run `memory-init`). The memory checks measure what a session loads: check 6 runs `memory-index --digest-fit` on every pool and WARNs when a pool's entries lose their descriptions in the 9,000-character digest (with an older indexer it falls back to the 24 KB `MEMORY.md` check), -and 6b WARNs on a pool over 60 entries; both FAIL only when the indexer cannot -run or cannot read a pool, because a pool's size is its owner's call. Check 9b +and FAILs only when the indexer cannot run or cannot read a pool, because a +pool's size is its owner's call. Check 6b reads the nightly memory settle's +status file where the settle is installed (a SKIP everywhere else; "The nightly +memory settle" below). Check 9b WARNs on a `SKILL.md` over 16 KB or with a line over 1,500 characters, skipping synced and symlinked skills. Check 5 reads a tracker project number (`P` plus 8 digits, a dot, 4 digits) as an ID, not a principle citation. Check @@ -522,26 +524,499 @@ frontmatter for three more jobs, all read-only: network, tens of milliseconds. It stays silent for a message the harness sent (slash commands, compaction summaries, batons, scheduled wakes, task notifications, notes from other agents, quote replies) and for a lane. - `memory-index --find ` is the same scorer by hand: the best matches - with their scores, no strong-match bar, the way to find an entry the digest - did not describe. + It also reads both pools' `_archive/` (an archived hit shows its path). + `memory-index --find ` is the same scorer by hand over this pool, the + root pool, both archives and the `CONTEXT/projects/*.md` lessons paragraphs + (one row per match: score, source, ref, text; `--json`, `--exclude PATH`, + `--pool DIR`), the way to find an entry the digest did not describe. - `--check ` exits 2 when a file has neither `title:` nor `name:` (an entry with only `name:`, the pool entry format, is labelled by it, Title Cased). - A pool of more than 60 entries is a WARN on stderr and nothing else: the - index is still written, the exit status does not change and no entry is - removed, because a pool is its owner's. Past about 40 entries the digest can no - longer describe every one, so the tail loses its descriptions; pruning the - pool (fold, merge or delete entries) is the fix, whenever you choose it. More - than 20 pinned entries warns the same way. - -Tests: `tests/memory-index-test.sh`, `tests/memory-digest-test.sh`, -`tests/memory-boundary-test.py`, `tests/memory-init-test.sh` (conflicting pools + A pool has no entry cap (its 60-entry warning went with the settle, 2026-12-04): + past about 40 entries the digest can no longer describe every one, so the + tail loses its descriptions. Where the nightly settle runs it archives that + tail each night; elsewhere pruning the pool (fold, merge or delete entries) is + the fix, whenever you choose it. More than 20 pinned entries is a WARN on + stderr. + +### The nightly memory settle + +``` +memory-index --settle [--dry-run] [...] +memory-index --restore [--pool ] [--dry-run] +memory-index --health +``` + +Why: a pool fills faster than anyone prunes it, and a prune that needs the +owner's sign-off reaches the owner as work. The settle is a nightly mover that +archives and never deletes. It is opt-in per box and off until a box's named +rollout installs it (below); nothing in a template update turns it on. + +- **The move.** For each non-empty live pool, while any of the pool's own entries + is listed by name only or not shown in the digest (the same count as + `--digest-fit `), the lowest-ranked eligible entry in digest order goes to + `/_archive/.md` byte for byte, and the fit is recomputed. A described + entry is never moved. Never moved at all: a pinned entry, `type: user`, one with + no valid `metadata.modified`, one changed in the last 48 hours (the later of + `metadata.modified` and its last git content change), one untracked, staged or + modified in the checkout, one whose destination is occupied, and a path that + escapes the pool. The archive has no `MEMORY.md`; the digest, `--digest-fit` and + the counts never list it, and `--find` and `--hint` read it. +- **Local mode, the only mode.** Selected by configuration, never by whether a + remote exists: `MEMORY_SETTLE_MODE=local` and `MEMORY_SETTLE_ROOT=` in `~/.config/ops/memory-settle.env`. + `memory-index` reads the file itself, so `--settle`, `--dry-run`, `--restore` and + `--health` run by hand pick the same checkout as the timer; where the environment + also sets them (systemd passes the file's lines that way) they must match the + file. No mode line, any other value, an empty one, a missing or relative root, a + root that is not the top of its checkout, or an `--ops` naming another checkout is + refused. So is any form of the two names that systemd and a hand run could read + differently (a backslash, `$`, backtick or partial quote, `export`, a continued + line). The run commits in that checkout on whatever branch is checked out and + never fetches, adds a remote or pushes. +- **Its write path.** The settle lock, then an `flock` on the checkout directory + (the lock a box sync takes); recovery of a stopped run from its journal; a refusal + on a detached or unborn HEAD, a merge, rebase, cherry-pick, revert, bisect or + sequencer in progress, unmerged entries, a split or sparse index, an executable + `pre-commit`, `prepare-commit-msg`, `commit-msg`, `pre-merge-commit` or + `post-commit` hook (`core.hooksPath` honoured; the dry run lists it under "would + refuse"), or an `index.lock` that stays past `MEMORY_SETTLE_INDEX_WAIT` (10 s). + Every path it can touch is captured from HEAD, the index, the worktree and `git + status`, and a dirty or colliding one is refused. The commit is HEAD's tree plus + exactly the run's paths, built in a temporary index, so the owner's staged files + never ride along. Holding git's `index.lock` with SIGTERM, SIGINT and SIGHUP + deferred, it reads every capture again, moves the files, moves the branch by + compare-and-swap from the captured HEAD (a commit that landed meanwhile makes the + run roll back) and updates the index entries of its own paths only. The commit is + plumbing (`commit-tree` and `update-ref`), which runs no commit hook, hence the + hook refusal above: hooks are never bypassed. Exit 75 when either lock is held. + Lock order: the settle lock, the checkout `flock`, git's `index.lock`. +- **The index writer and the settle.** `memory-index ` and the SessionStart + hook take the settle lock around their write when local mode is configured and the + pool is in `MEMORY_SETTLE_ROOT`'s store, so a session cannot rewrite `MEMORY.md` + between the settle's last check and its write. Held: it waits up to + `MEMORY_INDEX_SETTLE_WAIT` seconds (default 5), then skips that regeneration with + one `[memory-index] skipped ...` line on stderr and exit 0; the next session start + regenerates it. Known limit: the lock file is in the state directory, so a timer + and a session started with different `OPS_STATE_DIR` values use two locks; before + enabling the settle on a box, confirm nothing there sets a state directory override. +- **`--dry-run`** reads the configured checkout read-only, prints every proposed + move, every protection reason, the fit counts and what an apply run would refuse, + and writes nothing. +- **Status files**, in `${OPS_STATE_DIR:-~/.local/state/ops}`: + `memory-settle-status.json` (schema 1: `last_attempt_at`, `last_attempt_result` + of `ok`, `noop`, `failed` or `disabled`, `last_success_at`, `commit`, `error`, and + per pool counts); the exit status is 0 for `ok`, `noop` and `disabled`. + `memory-health.tsv` gets one row per run and `memory-dupes.jsonl` the refs, never + the bodies, of new entries that look like repeats of something already on disk. +- **Code.** The mover is `bin/memory_settle.py`, which `memory-index` imports only + for `--settle`, `--restore` and `--health`. `bin/memory-backfill-modified + [--apply] ...` lists (by default) or writes the missing + `metadata.modified` stamps from each entry's last git content change; run it once + before the first settle, since an entry with no stamp is never moved. +- **Team box install (local mode).** The units `systemd/memory-settle.{service,timer}` + (a `Type=oneshot` service bounded by `TimeoutStartSec=30min` whose result is the + mover's exit status; the timer daily at 03:10 with `Persistent=true`) plus the + drop-in `systemd/memory-settle.service.d/local-mode.conf`, which runs the unit only + when `MEMORY_SETTLE_OWNER=1`, `MEMORY_SETTLE_MODE=local` and an absolute + `MEMORY_SETTLE_ROOT` are all set, as `/usr/bin/env python3 + ${MEMORY_SETTLE_ROOT}/.claude-config/bin/memory-index --settle`. Opt-in by + presence: `deploy.sh` keeps installed copies current and never installs a first + one, never creates the env file and never enables anything. The named rollout, + per box: confirm no state directory override; `install -D -m 600 + .claude-config/systemd/memory-settle.env ~/.config/ops/memory-settle.env`, set + `MEMORY_SETTLE_OWNER=1` and `MEMORY_SETTLE_ROOT` in it; run + `memory-backfill-modified` on each pool and commit what it stamps; `install -D -m + 644` the two units and the drop-in under `~/.config/systemd/user/`; `systemctl + --user daemon-reload` (not while `t3code.service` awaits one); read back + `systemctl --user show -p ExecStart -p ExecCondition memory-settle.service`; run + `memory-index --settle --dry-run`; start the service once and read its status + file; then `systemctl --user enable --now memory-settle.timer` and read the next + run in `systemctl --user list-timers memory-settle.timer`. +- **Turning it off.** Pause the mover but keep the timer: `MEMORY_SETTLE=0` in the + env file (a run records `disabled`, exits 0, and the gate SKIPs). Stop it: + `systemctl --user disable --now memory-settle.timer`, then set + `MEMORY_SETTLE_OWNER=0` so the gate SKIPs instead of failing on a stale status; + remove the units and the drop-in and reload to take it off the box. Without the + timer nothing is archived and the digest drops entries to names only again, but + nothing is lost. +- **When it fails.** Read `systemctl --user status memory-settle.service`, then the + status file's `error`, then `memory-index --settle --dry-run` (it writes nothing). +- **Restore an archived entry.** `memory-index --restore [--pool ]` moves it back through the same checked write path. By hand: `git mv + /_archive/.md /.md`, add `metadata.pinned: true` if it + must stay in the digest, run `memory-index ` and commit. `git revert + ` undoes a whole settle commit. + +Tests: `tests/memory-settle-test.py` (the mover in local mode, sandboxed, with +throwaway repositories and an outside sentinel: selection, every never-moved +class, the write path with and without `origin`, refusals, the compare-and-swap, +a killed run before and after its commit, restore, status, health and the +backfill), `tests/memory-settle-timer-test.sh` (the units, the drop-in, the env +template and `deploy.sh`'s keep step against a temp HOME, nothing started), and +the check 6b cases in `verify-ops-selftest.sh`. + +Tests of the index, digest, hint and pools: `tests/memory-index-test.sh`, +`tests/memory-digest-test.sh`, `tests/memory-boundary-test.py`, +`tests/memory-init-test.sh` (conflicting pools and the push gate), `tests/memory-init-hostkey-test.sh` (the host key flags and which cwds get a pool), `tests/memory-host-key-rule-test.sh` and `tests/memory-init-windows-test.ps1`. The hint hook's own suite is `tests/memory-hint-test.sh`; `tests/memory-digest-test.sh` also drives `hooks/memory-digest.sh`. +## `desk`: a read-only check of the AI context on a box + +`desk` reports only what it can prove is wrong with the instructions a session +loads at start, and its one-line result shows in the session briefing. A false +alarm or a false "clean" costs every teammate's trust in it, so each finding +needs exact evidence and anything it could not read is listed as `unread`, +never counted as clean. One Python file with no imports from the repo; it runs +unchanged on a box made from this template (root `~/OPS`, state dir +`${OPS_STATE_DIR:-~/.local/state/ops}`) and on the tree the template comes from, +which it tells apart by that tree's port marker. + +```bash +desk # scan, readable text, refresh the cache +desk --json # scan, the full record, refresh the cache +desk --counts # scan, bounded integer counts and a coverage word only; never writes the cache +desk --line # the cached briefing text; never scans; nothing when there is nothing to show +desk --root PATH --state-dir PATH --cache FILE --pin SHA --mode owner|team --no-cache +``` + +What it proves, and what it will not say: + +- `stale_core`: `CONTEXT/core.md`, `foreman.md` or `how-i-work.md` differs from + the pinned template version and its bytes equal an older template version, or + one older version with one later template commit's patch replayed on it (the + 2026-12-02 shape: a template change copied in by hand onto a box that was + behind). Nothing the owner wrote is in such a file. A difference with no exact + match is `unresolved_core`, an owner edit is possible, and it never reaches + the briefing. Not applicable on the owner's box (the tree the template comes + from, marked by `.claude-config/ops-port-ref`). +- `dead_references` in the always-loaded files (the global `CLAUDE.md`, the + repo `CLAUDE.md` and `AGENTS.md`, `core.md`, `foreman.md`, the rulings file or + the older preferences files, every `.md` under `~/.claude/rules/` (how a team + box loads its core), and every real `@import`): a rules link whose target is + gone (`broken_link`), an exact retired model + id from `CONTEXT/model-roles.md` (a built-in copy when the box has none), a + required literal repo path that does not exist, a required skill that is not + installed. Examples, fenced code, optional paths ("if it exists", "when the + Operator keeps one"), placeholders, bans and history are skipped and counted + under `indeterminate_skipped`. Precision over recall. +- `rulings`: rows of `CONTEXT/standing-orders.md` with a Kind column: no valid + kind, or a `setup` row past its `review by` date (still in the table, so + `desk lapse` did not move it). A table with no Kind column yet is + `unmigrated` and is not judged. `counts.rulings_lapsed_recent` (record and + `--counts`) is the setup rulings the archive says lapsed in the last 7 days, + seen or restored or not; not a defect, but `--counts` reports it. +- `duplicate_pools`: two memory pool directories with byte-identical entries. + Local only; memory never reaches the briefing line or `--counts`. +- `worth_a_look`: a ruling that says it overrides a core default and predates + the template's last change to that file. A separate list, never a defect. +- `size`: bytes per always-loaded file and the total. A measurement; the + reporting threshold is not set until the first fleet measurements exist. +- Roster: `not checked`. Person findings belong to the shared-documents sweep. + +Read-only, and why it is safe on a teammate's box. It reads template history +only from objects already in the checkout; it never fetches, never adds a +remote and never takes an object by URL (an absent pin object is `unread`). The +replay proof runs in a throwaway directory with an empty git config. The only +file it writes is `desk-last.json` in the state dir (atomic rename), and it +refuses a cache path inside the checkout. Exit 0: the scan finished (read +`coverage.unread`); 1: the scan could not run and the previous cache is left as +it was; 2: usage. The template pin is `last_synced` in +`.claude-config/ops-upstream-ref`; `--pin` or `DESK_PIN` supplies a +controller's effective pin. + +Surfaces. `daily-sync.sh` runs `desk` once a day (stage 4b, non-fatal, one line +in `sync.log`). `hooks/session-briefing.sh` `desk_line` reads the cache and +never scans: nothing when the cache is absent, older than 8 days, written for +another checkout or empty; one line naming the file when the cache cannot be +parsed. The owner review adds `review`, `commit-review` and `undo` +to the same file through `COMMANDS`, `parse_rulings_table()` and `CheckedWrite`. + +### Kinds, and setup rulings that lapse (`desk lapse`, `desk keep`) + +The rule (2026-12-04): a ruling written during first-day setup as a +temporary measure lapses 14 days later unless its owner says keep (two such +rows once made a teammate's sessions stop before every step for two weeks). +A migrated `standing-orders.md` table has a fourth column, `Kind`: + +- `setup, review by YYYY-MM-DD`: a posture chosen at setup as temporary; the + review date is 14 days after the ruling date, in the Kind cell (the older + form, a `review by` date anywhere in the row, is read too). +- `preference`: how the owner wants things done. Never lapses. +- `guardrail`: prevents a named event or keeps a box fact (no git remote, + never sign out); the row says which. Never lapses. + +```bash +desk lapse # move setup rows past their review date; one commit; a one-time notice +desk keep 2026-11-20 Autonomy # keep that ruling: setup becomes preference, or a lapsed one comes back +desk lapse|keep --root PATH --state-dir PATH --mode owner|team +``` + +- **The date rule.** The box's local date. A setup row is in force through + its review date and lapses on the first run after it (the scan's + `setup_overdue` uses the same function, `setup_due`). +- **Identity.** A ruling is its date cell plus its area cell (spacing and case + ignored). `keep` refuses when two rows, or a row and an unrestored lapsed + entry, share it; `lapse` refuses the whole run rather than archive two rows + keep could not tell apart. +- **The archive**, `CONTEXT/standing-orders-archive.md`, is never loaded. Each + entry is a `### date | area` section with `- Reason: lapsed`, `- Moved: + YYYY-MM-DD` and the original row byte for byte in a `~~~text` fence; a restore + adds `- Restored: YYYY-MM-DD, by desk keep` and keeps the entry. A new + archive starts with a short header; an existing one only grows at its end. +- **`keep`** before a lapse rewrites only the Kind cell to `preference` (the + review date goes with it; the text is unchanged). After a lapse it puts the + archived row back at the end of the table with its Kind cell `preference`. + Twice is a no-op. +- **The notice.** A successful lapse adds an event to `desk-lapse-notice.json` + in the state dir (`{schema, root, events: [{id, moved, commit, rows: [{date, + area}]}]}`; events older than 30 days are dropped). It is separate from + `desk-last.json`, so no scan erases it. `session-briefing.sh` + `desk_lapse_notice` prints `N setup rulings lapsed on ; say keep to + restore` once per event and appends the id to `desk-lapse-shown`; only the + briefing writes that file. Each lapse run also adds a `recovered-` event for + any lapse in the committed archive from the last 7 days that the receipt + lacks, such as a run killed after its commit. +- **Only for migrated tables.** No table, a table with no Kind column, or the + owner's own layout is "nothing to do" for lapse (exit 0). Both commands + check for interrupted writes even if the table is missing. With nothing + due and no journal waiting, lapse runs no checks that could refuse. + +The write path (`CheckedWrite`; lapse and keep, and the owner review after them). The +commit is plumbing, the mechanic of `memory_settle.py` local mode, copied into +desk because desk is one self-contained file: the commit holds exactly the +planned bytes, never the live files, and no `git add` or `git commit` runs. + +1. Locks, in this order: the flock on the checkout directory (the lock + a box sync and the memory settle take; a + held lock refuses after 30 s), then, for the write itself, git's own + `index.lock` with desk's nonce in it (a session's git is waited for up to + 10 s). The settle takes its settle lock, then the same flock, then + `index.lock`; the sync takes the flock, then git. All three take the flock + before `index.lock`, so none waits on another in a cycle. +2. Refuse a detached or unborn HEAD, or a merge, rebase, cherry-pick, revert, + bisect or sequencer in the git dir. Then finish or undo an interrupted + write from `desk-write-journal.json` in the state dir (below). +3. Each file must be a regular file (not a symlink) in a real directory, + tracked (or, for a new archive, absent from disk, index and HEAD), UTF-8, + with an empty `git status` for its path, and the table must parse (every + row the header's cell count). +4. Before anything is written, refuse: an executable `pre-commit`, + `prepare-commit-msg`, `commit-msg`, `pre-merge-commit` or `post-commit` + hook in the effective hooks directory (`core.hooksPath` when set). The + plumbing commit runs no commit hook and hooks are never bypassed, so desk + does not commit where one exists; the owner disables it or moves the + ruling by hand. Also refused: unmerged index entries, a split or sparse + index, and a staged, skip-worktree or assume-unchanged entry for a planned + path. Then probe Linux `renameat2` (exchange and no-replace) in a scratch + directory beside the files: desk's writes need it, and a system without + it (not Linux, an old libc, a filesystem that answers EINVAL or ENOSYS) is + refused here, before anything is written. ext4 and OpenZFS, the team boxes' + filesystems, support it. With nothing due, `desk lapse` reaches none of + these checks. +5. Build the commit: `git hash-object -w --path= --stdin` of each planned + file's bytes (git's filters apply), `git read-tree ` into a temporary + index, `git update-index -z --index-info` with those blobs, `git + write-tree`, `git commit-tree -p -m `. Journal it + (phase `prepared`, with the commit id). +6. Take `index.lock`; recheck HEAD, Git operations in progress, commit hooks + and the planned paths' index entries against the capture; record the index file's + identity in journal phase `writing` and sync the journal directory before + renaming either file; write each file (the archive first: an interruption + leaves the row in both files, never in neither) as below, sync the + directory; then `git update-ref -m `, which + fails if anyone moved the branch meanwhile. +7. Journal phase `committed`; set the real index entries of the planned paths + to the commit's through a synced copy of the index renamed into place. + Desk changes only entries that still match its capture, leaving every + other entry untouched. After a clean run `git status` is + empty for those paths. Phase `complete`, journal removed, `index.lock` + released. Stop signals (TERM, INT, HUP) are held across steps 6 and 7. +8. A failure before the branch moved rolls the renames back newest first (the + active file before the archive) and refuses; anything that cannot be put + back is named, and the journal stays. If desk cannot read the branch to + confirm whether a failed update moved it, the files and journal stay for + recovery. + +How a file is put in place, so that an editor's save (written to a temp file +and renamed over the rulings file) is never overwritten, whenever it lands: + +1. Desk's bytes go to `..desk-tmp` beside the file (created exclusively), + fsynced. If the file no longer holds what desk read, desk refuses here. +2. A new file (the first archive): `renameat2(tmp, file, RENAME_NOREPLACE)`; + if someone created it meanwhile, desk refuses and their file stays. +3. An existing file: `renameat2(tmp, file, RENAME_EXCHANGE)`. The temp name now + holds what was displaced. If those are the bytes desk read, they are + removed and the write goes on. +4. Otherwise a save landed in the instant before the exchange: desk exchanges + back, so the save is at the file again, and refuses once it sees its own + bytes come out (the other file is then rolled back). If a second save + landed in that instant too, desk exchanges once more so the file holds the + newest save, keeps the one before it as `.desk-displaced-` + beside the file, and fails naming both. + +Rollback and recovery put files back through the same exchange, and take away +a new archive by renaming it aside and comparing before deleting. Desk never +deletes bytes it did not write and has not compared. +If an exchange succeeds and desk cannot finish the replacement, it keeps the +temp file, earlier writes, journal and index lock for recovery. Rolling back +just the earlier archive write could leave the ruling missing from both files. + +An owner save after the exchange (once desk's bytes are in place) is never in +desk's commit and is never overwritten: it stays as an uncommitted edit on top +of the new HEAD, and desk prints a note naming the file and the commit (the +run still succeeds). + +Recovery, at the start of the next run, under the flock: + +- Phase `prepared` or `complete`: nothing in the checkout changed; an + `index.lock` holding the journal's nonce is removed, and so is the journal. +- Desk's commit is on the branch (the tip or in its history): finish its + index entries if they still need updating and the index file is the one + desk captured. If Git replaced the index, an entry may be the owner's + explicit staging even if it matches the old entry. In that case desk + leaves the files, index and journal in place for the owner to review. +- Not on the branch and the branch did not move: each file still holding + desk's bytes goes back, newest first, unless a planned path was staged since + (then nothing is touched and the run refuses). +- Not on the branch and the branch moved (an owner commit after they removed + the lock): nothing is touched and the run refuses. + +In every refusal the journal stays for the owner to resolve. A kill while desk +holds `index.lock` leaves it in place (with desk's nonce), so the owner's git +reports "index.lock exists" until the next desk run or until they remove it. +A kill between an exchange and its comparison leaves the displaced file at +`..desk-tmp`: recovery removes it only when it holds the journal's old +or new bytes for that file, and otherwise keeps it as +`.desk-displaced-`. Recovery records the hold before moving that file, +so later runs still refuse until the owner resolves it. Recovery removes +`.desk-index.` copies. Each probe cleans up only the directory it created. +A kill during a probe can leave that scratch directory behind. + +Test hooks: `DESK_TODAY` (the date), `DESK_LOCK_WAIT` and `DESK_INDEX_WAIT` +(seconds) and `DESK_FAULT` (`captured`, `before-swap`, `after-swap`, +`before-swap-back`, `after-first-write`, `before-commit`, `after-commit`: the +process ends there as a kill would; `after-commit` is after update-ref and +before the index update). Nothing but the suites sets them. + +`daily-sync.sh` stage 4a runs `desk lapse` before the check (non-fatal; every +output line goes to `sync.log` as `LAPSE:`). + +To turn it off: remove stage 4b (`run_desk`) from `daily-sync.sh` and delete +`desk-last.json`; the briefing line is silent without a cache. To stop only +the lapse, remove stage 4a (`run_lapse`); a setup row past its date then shows +as `setup_overdue`. To undo one lapse, `desk keep` the ruling, or `git revert` +the recorded lapse commit. + +Tests: `tests/desk-test.py` (fixture trees and a fake template repo with +history; the five shared stale-core proof cases; every finding, a broken rules +link among them; both older layouts and an unknown one; the cache; read-only; +no repo imports; the daily-sync stages), `tests/desk-lapse-test.py` (lapse and +keep against throwaway git boxes, with an outside sentinel: the date boundary, +first-use and existing archive, exactly the two planned files committed with +unrelated staged, dirty and untracked work intact and the planned paths clean +afterwards, every commit hook refused, an owner save, stage, commit or +`commit -a` at each point of the write, an editor's save between desk's last +read and its rename, during a rollback and twice in one instant, a first +archive someone else created, no renameat2, every refusal, interrupted points +with recovery, a failed rollback, keep before and after and twice, the receipt and +the counts) and `tests/session-briefing-desk-test.sh` +(the briefing line and the one-time notice). All three carry the sandbox guard +(`desk` is in `verify-ops.sh` `OPS_DESTRUCTIVE_TOOLS`) and run in `sandbox-run`; +CI runs every suite by glob. + +### The owner review (`desk review`, `desk commit-review`, `desk undo`) + +"Clean my desk": the owner answers keep, narrow or retire for a short list of +their own rulings, and desk commits exactly those answers. Nothing is deleted: a retired ruling moves to the archive, and undo +puts the bytes back. + +```bash +desk review [--json] [--all] # at most ten items; read-only; --all shows answered ones too +desk commit-review [--file F] [--json] # the answers as JSON (stdin by default); one commit +desk undo # reverse the latest review commit +desk review|commit-review|undo --root PATH --state-dir PATH --mode owner|team +``` + +- **Where the rulings are.** A team box: the table in + `CONTEXT/standing-orders.md` (with or without the Kind column). The owner's + box: the table under `## Standing orders` in `CONTEXT/how-i-work.md`. The + older layout (`CONTEXT/working-preferences.md`, no table, the way the scan + reads it): list items outside fenced code and comments are reviewable. + Parent items whose nested blocks would be left behind are skipped. +- **The list.** Ranked: `setup` rulings first, then rulings that say they + override a core default (the scan's candidate rule), absolute words (never, + always, ever, must), the scan's worth-a-look collision, a dead reference, + then the largest first; file, line and text make the order total. At most + ten. Items the owner already answered (`desk-review-done.json` in the state + dir, by file and text) are not shown again; `--all` shows them. +- **An item** is its file and exact text, with a content hash: + `{rank, id, file, line, content, content_sha256, bytes, type, kind, + review_by, date, area, text, why[], flags{setup, overrides, absolute, + worth_a_look, dead_reference}, alone, protects, dead_references[{kind, ref, + correction}], answers[]}`. `type` is `ruling`, `legacy_preference` or + `dead_reference`. A guardrail has `alone: true` and `protects`, the row's own + text (the template asks each guardrail row to name its event); the text view + prints it apart from the batch. A dead reference in the rulings file is + attached to that ruling; one elsewhere in the checkout is an item of its own + (keep or narrow only). Dead references outside the checkout, or in a core + file the template owns on a team box, are listed under `not_listed`. +- **A correction** is proposed only when it is provable: a missing path whose + file name matches exactly one tracked file in the checkout gives + `{ref, content}` (the line with the reference replaced, when the old one is + on it once). Otherwise `correction` is null. +- **The answers** (`commit-review` input): `{"answers": [{"file", "content", + "answer": "keep"}, {..., "answer": "narrow", "text": "new text"}, + {..., "answer": "retire", "reason": "the owner's reason"}]}`. `file` and + `content` are copied from the item. Keep on a `setup` ruling makes it a + preference (as `desk keep` does); keep on anything else changes nothing. + Narrow on a table ruling replaces only its text cell (one line; a `|` is + escaped), keeping its date, area and kind; on any other item it replaces + the item's whole text. Retire moves a ruling to + `CONTEXT/standing-orders-archive.md` in the lapse's entry format with reason + `retired`, the original row (so its date) and a `- Owner's reason:` line; a + legacy item's entry holds a one-line row and then its exact lines in a + `~~~markdown` fence. +- **Refusals.** The item's text must appear exactly once in its file and still + identify a live ruling or a reported dead-reference line. Guardrail + retirements go in their own requests. Desk can retire rulings and edit + Markdown files inside the checkout. It reserves the archive for its own + writes and leaves template-owned core files to the team updater. + `CheckedWrite` refuses dirty or staged files, an operation in progress or a + held lock. A malformed request exits 2. +- **The commit.** One `CheckedWrite` transaction (the archive first), message + `chore(rulings): record a desk review (keep N, narrow N, retire N)` with the + trailers `Desk-Review: ` and one `Desk-Review-Path:` per path. The + record `desk-review-last.json` keeps the planned parent, paths and content + hashes while a review is pending, plus the prior record in case the new + commit fails. It records the new commit once it lands. The command ends with + the change summary (kept, narrowed, retired, unchanged, the commit). +- **Undo** finds the newest commit on HEAD's first-parent line (last 500) with + a `Desk-Review` or `Desk-Review-Undo` trailer. An undo there, or none, is + "nothing to undo" (exit 0, nothing written). For a review it refuses when a + named path's HEAD bytes differ from the review's commit (it names the path + and the commit that changed it), when the path has uncommitted or staged + work, or when the commit cannot be verified against the local review record. + A pending review is verified against its planned parent, paths and content + hashes. Keep the local record to undo a review. Undo writes each path's + pre-review bytes through `CheckedWrite` (the archive last) + and commits with `Desk-Review-Undo: `. An archive the review created is + left holding its header only, because desk deletes no file. + +To turn it off: nothing runs it on a schedule; it runs only when an agent or +the owner calls it. Delete `desk-review-done.json` to see answered items again. + +Tests: `tests/desk-review-test.py` (throwaway git boxes with an outside +sentinel, under `sandbox-run`): ten ranked items over thirteen, the guardrail +shown alone, the older and the owner's layouts, dead references with and +without a correction, keep, narrow and retire committing only their paths with +unrelated staged, dirty and untracked work intact, the stale and guardrail +refusals, undo restoring bytes, refusing over later edits and running twice. +CI runs it by glob, in `sandbox-run`. + ## `memory-hint.sh`, `report-lint.sh`, `askuser-cancel.sh`, `model-fallback-watch.sh`, `foreman-context.sh`: prompt, stop and boot hooks Five fail-open hooks (exit 0 always, nothing printed when there is nothing to @@ -744,8 +1219,13 @@ the path, GET only). On protocol 2 the answers are translated to the protocol-1 shape callers read, every V2 key kept beside it, and an HTML or non-JSON answer exits 6 instead of passing as data. Writes on protocol 2 are one `orchestration.dispatchCommand` over a WebSocket (`lib/t3_ws.py`): `send -`, `compact ` (an exact `/compact`, printing the message id it minted), -`stop `, `settle ` (only when the thread is idle, its queued runs, pending +`, `compact [--arm-record FILE]` (an exact `/compact`, printing the +message id it minted; with the armed cycle's `arm-.json` it first rechecks the +thread on the `/bounded` read the dispatch already makes, through the lib op +`compact-arm-check`: an owner message or another run after the arming, or an +active run, exits 9 with the reason on stdout and sends nothing, and an answer or +record it cannot check exits 6; protocol 1 reads the thread afresh just before its +POST), `stop `, `settle ` (only when the thread is idle, its queued runs, pending requests and background work included; else exit 9), `settle-when-idle [--timeout SEC]` (a detached waiter that logs to `$OPS_STATE_DIR/t3-settle-when-idle.log`, default `~/.local/state/ops`), and diff --git a/.claude-config/bin/card b/.claude-config/bin/card index 67f0279..c1c3555 100755 --- a/.claude-config/bin/card +++ b/.claude-config/bin/card @@ -120,7 +120,7 @@ SECRET_HARD = [(n, re.compile(p)) for n, p in ( ("gitlab-pat", r"glpat-[A-Za-z0-9_-]{20,}"), ("private-key-block", r"-----BEGIN [A-Z ]*PRIVATE KEY-----"), ("jwt", r"eyJ[A-Za-z0-9_-]{15,}\.eyJ[A-Za-z0-9_-]{10,}"), - ("age-secret-key", r"AGE-SECRET-KEY-1[A-Z0-9]{20,}"), + ("age-secret-key", r"AGE-SECRET-KEY-(?:PQ-)?1[A-Z0-9]{20,}"), ("sshpass-flag-password", r"""sshpass\s+-p\s*["'`]?[^<$"'`\s]\S{5,}"""), ("mysql-inline-password", r"mysql[a-z]*\b.*\s-p[^<$\s-]\S{4,}"), ("curl-user-password", r"(curl|wget)\b.*\s(-u|--user)[\s=]+[^\s:<$]+:[^\s<$]{3,}"), diff --git a/.claude-config/bin/desk b/.claude-config/bin/desk new file mode 100755 index 0000000..7a59ba3 --- /dev/null +++ b/.claude-config/bin/desk @@ -0,0 +1,3737 @@ +#!/usr/bin/env python3 +"""desk: a read-only check of the AI context on this box. It reports only what it can prove is wrong. + +Usage: + desk scan, print readable text, refresh the cache + desk --json scan, print the full record as JSON, refresh the cache + desk --counts scan, print bounded integer counts and a coverage word only; never writes the cache + desk --line print the cached one-line briefing text (nothing when there is nothing to show); + never scans + desk --root PATH --state-dir PATH --pin SHA --cache FILE --no-cache --mode owner|team + overrides (tests and the weekly collector use them) + desk lapse move each setup ruling past its review date to CONTEXT/standing-orders-archive.md, + in one commit of those two files, and leave a one-time notice for the briefing + desk keep DATE AREA keep the ruling with that identity: an active setup row becomes a preference; a + lapsed one comes back from the archive as a preference. Twice is a no-op. + (lapse and keep take --root and --state-dir too; see "Writes" below) + desk review [--json] [--all] at most ten of the owner's rulings to keep, narrow or retire; read-only + desk commit-review [--file F] apply the owner's answers (JSON, stdin by default) in one checked commit + desk undo reverse the latest commit-review commit while no path it wrote has changed since + (the owner review, clean desk piece D: see its block at the end of this file and bin/README.md) + +What it proves (each only when the evidence is exact): + stale_core a core file (CONTEXT/core.md, foreman.md, how-i-work.md) that differs from the pinned + template version and whose bytes equal either an older template version or one older + version with one later template commit's patch replayed on it: nothing the owner wrote + is in it, so the template can replace it. A readable difference with no such match is + reported as `unresolved_core` (an owner edit is possible) and is never a defect. + dead_references in the always-loaded files: an exact retired model id in an active instruction, a required + literal repo path that does not exist, a required skill that is not installed. + rulings rows of CONTEXT/standing-orders.md with a Kind column: a row with no valid kind, a setup + row past its review date still in the table. + duplicate_pools two memory pool directories whose entries are byte-identical file for file. Local only. + worth_a_look a separate list, never a defect: a ruling that says it overrides a core default and is + older than the last template change to that file. + size bytes per always-loaded file and the total. A measurement, never a finding. +Coverage that could not be read is listed under `unread` and the one-line text says so; it is never "clean". + +Two boxes, one file. The owner's box (marker file .claude-config/ops-port-ref, state dir +~/.local/state/cowork) has no stale-core check: that tree is where the template comes from. A team box +(root ~/OPS, state dir ${OPS_STATE_DIR:-~/.local/state/ops}) reads its template pin from +.claude-config/ops-upstream-ref (`last_synced=`); DESK_PIN or --pin supplies a controller's effective pin. + +Template history is read from objects already in the checkout. desk never fetches, never adds a remote and +never takes an object by URL: an absent object is `unread`. The replay proof runs in a throwaway directory +with its own empty git config, with no link to the checkout. + +The scan writes one file, desk-last.json in the state dir (atomic rename), and temp files outside the +checkout. Exit codes: 0 the scan finished (coverage may be incomplete: read `unread`); 1 the scan itself +could not run (the cache is left as it was); 2 usage. + +Writes (lapse and keep; clean desk piece C). The only commands that change the checkout, and only +CONTEXT/standing-orders.md and CONTEXT/standing-orders-archive.md, through CheckedWrite: the team sync's +flock on the checkout directory, refusal on any dirty, staged, symlinked or unparseable file, an operation +in progress, a detached or unborn HEAD or an executable commit hook, atomic replacement with a re-read +before each rename under git's index.lock, a journal in the state dir that the next run uses to finish or +undo an interrupted write, and a plumbing commit of exactly the planned bytes (commit-tree on the captured +HEAD, update-ref with it as the expected old value); the owner's index changes only for those paths. A row is in force through its review +date and lapses on the first run after it (the same rule as the scan's setup_overdue). A table with no +Kind column is never judged and never touched. Exit codes: 0 done or nothing to do; 1 refused or failed +with nothing changed (or with the reason it could not be undone named); 2 usage. + +Later pieces add subcommands through COMMANDS and reuse parse_rulings_table() and CheckedWrite. +""" +import argparse +import base64 +import datetime +import hashlib +import json +import os +import re +import shutil +import stat +import subprocess +import sys +import tempfile +import time + +SCHEMA = 1 +CACHE_NAME = "desk-last.json" +CACHE_MAX_AGE = 8 * 86400 # the briefing shows nothing from a cache older than this +CORE_PATHS = ("CONTEXT/core.md", "CONTEXT/foreman.md", "CONTEXT/how-i-work.md") +KINDS = ("setup", "preference", "guardrail") +ZERO = "0" * 40 +REGULAR_MODES = ("100644", "100755") +GIT_TIMEOUT = 60 +MAX_HISTORY = 120 # template commits per core file the replay will consider +MAX_REPLAYS = 4000 # patch applications per core file +MAX_FILE_BYTES = 4 * 1024 * 1024 +MAX_UNREAD = 40 # unread entries kept in the record; the count stays exact +MIN_POOL_ENTRIES = 2 # a pool this small is not worth calling a duplicate of another +MAX_POOL_ENTRIES = 20000 +MAX_IMPORT_DEPTH = 5 +ACTIVE_REL = "CONTEXT/standing-orders.md" +ARCHIVE_REL = "CONTEXT/standing-orders-archive.md" +NOTICE_NAME = "desk-lapse-notice.json" # the pending-notice receipt; never the scan cache (a scan cannot erase it) +SHOWN_NAME = "desk-lapse-shown" # event ids the briefing has shown, one per line; only the briefing appends +JOURNAL_NAME = "desk-write-journal.json" # an unfinished write's before and after bytes, for the next run to undo +LAPSED_RECENT_DAYS = 7 # counts.rulings_lapsed_recent: the weekly collector's report period +NOTICE_KEEP_DAYS = 30 # receipt events older than this are dropped (shown or not) +LOCK_WAIT = 30 # seconds to wait for the team sync's flock on the checkout +# ponytail: no size threshold yet. The plan sets it from the first fleet measurements before release; +# until then size is reported, never judged. Set DESK_SIZE_THRESHOLD (bytes) to see the report path. +SIZE_THRESHOLD = None + +# The retired and banned model ids come from CONTEXT/model-roles.md (its Retired and Banned rows). A box with +# no model-roles.md (the older layouts) uses this copy, taken from those rows on 2026-12-04, and says so in +# its coverage notes. +BUILTIN_RETIRED = ("claude-sonnet-5", "claude-opus-4-8", "claude-opus-5") +BUILTIN_HAIKU_ALLOWED = ("claude-haiku-5-5",) + +# Words that make a mention indeterminate, so it is skipped instead of flagged. Precision over recall: the +# check reports only what it can prove, so any sign that a mention is conditional, an example, historical or +# a ban keeps it out. +OPTIONAL_RE = re.compile( + r"\b(optional(?:ly)?|exists?|existing|present|available|unavailable|missing|absent|fall(?:s|ing)? ?back|" + r"fallback|failing that|e\.g\.|i\.e\.|for example|for instance|such as|examples?|placeholders?|samples?|" + r"draft|pending|proposed|planned|future|when built|once built|to be built)\b|" + # "when the Operator keeps one", "if you use it", "where a box has one": a condition on the path's existence + r"\b(?:if|when|whenever|where|unless)\b[^|]*?\b(?:keeps?|kept|has|have|having|uses?|runs?|wants?|chooses?|" + r"needs?|maintains?|owns?|configured|installed|enabled|set up|writes?|creates?|created|there (?:is|are))\b", re.I) +HISTORICAL_RE = re.compile( + r"\b(was|were|formerly|previously|used to|until|retired|removed|replaced|replaces|superseded|supersedes|" + r"deprecated|legacy|older|obsolete|no longer|historical(?:ly)?|moved to|renamed|dropped|old)\b", re.I) +NEGATION_RE = re.compile( + r"\b(banned?|bans|never|not|nothing may|nothing|instead|tripwire|forbidden|avoid|except|must not|do not|" + r"don't|doesn't|isn't|aren't|without)\b|n't\b", re.I) +PLACEHOLDER_RE = re.compile(r"[<>*{}$?|\\]|\.\.\.|YYYY|NNN|\bXXX\b|<[^>]*>") +ABBREV_RE = re.compile(r"\b(e\.g\.|i\.e\.|vs\.|etc\.|cf\.|approx\.)", re.I) +# Directories whose contents are made on demand or cloned later; a missing file under one is not a dead path. +ON_DEMAND_PREFIXES = ("CONTEXT/projects/", "NOTES/", "DELIVERABLES/", "PROJECTS/", "ARCHIVE/", ".claude-memory/", + ".claude-handoffs/", "SKILLS/_") +CHECKED_HOME_PREFIXES = ("~/COWORK/", "~/OPS/") +CHECKED_ROOT_PREFIXES = ("CONTEXT/", "SKILLS/", ".claude-config/") +OLD_LAYOUT_CONTEXT = ("about-me.md", "brand-voice.md", "operating-doctrine.md", "foreman-charter.md") + + +class ScanError(Exception): + """The scan itself cannot run. The cache keeps its previous content.""" + + +class GitUnavailable(Exception): + """A git read failed (no git, a timeout, a bad object); the caller records `unread`.""" + + +# --------------------------------------------------------------------------------------------------- +# small helpers + +def today(): + forced = os.environ.get("DESK_TODAY") + if forced: + return datetime.date.fromisoformat(forced) + return datetime.date.today() + + +def read_bytes(path): + with open(path, "rb") as fh: + data = fh.read(MAX_FILE_BYTES + 1) + if len(data) > MAX_FILE_BYTES: + raise OSError("file larger than %d bytes" % MAX_FILE_BYTES) + return data + + +def read_text(path): + return read_bytes(path).decode("utf-8", errors="replace") + + +def blob_oid(data): + return hashlib.sha1(b"blob %d\0" % len(data) + data).hexdigest() + + +def inside(path, parent): + path = os.path.realpath(path) + parent = os.path.realpath(parent) + return path == parent or path.startswith(parent + os.sep) + + +def parse_date(text): + try: + return datetime.date.fromisoformat(text) + except (TypeError, ValueError): + return None + + +def clip(text, n): + text = " ".join(str(text).split()) + return text if len(text) <= n else text[: n - 1] + "..." + + +# --------------------------------------------------------------------------------------------------- +# context: where this scan runs + +class Ctx: + def __init__(self, root, mode, state_dir, pin, pin_source): + self.root = os.path.realpath(root) + self.home = os.path.expanduser("~") + self.mode = mode + self.state_dir = state_dir + self.pin = pin + self.pin_source = pin_source + self.unread = [] + self.notes = [] + self.skipped = {"optional": 0, "historical": 0, "placeholder": 0, "negated": 0} + self.broken_links = [] # dead symlinks in a rules folder; check_dead_references reports them + self._git_facts = None + self._history = {} + + def add_unread(self, check, subject, reason): + self.unread.append({"check": check, "subject": subject, "reason": reason}) + + def note(self, text): + if text not in self.notes: + self.notes.append(text) + + def disp(self, path): + """A path for the record: relative to the harness root, else ~-relative, else absolute.""" + for p in (os.path.abspath(path), os.path.realpath(path)): + if p == self.root or p.startswith(self.root + os.sep): + return os.path.relpath(p, self.root) + for p in (os.path.abspath(path), os.path.realpath(path)): + if p.startswith(self.home + os.sep): + return "~/" + os.path.relpath(p, self.home) + return path + + +def git(ctx, args): + """Run a read-only git command in the checkout. Optional locks off so nothing refreshes the index.""" + env = dict(os.environ) + for key in ("GIT_DIR", "GIT_WORK_TREE", "GIT_INDEX_FILE", "GIT_OBJECT_DIRECTORY", + "GIT_ALTERNATE_OBJECT_DIRECTORIES"): + env.pop(key, None) + env.update({"GIT_OPTIONAL_LOCKS": "0", "GIT_TERMINAL_PROMPT": "0", "LC_ALL": "C", "GIT_PAGER": "cat"}) + cmd = ["git", "-c", "core.fsmonitor=false", "-C", ctx.root] + list(args) + try: + proc = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=GIT_TIMEOUT, env=env) + except (OSError, subprocess.TimeoutExpired) as exc: + raise GitUnavailable("git did not run: %s" % exc) + return proc.returncode, proc.stdout, proc.stderr.decode("utf-8", errors="replace") + + +def git_facts(ctx): + """(shallow, object_format_is_sha1): whether the checkout's history is complete enough to prove from.""" + if ctx._git_facts is None: + rc, out, err = git(ctx, ["rev-parse", "--is-shallow-repository", "--show-object-format"]) + if rc != 0: + raise GitUnavailable("not a git checkout: %s" % clip(err, 120)) + words = out.decode().split() + ctx._git_facts = (words[:1] == ["true"], words[1:2] == ["sha1"]) + return ctx._git_facts + + +def tmp_git(args, cwd, stdin=None): + """git in a throwaway directory: its own empty config, no repository, no network.""" + env = {"PATH": os.environ.get("PATH", "/usr/bin:/bin"), "LC_ALL": "C", "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_CONFIG_SYSTEM": os.devnull, "GIT_CONFIG_NOSYSTEM": "1", "GIT_TERMINAL_PROMPT": "0", + "HOME": cwd} + cmd = ["git", "-c", "core.autocrlf=false", "-c", "core.safecrlf=false", "-c", "diff.mnemonicPrefix=false", + "-c", "diff.noprefix=false", "-c", "apply.whitespace=nowarn"] + list(args) + try: + proc = subprocess.run(cmd, cwd=cwd, input=stdin, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + timeout=GIT_TIMEOUT, env=env) + except (OSError, subprocess.TimeoutExpired) as exc: + raise GitUnavailable("git did not run: %s" % exc) + return proc.returncode, proc.stdout + + +# --------------------------------------------------------------------------------------------------- +# mode, layout and pin + +def detect_mode(root): + """The owner's box carries .claude-config/ops-port-ref (the port's receipt); no team box does.""" + marker = os.path.join(root, ".claude-config", "ops-port-ref") + return "owner" if os.path.isfile(marker) else "team" + + +def default_state_dir(mode): + home = os.path.expanduser("~") + if mode == "owner": + return os.environ.get("COWORK_STATE_DIR") or os.path.join(home, ".local", "state", "cowork") + return os.environ.get("OPS_STATE_DIR") or os.path.join(home, ".local", "state", "ops") + + +def read_pin(root): + """last_synced from .claude-config/ops-upstream-ref, or None.""" + path = os.path.join(root, ".claude-config", "ops-upstream-ref") + try: + text = read_text(path) + except OSError: + return None + for line in text.splitlines(): + key, _, value = line.strip().partition("=") + if key == "last_synced" and re.fullmatch(r"[0-9a-f]{40}", value.strip()): + return value.strip() + return None + + +def detect_layout(root, mode): + ctxdir = os.path.join(root, "CONTEXT") + has = lambda name: os.path.isfile(os.path.join(ctxdir, name)) + if mode == "owner": + return "owner" + if has("core.md") and has("standing-orders.md"): + return "standing-orders" + if has("core.md") and has("working-preferences.md"): + return "working-preferences" + if has("core.md"): + return "unknown" + if has("working-preferences.md"): + return "fork" + return "unknown" + + +# --------------------------------------------------------------------------------------------------- +# prose scanning: units, sentences, references + +class Unit: + """A paragraph, list item, heading or table row outside fences and comments, with its line numbers.""" + + def __init__(self): + self.lines = [] + + def add(self, no, text): + self.lines.append((no, text)) + + @property + def text(self): + return " ".join(t.strip() for _, t in self.lines) + + def line_at(self, offset): + pos = 0 + for no, t in self.lines: + pos += len(t.strip()) + 1 + if offset < pos: + return no + return self.lines[-1][0] + + +FENCE_RE = re.compile(r"^\s*(```|~~~)") +BLOCK_START_RE = re.compile(r"^(#{1,6}\s|[-*+]\s|\d+[.)]\s)") + + +def prose_units(text): + """Split markdown into units, dropping fenced code (examples) and HTML comments.""" + units, cur = [], None + in_fence, fence_tok, in_comment = False, None, False + + def flush(): + nonlocal cur + if cur is not None and cur.lines: + units.append(cur) + cur = None + + for no, raw in enumerate(text.split("\n"), 1): + line = raw.rstrip("\r") + m = FENCE_RE.match(line) + if in_fence: + if m and m.group(1) == fence_tok: + in_fence = False + continue + if m: + flush() + in_fence, fence_tok = True, m.group(1) + continue + s = line + if in_comment: + end = s.find("-->") + if end < 0: + continue + s, in_comment = s[end + 3:], False + while True: + start = s.find("", start + 4) + if end < 0: + s, in_comment = s[:start], True + break + s = s[:start] + " " + s[end + 3:] + stripped = s.strip() + if not stripped: + flush() + continue + if stripped.startswith("|"): + flush() + cur = Unit() + cur.add(no, s) + flush() + continue + if BLOCK_START_RE.match(stripped): + flush() + cur = Unit() + cur.add(no, s) + if stripped.startswith("#"): + flush() + continue + if cur is None: + cur = Unit() + cur.add(no, s) + flush() + return units + + +def sentence_spans(text): + """(start, end) of each sentence in a unit's text. Abbreviation and code-span periods do not split.""" + masked = ABBREV_RE.sub(lambda m: m.group(0).replace(".", "\x00"), text) + masked = re.sub(r"`[^`\n]*`", lambda m: m.group(0).replace(".", "\x00"), masked) + spans, start = [], 0 + for m in re.finditer(r"(?<=[.!?])\s+(?=[A-Z`\[(*\"'])", masked): + spans.append((start, m.start())) + start = m.end() + spans.append((start, len(text))) + return spans + + +def sentence_of(text, offset): + for s, e in sentence_spans(text): + if s <= offset < max(e, s + 1): + return text[s:e] + return text + + +def conditional_reason(sentence, negation=False): + """Why a mention is indeterminate (optional, example, historical, negated), or None. + Inline code is blanked first: a path or id that happens to contain a trigger word ("missing-doc.md") + says nothing about the sentence around it.""" + sentence = re.sub(r"`[^`\n]*`", " CODE ", sentence) + sentence = re.sub(r"\]\([^)\n]*\)", "] ", sentence) # a link's target is a path, not prose + if OPTIONAL_RE.search(sentence): + return "optional" + if HISTORICAL_RE.search(sentence): + return "historical" + if negation and NEGATION_RE.search(sentence): + return "negated" + return None + + +CODE_SPAN_RE = re.compile(r"`([^`\n]+)`") +LINK_RE = re.compile(r"\[[^\]\n]*\]\(([^)\s]+)(?:\s+\"[^\"]*\")?\)") +IMPORT_RE = re.compile(r"(?\"']*[\w])") +SKILL_RE = re.compile(r"`([a-z0-9][a-z0-9:_-]*)`\s+skills?\b|\bskills?\s+`([a-z0-9][a-z0-9:_-]*)`") +FILE_LIKE_RE = re.compile(r"^[\w.\-~/]+$") + + +def clean_ref(tok): + t = tok.strip() + t = re.sub(r"#.*$", "", t) + t = re.sub(r":\d+(-\d+)?$", "", t) + return t.rstrip(".,;:") + + +def checkable_path(ctx, token, base_dir, from_link): + """The absolute path a reference names when this check may judge it, else None.""" + t = clean_ref(token) + if not t or " " in t or not FILE_LIKE_RE.match(t) or PLACEHOLDER_RE.search(t) or t.endswith("/"): + return None + if t.startswith("~/"): + if not t.startswith(CHECKED_HOME_PREFIXES): + return None + return os.path.join(ctx.home, t[2:]) + if t.startswith(CHECKED_ROOT_PREFIXES): + if t.startswith(ON_DEMAND_PREFIXES): + return None + return os.path.join(ctx.root, t) + if from_link and not re.match(r"^[a-z][a-z0-9+.-]*:", t) and not t.startswith("/") and "." in os.path.basename(t): + return os.path.normpath(os.path.join(base_dir, t)) + return None + + +# --------------------------------------------------------------------------------------------------- +# the always-loaded set + +def global_config_dirs(ctx): + dirs = [] + primary = os.environ.get("CLAUDE_CONFIG_DIR") or os.path.join(ctx.home, ".claude") + for d in (primary, os.path.join(ctx.home, ".claude-personal")): + if os.path.isdir(d) and d not in dirs: + dirs.append(d) + return dirs + + +def collect_always_loaded(ctx, layout): + """[{path, role}] for every file a session loads at start, following real @imports.""" + entries, seen = [], set() + + def add(path, role): + real = os.path.realpath(path) + if real in seen: + return None + seen.add(real) + entry = {"path": path, "real": real, "role": role} + entries.append(entry) + return entry + + for d in global_config_dirs(ctx): + p = os.path.join(d, "CLAUDE.md") + if os.path.isfile(p): + add(p, "global") + ctxdir = os.path.join(ctx.root, "CONTEXT") + repo = [("CLAUDE.md", "repo"), ("AGENTS.md", "repo"), ("CONTEXT/core.md", "core"), + ("CONTEXT/foreman.md", "core")] + if layout == "standing-orders": + repo.append(("CONTEXT/standing-orders.md", "rulings")) + if layout in ("working-preferences", "fork"): + repo.append(("CONTEXT/working-preferences.md", "rulings")) + repo.extend(("CONTEXT/" + n, "older-layout") for n in OLD_LAYOUT_CONTEXT) + for rel, role in repo: + p = os.path.join(ctx.root, rel) + if os.path.isfile(p): + add(p, role) + # After the repo files, so a rules link to CONTEXT/core.md (how a team box loads its core) keeps the + # core role when the two resolve to one file. + collect_rules(ctx, add) + # follow imports (depth-limited, cycle-safe) from every file added so far + frontier = [(e, 0) for e in list(entries)] + while frontier: + entry, depth = frontier.pop(0) + try: + text = read_text(entry["real"]) + except OSError as exc: + entry["unreadable"] = str(exc) + ctx.add_unread("always_loaded", ctx.disp(entry["path"]), "cannot read: %s" % clip(exc, 80)) + continue + entry["text"] = text + for unit in prose_units(text): + utext = unit.text + for m in IMPORT_RE.finditer(utext): + raw = m.group(1) + if PLACEHOLDER_RE.search(raw): + continue + base = os.path.dirname(entry["real"]) + target = os.path.expanduser(raw) if raw.startswith("~/") else ( + raw if raw.startswith("/") else os.path.normpath(os.path.join(base, raw))) + if os.path.isfile(target): + if depth + 1 <= MAX_IMPORT_DEPTH: + new = add(target, "import") + if new is not None: + frontier.append((new, depth + 1)) + continue + fb = import_fallback(ctx, raw, text) + if fb: + ctx.note("import %s in %s is unresolved; the file names a fallback that exists (%s)" % + (raw, ctx.disp(entry["path"]), fb)) + else: + ctx.add_unread("always_loaded", ctx.disp(entry["path"]), + "import %s does not resolve and the file names no fallback" % raw) + return entries + + +def collect_rules(ctx, add): + """Every file under /rules/, which Claude Code loads at start like CLAUDE.md. A team box loads + its core through ~/.claude/rules/ops-core.md -> ~/OPS/CONTEXT/core.md, so a link whose target is gone + means a session starts without that file: a dead reference, never a silent skip (one such link was + found on a team box on 2026-11-16). A folder that cannot be listed is unread.""" + for d in global_config_dirs(ctx): + rules = os.path.join(d, "rules") + if not os.path.lexists(rules): + continue + if not os.path.isdir(rules): + ctx.add_unread("always_loaded", ctx.disp(rules), "the rules path is not a readable directory") + continue + walk_errors = [] + for dirpath, dirnames, filenames in os.walk(rules, onerror=walk_errors.append): + if dirpath[len(rules):].count(os.sep) >= 3: + dirnames[:] = [] + dirnames.sort() + for name in sorted(filenames + [n for n in dirnames if os.path.islink(os.path.join(dirpath, n))]): + p = os.path.join(dirpath, name) + if os.path.islink(p) and not os.path.exists(p): + try: + target = os.readlink(p) + except OSError as exc: + target = "unreadable link: %s" % clip(exc, 60) + # the link's own path, not ctx.disp's realpath form (that would name the missing target) + shown = ("~/" + os.path.relpath(p, ctx.home)) if p.startswith(ctx.home + os.sep) else p + ctx.broken_links.append({"kind": "broken_link", "file": shown, "line": 0, "ref": target, + "context": "a rules link whose target does not exist"}) + elif name.endswith(".md") and os.path.isfile(p): + add(p, "rules") + for exc in walk_errors: + ctx.add_unread("always_loaded", ctx.disp(getattr(exc, "filename", None) or rules), + "cannot list the rules folder: %s" % clip(exc, 80)) + + +def import_fallback(ctx, raw, text): + """The other harness alias of an unresolved ~/COWORK or ~/OPS import, when the file names it and it exists.""" + for alias in ("~/COWORK/", "~/OPS/"): + if raw.startswith(alias): + tail = raw[len(alias):] + for other in ("~/COWORK/", "~/OPS/"): + cand = other + tail + if other != alias and cand in text and os.path.isfile(os.path.join(ctx.home, cand[2:])): + return cand + return None + + +# --------------------------------------------------------------------------------------------------- +# size + +def check_size(ctx, entries): + files, total = [], 0 + for e in entries: + try: + n = os.stat(e["real"]).st_size + except OSError: + continue + files.append({"path": ctx.disp(e["path"]), "bytes": n, "role": e["role"]}) + total += n + threshold = SIZE_THRESHOLD + forced = os.environ.get("DESK_SIZE_THRESHOLD") + if forced and forced.isdigit(): + threshold = int(forced) + return {"files": files, "total": total, "threshold": threshold, + "over_threshold": (total > threshold) if threshold else None} + + +# --------------------------------------------------------------------------------------------------- +# dead references + +def load_retired_models(ctx): + """(exact_ids, haiku_allowed, source) from model-roles.md's Retired and Banned rows, else the built-in copy.""" + path = os.path.join(ctx.root, "CONTEXT", "model-roles.md") + if not os.path.isfile(path): + ctx.note("retired model ids: built-in list (this box has no CONTEXT/model-roles.md)") + return set(BUILTIN_RETIRED), set(BUILTIN_HAIKU_ALLOWED), "builtin" + try: + text = read_text(path) + except OSError as exc: + ctx.add_unread("dead_references", ctx.disp(path), "cannot read the retired model list: %s" % clip(exc, 80)) + return set(), set(), "unreadable" + exact, allowed, found = set(), set(), False + for line in text.splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if len(cells) < 3 or not line.lstrip().startswith("|"): + continue + label = cells[0].replace("*", "").strip().lower() + if label not in ("retired", "banned"): + continue + found = True + for segment in cells[2].split(";"): + ids = re.findall(r"`([^`]+)`", segment) + if re.search(r"every haiku", segment, re.I): + allowed.update(i for i in ids) + else: + exact.update(i for i in ids if i.startswith("claude-")) + if not found: + ctx.add_unread("dead_references", ctx.disp(path), "no Retired or Banned row found in model-roles.md") + return set(BUILTIN_RETIRED), set(BUILTIN_HAIKU_ALLOWED), "builtin" + return exact, allowed, "model-roles.md" + + +def model_patterns(exact): + pats = [] + for mid in sorted(exact): + pats.append((mid, re.compile(r"(? 6: + dirnames[:] = [] + continue + if "SKILL.md" in filenames: + names.add(os.path.basename(dirpath)) + return names if readable else None + + +def check_dead_references(ctx, entries): + findings = [] + exact, haiku_allowed, source = load_retired_models(ctx) + pats = model_patterns(exact) + skills = skill_lookup(ctx) + scanned = 0 + for entry in entries: + text = entry.get("text") + if text is None: + continue + scanned += 1 + base_dir = os.path.dirname(entry["real"]) + shown = ctx.disp(entry["path"]) + for unit in prose_units(text): + utext = unit.text + # retired model ids + hits = [] + for mid, rx in pats: + hits.extend((m.start(), mid) for m in rx.finditer(utext)) + for m in HAIKU_TOKEN_RE.finditer(utext): + tok = m.group(1).rstrip(".-") + if tok not in haiku_allowed: + hits.append((m.start(), tok)) + for off, mid in hits: + sentence = sentence_of(utext, off) + why = conditional_reason(sentence, negation=True) + if why: + ctx.skipped["negated" if why == "negated" else why] += 1 + continue + findings.append({"kind": "retired_model", "file": shown, "line": unit.line_at(off), "ref": mid, + "context": clip(sentence, 160)}) + # literal paths + refs = [(m.start(1), m.group(1), False) for m in CODE_SPAN_RE.finditer(utext)] + refs += [(m.start(1), m.group(1), True) for m in LINK_RE.finditer(utext)] + for off, tok, from_link in refs: + target = checkable_path(ctx, tok, base_dir, from_link) + if target is None or os.path.lexists(target): + continue + sentence = sentence_of(utext, off) + why = conditional_reason(sentence) + if why: + ctx.skipped[why] += 1 + continue + findings.append({"kind": "missing_path", "file": shown, "line": unit.line_at(off), + "ref": clean_ref(tok), "context": clip(sentence, 160)}) + # required skills + if skills is not None: + for m in SKILL_RE.finditer(utext): + slug = m.group(1) or m.group(2) + if PLACEHOLDER_RE.search(slug): + continue + leaf = slug.split(":")[-1] + if slug in skills or leaf in skills: + continue + sentence = sentence_of(utext, m.start()) + why = conditional_reason(sentence) + if why: + ctx.skipped[why] += 1 + continue + findings.append({"kind": "missing_skill", "file": shown, "line": unit.line_at(m.start()), + "ref": slug, "context": clip(sentence, 160)}) + if skills is None: + ctx.add_unread("dead_references", "skills", "the installed skill directories could not be read") + findings.extend(ctx.broken_links) + # one finding per (file, kind, ref, line) + seen, unique = set(), [] + for f in findings: + key = (f["file"], f["kind"], f["ref"], f["line"]) + if key not in seen: + seen.add(key) + unique.append(f) + return unique, {"files_scanned": scanned, "model_list": source, "skills_known": None if skills is None else len(skills)} + + +# --------------------------------------------------------------------------------------------------- +# template history and the stale-core proof + +def template_history(ctx, rel): + """Newest-first list of template changes to rel in the pin's ancestry. Raises GitUnavailable when + the history cannot be read completely (the caller records `unread`, never a guess).""" + if rel in ctx._history: + return ctx._history[rel] + require_pin(ctx) + rc, out, err = git(ctx, ["log", "--raw", "--no-abbrev", "--no-renames", "--root", "-m", + "--format=%x01%H %ct", ctx.pin, "--", rel]) + if rc != 0: + raise GitUnavailable("history read failed: %s" % clip(err, 120)) + changes = [] + for chunk in out.decode("utf-8", errors="replace").split("\x01"): + lines = chunk.splitlines() + if not lines: + continue + head = lines[0].split() + if len(head) != 2: + continue + commit, ct = head[0], int(head[1]) + for line in lines[1:]: + if not line.startswith(":"): + continue + meta, _, path = line.partition("\t") + f = meta[1:].split() + if len(f) < 5 or path != rel: + continue + changes.append({"commit": commit, "ct": ct, "mode_old": f[0], "mode_new": f[1], + "old": f[2], "new": f[3], "status": f[4][0]}) + if len(changes) > MAX_HISTORY: + raise GitUnavailable("more than %d template changes to read" % MAX_HISTORY) + ctx._history[rel] = changes + return changes + + +def cat_blob(ctx, oid): + rc, out, err = git(ctx, ["cat-file", "blob", oid]) + if rc != 0: + raise GitUnavailable("object %s unreadable: %s" % (oid[:12], clip(err, 80))) + return out + + +def prove_no_owner_edit(ctx, rel, local, pinned_oid, changes): + """Exact proof that `local` holds nothing but template material, or None. + + Case 1: the local bytes are an older template version of the file. + Case 2: the local bytes are an older version with exactly one later template commit's + parent-to-child patch for this file replayed on it (the 2026-12-02 shape: a template + change copied in by hand onto a box that was behind). + Anything else (a line no template version holds, two separate patches needed, an unreadable + history) proves nothing and the caller does not call the file stale. + """ + local_oid = blob_oid(local) + for c in changes: + if c["new"] != ZERO and c["new"] == local_oid: + return {"match": "older_version", "template_commit": c["commit"]} + if inside(tempfile.gettempdir(), ctx.root): + raise GitUnavailable("the temp directory is inside the checkout; nothing is written there") + work = tempfile.mkdtemp(prefix="desk-proof-") + try: + replays = 0 + blobs = {} + + def blob(oid): + if oid not in blobs: + blobs[oid] = cat_blob(ctx, oid) + return blobs[oid] + + for i, c in enumerate(changes): + if (c["status"] != "M" or c["old"] == ZERO or c["new"] == ZERO or c["old"] == c["new"] + or c["mode_old"] not in REGULAR_MODES or c["mode_new"] not in REGULAR_MODES): + continue + for d in ("a", "b"): + os.makedirs(os.path.join(work, d), exist_ok=True) + with open(os.path.join(work, "a", "f"), "wb") as fh: + fh.write(blob(c["old"])) + with open(os.path.join(work, "b", "f"), "wb") as fh: + fh.write(blob(c["new"])) + rc, patch = tmp_git(["diff", "--no-index", "--no-color", "--no-ext-diff", "-U3", "--", "a/f", "b/f"], work) + if rc not in (0, 1): + raise GitUnavailable("could not build the template patch") + if not patch.strip(): + continue # an empty patch proves nothing + patch_file = os.path.join(work, "p.diff") + with open(patch_file, "wb") as fh: + fh.write(patch) + older = [] + for j in range(i + 1, len(changes)): + oid = changes[j]["new"] + if oid != ZERO and oid not in (c["old"], c["new"]) and oid not in older: + older.append(oid) + for oid in older: + replays += 1 + if replays > MAX_REPLAYS: + raise GitUnavailable("replay limit reached") + target = os.path.join(work, "t") + os.makedirs(target, exist_ok=True) + tf = os.path.join(target, "f") + with open(tf, "wb") as fh: + fh.write(blob(oid)) + rc, _out = tmp_git(["apply", "-p2", "--whitespace=nowarn", patch_file], target) + if rc == 0: + with open(tf, "rb") as fh: + result = fh.read() + if result == local: + base = next((x["commit"] for x in changes if x["new"] == oid), None) + return {"match": "rebuild", "template_commit": c["commit"], "base_commit": base} + return None + finally: + shutil.rmtree(work, ignore_errors=True) + + +def require_pin(ctx): + """Raise GitUnavailable unless the pinned template commit can be read from this checkout.""" + shallow, sha1 = git_facts(ctx) + if shallow: + raise GitUnavailable("shallow checkout: the template history is incomplete") + if not sha1: + raise GitUnavailable("the checkout does not use sha1 objects") + rc, _o, _e = git(ctx, ["cat-file", "-e", ctx.pin + "^{commit}"]) + if rc != 0: + raise GitUnavailable("the pinned template commit is not in this checkout (desk never fetches)") + + +def check_core(ctx, layout): + """Per core path: {path, state, ...}. States: current, stale, unresolved, not_applicable, unread.""" + results = [] + for rel in CORE_PATHS: + res = {"path": rel, "state": "unread"} + results.append(res) + if ctx.mode == "owner": + res.update(state="not_applicable", reason="this is the template's source tree") + continue + local_path = os.path.join(ctx.root, rel) + if not os.path.lexists(local_path): + res.update(state="not_applicable", reason="the file is not on this box") + continue + try: + if os.path.islink(local_path) or not os.path.isfile(local_path): + raise GitUnavailable("not a regular file") + if not ctx.pin: + raise GitUnavailable("no template pin (.claude-config/ops-upstream-ref has no last_synced)") + rc, _o, _e = git(ctx, ["ls-files", "--error-unmatch", "-z", "--", rel]) + if rc != 0: + raise GitUnavailable("not tracked by the checkout") + local = read_bytes(local_path) + require_pin(ctx) + rc, tree, err = git(ctx, ["ls-tree", "-z", ctx.pin, "--", rel]) + if rc != 0: + raise GitUnavailable("the pinned template tree is unreadable: %s" % clip(err, 100)) + if not tree.strip(): + res.update(state="not_applicable", reason="the pinned template has no such file") + continue + pinned_oid = tree.decode("utf-8", errors="replace").split("\t")[0].split()[2] + if blob_oid(local) == pinned_oid: + res.update(state="current") + continue + changes = template_history(ctx, rel) + if changes: + res["last_template_change"] = datetime.datetime.fromtimestamp( + changes[0]["ct"], datetime.timezone.utc).strftime("%Y-%m-%d") + proof = prove_no_owner_edit(ctx, rel, local, pinned_oid, changes) + if proof: + res.update(state="stale", **proof) + else: + res.update(state="unresolved", reason="differs from the pinned template with no exact match " + "to template material") + except (GitUnavailable, OSError) as exc: + res.update(state="unread", reason=clip(exc, 160)) + ctx.add_unread("stale_core", rel, clip(exc, 160)) + return results + + +# --------------------------------------------------------------------------------------------------- +# rulings + +def split_cells(line): + s = line.strip() + if s.startswith("|"): + s = s[1:] + if s.endswith("|") and not s.endswith("\\|"): + s = s[:-1] + return [c.strip().replace("\\|", "|") for c in re.split(r"(?" in line: + in_comment = False + visible.append(None) + continue + if "" not in line: + in_comment = True + visible.append(None) + continue + visible.append(line) + while i < n - 1: + head, sep = visible[i], visible[i + 1] + if (head and sep and head.lstrip().startswith("|") and re.fullmatch(r"\s*\|?\s*:?-{3,}:?\s*(\|\s*:?-{3,}:?\s*)*\|?\s*", sep)): + header = split_cells(head) + if header and "date" in header[0].lower(): + cols = {"date": 0, "area": 1 if len(header) > 1 else None, "text": 2 if len(header) > 2 else None, "kind": None} + for idx, name in enumerate(header): + if name.strip().lower() == "kind": + cols["kind"] = idx + rows, j = [], i + 2 + while j < n and visible[j] and visible[j].lstrip().startswith("|"): + rows.append({"line": j + 1, "cells": split_cells(visible[j]), "raw": visible[j]}) + j += 1 + return {"header": header, "columns": cols, "rows": rows, "first_line": i + 1, "last_line": j} + i += 1 + return None + + +def row_cell(table, row, name): + idx = table["columns"].get(name) + if idx is None or idx >= len(row["cells"]): + return "" + return row["cells"][idx] + + +def is_example_row(table, row): + return "YYYY" in row_cell(table, row, "date") or row_cell(table, row, "area").upper().startswith("EXAMPLE") + + +CORE_MENTION = {"CONTEXT/core.md": re.compile(r"\bcore(?:\.md)?\b", re.I), + "CONTEXT/foreman.md": re.compile(r"\bforeman(?:\.md)?\b", re.I), + "CONTEXT/how-i-work.md": re.compile(r"how-i-work", re.I)} +REVIEW_RE = re.compile(r"review by (\d{4}-\d{2}-\d{2})", re.I) +# The Kind cell: one kind word, and for setup its review date in the same cell ("setup, review by +# 2026-12-18"), so `desk keep` can drop the date without touching the ruling's text. +KIND_CELL_RE = re.compile(r"[`*_\s]*(setup|preference|guardrail)[`*_]*(?:[\s,;:(-]*review by\s+(\d{4}-\d{2}-\d{2})" + r"\s*\)?)?[\s.]*", re.I) + + +def parse_kind(cell): + """(kind, review date text or None) from a Kind cell, or (None, None) when it names no valid kind.""" + m = KIND_CELL_RE.fullmatch(cell or "") + if not m: + return None, None + return m.group(1).lower(), m.group(2) + + +def setup_review(table, row): + """The review date of a setup row: the one in its Kind cell, else (piece A's first form) a + `review by` date anywhere in the row. None when there is none or it is not a real date.""" + _kind, in_cell = parse_kind(row_cell(table, row, "kind")) + if in_cell: + return parse_date(in_cell) + m = REVIEW_RE.search(row["raw"]) + return parse_date(m.group(1)) if m else None + + +def setup_due(review, on): + """The one boundary rule, shared by the scan and `desk lapse`: a setup row is in force through its + review date and lapses on the first day after it. "review by" gives the owner the whole date to say + keep, and the scan already called a row overdue only after that date.""" + return review is not None and on > review + + +def identity(date, area): + """A ruling's identity: its date cell and its area cell, whitespace collapsed and case folded.""" + return (str(date).strip(), " ".join(str(area).split()).casefold()) + + +def check_rulings(ctx, layout): + """{status, table, no_kind, setup_overdue, candidates} for CONTEXT/standing-orders.md.""" + res = {"status": "not_applicable", "reason": "", "rows": 0, "no_kind": [], "setup_overdue": [], "candidates": [], + "lapsed_recent": 0} + if layout == "standing-orders": + res["lapsed_recent"] = count_lapsed_recent(ctx) + if layout == "owner": + res["reason"] = "the owner's rulings are indexed in how-i-work.md, which is a different table" + return res + if layout in ("working-preferences", "fork"): + res["reason"] = "the older preferences layout has no rulings table" + return res + if layout == "unknown": + res.update(status="unread", reason="layout not recognized") + ctx.add_unread("rulings", "CONTEXT", "layout not recognized (no standing-orders.md or working-preferences.md)") + return res + path = os.path.join(ctx.root, "CONTEXT", "standing-orders.md") + try: + text = read_text(path) + except OSError as exc: + res.update(status="unread", reason="cannot read: %s" % clip(exc, 80)) + ctx.add_unread("rulings", "CONTEXT/standing-orders.md", res["reason"]) + return res + table = parse_rulings_table(text) + if table is None: + res.update(status="unread", reason="no rulings table found") + ctx.add_unread("rulings", "CONTEXT/standing-orders.md", res["reason"]) + return res + res["table"] = {"header": table["header"], "has_kind_column": table["columns"]["kind"] is not None} + rows = [r for r in table["rows"] if not is_example_row(table, r)] + res["rows"] = len(rows) + res["status"] = "checked" if table["columns"]["kind"] is not None else "unmigrated" + if res["status"] == "unmigrated": + res["reason"] = "the table has no Kind column yet, so rows are not judged" + for r in rows: + shown = {"line": r["line"], "date": row_cell(table, r, "date"), "area": clip(row_cell(table, r, "area"), 80)} + if table["columns"]["kind"] is not None: + kind, _review = parse_kind(row_cell(table, r, "kind")) + if kind is None: + res["no_kind"].append(dict(shown, kind=row_cell(table, r, "kind").strip("` *").lower())) + elif kind == "setup": + review = setup_review(table, r) + if review is None: + ctx.add_unread("rulings", "CONTEXT/standing-orders.md line %d" % r["line"], + "a setup ruling with no review date") + elif setup_due(review, today()): + res["setup_overdue"].append(dict(shown, review_by=review.isoformat())) + body = r["raw"] + if re.search(r"overrid", body, re.I): + files = [p for p, rx in CORE_MENTION.items() if rx.search(body)] + if files: + res["candidates"].append(dict(shown, files=files)) + return res + + +def count_lapsed_recent(ctx): + """Archive entries with reason `lapsed` moved in the last LAPSED_RECENT_DAYS days, restored or not and + whether or not the owner saw the notice: the archive is the durable record, the notice is not.""" + path = os.path.join(ctx.root, ARCHIVE_REL) + if not os.path.lexists(path): + return 0 + try: + if os.path.islink(path) or not os.path.isfile(path): + raise OSError("not a regular file") + entries = parse_archive(read_bytes(path).decode("utf-8")) + except (OSError, UnicodeDecodeError, ArchiveError) as exc: + ctx.add_unread("rulings", ARCHIVE_REL, "cannot count lapsed rulings: %s" % clip(exc, 100)) + return 0 + on = today() + n = 0 + for e in entries: + moved = parse_date(e["moved"]) + if e["reason"] == "lapsed" and moved is not None and 0 <= (on - moved).days < LAPSED_RECENT_DAYS: + n += 1 + return n + + +def check_worth_a_look(ctx, rulings, core_results): + """Rulings that override a core default and predate the last template change to that file.""" + out = [] + for cand in rulings.get("candidates", []): + ruling_date = parse_date(cand["date"]) + if ruling_date is None: + continue + for rel in cand["files"]: + changed = None + for res in core_results: + if res["path"] == rel and res.get("last_template_change"): + changed = res["last_template_change"] + if changed is None: + if ctx.mode == "owner" or not ctx.pin: + continue + try: + hist = template_history(ctx, rel) + except GitUnavailable as exc: + ctx.add_unread("worth_a_look", rel, "template history unavailable: %s" % clip(exc, 100)) + continue + if not hist: + continue + changed = datetime.datetime.fromtimestamp(hist[0]["ct"], datetime.timezone.utc).strftime("%Y-%m-%d") + cdate = parse_date(changed) + if cdate and ruling_date < cdate: + out.append({"file": "CONTEXT/standing-orders.md", "line": cand["line"], "ruling_date": cand["date"], + "area": cand["area"], "overrides": rel, "template_changed": changed}) + return out + + +# --------------------------------------------------------------------------------------------------- +# duplicate memory pools + +def pool_dirs(ctx): + dirs = [] + store = os.path.join(ctx.root, ".claude-memory") + if os.path.isdir(store): + for name in sorted(os.listdir(store)): + p = os.path.join(store, name) + if os.path.isdir(p) and not os.path.islink(p) and not name.startswith("_"): + dirs.append(p) + for cfg in global_config_dirs(ctx): + proj = os.path.join(cfg, "projects") + if not os.path.isdir(proj): + continue + for name in sorted(os.listdir(proj)): + p = os.path.join(proj, name, "memory") + if os.path.isdir(p) and not os.path.islink(p): + dirs.append(p) + return dirs + + +def check_duplicate_pools(ctx): + fingerprints, seen_real, scanned = {}, set(), 0 + for p in pool_dirs(ctx): + real = os.path.realpath(p) + if real in seen_real: + continue + seen_real.add(real) + try: + names = sorted(n for n in os.listdir(p) if n.endswith(".md") and n != "MEMORY.md" + and os.path.isfile(os.path.join(p, n))) + if len(names) > MAX_POOL_ENTRIES: + raise OSError("more than %d entries" % MAX_POOL_ENTRIES) + h = hashlib.sha256() + for n in names: + h.update(n.encode() + b"\0" + hashlib.sha256(read_bytes(os.path.join(p, n))).digest()) + except OSError as exc: + ctx.add_unread("duplicate_pools", ctx.disp(p), "cannot read the pool: %s" % clip(exc, 80)) + continue + scanned += 1 + if len(names) >= MIN_POOL_ENTRIES: + fingerprints.setdefault(h.hexdigest(), []).append((ctx.disp(p), len(names))) + dupes = [{"pools": [x[0] for x in group], "entries": group[0][1]} + for group in fingerprints.values() if len(group) > 1] + return dupes, {"pools_scanned": scanned} + + +# --------------------------------------------------------------------------------------------------- +# the scan, the record, the line + +def guarded(ctx, check, subject, fn, default): + """Run one check; a crash inside it is recorded as unread coverage, not hidden and not fatal.""" + try: + return fn() + except Exception as exc: # noqa: BLE001 - the record names it; the scan continues with the other checks + ctx.add_unread(check, subject, "check failed: %s: %s" % (type(exc).__name__, clip(exc, 100))) + return default + + +def scan(root, mode=None, state_dir=None, pin=None): + if not os.path.isdir(root): + raise ScanError("harness root is not a directory: %s" % root) + if not (os.path.isdir(os.path.join(root, "CONTEXT")) or os.path.isdir(os.path.join(root, ".claude-config"))): + raise ScanError("not a harness root (no CONTEXT or .claude-config): %s" % root) + root = os.path.realpath(root) + mode = mode or detect_mode(root) + pin_source = "none" + if mode == "team": + env_pin = pin or os.environ.get("DESK_PIN") + if env_pin: + if not re.fullmatch(r"[0-9a-f]{40}", env_pin): + raise ScanError("the supplied pin is not a 40-character commit id") + pin, pin_source = env_pin, "supplied" + else: + pin = read_pin(root) + pin_source = "ops-upstream-ref" if pin else "none" + else: + pin = None + state_dir = state_dir or default_state_dir(mode) + ctx = Ctx(root, mode, state_dir, pin, pin_source) + layout = detect_layout(root, mode) + now = datetime.datetime.now().astimezone() + + entries = guarded(ctx, "always_loaded", "files", lambda: collect_always_loaded(ctx, layout), []) + core = guarded(ctx, "stale_core", "core files", lambda: check_core(ctx, layout), []) + dead, dead_cov = guarded(ctx, "dead_references", "files", lambda: check_dead_references(ctx, entries), ([], {})) + rulings = guarded(ctx, "rulings", "standing orders", lambda: check_rulings(ctx, layout), + {"status": "unread", "rows": 0, "no_kind": [], "setup_overdue": [], "candidates": [], + "lapsed_recent": 0}) + worth = guarded(ctx, "worth_a_look", "rulings", lambda: check_worth_a_look(ctx, rulings, core), []) + dupes, dupe_cov = guarded(ctx, "duplicate_pools", "memory", lambda: check_duplicate_pools(ctx), ([], {})) + size = guarded(ctx, "size", "files", lambda: check_size(ctx, entries), + {"files": [], "total": 0, "threshold": None, "over_threshold": None}) + + findings = { + "stale_core": [{k: v for k, v in r.items() if k != "state"} for r in core if r["state"] == "stale"], + "unresolved_core": [{"path": r["path"], "reason": r.get("reason", "")} for r in core if r["state"] == "unresolved"], + "dead_references": dead, + "rulings": {"no_kind": rulings.get("no_kind", []), "setup_overdue": rulings.get("setup_overdue", [])}, + "duplicate_pools": dupes, + } + counts = { + "stale_core": len(findings["stale_core"]), + "dead_references": len(dead), + "rulings_no_kind": len(findings["rulings"]["no_kind"]), + "rulings_setup_overdue": len(findings["rulings"]["setup_overdue"]), + "duplicate_pools": len(dupes), + "unresolved_core": len(findings["unresolved_core"]), + "worth_a_look": len(worth), + # not a defect: setup rulings the box's lapse moved in the last 7 days (the weekly line counts them) + "rulings_lapsed_recent": rulings.get("lapsed_recent", 0), + } + unread_total = len(ctx.unread) + coverage = { + "status": "complete" if unread_total == 0 else "incomplete", + "unread_count": unread_total, + "unread": ctx.unread[:MAX_UNREAD], + "roster": "not checked", + "checks": { + "stale_core": summarize_core_status(core, mode), + "dead_references": dead_cov, + "rulings": {"status": rulings.get("status"), "reason": rulings.get("reason", ""), + "rows": rulings.get("rows", 0)}, + "duplicate_pools": dupe_cov, + }, + "notes": ctx.notes, + "indeterminate_skipped": ctx.skipped, + } + rec = { + "schema": SCHEMA, "tool": "desk", + "scanned_at": now.isoformat(timespec="seconds"), "scanned_epoch": int(now.timestamp()), + "root": root, "mode": mode, "layout": layout, + "pin": {"sha": pin, "source": pin_source}, + "findings": findings, "worth_a_look": worth, "core": core, "size": size, + "coverage": coverage, "counts": counts, + } + rec["line"] = build_line(rec) + return rec + + +def summarize_core_status(core, mode): + if mode == "owner": + return "not_applicable" + states = {r["state"] for r in core} + if "unread" in states: + return "partial" if states - {"unread"} else "unread" + if states <= {"not_applicable"}: + return "not_applicable" + return "checked" + + +def plural(n, one, many=None): + return "%d %s" % (n, one if n == 1 else (many or one + "s")) + + +def build_line(rec): + """The one-line briefing text: findings other than memory, and incomplete coverage, never 'clean'.""" + c, parts = rec["counts"], [] + if c["stale_core"]: + parts.append("%s behind the template with no local edit" % plural(c["stale_core"], "core file")) + if c["dead_references"]: + parts.append("%s in always-loaded files" % plural(c["dead_references"], "dead reference")) + if c["rulings_setup_overdue"]: + parts.append("%s past its review date" % plural(c["rulings_setup_overdue"], "setup ruling")) + if c["rulings_no_kind"]: + parts.append("%s with no kind" % plural(c["rulings_no_kind"], "ruling")) + unread = rec["coverage"]["unread_count"] + if not parts and not unread: + return "" + if parts: + text = "; ".join(parts) + if unread: + text += "; %s not checked" % plural(unread, "area") + return text + ". Run desk for the list." + return "%s not checked, so this is not a clean result. Run desk for details." % plural(unread, "area") + + +def format_text(rec): + out = [] + add = out.append + add("desk: %s box, layout %s, root %s" % (rec["mode"], rec["layout"], rec["root"])) + if rec["mode"] == "team": + pin = rec["pin"] + add("template pin: %s (%s)" % (pin["sha"] or "none", pin["source"])) + add("scanned %s" % rec["scanned_at"]) + f = rec["findings"] + add("") + add("Core files") + if rec["mode"] == "owner": + add(" not applicable: this tree is where the template comes from") + for r in rec["core"]: + if rec["mode"] == "owner": + continue + extra = "" + if r["state"] == "stale": + extra = " (matches %s%s)" % (r["match"].replace("_", " "), ", template commit " + r["template_commit"][:12]) + elif r.get("reason"): + extra = " (%s)" % r["reason"] + add(" %-24s %s%s" % (r["path"], r["state"], extra)) + if f["stale_core"]: + add(" -> %s behind the template with no local edit: the template can replace them." + % plural(len(f["stale_core"]), "file")) + if f["unresolved_core"]: + add(" note: %s differ from the template and cannot be matched to template material; an owner edit is possible" + % plural(len(f["unresolved_core"]), "file")) + add("") + add("Dead references in always-loaded files: %d" % len(f["dead_references"])) + for d in f["dead_references"]: + add(" %s:%d %s %s" % (d["file"], d["line"], d["kind"].replace("_", " "), d["ref"])) + add("") + r = f["rulings"] + cov = rec["coverage"]["checks"]["rulings"] + add("Rulings: %s%s" % (cov["status"], " (%s)" % cov["reason"] if cov.get("reason") else "")) + for row in r["no_kind"]: + add(" line %d no valid kind %s" % (row["line"], row["area"])) + for row in r["setup_overdue"]: + add(" line %d setup ruling past review (%s) %s" % (row["line"], row["review_by"], row["area"])) + if rec["counts"].get("rulings_lapsed_recent"): + add(" %s lapsed in the last %d days (%s; desk keep DATE AREA restores one)" + % (plural(rec["counts"]["rulings_lapsed_recent"], "setup ruling"), LAPSED_RECENT_DAYS, ARCHIVE_REL)) + add("") + add("Always-loaded size: %d bytes in %d files" % (rec["size"]["total"], len(rec["size"]["files"]))) + for s in sorted(rec["size"]["files"], key=lambda x: -x["bytes"])[:8]: + add(" %7d %s" % (s["bytes"], s["path"])) + if rec["size"].get("over_threshold"): + add(" over the reporting threshold of %d bytes" % rec["size"]["threshold"]) + add("") + add("Memory (local only, never in the briefing): %d duplicate pool group(s)" % len(f["duplicate_pools"])) + for d in f["duplicate_pools"]: + add(" %d identical entries in: %s" % (d["entries"], ", ".join(d["pools"]))) + if rec["worth_a_look"]: + add("") + add("Worth a look (not a defect): rulings that override a core default and predate the template's last change") + for w in rec["worth_a_look"]: + add(" line %d %s overrides %s, template changed %s" % (w["line"], w["area"], w["overrides"], w["template_changed"])) + add("") + cv = rec["coverage"] + if cv["unread_count"]: + add("NOT CHECKED (%d): this is not a clean result" % cv["unread_count"]) + for u in cv["unread"]: + add(" %s: %s: %s" % (u["check"], u["subject"], u["reason"])) + if cv["unread_count"] > len(cv["unread"]): + add(" and %d more" % (cv["unread_count"] - len(cv["unread"]))) + for n in cv["notes"]: + add("note: %s" % n) + add("roster: %s" % cv["roster"]) + add("") + add("Result: " + (rec["line"] or "nothing provably wrong in what was read.")) + return "\n".join(out) + "\n" + + +# The weekly collector reads these from both the record and this view; a key in one and not the other +# reports zero without saying so, so the record's counts and this list change together. +COUNTS_VIEW_KEYS = ("stale_core", "dead_references", "rulings_setup_overdue", "rulings_lapsed_recent") + + +def counts_view(rec): + """Bounded integers and a coverage word: what the weekly collector may carry off a box.""" + cap = lambda n: min(int(n), 9999) + c = rec["counts"] + return {"schema": SCHEMA, "scanned_epoch": rec["scanned_epoch"], "pin": rec["pin"]["sha"], + "coverage": rec["coverage"]["status"], "unread": cap(rec["coverage"]["unread_count"]), + "counts": {k: cap(c.get(k, 0)) for k in COUNTS_VIEW_KEYS}} + + +# --------------------------------------------------------------------------------------------------- +# the cache + +def cache_path(state_dir, explicit=None): + return explicit or os.path.join(state_dir, CACHE_NAME) + + +def write_cache(rec, path, root): + """Atomic: a temp file beside the target, fsync, rename. Never inside the checkout.""" + directory = os.path.dirname(os.path.abspath(path)) + if inside(directory, root): + raise ScanError("refusing to write the cache inside the checkout: %s" % path) + os.makedirs(directory, exist_ok=True) + fd, tmp = tempfile.mkstemp(prefix=".desk-last.", suffix=".tmp", dir=directory) + try: + with os.fdopen(fd, "w") as fh: + json.dump(rec, fh, indent=2, sort_keys=True) + fh.write("\n") + fh.flush() + os.fsync(fh.fileno()) + os.chmod(tmp, 0o644) + os.replace(tmp, path) + except BaseException: + try: + os.unlink(tmp) + except OSError: + pass + raise + + +def cached_line(path, root): + """The cached briefing text, or '' (absent, unreadable, another root's, older than 8 days, nothing to show).""" + try: + with open(path, "r") as fh: + rec = json.load(fh) + if rec.get("schema") != SCHEMA or os.path.realpath(rec.get("root", "")) != os.path.realpath(root): + return "" + if time.time() - int(rec["scanned_epoch"]) > CACHE_MAX_AGE: + return "" + return str(rec.get("line", "")).replace("\n", " ").strip() + except (OSError, ValueError, KeyError, TypeError): + return "" + + +# --------------------------------------------------------------------------------------------------- +# the archive: rulings moved out of the active table, each with its original row byte for byte + +ARCHIVE_HEADER = ( + "# Standing orders archive\n" + "\n" + "Rulings moved out of [standing-orders.md](standing-orders.md) by `desk`. Nothing in this file is loaded\n" + "into a session and nothing here is in force. Each entry keeps the original row byte for byte, the date it\n" + "moved and why. `desk keep ` brings a lapsed setup ruling back as a preference.\n" +) +ENTRY_FIELD_RE = re.compile(r"- (Reason|Moved|Restored): ?(.*?)\r?") +ROW_FENCE = "~~~text" # a row starts with "|", so it can never close a tilde fence + + +class ArchiveError(Exception): + """The archive file has an entry desk cannot read; nothing that needs it is done.""" + + +def parse_archive(text): + """Entries of the archive: a `### ` section with a `- Reason:` line, a `- Moved:` line and the original + row in a ~~~text fence. A `### ` section with no Reason line is the owner's own note and is skipped. + Each entry: {line, reason, moved, moved_index, restored, row, date, area}; row is the exact original + line (a trailing carriage return included), date and area its first two cells.""" + lines = text.split("\n") + starts = [i for i, line in enumerate(lines) if line.startswith("### ")] + entries = [] + for k, start in enumerate(starts): + end = starts[k + 1] if k + 1 < len(starts) else len(lines) + fields, row, j = {}, None, start + 1 + while j < end: + line = lines[j] + m = ENTRY_FIELD_RE.fullmatch(line) + if m and row is None: + key = m.group(1).lower() + if key in fields: + raise ArchiveError("the entry at line %d has two %s lines" % (start + 1, m.group(1))) + fields[key] = (j, m.group(2).strip()) + elif line.rstrip("\r") == ROW_FENCE and row is None: + if j + 2 < end and lines[j + 2].rstrip("\r") == "~~~" and lines[j + 1].lstrip().startswith("|"): + row = lines[j + 1] + j += 2 + else: + raise ArchiveError("the entry at line %d does not hold exactly one fenced table row" % (start + 1)) + j += 1 + if "reason" not in fields: + continue + if row is None or "moved" not in fields or parse_date(fields["moved"][1]) is None: + raise ArchiveError("the entry at line %d has no original row or no valid Moved date" % (start + 1)) + cells = split_cells(row.rstrip("\r")) + if len(cells) < 2: + raise ArchiveError("the entry at line %d holds a row with no area cell" % (start + 1)) + entries.append({"line": start + 1, "reason": fields["reason"][1], "moved": fields["moved"][1], + "moved_index": fields["moved"][0], "restored": fields.get("restored", (None, None))[1], + "row": row, "date": cells[0], "area": cells[1]}) + return entries + + +def format_entry(row, moved, reason): + cells = split_cells(row.rstrip("\r")) + return "\n### %s | %s\n\n- Reason: %s\n- Moved: %s\n- Original row:\n\n%s\n%s\n~~~\n" % ( + cells[0], cells[1], reason, moved, ROW_FENCE, row) + + +def append_entries(archive_text, entries_text): + """The archive with new entries at its end. Existing bytes are kept as they are; a new archive starts + with the header.""" + base = ARCHIVE_HEADER if archive_text is None else archive_text + if base and not base.endswith("\n"): + base += "\n" + return base + "".join(entries_text) + + +def replace_cell(line, idx, new): + """line with the content of cell idx replaced by new, keeping the cell's own padding, every other byte + of the line and a trailing carriage return. None when the line has no such cell.""" + eol = "\r" if line.endswith("\r") else "" + body = line[:-1] if eol else line + bars = [m.start() for m in re.finditer(r"(? ends the process right here, as a kill would (no cleanup runs). The + interrupted-write cases in tests/desk-lapse-test.py use it; nothing else sets it.""" + if os.environ.get("DESK_FAULT") == point: + os._exit(70) + + +def write_json_atomic(path, data): + directory = os.path.dirname(os.path.abspath(path)) + os.makedirs(directory, exist_ok=True) + fd, tmp = tempfile.mkstemp(prefix="." + os.path.basename(path) + ".", suffix=".tmp", dir=directory) + try: + with os.fdopen(fd, "w") as fh: + json.dump(data, fh, indent=2, sort_keys=True) + fh.write("\n") + fh.flush() + os.fsync(fh.fileno()) + os.replace(tmp, path) + except BaseException: + try: + os.unlink(tmp) + except OSError: + pass + raise + + +def sync_directory(path): + fd = os.open(path, os.O_RDONLY | os.O_DIRECTORY) + try: + os.fsync(fd) + finally: + os.close(fd) + + +# renameat2 flags (linux/fs.h). desk puts each file in place by exchanging it with what is there, so an +# editor's save that lands after desk's last read is displaced into desk's temp name, compared, and put +# back, never overwritten (second review of piece C, 2026-12-04). The memory settle calls it the same way. +RENAME_NOREPLACE, RENAME_EXCHANGE = 1, 2 +DISPLACED_SUFFIX = ".desk-displaced-" # a file desk displaced and could not verify; never deleted by desk +PROBE_PREFIX = ".desk-probe-" + + +class RenameUnsupported(OSError): + """This system cannot do renameat2 with the flags desk needs. An OSError, so every write path that + rolls back on an OSError rolls back on this too.""" + + +def libc_renameat2(): + """The C library's renameat2, or None (not Linux, or a libc without it). Tests replace this.""" + try: + import ctypes + fn = getattr(ctypes.CDLL(None, use_errno=True), "renameat2", None) + except (OSError, ImportError): + return None + if fn is not None: + fn.argtypes = [ctypes.c_int, ctypes.c_char_p, ctypes.c_int, ctypes.c_char_p, ctypes.c_uint] + fn.restype = ctypes.c_int + return fn + + +def renameat2(src, dst, flags): + """renameat2(AT_FDCWD, src, AT_FDCWD, dst, flags). RenameUnsupported when the call or the flag is not + available (missing, ENOSYS, EINVAL); OSError otherwise.""" + import ctypes + import errno + fn = libc_renameat2() + if fn is None: + raise RenameUnsupported("this system has no renameat2") + at_fdcwd = -100 + if fn(at_fdcwd, os.fsencode(src), at_fdcwd, os.fsencode(dst), flags) != 0: + err = ctypes.get_errno() + if err in (errno.ENOSYS, errno.EINVAL): + raise RenameUnsupported("renameat2 flag %d: %s" % (flags, os.strerror(err))) + raise OSError(err, os.strerror(err), src, None, dst) + + +def probe_renameat2(directory): + """Prove exchange and no-replace work in directory (its filesystem) with two scratch files, before + desk writes anything there. RenameUnsupported or OSError when they do not.""" + # A prefix does not establish ownership of directories already in the checkout. + with tempfile.TemporaryDirectory(prefix=PROBE_PREFIX, dir=directory) as work: + a, b, c = (os.path.join(work, n) for n in "abc") + for path, text in ((a, b"a"), (b, b"b")): + with open(path, "wb") as fh: + fh.write(text) + renameat2(a, b, RENAME_EXCHANGE) + renameat2(a, c, RENAME_NOREPLACE) + with open(b, "rb") as fb, open(c, "rb") as fc: + if (fb.read(), fc.read()) != (b"a", b"b"): + raise RenameUnsupported("renameat2 did not exchange the probe files") + try: + renameat2(c, b, RENAME_NOREPLACE) + raise RenameUnsupported("renameat2 replaced a file despite RENAME_NOREPLACE") + except FileExistsError: + pass + + +def displaced_name(path): + """A free name beside path for a file desk displaced and could not verify.""" + for n in range(100): + cand = "%s%s%d%s" % (path, DISPLACED_SUFFIX, os.getpid(), "" if n == 0 else "-%d" % n) + if not os.path.lexists(cand): + return cand + raise WriteFailed("no free name beside %s to keep a displaced file" % path) + + +GIT_OPERATIONS = (("MERGE_HEAD", "a merge"), ("CHERRY_PICK_HEAD", "a cherry-pick"), ("REVERT_HEAD", "a revert"), + ("BISECT_LOG", "a bisect"), ("rebase-merge", "a rebase"), ("rebase-apply", "a rebase or am"), + ("sequencer", "a cherry-pick or revert sequence")) + + +class checkout_lock: + """An flock on the checkout directory itself: the lock the team sync takes (sync_box.py repo_lock), + so a sync and a desk write never interleave on one box. Closing the descriptor releases it.""" + + def __init__(self, root): + self.root = root + self._fd = None + + def __enter__(self): + try: + import fcntl + except ImportError: + raise Refused("this platform has no flock, so the checkout cannot be locked against the team sync") + wait = float(os.environ.get("DESK_LOCK_WAIT") or LOCK_WAIT) # tests shorten the wait + fd = os.open(self.root, os.O_RDONLY | os.O_DIRECTORY) + deadline = time.monotonic() + wait + while True: + try: + fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB) + break + except BlockingIOError: + if time.monotonic() >= deadline: + os.close(fd) + raise Refused("another process (the team sync or another desk run) holds the checkout lock") + time.sleep(0.2) + self._fd = fd + return self + + def __exit__(self, *exc): + if self._fd is not None: + os.close(self._fd) + self._fd = None + return False + + +# Every hook `git commit` would run. desk commits with plumbing (commit-tree, update-ref), which runs none +# of them, and hooks are never bypassed, so a checkout with one of these executable is refused before +# anything is written. The same list and rule as memory_settle.py local mode (reviewed 2026-12-04). +COMMIT_HOOKS = ("pre-commit", "prepare-commit-msg", "commit-msg", "pre-merge-commit", "post-commit") +INDEX_LOCK_WAIT = 10 # seconds to wait for a session's git to release index.lock +INDEX_TMP_PREFIX = ".desk-index." # desk's copy of the real index, beside it, while it is rewritten +LITERAL = {"GIT_LITERAL_PATHSPECS": "1"} + + +def read_small(path): + try: + with open(path, "r", encoding="utf-8", errors="replace") as fh: + return fh.read(4096) + except (FileNotFoundError, IsADirectoryError): + return None + + +class deferred_signals: + """SIGTERM, SIGINT and SIGHUP held while desk holds index.lock and moves files and the branch, then + delivered: a stop in the middle would leave the owner's checkout locked or half written. SIGKILL and + power loss cannot be held; the journal covers them.""" + SIGNALS = ("SIGTERM", "SIGINT", "SIGHUP") + + def __enter__(self): + import signal + self.got = None + self.old = {} + for name in self.SIGNALS: + s = getattr(signal, name, None) + if s is not None: + self.old[s] = signal.signal(s, self._held) + return self + + def _held(self, signum, _frame): + self.got = self.got or signum + + def __exit__(self, *_exc): + import signal + for s, h in self.old.items(): + signal.signal(s, h) + if self.got: + signal.raise_signal(self.got) + return False + + +def take_index_lock(root, path, nonce): + """Create git's index.lock (the lock every git command that writes the index takes) holding desk's + nonce, so a recovery can tell a lock a killed run left from another command's. The lock appears + complete in one step (a hard link of a written temp file). Waits INDEX_LOCK_WAIT seconds + (DESK_INDEX_WAIT in tests) for a session's git to finish; refuses after.""" + wait = float(os.environ.get("DESK_INDEX_WAIT") or INDEX_LOCK_WAIT) + deadline = time.monotonic() + wait + tmp = None + try: + while True: + if not os.path.lexists(path): + if tmp is None: + fd, tmp = tempfile.mkstemp(prefix=INDEX_TMP_PREFIX, dir=os.path.dirname(path)) + with os.fdopen(fd, "w") as fh: + fh.write(nonce) + fh.flush() + os.fsync(fh.fileno()) + try: + os.link(tmp, path) + return path + except FileExistsError: + pass + if time.monotonic() >= deadline: + raise Refused("another git command holds the index (index.lock); nothing was written") + time.sleep(0.1) + finally: + if tmp is not None: + os.unlink(tmp) + + +def release_index_lock(path, nonce): + """Remove index.lock only when it is desk's own (it holds the run's nonce).""" + if path and nonce and read_small(path) == nonce: + os.unlink(path) + + +def index_info(entries): + """`git update-index -z --index-info` input for [(mode, object, path)]; mode "0" removes the path.""" + return b"".join(("%s %s\t%s" % e).encode("utf-8") + b"\0" for e in entries) + + +class CheckedWrite: + """Change a few named files in the checkout and commit exactly their planned bytes, or change nothing. + + with CheckedWrite(root, state_dir, "lapse") as w: + old = w.read(rel) # refuses dirty, staged, symlinked, untracked files + sha = w.commit([(rel, new_bytes)], msg) # writes the files, commits exactly those bytes + + The commit is plumbing, as memory_settle.py local mode commits (reviewed twice on 2026-12-04): the + planned bytes are hashed with their path (git's filters apply), set into a temporary index read from + the HEAD captured at the start, written as a tree and committed with commit-tree on that HEAD, and the + branch moves with update-ref and that HEAD as its expected old value. Nothing reads the live files for + the commit, so an owner's save after desk's rename is never in it; no `git add` or `git commit` runs, + so no hook can add other work and no intent-to-add entry appears in the owner's index. + + Order of work: + 1. __enter__: the checkout flock (the lock the team sync and the memory settle take, sync_box.py + repo_lock), no detached or unborn HEAD and no git operation in progress (GIT_OPERATIONS), then + an interrupted earlier write finished or undone from its journal; + 2. read(): each file a regular file in a real directory, tracked (or absent from disk, index and + HEAD, for a new one), with an empty `git status`; + 3. commit(), before anything is written: refuse an executable commit hook (COMMIT_HOOKS), unmerged + entries, a split or sparse index, a staged or flagged entry for a planned path; hash the planned + bytes and build the commit; journal it (phase "prepared"); + 4. under git's index.lock (desk's nonce in it) and with stop signals held: HEAD and the planned + paths' index entries rechecked; journal phase "writing"; each file replaced through a temp file + in its own directory, re-read just before the rename (a change since read() refuses), directory + synced; `git update-ref -m SUBJECT `; + 5. journal phase "committed"; the real index's entries for the planned paths set to the commit's, + only where they still are what they were at the capture (an entry the owner staged is left as + theirs); every other entry untouched; phase "complete", journal removed, index.lock released; + 6. a failure before the branch moved rolls the renames back in reverse order (the active file before + its archive, so a ruling is never in neither file) and refuses; anything it cannot put back is + named and the journal stays. + A file that no longer holds the planned bytes after the commit (an owner saved it meanwhile) is left + as the owner's uncommitted edit on top of the new HEAD, and desk says so on stderr. + """ + + def __init__(self, root, state_dir, op): + self.root = os.path.realpath(root) + self.state_dir = os.path.abspath(state_dir) + self.op = op + self.journal = os.path.join(self.state_dir, JOURNAL_NAME) + self.snap, self.modes = {}, {} + self.head = None + self.ref = None + self._lock = checkout_lock(self.root) + + # -- lock and preflight + def __enter__(self): + if inside(self.state_dir, self.root): + raise Refused("the state dir %s is inside the checkout" % self.state_dir) + self._lock.__enter__() + try: + self._preflight() + self._recover() + except BaseException: + self._lock.__exit__() + raise + return self + + def __exit__(self, *exc): + self._lock.__exit__() + return False + + def _git(self, args, **kw): + return rgit(self.root, args, **kw) + + def _gitp(self, args, what, **kw): + """git that must succeed; WriteFailed naming `what` otherwise. The output, stripped.""" + rc, out, err = self._git(args, **kw) + if rc != 0: + raise WriteFailed("%s failed: %s" % (what, clip(err or out, 200))) + return out.strip() if isinstance(out, str) else out + + def _git_path(self, name): + out = self._gitp(["rev-parse", "--git-path", name], "git rev-parse --git-path", raw_output=True) + p = os.fsdecode(out).rstrip("\n") + return p if os.path.isabs(p) else os.path.join(self.root, p) + + def _head(self): + """(branch ref, commit) now, or Refused for a detached or unborn HEAD.""" + rc, ref, _e = self._git(["symbolic-ref", "-q", "HEAD"]) + if rc != 0: + raise Refused("HEAD is detached; check out a branch first") + rc, head, _e = self._git(["rev-parse", "-q", "--verify", "HEAD^{commit}"]) + if rc != 0: + raise Refused("the branch has no commit yet (unborn HEAD)") + return ref.strip(), head.strip() + + def _preflight(self): + rc, top, err = self._git(["rev-parse", "--show-toplevel"]) + if rc != 0: + raise Refused("not a git checkout: %s" % clip(err, 120)) + if os.path.realpath(top.strip()) != self.root: + raise Refused("the root is not the top of its git checkout (%s)" % top.strip()) + self.ref, self.head = self._head() + self._check_operations() + + def _check_operations(self): + # index.lock is handled separately so recovery can reclaim its own lock. + args = ["rev-parse"] + for name, _label in GIT_OPERATIONS: + args += ["--git-path", name] + rc, out, err = self._git(args) + paths = out.splitlines() + if rc != 0 or len(paths) != len(GIT_OPERATIONS): + raise Refused("cannot read the git directory: %s" % clip(err, 120)) + for (name, label), p in zip(GIT_OPERATIONS, paths): + if os.path.lexists(p if os.path.isabs(p) else os.path.join(self.root, p)): + raise Refused("%s is in progress in this checkout (%s); finish or abort it first" % (label, name)) + + # -- files + def _path(self, rel): + path = os.path.join(self.root, rel) + parent = os.path.dirname(path) + if os.path.isabs(rel) or os.path.realpath(parent) != parent or not os.path.isdir(parent): + raise Refused("%s is not a plain directory in the checkout" % os.path.dirname(rel)) + return path + + @staticmethod + def _temp_path(path): + return os.path.join(os.path.dirname(path), ".%s.desk-tmp" % os.path.basename(path)) + + def _current(self, rel): + """The file's bytes now, None when absent, or False when it is not a regular file.""" + path = self._path(rel) + try: + st = os.lstat(path) + except FileNotFoundError: + return None + if not stat.S_ISREG(st.st_mode): + return False + return read_bytes(path) + + def read(self, rel, must_exist=True): + """The file's bytes (None when absent and allowed), after the checks in step 2.""" + path = self._path(rel) + try: + st = os.lstat(path) + except FileNotFoundError: + st = None + if st is None: + if must_exist: + raise Refused("%s does not exist" % rel) + rc, out, _e = self._git(["ls-files", "-z", "--", rel], extra_env=LITERAL) + if rc != 0 or out: + raise Refused("%s is missing from the disk but known to the index" % rel) + if tree_oid(self.root, self.head, rel) is not None: + raise Refused("%s is deleted in the working tree but not in the last commit" % rel) + self.snap[rel], self.modes[rel] = None, 0o644 + else: + if stat.S_ISLNK(st.st_mode): + raise Refused("%s is a symlink; desk edits only a regular file" % rel) + if not stat.S_ISREG(st.st_mode): + raise Refused("%s is not a regular file" % rel) + rc, _o, _e = self._git(["ls-files", "--error-unmatch", "--", rel], extra_env=LITERAL) + if rc != 0: + raise Refused("%s is not tracked by git" % rel) + try: + data = read_bytes(path) + except OSError as exc: + raise Refused("cannot read %s: %s" % (rel, clip(exc, 80))) + self.snap[rel], self.modes[rel] = data, stat.S_IMODE(st.st_mode) + rc, out, err = self._git(["status", "--porcelain=v1", "-z", "--untracked-files=all", "--", rel], + extra_env=LITERAL) + if rc != 0: + raise Refused("git status failed for %s: %s" % (rel, clip(err, 120))) + if out: + raise Refused("%s has uncommitted or staged changes; commit or discard them first" % rel) + return self.snap[rel] + + def _read_regular(self, path): + """Bytes of a regular file at path, or None for anything else (a link, a directory, nothing).""" + try: + if not stat.S_ISREG(os.lstat(path).st_mode): + return None + return read_bytes(path) + except OSError: + return None + + def _keep_displaced(self, tmp, path): + """Move bytes desk displaced and could not verify from its temp name to a clear name beside the + file. Returns that name. Never deletes them.""" + name = displaced_name(path) + renameat2(tmp, name, RENAME_NOREPLACE) + return name + + def _replace(self, rel, data, expect): + """Put data at rel only if rel holds expect (None: absent), never overwriting anything else: + 1. write data to the temp name beside rel (O_EXCL), fsync; + 2. cheap early refusal: rel no longer holds expect; + 3. absent target: renameat2(temp, rel, RENAME_NOREPLACE); EEXIST refuses, nothing overwritten; + 4. existing target: renameat2(temp, rel, RENAME_EXCHANGE), so the temp name holds what was + displaced; if those bytes are expect, unlink them and stop; + 5. otherwise an owner's save landed: exchange back (their file returns to rel), and if what + comes out is desk's data, unlink it and refuse; if it is neither (a second save in that + instant), exchange once more so rel holds that newest save, keep what comes out under a + .desk-displaced- name beside the file, and raise WriteFailed naming both. + desk never unlinks bytes it did not write and has not compared.""" + path = self._path(rel) + tmp = self._temp_path(path) + fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, self.modes.get(rel, 0o644)) + exchanged = False + try: + with os.fdopen(fd, "wb") as fh: + fh.write(data) + fh.flush() + os.fsync(fh.fileno()) + os.chmod(tmp, self.modes.get(rel, 0o644)) + if self._current(rel) != expect: + raise Refused("%s changed while desk was working; it was left as the other writer made it" % rel) + fault("before-swap") + if expect is None: + try: + renameat2(tmp, path, RENAME_NOREPLACE) + except FileExistsError: + raise Refused("%s was created while desk was working; it was left as the other writer made it" + % rel) + return + renameat2(tmp, path, RENAME_EXCHANGE) + exchanged = True + fault("after-swap") + if self._read_regular(tmp) == expect: + os.unlink(tmp) # the bytes desk read and journaled: verified, not the owner's + return + fault("before-swap-back") + renameat2(tmp, path, RENAME_EXCHANGE) # the owner's save back at rel + if self._read_regular(tmp) == data: + exchanged = False # the temp name again holds desk's data + raise Refused("%s changed while desk was working; it was left as the other writer made it" % rel) + renameat2(tmp, path, RENAME_EXCHANGE) # rel gets the newest save; what comes out is kept + kept = self._keep_displaced(tmp, path) + except BaseException as exc: + if exchanged: + # The active file can already lack the lapsed row. Rolling back only the completed + # archive write could remove the row from both files. + raise SwapIncomplete(f"could not finish replacing {rel}: {exc}. Desk kept {tmp} and " + f"the write journal at {self.journal} for recovery") from exc + try: + os.unlink(tmp) + except FileNotFoundError: + pass + except OSError as cleanup: + raise SwapIncomplete(f"could not replace {rel}: {exc} or remove {tmp}: {cleanup}. " + f"Desk kept the write journal at {self.journal}") from cleanup + raise + raise WriteFailed("%s was saved twice while desk was working: the newest save is at %s and the one " + "before it is kept at %s; compare them by hand" % (rel, rel, os.path.relpath(kept, self.root))) + + def _sync_parent(self, rel): + sync_directory(os.path.dirname(self._path(rel))) + + def _remove(self, rel, expect): + """Take away a file desk created, only if it still holds expect: rename it to the temp name + (RENAME_NOREPLACE) and compare; anything else goes back to rel, or beside it when rel was + recreated meanwhile. A problem string, or None.""" + path = self._path(rel) + tmp = self._temp_path(path) + renameat2(path, tmp, RENAME_NOREPLACE) + if self._read_regular(tmp) == expect: + os.unlink(tmp) + return None + try: + renameat2(tmp, path, RENAME_NOREPLACE) + return "%s changed after desk wrote it and was left as it is" % rel + except FileExistsError: + kept = self._keep_displaced(tmp, path) + return ("%s changed after desk wrote it: the newer file is at %s and the one desk took away is kept at %s" + % (rel, rel, os.path.relpath(kept, self.root))) + + def _restore(self, rel, old, new): + """Put rel back to old when it still holds new, through the same exchange as _replace. A problem + string, or None.""" + cur = self._current(rel) + if cur == old: + return None + if cur != new: + return "%s changed after desk wrote it and was left as it is" % rel + try: + if old is None: + problem = self._remove(rel, new) + if problem: + return problem + else: + self._replace(rel, old, expect=new) + self._sync_parent(rel) + except (OSError, Refused, WriteFailed, RenameUnsupported) as exc: + return "%s could not be restored: %s" % (rel, clip(exc, 200)) + return None + + def _undo(self, pairs): + """Roll the renames back newest first: for a lapse the active file (the row back) before the + archive (its copy gone), so a stop part way leaves the row in both files, never in neither. + Raises WriteFailed naming the first path that cannot be put back.""" + for rel, old, new in reversed(pairs): + problem = self._restore(rel, old, new) + if problem: + raise WriteFailed("NOT fully restored: %s (journal kept at %s)" % (problem, self.journal)) + + # -- git state + def _hook_refusal(self): + """Why desk will not commit here because of an executable hook, or None.""" + for name in COMMIT_HOOKS: + h = self._git_path("hooks/" + name) + if os.path.isfile(h) and os.access(h, os.X_OK): + return ("an executable %s hook (%s) would not run for desk's plumbing commit, and hooks are never " + "bypassed; disable it, or make this change by hand" % (name, h)) + return None + + def _busy(self): + """Why the index is not one desk writes, or None.""" + rc, out, err = self._git(["ls-files", "-u", "-z"]) + if rc != 0: + return "cannot read the index: %s" % clip(err, 120) + if out: + return "the index has unmerged entries" + for key in ("core.splitIndex", "index.sparse"): + rc, out, _e = self._git(["config", "--bool", "--get", key]) + if out.strip() == "true": + return "%s is on, an index format desk does not write" % key + # git update-index --split-index can enable this format without setting core.splitIndex. + if self._gitp(["rev-parse", "--shared-index-path"], "checking for a split index"): + return "the checkout uses a split index, a format desk does not write" + return None + + def _tree(self, commit, rels): + """{rel: (mode, type, object)} of each path commit holds.""" + out = self._gitp(["ls-tree", "-z", commit, "--"] + list(rels), "git ls-tree", extra_env=LITERAL) + found = {} + for rec in out.split("\0"): + if rec: + meta, path = rec.split("\t", 1) + found[path] = tuple(meta.split()) + return found + + def _index(self, rels): + """{rel: ((mode, object, stage), ...)} of the real index, and the paths whose flags hide edits.""" + out = self._gitp(["ls-files", "-v", "-s", "-z", "--"] + list(rels), "git ls-files", extra_env=LITERAL) + found, hidden = {}, set() + for rec in out.split("\0"): + if not rec: + continue + meta, path = rec.split("\t", 1) + parts = meta.split() + found.setdefault(path, []).append(tuple(parts[1:])) + if parts[0] == "S" or parts[0].islower(): + hidden.add(path) + return {p: [list(e) for e in sorted(v)] for p, v in found.items()}, hidden + + def _capture(self, rels): + """Each planned path's committed entry and real index entries, compared again under index.lock.""" + tree = self._tree(self.head, rels) + idx, hidden = self._index(rels) + cap = {} + for rel in rels: + t = tree.get(rel) + if rel in hidden: + raise Refused("%s has skip-worktree or assume-unchanged set in the index" % rel) + if t is not None and (t[1] != "blob" or t[0] not in REGULAR_MODES): + raise Refused("%s is not a regular file in the last commit" % rel) + want = [[t[0], t[2], "0"]] if t else [] + if idx.get(rel, []) != want: + raise Refused("%s has a staged change; commit or unstage it first" % rel) + cap[rel] = {"tree": list(t) if t else None, "index": want} + return cap + + def _landed(self, new, tip): + """Whether the commit desk made is the branch tip or in its history.""" + if tip == new: + return True + rc, _o, err = self._git(["merge-base", "--is-ancestor", new, tip]) + if rc not in (0, 1): + raise WriteFailed("cannot tell whether commit %s landed: %s (journal kept at %s)" + % (new[:12], clip(err, 120), self.journal)) + return rc == 0 + + def _update_index(self, entries): + """Set exactly these real index entries: a copy of the index is updated and renamed into place, so + every other entry (the owner's staged work) stays as it was. The caller holds index.lock.""" + ipath = self._git_path("index") + fd, tmp = tempfile.mkstemp(prefix=INDEX_TMP_PREFIX, dir=os.path.dirname(ipath)) + try: + with os.fdopen(fd, "wb") as dst, open(ipath, "rb") as src: + os.fchmod(dst.fileno(), stat.S_IMODE(os.fstat(src.fileno()).st_mode)) + dst.write(src.read()) + self._gitp(["update-index", "-z", "--index-info"], "git update-index (a copy of the index)", + stdin=index_info(entries), extra_env=dict(LITERAL, GIT_INDEX_FILE=tmp)) + with open(tmp, "rb") as fh: + os.fsync(fh.fileno()) + os.replace(tmp, ipath) + sync_directory(os.path.dirname(ipath)) + except BaseException: + try: + os.unlink(tmp) + except OSError: + pass + raise + + def _index_stamp(self): + st = os.stat(self._git_path("index")) + return [st.st_dev, st.st_ino, st.st_size, st.st_mtime_ns, st.st_ctime_ns] + + def _finish_index(self, j, recovering=False): + """A commit of desk's that is on the branch: each planned path's real index entry becomes the + commit's, where HEAD still holds desk's version and the entry is what it was at the capture. An + entry staged since is the owner's and is left. The caller holds index.lock.""" + rels = [p["rel"] for p in j["paths"]] + new_t = self._tree(j["new"], rels) + _ref, tip = self._head() + head_t = new_t if tip == j["new"] else self._tree(tip, rels) + cur, hidden = self._index(rels) + zero = "0" * len(j["new"]) + entries = [] + for p in j["paths"]: + rel, n = p["rel"], new_t.get(p["rel"]) + target = [[n[0], n[2], "0"]] if n else [] + if rel in hidden or n != head_t.get(rel) or cur.get(rel, []) != p["index"] or target == p["index"]: + continue + entries.append((n[0], n[2], rel) if n else ("0", zero, rel)) + if entries: + # After a kill an owner can remove index.lock and explicitly stage the old entry. + # Git can replace the index with identical bytes, so equality of entries or bytes + # is insufficient evidence that the stale entries are desk's to replace. + if recovering and self._index_stamp() != j.get("index_stamp"): + raise Refused("the index changed after desk started; review the staged changes and resolve the index " + "by hand before removing %s" % self.journal) + self._update_index(entries) + + def _phase(self, j, phase): + # Persist the directory entry for the journal before the checkout can get ahead of it. + try: + write_json_atomic(self.journal, dict(j, phase=phase)) + sync_directory(os.path.dirname(self.journal)) + except OSError as exc: + raise WriteFailed(f"cannot record phase {phase} in {self.journal}: {exc}") from exc + j["phase"] = phase + + def commit(self, changes, message): + """Write each (rel, new bytes) in order and commit exactly those bytes. Returns the commit id.""" + rels = [rel for rel, _ in changes] + for rel in rels: + if rel not in self.snap: + raise Refused("internal: %s was not read before the write" % rel) + why = self._hook_refusal() or self._busy() + if why: + raise Refused(why) + for directory in sorted({os.path.dirname(self._path(rel)) for rel in rels}): + try: + probe_renameat2(directory) + except (RenameUnsupported, OSError) as exc: + raise Refused("desk writes need Linux renameat2 (exchange and no-replace) in %s, which this system " + "cannot do (%s); nothing was written" % (os.path.relpath(directory, self.root), clip(exc, 120))) + cap = self._capture(rels) + # the commit, built from the planned bytes before anything visible changes (its objects are + # unreachable until the branch moves) + entries = [] + for rel, new in changes: + oid = self._gitp(["hash-object", "-w", "--path=" + rel, "--stdin"], "git hash-object", stdin=new) + entries.append((cap[rel]["tree"][0] if cap[rel]["tree"] else "100644", oid, rel)) + work = tempfile.mkdtemp(prefix="desk-tree-") + try: + env = dict(LITERAL, GIT_INDEX_FILE=os.path.join(work, "index")) + self._gitp(["read-tree", self.head], "git read-tree", extra_env=env) + self._gitp(["update-index", "-z", "--index-info"], "git update-index (a temporary index)", + stdin=index_info(entries), extra_env=env) + tree = self._gitp(["write-tree"], "git write-tree", extra_env=env) + finally: + shutil.rmtree(work, ignore_errors=True) + new = self._gitp(["commit-tree", tree, "-p", self.head, "-m", message], "git commit-tree") + subject = message.split("\n", 1)[0] + b64 = lambda b: None if b is None else base64.b64encode(b).decode() + nonce = "desk %d %s\n" % (os.getpid(), os.urandom(8).hex()) + lock_path = self._git_path("index.lock") + j = {"schema": 2, "op": self.op, "root": self.root, "ref": self.ref, "old": self.head, "new": new, + "nonce": nonce, "created": datetime.datetime.now().astimezone().isoformat(timespec="seconds"), + "paths": [{"rel": rel, "old": b64(self.snap[rel]), "new": b64(data), "mode": e[0], "oid": e[1], + "index": cap[rel]["index"]} for (rel, data), e in zip(changes, entries)]} + try: + self._phase(j, "prepared") + except WriteFailed as exc: + raise Refused(str(exc)) from exc + pairs = [(rel, self.snap[rel], data) for rel, data in changes] + written, tried_ref, lock = [], False, None + with deferred_signals(): + try: + fault("captured") + lock = take_index_lock(self.root, lock_path, nonce) + try: + # everything again, under git's lock: nothing may have changed since the capture + if self._head() != (self.ref, self.head): + raise Refused("the branch moved while desk prepared; nothing was written") + self._check_operations() + why = self._hook_refusal() or self._busy() + if why: + raise Refused(why) + if self._capture(rels) != cap: + raise Refused("a planned path's index entry changed while desk prepared; nothing was written") + j["index_stamp"] = self._index_stamp() + self._phase(j, "writing") + for rel, _old, data in pairs: + self._replace(rel, data, expect=self.snap[rel]) + written.append((rel, self.snap[rel], data)) + self._sync_parent(rel) + fault("after-first-write") + fault("before-commit") + tried_ref = True + rc, out, err = self._git(["update-ref", "-m", subject, self.ref, new, self.head]) + if rc != 0: + raise WriteFailed("git update-ref failed (the branch may have moved): %s" + % clip(err or out, 200)) + except SwapIncomplete: + lock = None # leave desk's index.lock in place for recovery, as after an interruption + raise + except (Refused, WriteFailed, OSError) as exc: + landed = False + if tried_ref: + # A failed read cannot establish the commit did not land. + tip = self._gitp(["rev-parse", "-q", "--verify", self.ref], + f"checking {self.ref} after update-ref (journal kept at {self.journal})") + landed = tip != self.head and self._landed(new, tip) + if not landed: + if j["phase"] == "writing": + try: + self._undo(written) + except WriteFailed as undo_exc: + raise WriteFailed("%s; %s" % (exc, undo_exc)) + self._phase(j, "complete") + if isinstance(exc, Refused): + raise + raise WriteFailed("%s; the files are back as they were" % exc) + fault("after-commit") + try: + self._phase(j, "committed") + self._finish_index(j) + self._phase(j, "complete") + except (WriteFailed, OSError) as exc: + raise WriteFailed(f"commit {new[:12]} is on {self.ref}, but its index or journal could not " + f"be finalized ({clip(exc, 160)}). Recovery uses {self.journal}") from exc + finally: + release_index_lock(lock, nonce) + if j.get("phase") in ("prepared", "complete"): + os.unlink(self.journal) + for rel, data in changes: + if self._current(rel) != data: + print("desk: note: %s changed after desk wrote it (an edit saved meanwhile); commit %s holds desk's " + "version and the edit is left uncommitted on top of it" % (rel, new[:12]), file=sys.stderr) + return new + + # -- an interrupted earlier write + def _recover(self): + """Finish or undo a write a kill interrupted, from its journal, under the checkout flock: + prepared or complete: nothing in the checkout changed; a lock left with the nonce is removed; + desk's commit is on the branch (the tip or in its history): its index entries are finished + if the index has not been replaced; the files are kept as they are; + not on the branch and the branch did not move: each file still holding desk's bytes goes back, + newest first, unless a planned path's index entry was staged since (then nothing is touched); + not on the branch and the branch moved (an owner commit after the lock was removed): nothing is + touched. + Anything not handled refuses with the journal kept, for the owner to resolve.""" + if not os.path.exists(self.journal): + return + try: + with open(self.journal) as fh: + j = json.load(fh) + if j.get("schema") != 2 or not isinstance(j.get("nonce"), str) or not j["nonce"]: + raise ValueError("not a journal this desk writes (schema %r)" % j.get("schema")) + pairs = [(p["rel"], None if p["old"] is None else base64.b64decode(p["old"]), + base64.b64decode(p["new"])) for p in j["paths"]] + for key in ("ref", "old", "new", "phase"): + if not isinstance(j.get(key), str): + raise ValueError("no %s" % key) + displaced = j.get("displaced") + if displaced is not None and (not isinstance(displaced, list) or len(displaced) != 2 or + not all(isinstance(p, str) and p for p in displaced)): + raise ValueError("invalid displaced file names") + except (OSError, ValueError, KeyError, TypeError, AttributeError) as exc: + raise Refused("the write journal %s cannot be used (%s); check the files by hand, then remove it" + % (self.journal, clip(exc, 80))) + if os.path.realpath(j.get("root", "")) != self.root: + raise Refused("the write journal %s belongs to another checkout (%s)" % (self.journal, j.get("root"))) + lock_path, nonce = self._git_path("index.lock"), j["nonce"] + move_error = "" + if displaced is None: + for rel, old, new in pairs: + path = self._path(rel) + tmp = self._temp_path(path) + if not os.path.lexists(tmp): + continue + current = self._read_regular(tmp) + if current is not None and current in (old, new): + os.unlink(tmp) + continue + name = displaced_name(path) + displaced = [os.path.relpath(p, self.root) for p in (name, tmp)] + # Persist the refusal before moving the file away from .desk-tmp. The next daily + # run must still wait for the owner, even if this run dies during the move. + j["displaced"] = displaced + self._phase(j, j["phase"]) + try: + renameat2(tmp, name, RENAME_NOREPLACE) + self._sync_parent(rel) + except OSError as exc: + move_error = " (%s)" % clip(exc, 100) + break + if displaced is not None: + name, tmp = displaced + raise Refused(f"an interrupted desk write displaced an unverified file{move_error}. Compare {name} " + f"(or {tmp} if still there) with the rulings file, then remove {self.journal} " + f"(and {lock_path} if git says its index is locked)") + idir = os.path.dirname(lock_path) + for fn in os.listdir(idir): + if fn.startswith(INDEX_TMP_PREFIX): + os.unlink(os.path.join(idir, fn)) + if j["phase"] in ("prepared", "complete"): + release_index_lock(lock_path, nonce) + os.unlink(self.journal) + return + with deferred_signals(): + lock = lock_path if read_small(lock_path) == nonce else take_index_lock(self.root, lock_path, nonce) + try: + self._check_operations() + why = self._busy() + if why: + raise Refused(why) + ref, tip = self._head() + if ref != j["ref"]: + raise Refused("an interrupted desk write belongs to %s and HEAD is on %s; resolve it by hand, " + "then remove %s" % (j["ref"], ref, self.journal)) + if tip != j["old"] and self._landed(j["new"], tip): + self._finish_index(j, recovering=True) + note = "finished the index of commit %s, which an interrupted %s had made" % (j["new"][:12], j["op"]) + elif tip != j["old"]: + raise Refused("an interrupted desk write's commit is not on %s and the branch moved since; the " + "files were left as they are. Resolve them by hand, then remove %s" + % (ref, self.journal)) + else: + cur, _hidden = self._index([p["rel"] for p in j["paths"]]) + staged = [p["rel"] for p in j["paths"] if cur.get(p["rel"], []) != p["index"]] + if staged: + raise Refused("an interrupted desk write was not undone: %s was staged since and was left as " + "it is. Resolve it by hand, then remove %s" % (", ".join(staged), self.journal)) + for rel, _o, _n in pairs: + try: + self.modes[rel] = stat.S_IMODE(os.lstat(self._path(rel)).st_mode) + except OSError: + self.modes[rel] = 0o644 + try: + self._undo(pairs) + except WriteFailed as exc: + raise Refused("an interrupted desk write could not be undone: %s" % exc) + note = "undid an interrupted %s write" % j["op"] + self._phase(j, "complete") + finally: + release_index_lock(lock, nonce) + self.modes = {} + os.unlink(self.journal) + print("desk: %s from %s" % (note, j.get("created", "?")), file=sys.stderr) + + +# --------------------------------------------------------------------------------------------------- +# lapse and keep + +def rulings_root(args_root, args_state_dir, args_mode): + """(root, mode, state_dir, layout) for a write command. A checkout that is not the box's own harness + root needs an explicit --state-dir, so its receipt and journal never land in the box's state dir.""" + root = os.path.realpath(resolve_root(args_root)) + if not os.path.isdir(root): + raise Refused("harness root is not a directory: %s" % root) + mode = args_mode or detect_mode(root) + if not args_state_dir and not is_box_root(root): + raise Refused("%s is not this box's harness root; pass --state-dir to work on it" % root) + state_dir = args_state_dir or default_state_dir(mode) + return root, mode, state_dir, detect_layout(root, mode) + + +def table_lines(text, table): + """The file's lines (split on \\n only, so each keeps any carriage return) and a check that every row the + parser found is the line it says it is.""" + lines = text.split("\n") + for r in table["rows"]: + if lines[r["line"] - 1].rstrip("\r") != r["raw"]: + raise Refused("the rulings table did not parse consistently at line %d" % r["line"]) + return lines + + +def judged_rows(table): + """The table's real rows (no template example), refusing a row whose cell count differs from the + header's: its Kind cell cannot be found for certain, so nothing in the table is judged.""" + rows = [r for r in table["rows"] if not is_example_row(table, r)] + for r in rows: + if len(r["cells"]) != len(table["header"]): + raise Refused("line %d of %s has %d cells and the header has %d; fix the row first" + % (r["line"], ACTIVE_REL, len(r["cells"]), len(table["header"]))) + return rows + + +def decode(data, rel): + try: + return data.decode("utf-8") + except UnicodeDecodeError: + raise Refused("%s is not UTF-8 text" % rel) + + +def migrated_table(root): + """(table or None, why not). A quick read with no lock, to skip a box with nothing to judge.""" + try: + text = read_bytes(os.path.join(root, ACTIVE_REL)).decode("utf-8", errors="replace") + except OSError as exc: + return None, "cannot read %s: %s" % (ACTIVE_REL, clip(exc, 80)) + table = parse_rulings_table(text) + if table is None: + return None, "%s has no rulings table; nothing is judged or moved" % ACTIVE_REL + if table["columns"]["kind"] is None: + return None, "the rulings table has no Kind column yet (not migrated); nothing is judged or moved" + return table, "" + + +def plan_lapse(active_text, archive_text, on): + """(new active text, new archive text, moved rows) for the setup rows due on `on`; ([], ...) when none.""" + table = parse_rulings_table(active_text) + if table is None or table["columns"]["kind"] is None: + raise Refused("the rulings table is missing or has no Kind column") + lines = table_lines(active_text, table) + rows = judged_rows(table) + entries = parse_archive(archive_text) if archive_text is not None else [] + due = [] + for r in rows: + kind, _review = parse_kind(row_cell(table, r, "kind")) + if kind == "setup" and setup_due(setup_review(table, r), on): + due.append(r) + if not due: + return active_text, archive_text, [] + ids = [identity(row_cell(table, r, "date"), row_cell(table, r, "area")) for r in rows] + pending = [identity(e["date"], e["area"]) for e in entries if e["reason"] == "lapsed" and not e["restored"]] + for r in due: + me = identity(row_cell(table, r, "date"), row_cell(table, r, "area")) + if ids.count(me) > 1 or me in pending: + raise Refused("the ruling at line %d shares its date and area with another ruling, so keep could not " + "tell them apart; rename one area first" % r["line"]) + gone = {r["line"] - 1 for r in due} + new_active = "\n".join(line for i, line in enumerate(lines) if i not in gone) + moved = on.isoformat() + new_archive = append_entries(archive_text, [format_entry(lines[r["line"] - 1], moved, "lapsed") for r in due]) + return new_active, new_archive, [{"date": row_cell(table, r, "date"), "area": row_cell(table, r, "area"), + "line": r["line"]} for r in due] + + +def cmd_lapse(argv): + ap = argparse.ArgumentParser(prog="desk lapse", description="Move setup rulings past their review date to the " + "archive, in one commit of the two files, and leave a one-time notice.") + ap.add_argument("--root", help="harness root (default: this script's checkout)") + ap.add_argument("--state-dir", help="state directory for the notice and the write journal (default by box)") + ap.add_argument("--mode", choices=("owner", "team"), help="force the box kind (default: detected)") + args = ap.parse_args(argv) + try: + root, _mode, state_dir, layout = rulings_root(args.root, args.state_dir, args.mode) + if layout == "standing-orders": + table, why = migrated_table(root) + else: + table, why = None, f"this layout ({layout}) has no rulings table desk judges" + if table is None: + if os.path.exists(os.path.join(state_dir, JOURNAL_NAME)): + # A removed or rewritten table must not hide an interrupted write or its index lock. + with CheckedWrite(root, state_dir, "lapse"): + pass + print("desk lapse: nothing to do: %s" % why) + return 0 + on = today() + due_now = any(parse_kind(row_cell(table, r, "kind"))[0] == "setup" and setup_due(setup_review(table, r), on) + for r in table["rows"] if not is_example_row(table, r)) + if not due_now and not os.path.exists(os.path.join(state_dir, JOURNAL_NAME)): + # Nothing to move: no checks that could refuse (an owner's uncommitted edit to the rulings + # file is not this run's business), only the notice check, under the same lock. + with checkout_lock(root): + notice_problem = update_notice(root, state_dir, on, [], None) + print("desk lapse: no setup ruling is past its review date") + if notice_problem: + print("desk lapse: %s" % notice_problem, file=sys.stderr) + return 1 + return 0 + with CheckedWrite(root, state_dir, "lapse") as w: + active = decode(w.read(ACTIVE_REL), ACTIVE_REL) + raw_archive = w.read(ARCHIVE_REL, must_exist=False) + archive = None if raw_archive is None else decode(raw_archive, ARCHIVE_REL) + try: + new_active, new_archive, moved = plan_lapse(active, archive, on) + except ArchiveError as exc: + raise Refused("%s: %s" % (ARCHIVE_REL, exc)) + sha = None + if moved: + names = "\n".join("- %s, %s" % (m["date"], m["area"]) for m in moved) + message = ("chore(rulings): lapse %s past review\n\n%s\n\nMoved by desk lapse to %s. `desk keep " + " ` brings one back as a preference." + % (plural(len(moved), "setup ruling"), names, ARCHIVE_REL)) + # the archive first: an interruption between the two renames leaves the row in both + # files (the journal undoes it), never in neither + sha = w.commit([(ARCHIVE_REL, new_archive.encode("utf-8")), + (ACTIVE_REL, new_active.encode("utf-8"))], message) + notice_problem = update_notice(root, state_dir, on, moved, sha) + except (Refused, WriteFailed, ScanError) as exc: + print("desk lapse: %s" % exc, file=sys.stderr) + return 1 + if moved: + print("desk lapse: %s moved to %s in commit %s" + % (plural(len(moved), "setup ruling"), ARCHIVE_REL, sha[:12])) + for m in moved: + print(" %s %s" % (m["date"], m["area"])) + else: + print("desk lapse: no setup ruling is past its review date") + if notice_problem: + print("desk lapse: %s" % notice_problem, file=sys.stderr) + return 1 + return 0 + + +# The pending notice. desk writes the receipt (under the checkout lock); only the session briefing +# appends to the shown list. Two writers never share a file, so no update is lost; at worst two sessions +# starting in the same instant both show a notice once. + +def notice_path(state_dir): + return os.path.join(state_dir, NOTICE_NAME) + + +def update_notice(root, state_dir, on, moved, sha): + """Add this run's event, recover any recent lapse the receipt is missing (a run killed after its + commit), and drop old events. A problem string, or None.""" + path = notice_path(state_dir) + rec, problem = None, None + try: + with open(path) as fh: + rec = json.load(fh) + if not (isinstance(rec, dict) and rec.get("schema") == 1 and isinstance(rec.get("events"), list) + and isinstance(rec.get("root"), str) and os.path.realpath(rec["root"]) == root): + rec = None + except FileNotFoundError: + pass + except (OSError, ValueError) as exc: + problem = "the notice receipt %s could not be read (%s) and was rewritten" % (path, clip(exc, 60)) + rec = rec or {"schema": 1, "root": root, "events": []} + # only well-formed events survive a rewrite; a malformed one cannot be shown by the briefing anyway + events = [e for e in rec["events"] if isinstance(e, dict) and isinstance(e.get("moved"), str) + and isinstance(e.get("rows"), list) and all(isinstance(r, dict) for r in e["rows"])] + if moved: + events.append({"id": "lapse-" + sha[:16], "moved": on.isoformat(), "commit": sha, + "rows": [{"date": m["date"], "area": m["area"]} for m in moved]}) + covered = {(e.get("moved"),) + identity(r.get("date", ""), r.get("area", "")) + for e in events for r in e.get("rows", [])} + entries = [] + try: + # Recovery is for a lapse whose commit landed before its receipt was written. A working + # copy can also contain an owner's draft or a rename from an interrupted, uncommitted lapse. + if os.path.lexists(os.path.join(root, ARCHIVE_REL)): + oid = tree_oid(root, sha or "HEAD", ARCHIVE_REL) + if oid: + rc, archive, err = rgit(root, ["cat-file", "blob", oid], raw_output=True) + if rc != 0: + raise WriteFailed(clip(err, 120)) + if len(archive) > MAX_FILE_BYTES: + raise ArchiveError("file larger than %d bytes" % MAX_FILE_BYTES) + entries = parse_archive(archive.decode("utf-8")) + except (WriteFailed, UnicodeDecodeError, ArchiveError) as exc: + problem = "the archive could not be read to check the notice: %s" % clip(exc, 80) + missing = {} + for e in entries: + mdate = parse_date(e["moved"]) + if (e["reason"] == "lapsed" and not e["restored"] and mdate is not None + and 0 <= (on - mdate).days < LAPSED_RECENT_DAYS + and (e["moved"],) + identity(e["date"], e["area"]) not in covered): + missing.setdefault(e["moved"], []).append({"date": e["date"], "area": e["area"]}) + for mdate, rows in sorted(missing.items()): + digest = hashlib.sha1(json.dumps([mdate, rows], sort_keys=True).encode()).hexdigest()[:16] + events.append({"id": "recovered-" + digest, "moved": mdate, "commit": None, "rows": rows}) + rec["events"] = [e for e in events if parse_date(e.get("moved")) is not None + and (on - parse_date(e["moved"])).days <= NOTICE_KEEP_DAYS] + if moved or missing or problem: + try: + write_json_atomic(path, rec) + except OSError as exc: + return "the lapse is committed but its notice could not be written to %s: %s" % (path, clip(exc, 80)) + return problem + + +def cmd_keep(argv): + ap = argparse.ArgumentParser(prog="desk keep", description="Keep a setup ruling: make it a preference, or " + "bring a lapsed one back from the archive as a preference.") + ap.add_argument("date", help="the ruling's date cell, YYYY-MM-DD") + ap.add_argument("area", nargs="+", help="the ruling's area cell (case and spacing do not matter)") + ap.add_argument("--root", help="harness root (default: this script's checkout)") + ap.add_argument("--state-dir", help="state directory for the write journal (default by box)") + ap.add_argument("--mode", choices=("owner", "team"), help="force the box kind (default: detected)") + args = ap.parse_args(argv) + want = identity(args.date, " ".join(args.area)) + shown = "%s, %s" % (args.date, " ".join(args.area)) + try: + root, _mode, state_dir, layout = rulings_root(args.root, args.state_dir, args.mode) + if layout == "standing-orders": + table, why = migrated_table(root) + else: + table, why = None, f"this layout ({layout}) has no rulings table desk manages" + if table is None: + if os.path.exists(os.path.join(state_dir, JOURNAL_NAME)): + with CheckedWrite(root, state_dir, "keep"): + pass + raise Refused(why) + with CheckedWrite(root, state_dir, "keep") as w: + active = decode(w.read(ACTIVE_REL), ACTIVE_REL) + raw_archive = w.read(ARCHIVE_REL, must_exist=False) + archive = None if raw_archive is None else decode(raw_archive, ARCHIVE_REL) + table = parse_rulings_table(active) + if table is None or table["columns"]["kind"] is None: + raise Refused("the rulings table is missing or has no Kind column") + lines = table_lines(active, table) + rows = judged_rows(table) + try: + entries = parse_archive(archive) if archive is not None else [] + except ArchiveError as exc: + raise Refused("%s: %s" % (ARCHIVE_REL, exc)) + live = [r for r in rows if identity(row_cell(table, r, "date"), row_cell(table, r, "area")) == want] + lapsed = [e for e in entries if e["reason"] == "lapsed" and not e["restored"] + and identity(e["date"], e["area"]) == want] + if len(live) + len(lapsed) > 1: + where = ["%s line %d" % (ACTIVE_REL, r["line"]) for r in live] + where += ["%s line %d" % (ARCHIVE_REL, e["line"]) for e in lapsed] + raise Refused("more than one ruling is %s (%s); give one a different area first" + % (shown, ", ".join(where))) + kidx = table["columns"]["kind"] + if live: + r = live[0] + kind, _review = parse_kind(row_cell(table, r, "kind")) + if kind != "setup": + print("desk keep: %s is already a %s; nothing to do" % (shown, kind or "row with no valid kind")) + return 0 + new_line = replace_cell(lines[r["line"] - 1], kidx, "preference") + if new_line is None: + raise Refused("cannot find the Kind cell on line %d" % r["line"]) + lines[r["line"] - 1] = new_line + sha = w.commit([(ACTIVE_REL, "\n".join(lines).encode("utf-8"))], + "chore(rulings): keep a setup ruling as a preference\n\n- %s\n\nMade permanent by " + "desk keep before it lapsed; its text is unchanged." % shown) + print("desk keep: %s is now a preference (commit %s)" % (shown, sha[:12])) + return 0 + if not lapsed: + restored = [e for e in entries if e["restored"] and identity(e["date"], e["area"]) == want] + if restored: + print("desk keep: %s was already brought back on %s; nothing to do" % (shown, restored[0]["restored"])) + return 0 + raise Refused("no ruling is %s, in the table or among the lapsed rulings in the archive" % shown) + e = lapsed[0] + row = e["row"] + if len(split_cells(row.rstrip("\r"))) != len(table["header"]): + raise Refused("the archived row has a different number of cells than the table's header") + new_row = replace_cell(row, kidx, "preference") + if new_row is None: + raise Refused("cannot find the Kind cell in the archived row") + # the restored row matches the table's line endings, whatever the archive stored + crlf = lines[table["first_line"] - 1].endswith("\r") + new_row = new_row.rstrip("\r") + ("\r" if crlf else "") + at = table["last_line"] # after the table's last line + lines.insert(at, new_row) + alines = archive.split("\n") + eol = "\r" if alines[e["moved_index"]].endswith("\r") else "" + alines.insert(e["moved_index"] + 1, "- Restored: %s, by desk keep%s" % (today().isoformat(), eol)) + sha = w.commit([(ACTIVE_REL, "\n".join(lines).encode("utf-8")), + (ARCHIVE_REL, "\n".join(alines).encode("utf-8"))], + "chore(rulings): restore a lapsed setup ruling as a preference\n\n- %s\n\nBrought back " + "by desk keep from %s with its original text and date." % (shown, ARCHIVE_REL)) + print("desk keep: %s is back in force as a preference (commit %s)" % (shown, sha[:12])) + return 0 + except (Refused, WriteFailed, ScanError) as exc: + print("desk keep: %s" % exc, file=sys.stderr) + return 1 + + +# --------------------------------------------------------------------------------------------------- +# command line + +# name -> callable(argv) -> exit code; later pieces register subcommands here +COMMANDS = {"lapse": cmd_lapse, "keep": cmd_keep} + + +def resolve_root(arg): + if arg: + return arg + env = os.environ.get("DESK_ROOT") + if env: + return env + script = globals().get("__file__") # absent when the script is piped to python3 - + if script: + candidate = os.path.dirname(os.path.dirname(os.path.dirname(os.path.realpath(script)))) + if os.path.isdir(os.path.join(candidate, ".claude-config")): # /.claude-config/bin/desk + return candidate + home = os.path.expanduser("~") + for name in ("COWORK", "OPS"): + if os.path.isdir(os.path.join(home, name)): + return os.path.join(home, name) + raise ScanError("cannot find the harness root; pass --root") + + +def is_box_root(root): + """The box's own harness checkout: ~/COWORK, ~/OPS, or the DESK_ROOT the owner named.""" + home = os.path.expanduser("~") + named = [os.path.join(home, "COWORK"), os.path.join(home, "OPS")] + if os.environ.get("DESK_ROOT"): + named.append(os.environ["DESK_ROOT"]) + return os.path.realpath(root) in {os.path.realpath(n) for n in named} + + +def cmd_scan(argv): + ap = argparse.ArgumentParser(prog="desk", description="Read-only check of the AI context on this box.") + ap.add_argument("--json", action="store_true", help="print the full record as JSON") + ap.add_argument("--line", action="store_true", help="print the cached one-line briefing text; never scans") + ap.add_argument("--counts", action="store_true", help="print bounded counts only; never writes the cache") + ap.add_argument("--no-cache", action="store_true", help="scan without refreshing the cache") + ap.add_argument("--root", help="harness root (default: this script's checkout)") + ap.add_argument("--state-dir", help="state directory (default by box)") + ap.add_argument("--cache", help="cache file (default /desk-last.json)") + ap.add_argument("--pin", help="the template commit to compare against (a controller's effective pin)") + ap.add_argument("--mode", choices=("owner", "team"), help="force the box kind (default: detected)") + args = ap.parse_args(argv) + root = resolve_root(args.root) + mode = args.mode or (detect_mode(os.path.realpath(root)) if os.path.isdir(root) else "team") + state_dir = args.state_dir or default_state_dir(mode) + target = cache_path(state_dir, args.cache) + if args.line: + text = cached_line(target, root) + if text: + print(text) + return 0 + try: + rec = scan(root, mode=args.mode, state_dir=state_dir, pin=args.pin) + if not (args.no_cache or args.counts): + if args.cache or args.state_dir or is_box_root(rec["root"]): + write_cache(rec, target, rec["root"]) + else: + # A worktree or a scratch copy must not replace the box's cache with its own root: the + # briefing would then ignore it as another checkout's and go quiet until the next daily run. + print("desk: cache not refreshed: %s is not this box's harness root (pass --cache or --state-dir " + "to write one)" % rec["root"], file=sys.stderr) + except ScanError as exc: + print("desk: scan could not run: %s" % exc, file=sys.stderr) + return 1 + if args.counts: + print(json.dumps(counts_view(rec), sort_keys=True)) + elif args.json: + print(json.dumps(rec, indent=2, sort_keys=True)) + else: + sys.stdout.write(format_text(rec)) + return 0 + + +def main(argv=None): + argv = list(sys.argv[1:] if argv is None else argv) + if argv and argv[0] in COMMANDS: + return COMMANDS[argv[0]](argv[1:]) + if argv and argv[0] == "scan": + argv = argv[1:] + try: + return cmd_scan(argv) + except Exception as exc: # noqa: BLE001 - a crash is an error exit, never a cache refresh + print("desk: scan failed: %s: %s" % (type(exc).__name__, exc), file=sys.stderr) + return 1 + + +# --------------------------------------------------------------------------------------------------- +# the owner review (clean desk piece D): desk review, desk commit-review, desk undo +# +# `review` lists at most ten of the owner's rulings for them to keep, narrow or retire; `commit-review` +# applies their answers in one CheckedWrite transaction; `undo` reverses the latest review commit. An +# item is named by its file and its exact text, never by a line number alone: the commit refuses when +# that text is no longer in the file exactly once, so nothing changes that the owner did not see. +# Nothing is deleted: a retired ruling moves to the archive in C's entry format, and undo puts bytes +# back from git. This block calls piece C's parsers and CheckedWrite and changes none of them. + +REVIEW_MAX_ITEMS = 10 +REVIEW_STATE_NAME = "desk-review-last.json" # the latest review: id, commit, paths; undo cross-checks it +REVIEW_DONE_NAME = "desk-review-done.json" # items the owner answered, so the next review shows new ones +REVIEW_DONE_KEEP = 2000 # answered items remembered (oldest dropped first) +REVIEW_LOG_DEPTH = 500 # first-parent commits undo searches for the latest review +REVIEW_TRAILER = "Desk-Review" +UNDO_TRAILER = "Desk-Review-Undo" +PATH_TRAILER = "Desk-Review-Path" +LEGACY_REL = "CONTEXT/working-preferences.md" +OWNER_RULINGS_REL = "CONTEXT/how-i-work.md" +OWNER_RULINGS_HEADING = "## standing orders" +ANSWERS = ("keep", "narrow", "retire") +ABSOLUTE_RE = re.compile(r"\b(never|always|ever|must)\b", re.I) +LIST_ITEM_RE = re.compile(r"^\s*(?:[-*+]|\d+[.)])\s+\S") +RULE_LINE_RE = re.compile(r"^\s*(?:[-*_]\s*){3,}$") # "* * *" is a horizontal rule, not a list item +REVIEW_TRAILER_RE = re.compile(r"(Desk-Review(?:-Undo|-Path|-Reverts)?): (\S.*)") + + +def review_source(layout): + """(rel, format, reason): where this box's rulings live. 'table' is a rulings table, with or without a + Kind column (the owner's box keeps its table under "Standing orders" in how-i-work.md); 'legacy' is the + older preferences file, whose list items are the rulings; None when the layout is not recognized.""" + if layout == "owner": + return OWNER_RULINGS_REL, "table", "" + if layout == "standing-orders": + return ACTIVE_REL, "table", "" + if layout in ("working-preferences", "fork"): + return LEGACY_REL, "legacy", "" + return None, None, "layout not recognized (no standing-orders.md or working-preferences.md)" + + +def owner_table(text): + """The rulings table under the owner's "## Standing orders" heading, or None. The lines before the + heading are blanked rather than cut, so every line number stays the file's own.""" + start = end = None + for unit in prose_units(text): + no, first = unit.lines[0] + s = first.strip() + if start is None and s.lower() == OWNER_RULINGS_HEADING: + start = no - 1 + elif start is not None and re.match(r"^#{1,2}\s", s): + end = no + break + if start is None: + return None + lines = text.split("\n") + table = parse_rulings_table("\n".join([""] * start + lines[start:])) + if table is None or (end is not None and table["first_line"] > end): + return None + return table + + +def source_table(rel, text): + return owner_table(text) if rel == OWNER_RULINGS_REL else parse_rulings_table(text) + + +def legacy_spans(text): + """[(first line number, exact content, heading)] for each list item of the older preferences file, + outside fenced code and comments. Paragraphs, headings and tables are not items: precision over + recall, as in the scan. Skip items with comments or nested blocks the prose scan split off.""" + lines = text.split("\n") + heading, out = "", [] + for unit in prose_units(text): + no, first = unit.lines[0] + s = first.strip() + if s.startswith("#"): + heading = s.lstrip("#").strip() + continue + if not LIST_ITEM_RE.match(first) or RULE_LINE_RE.match(first): + continue + nos = [n for n, _ in unit.lines] + if nos != list(range(nos[0], nos[-1] + 1)): + continue + content_lines = [lines[n - 1].rstrip("\r") for n in nos] + if any("" in x for x in content_lines): + continue + following = nos[-1] + while following < len(lines) and not lines[following].strip(): + following += 1 + if following < len(lines): + marker = first.expandtabs(4) + next_line = lines[following].expandtabs(4) + if len(next_line) - len(next_line.lstrip()) > len(marker) - len(marker.lstrip()): + # Retiring only the parent leaves its children live without the rule that qualifies them. + continue + out.append((nos[0], "\n".join(content_lines), heading)) + return out + + +def content_id(rel, content): + return hashlib.sha256((rel + "\0" + content).encode("utf-8")).hexdigest()[:16] + + +def content_sha(content): + return hashlib.sha256(content.encode("utf-8")).hexdigest() + + +def overrides_of(text): + """The core files a ruling says it overrides: the scan's own candidate rule (check_rulings).""" + if not re.search(r"overrid", text, re.I): + return [] + return [p for p, rx in CORE_MENTION.items() if rx.search(text)] + + +def review_git(root, args): + """Read-only git in the checkout: (exit code, stdout bytes, stderr text). Never raises.""" + env = dict(os.environ) + for key in ("GIT_DIR", "GIT_WORK_TREE", "GIT_INDEX_FILE", "GIT_OBJECT_DIRECTORY", + "GIT_ALTERNATE_OBJECT_DIRECTORIES", "GIT_NAMESPACE"): + env.pop(key, None) + env.update({"GIT_OPTIONAL_LOCKS": "0", "GIT_TERMINAL_PROMPT": "0", "LC_ALL": "C", "GIT_PAGER": "cat"}) + try: + proc = subprocess.run(["git", "-C", root] + list(args), stdout=subprocess.PIPE, stderr=subprocess.PIPE, + timeout=GIT_TIMEOUT, env=env) + except (OSError, subprocess.TimeoutExpired) as exc: + return 128, b"", "git did not run: %s" % exc + return proc.returncode, proc.stdout, proc.stderr.decode("utf-8", errors="replace") + + +def propose_correction(root, mode, finding, line_text, tracked): + """A provable fix for a missing path: exactly one tracked file in the checkout has the missing file's + name, so the reference can point there. {ref, content} (content None when the old reference is not on + the line exactly once), or None. A retired model, a missing skill or a name with no single match + has no provable correction.""" + if finding.get("kind") != "missing_path" or tracked is None: + return None + ref = finding["ref"] + name = os.path.basename(ref) + matches = {t for t in tracked if os.path.basename(t) == name} + if len(matches) != 1: + return None + found, = matches + if not os.path.isfile(os.path.join(root, found)): + return None + alias = "~/%s/" % os.path.basename(root) + if ref.startswith(CHECKED_ROOT_PREFIXES): + new = found + elif ref.startswith(alias) and ref.startswith(CHECKED_HOME_PREFIXES): + new = alias + found + elif not ref.startswith(("~", "/")): + base = os.path.dirname(os.path.join(root, finding["file"])) + new = os.path.relpath(os.path.join(root, found), base) + else: + return None + if new == ref: + return None + return {"ref": new, "content": line_text.replace(ref, new) if line_text.count(ref) == 1 else None} + + +def review_done(state_dir, root): + """{(file, content sha256)} of items the owner already answered for this root.""" + try: + with open(os.path.join(state_dir, REVIEW_DONE_NAME)) as fh: + rec = json.load(fh) + if os.path.realpath(rec.get("root", "")) != os.path.realpath(root): + return set() + return {(e["file"], e["content_sha256"]) for e in rec.get("items", []) + if isinstance(e, dict) and "file" in e and "content_sha256" in e} + except FileNotFoundError: + return set() + except (OSError, ValueError, AttributeError, TypeError) as exc: + raise Refused("the answered-items record %s cannot be read (%s); move it aside to start over" + % (os.path.join(state_dir, REVIEW_DONE_NAME), clip(exc, 80))) + + +def review_items(root, mode, layout, rec): + """(source, items, not_listed): every reviewable item on the box, unranked.""" + rel, fmt, reason = review_source(layout) + source = {"file": rel, "format": fmt, "has_kind_column": None, "reason": reason} + items, spans = [], [] + + def item(rel_, line, content, typ, **extra): + it = {"id": content_id(rel_, content), "file": rel_, "line": line, "content": content, + "content_sha256": content_sha(content), "bytes": len(content.encode("utf-8")), "type": typ, + "kind": None, "review_by": None, "date": None, "area": None, "text": None, "why": [], + "flags": {"setup": False, "overrides": False, "absolute": False, "worth_a_look": False, + "dead_reference": False}, + "alone": False, "protects": None, "dead_references": [], + "answers": ["keep", "narrow", "retire"] if typ != "dead_reference" else ["keep", "narrow"]} + it.update(extra) + items.append(it) + spans.append((rel_, line, line + content.count("\n"), it)) + return it + + text = None + if rel is not None: + try: + text = read_bytes(os.path.join(root, rel)).decode("utf-8") + except FileNotFoundError: + source["reason"] = "%s does not exist" % rel + except (OSError, UnicodeDecodeError) as exc: + source["reason"] = "cannot read %s: %s" % (rel, clip(exc, 80)) + if text is not None and fmt == "table": + table = source_table(rel, text) + if table is None: + source["reason"] = "no rulings table found in %s" % rel + else: + source["has_kind_column"] = table["columns"]["kind"] is not None + lines = text.split("\n") + worth = {(w["line"], w["area"]) for w in rec.get("worth_a_look", []) if w.get("file") == rel} + for r in table["rows"]: + if is_example_row(table, r): + continue + content = lines[r["line"] - 1].rstrip("\r") + ruling = row_cell(table, r, "text") + it = item(rel, r["line"], content, "ruling", date=row_cell(table, r, "date"), + area=row_cell(table, r, "area"), text=ruling) + if table["columns"]["kind"] is not None: + kind, _cell_review = parse_kind(row_cell(table, r, "kind")) + it["kind"] = kind + if kind is None: + it["why"].append("no valid kind") + elif kind == "setup": + review = setup_review(table, r) + it["review_by"] = review.isoformat() if review else None + it["flags"]["setup"] = True + it["why"].append("setup ruling: %s" % ( + "no review date" if review is None else + ("past its review date %s" % review.isoformat()) if setup_due(review, today()) else + "lapses after %s unless kept" % review.isoformat())) + elif kind == "guardrail": + # A guardrail is answered alone, and the owner sees what it protects: the + # template asks each guardrail row to say which event or fact, in its own text. + it["alone"] = True + it["protects"] = ruling + it["why"].append("guardrail: answered alone") + files = overrides_of(content) + if files: + it["flags"]["overrides"] = True + it["why"].append("overrides a default in %s" % ", ".join(files)) + words = sorted({m.group(1).lower() for m in ABSOLUTE_RE.finditer(ruling)}) + if words: + it["flags"]["absolute"] = True + it["why"].append("absolute words: %s" % ", ".join(words)) + if (r["line"], clip(row_cell(table, r, "area"), 80)) in worth: + it["flags"]["worth_a_look"] = True + it["why"].append("worth a look: it predates the template's last change to the file it overrides") + elif text is not None and fmt == "legacy": + for line, content, heading in legacy_spans(text): + it = item(rel, line, content, "legacy_preference", kind="legacy", area=heading or None, text=content) + files = overrides_of(content) + if files: + it["flags"]["overrides"] = True + it["why"].append("overrides a default in %s" % ", ".join(files)) + words = sorted({m.group(1).lower() for m in ABSOLUTE_RE.finditer(content)}) + if words: + it["flags"]["absolute"] = True + it["why"].append("absolute words: %s" % ", ".join(words)) + # dead references: attached to the ruling they sit in, else an item of their own + not_listed, tracked = [], None + rc, out, _err = review_git(root, ["ls-files", "-z"]) + if rc == 0: + tracked = [t for t in out.decode("utf-8", errors="replace").split("\0") if t] + by_line, file_lines = {}, {} + for d in rec["findings"].get("dead_references", []): + f, line = d.get("file", ""), d.get("line", 0) + if not line or f.startswith(("~", "/")): + not_listed.append({"file": f, "line": line, "reason": "outside the checkout, so desk cannot commit a fix"}) + continue + if mode == "team" and f in CORE_PATHS: + not_listed.append({"file": f, "line": line, "reason": "the template owns this file; a template update fixes it"}) + continue + by_line.setdefault((f, line), []).append(d) + for (f, line), found in sorted(by_line.items()): + if f not in file_lines: + try: + file_lines[f] = read_bytes(os.path.join(root, f)).decode("utf-8").split("\n") + except (OSError, UnicodeDecodeError) as exc: + file_lines[f] = None + not_listed.append({"file": f, "line": line, "reason": "cannot read: %s" % clip(exc, 60)}) + flines = file_lines[f] + if flines is None or line > len(flines): + continue + line_text = flines[line - 1].rstrip("\r") + owner = next((s[3] for s in spans if s[0] == f and s[1] <= line <= s[2]), None) + refs = [{"kind": d["kind"], "ref": d["ref"], + "correction": propose_correction(root, mode, d, line_text, tracked)} for d in found] + if owner is None: + owner = item(f, line, line_text, "dead_reference") + else: + for r in refs: + if r["correction"]: + r["correction"]["content"] = None # a fix to a multi-line item is the owner's narrow + owner["dead_references"].extend(refs) + owner["flags"]["dead_reference"] = True + owner["why"].append("dead reference: %s" % ", ".join("%s %s" % (r["kind"].replace("_", " "), r["ref"]) + for r in refs)) + return source, items, not_listed + + +def review_key(it): + """Setup first, then overrides of a default, absolute words, the worth-a-look collision, a dead + reference, then the largest first; file and line make the order total.""" + f = it["flags"] + return (not f["setup"], not f["overrides"], not f["absolute"], not f["worth_a_look"], not f["dead_reference"], + -it["bytes"], it["file"], it["line"], it["content"]) + + +def build_review(root, mode, state_dir, pin=None, include_answered=False): + rec = scan(root, mode=mode, state_dir=state_dir, pin=pin) + root, mode, layout = rec["root"], rec["mode"], rec["layout"] + source, items, not_listed = review_items(root, mode, layout, rec) + done = set() if include_answered else review_done(state_dir, root) + fresh = [it for it in items if (it["file"], it["content_sha256"]) not in done] + fresh.sort(key=review_key) + shown = fresh[:REVIEW_MAX_ITEMS] + for n, it in enumerate(shown, 1): + it["rank"] = n + return {"schema": 1, "tool": "desk", "command": "review", "root": root, "mode": mode, "layout": layout, + "reviewed_at": datetime.datetime.now().astimezone().isoformat(timespec="seconds"), + "source": source, "candidates": len(fresh), "shown": len(shown), + "already_answered": len(items) - len(fresh), "not_listed": not_listed, + "coverage": {"status": rec["coverage"]["status"], "unread_count": rec["coverage"]["unread_count"]}, + "items": shown} + + +def format_review(rv): + out = ["desk review: %s box, layout %s, %s" % (rv["mode"], rv["layout"], rv["root"])] + src = rv["source"] + out.append("rulings: %s%s" % (src["file"] or "none", " (%s)" % src["reason"] if src["reason"] else "")) + out.append("%d of %d items shown%s" % (rv["shown"], rv["candidates"], "; %d answered before and not shown" + % rv["already_answered"] if rv["already_answered"] else "")) + batch = [it for it in rv["items"] if not it["alone"]] + alone = [it for it in rv["items"] if it["alone"]] + for it in batch: + out.append("") + out.append("%d. %s line %d [%s]" % (it["rank"], it["file"], it["line"], it["kind"] or it["type"])) + out.append(" " + clip(it["content"], 300)) + for w in it["why"]: + out.append(" why: %s" % w) + for d in it["dead_references"]: + c = d["correction"] + out.append(" proposed correction: %s -> %s" % (d["ref"], c["ref"]) if c else + " no provable correction for %s" % d["ref"]) + for it in alone: + out.append("") + out.append("%d. (answered alone) %s line %d [guardrail]" % (it["rank"], it["file"], it["line"])) + out.append(" " + clip(it["content"], 300)) + out.append(" protects: %s" % clip(it["protects"] or "", 300)) + if rv["coverage"]["unread_count"]: + out.append("") + out.append("note: %s not checked by the scan; run desk for details" % plural(rv["coverage"]["unread_count"], "area")) + out.append("") + out.append("Answers: keep, narrow (new text) or retire (with a reason); desk commit-review applies them.") + return "\n".join(out) + "\n" + + +def cmd_review(argv): + ap = argparse.ArgumentParser(prog="desk review", description="List at most ten of the owner's rulings to " + "keep, narrow or retire. Read-only.") + ap.add_argument("--json", action="store_true", help="print the review as JSON") + ap.add_argument("--all", action="store_true", help="include items the owner already answered") + ap.add_argument("--root", help="harness root (default: this script's checkout)") + ap.add_argument("--state-dir", help="state directory (default by box)") + ap.add_argument("--pin", help="the template commit to compare against") + ap.add_argument("--mode", choices=("owner", "team"), help="force the box kind (default: detected)") + args = ap.parse_args(argv) + try: + root = os.path.realpath(resolve_root(args.root)) + mode = args.mode or (detect_mode(root) if os.path.isdir(root) else "team") + state_dir = args.state_dir or default_state_dir(mode) + rv = build_review(root, args.mode, state_dir, pin=args.pin, include_answered=args.all) + except (ScanError, Refused) as exc: + print("desk review: %s" % exc, file=sys.stderr) + return 1 + if args.json: + print(json.dumps(rv, indent=2, sort_keys=True)) + else: + sys.stdout.write(format_review(rv)) + return 0 + + +# -- commit-review + +class BadRequest(Exception): + """The answers are not in the documented shape (exit 2).""" + + +def load_answers(raw): + try: + req = json.loads(raw) + except ValueError as exc: + raise BadRequest("the answers are not JSON: %s" % clip(exc, 100)) + answers = req.get("answers") if isinstance(req, dict) else None + if not isinstance(answers, list) or not answers: + raise BadRequest('expected {"answers": [...]} with at least one answer') + seen = set() + for n, a in enumerate(answers, 1): + if not isinstance(a, dict): + raise BadRequest("answer %d is not an object" % n) + for key in ("file", "content", "answer"): + if not isinstance(a.get(key), str) or not a[key]: + raise BadRequest("answer %d has no %s" % (n, key)) + if a["answer"] not in ANSWERS: + raise BadRequest("answer %d: %r is not keep, narrow or retire" % (n, a["answer"])) + if a["answer"] == "narrow" and not (isinstance(a.get("text"), str) and a["text"].strip()): + raise BadRequest("answer %d: narrow needs the new text in \"text\"" % n) + if a["answer"] == "retire" and not (isinstance(a.get("reason"), str) and a["reason"].strip()): + raise BadRequest("answer %d: retire needs the owner's reason in \"reason\"" % n) + key = (a["file"], a["content"]) + if key in seen: + raise BadRequest("answer %d repeats an item" % n) + seen.add(key) + return answers + + +def check_review_path(rel, mode): + """A path commit-review may change: a Markdown file inside the checkout, not the archive (only desk + writes it), not under .git, and on a team box not a core file (the template owns those).""" + norm = os.path.normpath(rel) + if (os.path.isabs(rel) or norm != rel or norm.startswith("..") or not rel.endswith(".md") + or ".git" in norm.split(os.sep)): + raise Refused("%s is not a Markdown file path inside the checkout" % rel) + if rel == ARCHIVE_REL: + raise Refused("%s is written only by desk; it is not an item" % ARCHIVE_REL) + if mode == "team" and rel in CORE_PATHS: + raise Refused("%s belongs to the template on this box; a template update changes it" % rel) + + +def locate(lines, content): + """Every index where content's lines start in lines (carriage returns ignored).""" + want = content.split("\n") + k = len(want) + bare = [x.rstrip("\r") for x in lines] + return [i for i in range(len(bare) - k + 1) if bare[i:i + k] == want] + + +def escape_cell(text): + return re.sub(r"(? 1: + raise Refused("answer %d: that text appears %d times in %s, so desk cannot tell which one the owner " + "meant; nothing was written" % (n, len(at), rel)) + i, k = at[0], content.count("\n") + 1 + crlf = lines[i].endswith("\r") + label = clip(content, 80) + typ, table, row = "line", None, None + if rel == src_rel and src_fmt == "table" and k == 1: + table = source_table(rel, texts[rel]) + if table is not None: + row = next((r for r in table["rows"] if r["line"] == i + 1 and not is_example_row(table, r)), None) + if row is not None: + typ = "ruling" + label = "%s, %s" % (row_cell(table, row, "date"), clip(row_cell(table, row, "area"), 60)) + elif rel == src_rel and src_fmt == "legacy": + if any(line == i + 1 and c == content for line, c, _h in legacy_spans(texts[rel])): + typ = "legacy" + if typ == "line": + # An exact match can survive a move into a fence, comment or unrelated section. Only + # live rulings and the scan's current standalone reference lines can be answered. + if reference_lines is None: + rec = scan(root, mode=mode, state_dir=state_dir) + _source, items, _not_listed = review_items(root, mode, layout, rec) + reference_lines = {(it["file"], it["line"], it["content"]) for it in items + if it["type"] == "dead_reference"} + if (rel, i + 1, content) not in reference_lines: + raise Refused(f"answer {n}: that text in {rel} is no longer a review item. Run desk review again.") + kind = None + if typ == "ruling" and table["columns"]["kind"] is not None: + kind = parse_kind(row_cell(table, row, "kind"))[0] + new = None # None: unchanged; [] removes the span; else the replacement lines + if answer == "keep": + if kind == "setup": + line = replace_cell(lines[i], table["columns"]["kind"], "preference") + if line is None: + raise Refused("answer %d: cannot find the Kind cell of %s" % (n, label)) + new = [line] + summary["kept"].append("%s (setup, now a preference)" % label) + else: + summary["unchanged"].append("%s (kept as it is)" % label) + elif answer == "narrow": + text = a["text"] + if typ == "ruling": + if "\n" in text or "\r" in text: + raise Refused("answer %d: a ruling's new text must be one line" % n) + if table["columns"]["text"] is None: + raise Refused("answer %d: the table has no ruling text column" % n) + line = replace_cell(lines[i], table["columns"]["text"], escape_cell(text.strip())) + if line is None or len(split_cells(line.rstrip("\r"))) != len(table["header"]): + raise Refused("answer %d: cannot replace the ruling text of %s cleanly" % (n, label)) + new = [line] + else: + new = [x.rstrip("\r") + ("\r" if crlf else "") for x in text.rstrip("\r\n").split("\n")] + if [x.rstrip("\r") for x in new] == [x.rstrip("\r") for x in lines[i:i + k]]: + new = None + summary["unchanged"].append("%s (the narrowed text is the same)" % label) + else: + summary["narrowed"].append(label) + else: # retire + if typ not in ("ruling", "legacy"): + raise Refused("answer %d: only a ruling can be retired; %s line %d is not one (narrow it instead)" + % (n, rel, i + 1)) + if kind == "guardrail": + guardrail_retire = label + reason = " ".join(a["reason"].split()) + if typ == "ruling": + entry = format_entry(lines[i], on.isoformat(), "retired") + else: + heading = next((h for line, c, h in legacy_spans(texts[rel]) if line == i + 1), "") + row = "| undated | %s | %s |" % (escape_cell("%s: %s" % (os.path.basename(rel), heading or "list item")), + escape_cell(" ".join(content.split()))) + entry = format_entry(row, on.isoformat(), "retired") + entry += "- Original lines (%s):\n\n~~~markdown\n%s\n~~~\n" % (rel, "\n".join(lines[i:i + k])) + entries.append(entry + "- Owner's reason: %s\n" % reason) + new = [] + summary["retired"].append("%s (reason: %s)" % (label, clip(reason, 120))) + if answer != "retire": + answered.append((rel, content if new is None else "\n".join(x.rstrip("\r") for x in new))) + if new is not None: + for j, kk, _new in edits.get(rel, []): + if i < j + kk and j < i + k: + raise Refused("answer %d overlaps another answer in %s" % (n, rel)) + edits.setdefault(rel, []).append((i, k, new)) + if guardrail_retire and len(answers) > 1: + raise Refused("%s is a guardrail; a guardrail is retired only alone, never in a batch. Send its retire " + "as its own request; nothing was written." % guardrail_retire) + out = {} + for rel, spans in edits.items(): + lines = texts[rel].split("\n") + for i, k, new in sorted(spans, reverse=True): + lines[i:i + k] = new + out[rel] = "\n".join(lines) + return out, entries, summary, answered + + +def read_review_state(state_dir, root): + path = os.path.join(state_dir, REVIEW_STATE_NAME) + try: + with open(path) as fh: + state = json.load(fh) + if not isinstance(state, dict) or state.get("schema") != 1: + raise ValueError("unexpected record format") + if state.get("root") != root: + raise ValueError("the record belongs to another checkout") + return state + except FileNotFoundError: + return None + except (OSError, ValueError) as exc: + raise Refused(f"the review record {path} cannot be read ({clip(exc, 80)})") + + +def prior_review_state(root, head, state): + if state is None or state.get("status") != "pending": + return state + # A kill can leave a pending entry even though the commit reached HEAD. Keep that entry if + # it reached history, or keep its predecessor if the attempted commit never happened. + what, _sha, tr = latest_review(root, head) + if what == "review" and tr.get(REVIEW_TRAILER) == [state.get("id")]: + return {key: value for key, value in state.items() if key != "previous"} + return state.get("previous") + + +def write_review_state(state_dir, data): + path = os.path.join(state_dir, REVIEW_STATE_NAME) + try: + write_json_atomic(path, data) + except OSError as exc: + return "the review state %s could not be written: %s" % (path, clip(exc, 80)) + return None + + +def record_answered(state_dir, root, answered, on): + """Add answered items (file, content after the commit) to the done record. A problem string or None.""" + path = os.path.join(state_dir, REVIEW_DONE_NAME) + try: + try: + with open(path) as fh: + rec = json.load(fh) + if not isinstance(rec, dict) or os.path.realpath(rec.get("root", "")) != os.path.realpath(root): + rec = None + except FileNotFoundError: + rec = None + rec = rec or {"schema": 1, "root": root, "items": []} + items = [e for e in rec.get("items", []) if isinstance(e, dict)] + items += [{"file": f, "content_sha256": content_sha(c), "on": on.isoformat()} for f, c in answered] + rec["items"] = items[-REVIEW_DONE_KEEP:] + write_json_atomic(path, rec) + except (OSError, ValueError) as exc: + return "the answered items could not be recorded in %s: %s" % (path, clip(exc, 80)) + return None + + +def cmd_commit_review(argv): + ap = argparse.ArgumentParser(prog="desk commit-review", description="Apply the owner's answers to a desk " + "review in one commit of exactly the files they touch.") + ap.add_argument("--file", default="-", help="the answers as JSON (default: stdin)") + ap.add_argument("--json", action="store_true", help="print the change summary as JSON") + ap.add_argument("--root", help="harness root (default: this script's checkout)") + ap.add_argument("--state-dir", help="state directory for the journal and the review record (default by box)") + ap.add_argument("--mode", choices=("owner", "team"), help="force the box kind (default: detected)") + args = ap.parse_args(argv) + try: + raw = sys.stdin.read() if args.file == "-" else open(args.file, encoding="utf-8").read() + answers = load_answers(raw) + except (OSError, UnicodeDecodeError, BadRequest) as exc: + print("desk commit-review: %s" % exc, file=sys.stderr) + return 2 + on = today() + sha, rid, notes = None, None, [] + try: + root, mode, state_dir, layout = rulings_root(args.root, args.state_dir, args.mode) + for a in answers: + check_review_path(a["file"], mode) + with CheckedWrite(root, state_dir, "review") as w: + texts = {rel: decode(w.read(rel), rel) for rel in sorted({a["file"] for a in answers})} + new_texts, entries, summary, answered = plan_review(answers, texts, root, mode, layout, state_dir, on) + changes = [] + if entries: + raw_archive = w.read(ARCHIVE_REL, must_exist=False) + archive = None if raw_archive is None else decode(raw_archive, ARCHIVE_REL) + try: + if archive is not None: + parse_archive(archive) + except ArchiveError as exc: + raise Refused("%s: %s" % (ARCHIVE_REL, exc)) + # the archive first: an interruption leaves a retired row in both files, never in neither + changes.append((ARCHIVE_REL, append_entries(archive, entries).encode("utf-8"))) + changes += [(rel, new_texts[rel].encode("utf-8")) for rel in sorted(new_texts)] + if changes: + rid = hashlib.sha1(("%s\0%s\0%s" % (w.head, time.time(), raw)).encode("utf-8")).hexdigest()[:12] + paths = [rel for rel, _ in changes] + counts = "keep %d, narrow %d, retire %d" % (len(summary["kept"]), len(summary["narrowed"]), + len(summary["retired"])) + body = ["- kept: %s" % s for s in summary["kept"]] + ["- narrowed: %s" % s for s in summary["narrowed"]] + body += ["- retired to %s: %s" % (ARCHIVE_REL, s) for s in summary["retired"]] + message = ("chore(rulings): record a desk review (%s)\n\n%s\n\nCommitted by desk commit-review; " + "`desk undo` reverses it while these paths are unchanged.\n\n%s: %s\n%s" + % (counts, "\n".join(body), REVIEW_TRAILER, rid, + "\n".join("%s: %s" % (PATH_TRAILER, p) for p in paths))) + state = {"schema": 1, "root": root, "id": rid, "status": "pending", "head": w.head, + "paths": paths, "commit": None, + "sha256": {rel: hashlib.sha256(data).hexdigest() for rel, data in changes}} + previous = prior_review_state(root, w.head, read_review_state(state_dir, root)) + problem = write_review_state(state_dir, {**state, "previous": previous}) + if problem: + raise Refused(problem) + sha = w.commit(changes, message) + problem = write_review_state(state_dir, {**state, "status": "committed", "commit": sha, + "on": on.isoformat()}) + if problem: + notes.append(problem + " (undo can still verify the pending review record)") + problem = record_answered(state_dir, root, answered, on) + if problem: + notes.append(problem) + except (Refused, WriteFailed, ScanError) as exc: + print("desk commit-review: %s" % exc, file=sys.stderr) + return 1 + result = {"commit": sha, "review_id": rid, "kept": summary["kept"], "narrowed": summary["narrowed"], + "retired": summary["retired"], "unchanged": summary["unchanged"], "notes": notes} + if args.json: + print(json.dumps(result, indent=2, sort_keys=True)) + else: + print("desk commit-review: %s" % ("committed %s (review %s)" % (sha[:12], rid) if sha else + "nothing to change; no commit")) + for key, label in (("kept", "kept"), ("narrowed", "narrowed"), ("retired", "retired to " + ARCHIVE_REL), + ("unchanged", "unchanged")): + for s in result[key]: + print(" %s: %s" % (label, s)) + if sha: + print("desk undo reverses this commit while those paths are unchanged.") + for note in notes: + print("desk commit-review: %s" % note, file=sys.stderr) + return 1 if notes else 0 + + +# -- undo + +def review_trailers(body): + """{key: [values]} from the trailer block (the last paragraph) of a commit message.""" + paras = [p for p in body.strip().split("\n\n") if p.strip()] + out = {} + if not paras: + return out + for line in paras[-1].splitlines(): + m = REVIEW_TRAILER_RE.fullmatch(line.strip()) + if m: + out.setdefault(m.group(1), []).append(m.group(2).strip()) + return out + + +def latest_review(root, head): + """('review'|'undo'|None, commit, trailers): the newest trailer on the given first-parent line.""" + rc, out, err = review_git(root, ["log", "--first-parent", "-n", str(REVIEW_LOG_DEPTH), "-z", + "--format=%H%n%B", head]) + if rc != 0: + raise Refused("cannot read the history: %s" % clip(err, 120)) + for chunk in out.decode("utf-8", errors="replace").split("\0"): + sha, _, body = chunk.strip("\n").partition("\n") + if not re.fullmatch(r"[0-9a-f]{40,64}", sha): + continue + tr = review_trailers(body) + if UNDO_TRAILER in tr: + return "undo", sha, tr + if REVIEW_TRAILER in tr: + return "review", sha, tr + return None, None, {} + + +def blob_at(root, rev, rel): + """(object id, bytes) of rel at rev, or (None, None) when rev does not have it.""" + rc, entry, err = review_git(root, ["ls-tree", "--full-tree", "-z", rev, "--", ":(literal)" + rel]) + if rc != 0: + raise Refused(f"cannot read the tree at {rev[:12]}: {clip(err, 80)}") + if not entry: + return None, None + metadata, _, path = entry.partition(b"\t") + _mode, kind, oid = metadata.decode().split() + if path != os.fsencode(rel) + b"\0" or kind != "blob": + raise Refused(f"{rel} at {rev[:12]} is not a single blob") + rc, data, err = review_git(root, ["cat-file", "blob", oid]) + if rc != 0: + raise Refused("cannot read %s at %s: %s" % (rel, rev[:12], clip(err, 80))) + return oid, data + + +def cmd_undo(argv): + ap = argparse.ArgumentParser(prog="desk undo", description="Reverse the latest desk review commit while no " + "path it wrote has changed since.") + ap.add_argument("--root", help="harness root (default: this script's checkout)") + ap.add_argument("--state-dir", help="state directory for the journal and the review record (default by box)") + ap.add_argument("--mode", choices=("owner", "team"), help="force the box kind (default: detected)") + args = ap.parse_args(argv) + try: + root, mode, state_dir, _layout = rulings_root(args.root, args.state_dir, args.mode) + with CheckedWrite(root, state_dir, "undo") as w: + what, sha, tr = latest_review(root, w.head) + if what is None: + print("desk undo: nothing to undo: no desk review commit in the last %d commits" % REVIEW_LOG_DEPTH) + return 0 + if what == "undo": + print("desk undo: nothing to undo: review %s was already undone in commit %s" + % (tr[UNDO_TRAILER][0], sha[:12])) + return 0 + ids, paths = tr[REVIEW_TRAILER], tr.get(PATH_TRAILER, []) + if len(ids) != 1 or not paths or len(set(paths)) != len(paths): + raise Refused(f"review commit {sha[:12]} has invalid review trailers; nothing was undone") + rid = ids[0] + state = read_review_state(state_dir, root) + if state is not None and state.get("id") != rid: + state = state.get("previous") + if not isinstance(state, dict) or state.get("id") != rid or state.get("paths") != paths: + raise Refused(f"commit {sha[:12]} has no matching local review record; nothing was undone") + if state.get("commit") and state["commit"] != sha: + raise Refused("the review record names commit %s for review %s but the history has %s; nothing " + "was undone" % (str(state["commit"])[:12], rid, sha[:12])) + # A pending entry has no commit id after a kill. Bind it to the planned parent, paths + # and bytes before treating a commit message as permission to restore files. + rc, parents, err = review_git(root, ["rev-list", "-1", "--parents", sha]) + if rc != 0: + raise Refused(f"cannot read the review's parent: {clip(err, 80)}") + if parents.decode().split() != [sha, state.get("head")]: + raise Refused(f"commit {sha[:12]} does not have the planned review parent; nothing was undone") + parent = state["head"] + rc, names, err = review_git(root, ["diff-tree", "--no-commit-id", "--no-renames", "--name-only", + "-r", "-z", parent, sha]) + if rc != 0: + raise Refused(f"cannot read the review's changed paths: {clip(err, 80)}") + touched = {os.fsdecode(n) for n in names.split(b"\0") if n} + if touched != set(paths): + raise Refused(f"commit {sha[:12]} did not change exactly the review's paths; nothing was undone") + changes = [] + for rel in paths: + if rel != ARCHIVE_REL: + check_review_path(rel, mode) + after_oid, after = blob_at(root, sha, rel) + if after_oid is None: + raise Refused("review commit %s removed %s, which a review never does; nothing was undone" + % (sha[:12], rel)) + if not state.get("commit") and state.get("sha256", {}).get(rel) != hashlib.sha256(after).hexdigest(): + raise Refused(f"commit {sha[:12]} does not have the planned review bytes for {rel}; " + "nothing was undone") + head_oid, _head = blob_at(root, w.head, rel) + if head_oid != after_oid: + _rc, by, _e = review_git(root, ["log", "-1", "--format=%h %s", f"{sha}..{w.head}", + "--", ":(literal)" + rel]) + raise Refused("%s changed since the review (%s); nothing was undone" + % (rel, clip(by.decode("utf-8", errors="replace").strip() or "not in HEAD", 100))) + current = w.read(rel) # refuses uncommitted or staged owner work on the path + if current != after: + raise Refused("%s on disk differs from the review's commit; nothing was undone" % rel) + _before_oid, before = blob_at(root, parent, rel) + if before is None: + if rel != ARCHIVE_REL: + raise Refused("review commit %s created %s, which only the archive may be; nothing was " + "undone" % (sha[:12], rel)) + # desk deletes nothing: an archive the review created is left with its header only + before = append_entries(None, []).encode("utf-8") + changes.append((rel, before)) + # the archive last: an interruption leaves a restored row in both files, never in neither + changes.sort(key=lambda c: c[0] == ARCHIVE_REL) + message = ("revert(rulings): undo desk review %s\n\nReverses commit %s, made by desk commit-review, on " + "%s.\n\n%s: %s\nDesk-Review-Reverts: %s" + % (rid, sha[:12], ", ".join(paths), UNDO_TRAILER, rid, sha)) + new_sha = w.commit(changes, message) + problem = write_review_state(state_dir, {**state, "status": "undone", "commit": sha, + "undone_by": new_sha}) + except (Refused, WriteFailed, ScanError) as exc: + print("desk undo: %s" % exc, file=sys.stderr) + return 1 + print("desk undo: review %s undone in commit %s (%s)" % (rid, new_sha[:12], ", ".join(paths))) + if problem: + print("desk undo: %s" % problem, file=sys.stderr) + return 1 + return 0 + + +COMMANDS.update({"review": cmd_review, "commit-review": cmd_commit_review, "undo": cmd_undo}) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/.claude-config/bin/memory-backfill-modified b/.claude-config/bin/memory-backfill-modified new file mode 100755 index 0000000..8e33fbd --- /dev/null +++ b/.claude-config/bin/memory-backfill-modified @@ -0,0 +1,189 @@ +#!/usr/bin/env python3 +# memory-backfill-modified - stamp metadata.modified on live memory entries +# that have none, from the last git commit that changed each file. +# +# Why: the nightly settle (memory-index --settle) dates an entry by the later +# of its metadata.modified stamp and its last commit, and protects any entry +# with no valid stamp, because file times differ between checkouts (a fresh +# clone would rank and move entries by the time it was cloned). A pool whose +# older entries carry no stamp settles nothing until they have one; this +# one-time pass gives each the date of its last content change, so they can +# settle like the rest. Run it once before the first settle on a box. +# +# Usage: +# memory-backfill-modified [--apply] ... +# +# Default is a dry run: it prints, per entry, what it would write and from +# which commit, and writes nothing. --apply rewrites each such file +# atomically, inserting one line, " modified: ", as the last child of the entry's metadata: block (a block is added +# at the end of the frontmatter when there is none); every other byte of the +# file stays as it was, and the result is read back. It never commits: the +# caller reviews the diff and commits it. Only /*.md entries are +# read (not MEMORY.md, not the _archive/ directory). Skipped and reported: an +# entry with a stamp (valid or not: an invalid one is reported, never +# replaced), one with no frontmatter, one git has no commit for (untracked), +# a symlink or a non-regular file. +# +# Exit: 0 when every entry was stamped, already stamped or skipped with a +# reason; 1 when a pool or an entry could not be read or written (the rest +# are still processed); 2 for bad arguments. +# +# The frontmatter parser and the stamp reader are the settle's own +# (memory-index parse_frontmatter, memory_settle.py stamp_latest), loaded +# through memory-index from beside this file, so the +# backfill and the settle can never disagree on what counts as a stamp. + +import os +import re +import subprocess +import sys +import tempfile +from importlib.machinery import SourceFileLoader + +sys.dont_write_bytecode = True +MI = SourceFileLoader( + "memory_index", os.path.join(os.path.dirname(os.path.realpath(__file__)), "memory-index")).load_module() +MS = MI.settle_module() + +USAGE = "usage: memory-backfill-modified [--apply] ..." +GIT_TIMEOUT = 30 + + +def last_commit_time(path): + """The committer time (ISO 8601 with its zone) of the last commit that + changed path, or None when git has none (untracked, or not a checkout).""" + d, fn = os.path.split(os.path.abspath(path)) + try: + r = subprocess.run(["git", "-C", d, "log", "-1", "--format=%cI", "--", fn], + capture_output=True, text=True, timeout=GIT_TIMEOUT, + stdin=subprocess.DEVNULL, env=MS.git_env(read_only=True)) + except (OSError, subprocess.SubprocessError) as e: + raise OSError(f"git log failed: {e}") from None + if r.returncode != 0: + return None + out = r.stdout.strip() + return out or None + + +def insert_stamp(raw, stamp): + """raw (the file's bytes) with " modified: " added as the last + child of the frontmatter's metadata: block, or with a metadata: block + holding it added at the end of the frontmatter. None when raw has no + frontmatter. The line ending follows the file's own (CRLF or LF).""" + text = raw.decode("utf-8") + nl = "\r\n" if "\r\n" in text.split("\n", 1)[0] + "\n" else "\n" + lines = text.split(nl) + if not lines or lines[0].strip() != "---": + return None + end = next((i for i in range(1, len(lines)) if lines[i].strip() == "---"), None) + if end is None: + return None + meta = next((i for i in range(1, end) if re.match(r"^metadata:\s*(?:#.*)?$", lines[i])), None) + if meta is None: + new = lines[:end] + ["metadata:", f" modified: {stamp}"] + lines[end:] + else: + last, indent = meta, " " + for i in range(meta + 1, end): + # YAML comments do not set a map's indentation. Treating an inline + # comment as a different key duplicates metadata; copying the + # indentation of a comment can instead create an invalid child. + if not lines[i].strip() or lines[i].lstrip().startswith("#"): + continue + m = re.match(r"^(\s+)\S", lines[i]) + if not m: + break + if last == meta: + indent = m.group(1) + last = i + new = lines[:last + 1] + [f"{indent}modified: {stamp}"] + lines[last + 1:] + return nl.join(new).encode("utf-8") + + +def process(path, apply): + """(status, detail) for one entry: stamped, would-stamp, has-stamp, skip, error.""" + if os.path.islink(path) or not os.path.isfile(path): + return "skip", "a symlink or not a regular file" + fm = MI.parse_frontmatter(path, limit=MI.FM_READ, errors="replace") + if fm["modified"]: + t, _note = MS.stamp_latest(fm["modified"]) + if t is None: + return "skip", f"has an invalid stamp {fm['modified']!r}; left alone, fix it by hand" + return "has-stamp", fm["modified"] + with open(path, "rb") as fh: + raw = fh.read() + if not raw.startswith(b"---"): + return "skip", "no frontmatter" + stamp = last_commit_time(path) + if not stamp: + return "skip", "no commit changes it (untracked?)" + try: + new = insert_stamp(raw, stamp) + except UnicodeDecodeError: + return "skip", "not UTF-8" + if new is None: + return "skip", "no closed frontmatter" + if not apply: + return "would-stamp", stamp + d = os.path.dirname(path) + st = os.stat(path) + fd, tmp = tempfile.mkstemp(prefix=".backfill.", dir=d) + try: + with os.fdopen(fd, "wb") as fh: + fh.write(new) + os.chmod(tmp, st.st_mode & 0o7777) + os.replace(tmp, path) + except BaseException: + try: + os.unlink(tmp) + except OSError: + pass + raise + got = MI.parse_frontmatter(path)["modified"] + if got != stamp: + return "error", f"read back {got!r}, expected {stamp!r}" + return "stamped", stamp + + +def main(argv): + apply, pools = False, [] + for a in argv[1:]: + if a == "--apply": + apply = True + elif a in ("-h", "--help"): + print(USAGE) + return 0 + elif a.startswith("-"): + sys.stderr.write(f"memory-backfill-modified: unknown flag {a}\n{USAGE}\n") + return 2 + else: + pools.append(a) + if not pools: + sys.stderr.write(USAGE + "\n") + return 2 + rc, counts = 0, {} + for pool in pools: + try: + names = sorted(f for f in os.listdir(pool) if f.endswith(".md") and f != "MEMORY.md") + except OSError as e: + sys.stderr.write(f"memory-backfill-modified: cannot list {pool}: {e.strerror or e}\n") + rc = 1 + continue + for fn in names: + path = os.path.join(pool, fn) + try: + status, detail = process(path, apply) + except OSError as e: + status, detail = "error", str(e) + if status == "error": + rc = 1 + counts[status] = counts.get(status, 0) + 1 + if status != "has-stamp": + print(f"{status}\t{path}\t{detail}") + mode = "applied" if apply else "dry run, nothing written" + print("summary (" + mode + "): " + ", ".join(f"{k} {v}" for k, v in sorted(counts.items()))) + return rc + + +if __name__ == "__main__": + sys.exit(main(sys.argv)) diff --git a/.claude-config/bin/memory-index b/.claude-config/bin/memory-index index df42e3b..e01e7c4 100755 --- a/.claude-config/bin/memory-index +++ b/.claude-config/bin/memory-index @@ -55,13 +55,23 @@ # memory-index --hint [--cwd DIR] [--ops DIR] # # UserPromptSubmit hook JSON on stdin; print at most # # three "Relevant memory:" lines for a strong match -# memory-index --find [--cwd DIR] [--ops DIR] [--limit N] -# # the same scorer by hand: top matches with scores +# memory-index --find [--cwd DIR] [--ops DIR] [--pool DIR] [--limit N] +# [--json] [--exclude PATH]... +# # one search over this pool, the root pool, both +# # archives and the CONTEXT/projects lessons +# # paragraphs (see "--find" below) # memory-index --digest-fit ... # # per pool: entries, described, by name only, not shown +# memory-index --digest-fit --cwd DIR [--ops DIR] +# # the same counts per source of the real combined digest # memory-index --pool-for [--cwd DIR] [--ops DIR] # # print the existing pool the digest uses for DIR; # # exit 4 when there is none; creates nothing +# memory-index --settle [--dry-run] [...] +# # the nightly mover (see "Settle" below) +# memory-index --restore [--pool ] [--dry-run] +# # move an archived entry back to its live pool +# memory-index --health # append one row to $STATE/memory-health.tsv # memory-index -h | --help # # Exit codes: @@ -71,16 +81,18 @@ # name:, or no frontmatter). The index is still emitted/written for the # files that are fine; the offenders are reported on stderr. Lets a # caller detect "backfill needed" without losing good lines. +# The 60-entry pool cap and its warning are gone (2026-12-04, with the +# nightly settle): the warning reached nobody (the hook discards stderr) +# and a pool at 60 already overflowed the digest. Where the settle runs it +# keeps each pool inside its digest; elsewhere the digest footer names the +# overflow. # --digest always exits 0: it prints the digest or its one-line failure -# notice. --digest-fit exits 1 when a pool could not be measured. +# notice. --digest-fit exits 1 when a pool could not be measured. --find +# exits 0 with no rows for no match and non-zero when the search failed. # --pool-for exits 0 with the pool on stdout, 4 when the directory has no -# pool, 1 for an unknown argument or an unusable host key file. -# -# A pool of more than POOL_CAP (60) entries is a WARN on stderr and nothing -# else: the index is still written, the exit status does not change, and no -# entry is ever removed. The digest can describe only about 40 entries in its -# budget, so a larger pool loses descriptions at the tail; the warning names the -# fix (prune the pool) and leaves the decision with the pool's owner. +# pool, 1 when the host key file is unusable. +# --settle and --restore: 0 for ok, noop and disabled, 1 for a failed run, +# 2 for bad arguments, 75 when another mover holds the lock. # # Digest mode. hooks/memory-digest.sh prints this digest at SessionStart when # Claude Code's native auto-memory is off (the Stage-1 settings turn it off), so @@ -97,6 +109,12 @@ # thread rooted in a project repo never saw the root pool, which contradicts the # core's routing of generic gotchas there. Budget and order are documented at # DIGEST_CAP and digest_order below. +# +# The archive (2026-11-15). Each pool may hold /_archive/: entries the +# nightly settle moved out byte-identically, same file format, indexed by +# no index of its own (nothing reads one). Every reader here lists only /*.md files, +# so the digest, the pool counts, --digest-fit and the live MEMORY.md never +# see an archived entry; --find and --hint do (see their sections). import collections import json @@ -111,12 +129,18 @@ import tempfile import time USAGE = ("usage: memory-index [--check] | --digest [--cwd DIR] [--ops DIR] | " - "--hint [--cwd DIR] [--ops DIR] | --find [--cwd DIR] [--ops DIR] [--limit N] | " - "--pool-for [--cwd DIR] [--ops DIR]") + "--hint [--cwd DIR] [--ops DIR] | --find [--cwd DIR] [--ops DIR] [--pool DIR] " + "[--limit N] [--json] [--exclude PATH]... | --digest-fit ... | " + "--digest-fit --cwd DIR [--ops DIR] | --pool-for [--cwd DIR] [--ops DIR] | " + "--settle [--dry-run] [...] | " + "--restore [--pool ] [--dry-run] | --health") # The index line separator (see the header): an em dash between spaces. INDEX_SEP = " \u2014 " +# The archive directory inside a pool (see the header). +ARCHIVE_DIR = "_archive" + # Fixed type precedence for grouping. Anything not listed sorts after these # (alphabetically by type), and type-less files sort dead last. TYPE_ORDER = {"project": 0, "feedback": 1, "reference": 2} @@ -551,11 +575,17 @@ def find_pool(root, cfg, store, host): return (os.path.realpath(found[0]) if found else None), expected -def load_pool(pool, src): +def load_pool(pool, src, archived=False, mtime_from=None): """(entries, not_read). Entries are unsorted, each tagged with src ("this" for the directory's own pool, "root" for the OPS root pool); build_digest orders them across both pools. not_read counts the files past - DIGEST_MAX_FILES. Raises DigestError when the pool cannot be listed.""" + DIGEST_MAX_FILES. Raises DigestError when the pool cannot be listed. + Only /*.md files are entries: the _archive/ directory is not one, so + the digest and every count leave archived entries out. archived marks the + entries of an archive directory (pool is then /_archive) for + --find and --hint. mtime_from names another copy of the same pool whose + file times stand in for these files' own: the settle reads a private + clone, whose checkout times are not the ones the session digest sees.""" try: names = sorted(f for f in os.listdir(pool) if f.endswith(".md") and f != "MEMORY.md") except OSError as e: @@ -569,18 +599,106 @@ def load_pool(pool, src): continue if not os.path.isfile(path): continue + mtime = st.st_mtime + if mtime_from: + try: + mtime = os.stat(os.path.join(mtime_from, fn)).st_mtime + except OSError: + pass # no authoritative copy: this file's own time, as the digest would fm = parse_frontmatter(path, limit=FM_READ, errors="replace") entries.append({ "stem": _CTRL.sub("?", fn[:-3]), "desc": clean(fm["description"]), "type": (fm["type"] or "").strip().lower(), - "when": recency(fm["modified"], st.st_mtime), + "when": recency(fm["modified"], mtime), "pinned": bool(fm["pinned"]), "src": src, + "arch": archived, + "path": path, + "fn": fn, + "modified": fm["modified"], }) return entries, max(0, len(names) - DIGEST_MAX_FILES) +def load_archive(pool, src): + """(entries, not_read) of /_archive/, tagged archived; none when the + pool has no archive yet. An archive that exists but cannot be listed + raises, like a pool: a search that silently skipped it would look like no + match. The same DIGEST_MAX_FILES bound applies (about ten months of + arrivals at 2026-11's rate); callers report not_read, never drop it + silently.""" + adir = os.path.join(pool, ARCHIVE_DIR) + if not os.path.lexists(adir): + return [], 0 + if not os.path.isdir(adir): + raise DigestError(f"{adir} is not a directory") + try: + names = sorted(f for f in os.listdir(adir) if f.endswith(".md") and f != "MEMORY.md") + except OSError as e: + raise DigestError(f"cannot list {adir}: {e.strerror or e}") from None + # The archive only grows (about seven entries a day), and the hint reads it + # on every prompt, so each file's parsed frontmatter is kept in a cache + # beside the lessons cache and reused while the file's size and mtime are + # unchanged, with its name and description words; a stat costs a fraction + # of an open, a parse and a tokenize. Measured 2026-11-15 on a busy host: + # 600 archived entries added about 100 ms to the hint without it. + cpath = os.path.join(os.path.dirname(lessons_state_dir()), "memory-archive-index", + claude_key(os.path.realpath(adir))[-200:] + ".json") + cache = {} + try: + with open(cpath, "r", encoding="utf-8") as fh: + c = json.load(fh) + if isinstance(c, dict) and c.get("v") == 1 and c.get("dir") == os.path.realpath(adir) \ + and isinstance(c.get("files"), dict): + cache = c["files"] + except (OSError, ValueError): + cache = {} + fresh, changed, entries = {}, False, [] + for fn in names[:DIGEST_MAX_FILES]: + path = os.path.join(adir, fn) + try: + st = os.stat(path) + except OSError: + continue + if not stat.S_ISREG(st.st_mode): + continue + row = cache.get(fn) + if not (isinstance(row, list) and len(row) == 8 and row[0] == st.st_size and row[1] == st.st_mtime_ns + and isinstance(row[2], str) and isinstance(row[3], str) and isinstance(row[5], bool) + and (row[4] is None or isinstance(row[4], str)) + and isinstance(row[6], list) and isinstance(row[7], list)): + fm = parse_frontmatter(path, limit=FM_READ, errors="replace") + desc = clean(fm["description"]) + row = [st.st_size, st.st_mtime_ns, desc, (fm["type"] or "").strip().lower(), fm["modified"], + bool(fm["pinned"]), sorted(set(tokens(_CTRL.sub("?", fn[:-3])))), sorted(set(tokens(desc)))] + changed = True + fresh[fn] = row + entries.append({ + "stem": _CTRL.sub("?", fn[:-3]), "desc": row[2], "type": row[3], + "when": recency(row[4], st.st_mtime), "pinned": row[5], "src": src, + "arch": True, "path": path, "fn": fn, "modified": row[4], + "ntoks": set(row[6]), "dtoks": set(row[7]), + }) + if changed or len(fresh) != len(cache): + try: + os.makedirs(os.path.dirname(cpath), mode=0o700, exist_ok=True) + fd, tmp = tempfile.mkstemp(prefix=".archive.", dir=os.path.dirname(cpath)) + try: + with os.fdopen(fd, "w", encoding="utf-8") as fh: + json.dump({"v": 1, "dir": os.path.realpath(adir), "files": fresh}, fh) + os.replace(tmp, cpath) + except BaseException: + try: + os.unlink(tmp) + except OSError: + pass + raise + except OSError: + pass # a speed-up only: the entries above were read from the files themselves + return entries, max(0, len(names) - DIGEST_MAX_FILES) + + # --- words: the digest's relevance rule and the prompt hint share one tokenizer # Words that carry no topic. Checked on the raw word and on its plural-stripped @@ -676,10 +794,6 @@ def cwd_tokens(root): # entries, then feedback entries; a pinned entry past PIN_MAX is demoted to the # head of this tier, so no ruling drops silently. Tier 2 is everything else. PIN_MAX = 20 -# A pool holds at most this many entries: past it the digest cannot describe what -# the pool holds. main() warns above it and changes nothing else (the index is -# still written, the exit status stays 0 or 2, no entry is removed). -POOL_CAP = 60 # Characters held back for the by-name-only tail when descriptions do not all # fit, so that a long run of described entries cannot squeeze the tail to # nothing. About 35 names. @@ -879,32 +993,57 @@ def build_digest(cwd, ops, pool_dir=None, root_dir=None): DIGEST_CAP, and per pool (pool, total, described, named, not shown), this directory's pool first. Raises DigestError (or anything unexpected) instead of returning a part.""" + text, fit, _order, _k, _j, _s = digest_core(cwd, ops, pool_dir, root_dir) + return text, fit + + +def root_cross(entries): + """The root pool's entries another directory's digest and hint see. The + root pool's project entries are OPS workstream state, so they stay out + of another project's digest; a pinned one is a ruling and stays.""" + return [e for e in entries if e["type"] != "project" or e["pinned"]] + + +def digest_core(cwd, ops, pool_dir=None, root_dir=None, loaded=None, show=None): + """build_digest's work, also returning the truncation order and its (k, j) + cut points, which the settle needs to see which own entries are described. + loaded = (this pool's entries, their not-read count, the root pool's + entries, theirs) replaces the pool reads, so the settle can measure the + digest a pool would give after a planned move without moving anything. + show = (pool path, root pool path) as the session sees them, when the + entries were read from another copy of the pools: the + header prints these, so its length, and with it the fit, is the session's.""" pool, expected, rpool, rexpected, at_root, root, indexer = resolve_pools( cwd, ops, pool_dir, root_dir) - a_entries, a_over = load_pool(pool, "this") if pool else ([], 0) b_entries, b_total, b_over = [], 0, 0 - if rpool and not at_root: - b_all, b_over = load_pool(rpool, "root") - b_total = len(b_all) - # The root pool's project entries are workstream state of the OPS copy - # itself, so they stay out of another project's digest; a pinned one is a - # ruling and stays. - b_entries = [e for e in b_all if e["type"] != "project" or e["pinned"]] + if loaded is None: + a_entries, a_over = load_pool(pool, "this") if pool else ([], 0) + if rpool and not at_root: + b_all, b_over = load_pool(rpool, "root") + b_total = len(b_all) + b_entries = root_cross(b_all) + else: + a_entries, a_over = list(loaded[0]), loaded[1] + if rpool and not at_root: + b_all, b_over = list(loaded[2]), loaded[3] + b_total = len(b_all) + b_entries = root_cross(b_all) + pool_shown, rpool_shown = show if show else (pool, rpool) head = [("OPS memory digest: the harness prints these pools' entries " "(descriptions first, names past the budget).")] if pool and a_entries: - head.append(f"Pool for this directory: {pool} ({len(a_entries) + a_over} entries; " + head.append(f"Pool for this directory: {pool_shown} ({len(a_entries) + a_over} entries; " f"{index_note(pool)}). An entry is /.md; read it before acting on it.") else: - where = f"{pool} is empty" if pool else expected + where = f"{pool_shown} is empty" if pool else expected head.append(f"No memory pool for this directory ({where}); do not create one. " "Project lessons go to CONTEXT/projects/-lessons.md, " "generic gotchas to the OPS root pool.") if b_entries: head.append(f"OPS root pool, cross-project entries ({len(b_entries)} of " - f"{b_total + b_over}; type project left out; [root] marks its lines): {rpool}") + f"{b_total + b_over}; type project left out; [root] marks its lines): {rpool_shown}") head.append("Write: route first (core.md Memory). A pool entry is one fact per file " "with frontmatter name, description (its line here), metadata.type (user, " "feedback, project or reference) and metadata.modified (ISO time); " @@ -920,18 +1059,22 @@ def build_digest(cwd, ops, pool_dir=None, root_dir=None): sections = [] # (label, pool, entries, overflow) if a_entries or a_over: - sections.append(("this pool", pool, a_entries, a_over)) + sections.append(("this pool", pool_shown, a_entries, a_over)) if b_entries or b_over: - sections.append(("root pool", rpool, b_entries, b_over)) + sections.append(("root pool", rpool_shown, b_entries, b_over)) order = order_entries(a_entries + b_entries, cwd_tokens(root)) mark_root = not at_root def footer(rows): # rows: (label, by name only, not shown, pool) bits = [f"{label} {named} by name only, {gone} not shown" for label, named, gone, _p in rows] idx = [f"{p}/MEMORY.md" for _l, _n, _g, p in rows] + # The settle is opt-in per box, so the footer names both cases: where it + # runs it archives the overflow each night; elsewhere the owner prunes. return (f"Over the {DIGEST_CAP:,}-character digest budget: {'; '.join(bits)}. " f"Full index: {', '.join(idx)}. Find an entry not shown: {indexer} --find " - ". Prune at closeout so entries keep their descriptions.") + ". It also searches each pool's _archive/ and the CONTEXT/projects " + "lessons. Where the nightly settle runs it archives what this digest cannot " + "describe; elsewhere prune the pool when you choose.") over_any = any(o for _l, _p, _e, o in sections) k = j = len(order) @@ -941,7 +1084,7 @@ def build_digest(cwd, ops, pool_dir=None, root_dir=None): k, j = fit_order(order, room, mark_root) blocks = render(order, k, j, mark_root) - rows, fit = [], [] + rows, fit, srcs = [], [], [] for label, p, entries, over in sections: src = "this" if label == "this pool" else "root" d = sum(1 for e in order[:k] if e["src"] == src) @@ -949,6 +1092,7 @@ def build_digest(cwd, ops, pool_dir=None, root_dir=None): gone = sum(1 for e in order[j:] if e["src"] == src) + over rows.append((label, named, gone, p)) fit.append((p, len(entries) + over, d, named, gone)) + srcs.append(src) parts = [head_text] for b in blocks: parts += ["", "\n".join(b)] @@ -957,7 +1101,7 @@ def build_digest(cwd, ops, pool_dir=None, root_dir=None): text = "\n".join(parts) if u16(text) > DIGEST_CAP: raise DigestError(f"assembled block is {u16(text)} characters, over {DIGEST_CAP}") - return text, fit + return text, fit, order, k, j, srcs def digest_main(cwd, ops): @@ -985,9 +1129,10 @@ def pool_for_main(cwd, ops): MEMORY_INDEX_DIR hook, then resolve_pools: the repository's main checkout, so a worktree shares its pool, the profile's projects//memory and the host key), so a caller that rebuilds the index rebuilds the pool the digest - reads. Why it exists: session-end rebuilds this directory's index, and a - second copy of the lookup would drift from the digest's. Creates nothing. - Exit 4, not 2 or 3: 2 already means entries need backfill.""" + reads. Why it exists (2026-11-17): session-end rebuilds this directory's + index, and a second copy of the lookup would drift from the digest's. + Creates nothing. Exit 4, not 2 or 3: 2 is backfill and 3 was the retired + pool cap.""" ops = resolve_ops(ops) cwd = cwd or os.environ.get("CLAUDE_PROJECT_DIR") or os.getcwd() try: @@ -1025,6 +1170,25 @@ def digest_fit_main(pools): return rc +def digest_fit_cwd_main(cwd, ops): + """The counts of the digest a session in cwd really gets: this directory's + pool beside the root pool's cross-project section, one row per source, + "\t\t\t\t\t". + The standalone form above measures a pool alone (no root section) and + keeps its row shape for verify-ops. Exit 1, with one "error" row, when + the digest cannot be built.""" + ops = resolve_ops(ops) + try: + _text, fit, _o, _k, _j, srcs = digest_core(cwd, ops, os.environ.get("MEMORY_INDEX_DIR"), + os.environ.get("MEMORY_DIGEST_ROOT_DIR")) + except Exception as e: # noqa: BLE001 - one error row, exit 1 + sys.stdout.write(f"{cwd}\terror\t{clean(f'{type(e).__name__}: {e}')}\n") + return 1 + for label, (p, total, described, named, gone) in zip(srcs, fit): + sys.stdout.write(f"{label}\t{p}\t{total}\t{described}\t{named}\t{gone}\n") + return 0 + + # --- memory hint (UserPromptSubmit) and --find -------------------------------- # # The digest cannot hold a pool, so the rulings that matter most are pinned and @@ -1121,6 +1285,15 @@ def score_prompt(ptoks, cands): live = {t for t in set(ptoks) if 0 < df[t] <= limit} norm = math.log(1.0 + n) idf = {t: math.log(1.0 + n / df[t]) / norm for t in live} + # A lessons paragraph longer than the average one is scored down by + # 1 + 0.5 * log2(its words / the average): a long bulleted section matches + # many words of a long query by chance. Measured on the four dupes.md + # cases (2026-11-15): without it the break-glass correction ranked 5th + # behind three long procedure lists; with it each prior paragraph ranks + # first or second. Entries (pools, archives) are never scaled, so the + # hint, which reads no lessons, scores as it was calibrated. + lens = [len(e["ntoks"] | e["dtoks"]) for e in cands if e["src"] == "lessons"] + avg = (sum(lens) / len(lens)) if lens else 0.0 rows = [] for e in cands: in_name = live & e["ntoks"] @@ -1130,6 +1303,10 @@ def score_prompt(ptoks, cands): sc = sum(idf[t] * (2.0 if t in in_name else 1.0) for t in matched) if e["pinned"]: sc *= 1.2 + if e["src"] == "lessons" and avg: + size = len(e["ntoks"] | e["dtoks"]) + if size > avg: + sc /= 1.0 + 0.5 * math.log2(size / avg) rows.append((sc, e, matched, in_name)) rows.sort(key=lambda r: r[1]["stem"]) rows.sort(key=lambda r: r[1]["when"], reverse=True) @@ -1146,19 +1323,55 @@ def strong_matches(rows): return [r for r in ok if r[0] >= HINT_REL * ok[0][0]][:HINT_MAX] -def candidates(cwd, ops): +def candidates(cwd, ops, pool_dir=None, skipped=None): """This directory's pool and the root pool's cross-project entries, as - the digest reads them, tagged by pool. A missing pool contributes nothing.""" + the digest reads them, tagged by pool, plus both pools' archives + (2026-11-15: an entry the settle archived must stay findable, or it is + written again). The root archive keeps the root pool's project + exclusion. A missing pool or archive contributes nothing. skipped, a + list, collects one note per archive past its read limit.""" pool, _e, rpool, _re, at_root, _root, _ix = resolve_pools( - cwd, ops, os.environ.get("MEMORY_INDEX_DIR"), os.environ.get("MEMORY_DIGEST_ROOT_DIR")) + cwd, ops, pool_dir or os.environ.get("MEMORY_INDEX_DIR"), + os.environ.get("MEMORY_DIGEST_ROOT_DIR")) + return candidates_for(pool, rpool, at_root, skipped) + + +def candidates_for(pool, rpool, at_root, skipped=None): + """candidates() for pools already resolved (the settle's duplicate count + scores entries of its clone with exactly this set).""" cands = [] - if pool: - cands += load_pool(pool, "this")[0] - if rpool and not at_root: - cands += [e for e in load_pool(rpool, "root")[0] if e["type"] != "project" or e["pinned"]] + for p, src, keep in ((pool, "this", lambda es: es), + (None if at_root else rpool, "root", root_cross)): + if not p: + continue + cands += keep(load_pool(p, src)[0]) + arch, over = load_archive(p, src) + cands += keep(arch) + if over and skipped is not None: + skipped.append(f"{over} archived entries in {os.path.join(p, ARCHIVE_DIR)} " + f"past the {DIGEST_MAX_FILES}-file read limit were not searched") return cands +def display_ref(e): + """What a search row or a hint names an entry by. A live entry of this + directory's pool or the root pool keeps its name, as the digest prints it. + An archived entry and a lessons paragraph carry their path (a paragraph + with :line), so an archived name never reads as a live entry and two + pools' archives holding one name stay apart.""" + if e["src"] == "lessons": + return f"{e['path']}:{e['line']}" + if e.get("arch"): + return os.path.realpath(e["path"]) + return e["stem"] + + +def source_of(e): + if e["src"] == "lessons": + return "lessons" + return "archive" if e.get("arch") else e["src"] + + def hint_log(msg): """One line to $MEMORY_HINT_LOG (set by hooks/memory-hint.sh) so a failing hint is findable; never raises, never prints.""" @@ -1173,6 +1386,17 @@ def hint_log(msg): pass +def hint_line(e): + """"Relevant memory: : ", at most HINT_LINE_CAP units. + Only the description is shortened: a cut reference (an archive path) is no + use to the reader, so a reference longer than the cap prints whole.""" + head = f"Relevant memory: {display_ref(e)}" + if not e["desc"]: + return head + room = HINT_LINE_CAP - u16(head) - 2 + return f"{head}: {cut_u16(e['desc'], max(room, 12))}" + + def hint_main(cwd, ops): """Read the UserPromptSubmit payload on stdin and print at most HINT_MAX "Relevant memory: : " lines. Prints nothing, and exits 0, @@ -1191,12 +1415,15 @@ def hint_main(cwd, ops): return 0 ops = resolve_ops(ops) cwd = cwd or os.environ.get("CLAUDE_PROJECT_DIR") or payload.get("cwd") or os.getcwd() - picks = strong_matches(score_prompt(ptoks, candidates(cwd, ops))) + skipped = [] + # Lessons paragraphs stay out of the hint: its bar (HINT_MIN_SCORE) was + # set on pool entries alone, and thousands of paragraphs would move + # every idf weight (settle plan, part 1). --find reads them. + picks = strong_matches(score_prompt(ptoks, candidates(cwd, ops, skipped=skipped))) + for note in skipped: + hint_log(note) if picks: - lines = [] - for _sc, e, _m, _n in picks: - s = f"Relevant memory: {e['stem']}: {e['desc']}" if e["desc"] else f"Relevant memory: {e['stem']}" - lines.append(cut_u16(s, HINT_LINE_CAP)) + lines = [hint_line(e) for _sc, e, _m, _n in picks] sys.stdout.buffer.write(("\n".join(lines) + "\n").encode("utf-8", "replace")) sys.stdout.flush() except Exception as e: # noqa: BLE001 - a hint must never fail a prompt; log and print nothing @@ -1204,26 +1431,430 @@ def hint_main(cwd, ops): return 0 -def find_main(cwd, ops, words, limit): - """The scorer by hand: `--find ` prints the best-matching entries of - this directory's pool and the root pool, "scorepoolname - description", best first, with no strong-match bar (one shared word is - enough). The way to find an entry the digest did not describe.""" +# --- lessons paragraphs (--find) ----------------------------------------------- +# +# Where a prune sends a lesson, CONTEXT/projects/-lessons.md and +# similar files, nothing used to reach it: of the 21 newest root entries on +# one long-lived box, 4 repeated a lesson already in those files and --find +# found none. +# So --find also scores the lessons files, one document per paragraph, not per +# heading (a review found a correction 150 lines below its section's first +# line, so a heading index would land on the recipe it corrects). A paragraph is a run of non-blank lines; a fenced code block is +# part of its paragraph and its "#" lines are not headings. Each paragraph +# carries the words of the heading it sits under as its "name" (doubled, like +# an entry's name); its ref is path:line of its first line, so a hit lands on +# the paragraph itself. Only the top level of CONTEXT/projects is read (the +# archive/ history files are not, as the plan scoped it). +LESSONS_DIR = os.path.join("CONTEXT", "projects") +LESSONS_TEXT_CAP = 200 +LESSONS_CACHE_VERSION = 2 +_HEADING = re.compile(r"^ {0,3}(#{1,6})\s+(.*?)\s*#*\s*$") +_FENCE = re.compile(r"^ {0,3}(`{3,}|~{3,})") + + +def lessons_paragraphs(text): + """[(line, heading, body)] for one lessons file's text: line is the + 1-based number of the paragraph's first body line, heading the text of + the heading above it ("" before any), body the paragraph's lines joined.""" + out, heading, buf, start, fence = [], "", [], 0, None + + def flush(): + if buf: + out.append((start, heading, "\n".join(buf))) + buf.clear() + + for n, line in enumerate(text.splitlines(), 1): + if fence: + buf.append(line) + m = _FENCE.match(line) + if m and m.group(1)[0] == fence[0] and len(m.group(1)) >= len(fence): + fence = None + continue + m = _FENCE.match(line) + if m: + if not buf: + start = n + buf.append(line) + fence = m.group(1) + continue + if not line.strip(): + flush() + continue + h = _HEADING.match(line) + if h: + flush() + heading = h.group(2) + continue + if not buf: + start = n + buf.append(line) + flush() + return out + + +def lessons_state_dir(): + return os.path.join(os.environ.get("OPS_STATE_DIR") + or os.path.join(os.path.expanduser("~"), ".local", "state", "ops"), + "memory-lessons-index") + + +def _lessons_cache_path(path): + return os.path.join(lessons_state_dir(), claude_key(path)[-200:] + ".json") + + +def _lessons_cache_read(path, st): + """The cached paragraphs of path, or None when the cache is missing, from + another size or mtime, or malformed (then the file is parsed again).""" + try: + with open(_lessons_cache_path(path), "r", encoding="utf-8") as fh: + c = json.load(fh) + except (OSError, ValueError): + return None + if not (isinstance(c, dict) and c.get("v") == LESSONS_CACHE_VERSION and c.get("path") == path + and c.get("size") == st.st_size and c.get("mtime_ns") == st.st_mtime_ns + and isinstance(c.get("paras"), list)): + return None + for p in c["paras"]: + if not (isinstance(p, list) and len(p) == 4 and isinstance(p[0], int) + and isinstance(p[1], list) and isinstance(p[2], list) and isinstance(p[3], str)): + return None + return c["paras"] + + +def _lessons_cache_write(path, st, paras): + """Store one file's parsed paragraphs. The cache is only a speed-up (the + corpus measured about 3 MB, 0.4 s to tokenize on a busy host), so a + failure to write it costs the next search that time and nothing else; + the search result never depends on it.""" + d = lessons_state_dir() + try: + os.makedirs(d, mode=0o700, exist_ok=True) + fd, tmp = tempfile.mkstemp(prefix=".lessons.", dir=d) + try: + with os.fdopen(fd, "w", encoding="utf-8") as fh: + json.dump({"v": LESSONS_CACHE_VERSION, "path": path, "size": st.st_size, + "mtime_ns": st.st_mtime_ns, "paras": paras}, fh) + os.replace(tmp, _lessons_cache_path(path)) + except BaseException: + try: + os.unlink(tmp) + except OSError: + pass + raise + except OSError: + pass # a speed-up only (above); the next search parses the file again + + +def load_lessons(ops): + """One document per lessons paragraph, shaped like a pool entry for + score_prompt. No CONTEXT/projects directory means no lessons (an OPS + checkout has none); one that cannot be listed, or a file that cannot be + read, raises: a search that skipped them would report "no match".""" + d = os.path.join(ops, LESSONS_DIR) + if not os.path.lexists(d): + return [] + try: + names = sorted(f for f in os.listdir(d) if f.endswith(".md")) + except OSError as e: + raise DigestError(f"cannot list {d}: {e.strerror or e}") from None + docs = [] + for fn in names: + path = os.path.realpath(os.path.join(d, fn)) + try: + st = os.stat(path) + except OSError as e: + raise DigestError(f"cannot read {path}: {e.strerror or e}") from None + if not stat.S_ISREG(st.st_mode): + continue + paras = _lessons_cache_read(path, st) + if paras is None: + try: + with open(path, "r", encoding="utf-8", errors="replace") as fh: + text = fh.read() + except OSError as e: + raise DigestError(f"cannot read {path}: {e.strerror or e}") from None + paras = [] + for line, heading, body in lessons_paragraphs(text): + shown = clean(f"{heading}: {body}" if heading else body) + paras.append([line, sorted(set(tokens(heading))), sorted(set(tokens(body))), + cut_u16(shown, LESSONS_TEXT_CAP)]) + _lessons_cache_write(path, st, paras) + for line, htoks, btoks, shown in paras: + docs.append({"stem": f"{fn}:{line:07d}", "desc": shown, "type": "lessons", + "when": (0, 0, 0, 0, 0, 0), "pinned": False, "src": "lessons", + "arch": False, "path": path, "line": line, + "ntoks": set(htoks), "dtoks": set(btoks)}) + return docs + + +def find_main(cwd, ops, words, limit, as_json=False, excludes=(), pool_dir=None): + """The scorer by hand: `--find ` scores this directory's pool, the + root pool, both pools' archives and the lessons paragraphs, and prints the + best matches with no strong-match bar (one shared word is enough), best + first: "scoresourcereftext", source one of this, root, + archive, lessons, ref the file's absolute path (a lessons paragraph adds + :line), score to one decimal. With --json, one JSON object per line: + score (unrounded), source, ref, path (canonical absolute path), line (a + number, or null for an entry), text and matched_words (the distinct + normalized words that matched). --exclude PATH drops that file before the + scoring and its word counts (a write-time duplicate check excludes the + entry it is checking; by path, since two pools may hold one name). + --pool DIR pins this directory's pool. No match prints nothing and exits + 0; a search that could not read a pool, an archive or a lessons file + exits 1, never as an empty result.""" ops = resolve_ops(ops) cwd = cwd or os.environ.get("CLAUDE_PROJECT_DIR") or os.getcwd() try: - rows = score_prompt(tokens(" ".join(words)), candidates(cwd, ops)) + skipped = [] + cands = candidates(cwd, ops, pool_dir, skipped=skipped) + load_lessons(ops) + drop = {os.path.realpath(x) for x in excludes} + if drop: + cands = [e for e in cands if os.path.realpath(e["path"]) not in drop] + rows = score_prompt(tokens(" ".join(words)), cands) except Exception as e: # noqa: BLE001 - report the failure, exit 1 sys.stderr.write(f"memory-index: --find failed ({type(e).__name__}: {e})\n") return 1 - for sc, e, _m, _n in rows[:limit]: - sys.stdout.write(f"{sc:.1f}\t{'root' if e['src'] == 'root' else 'this'}\t{e['stem']}\t{e['desc']}\n") + for note in skipped: + sys.stderr.write(f"memory-index: --find: {note}\n") + out = [] + for sc, e, matched, _n in rows[:limit]: + path = os.path.realpath(e["path"]) + line = e.get("line") + ref = f"{path}:{line}" if line else path + if as_json: + out.append(json.dumps({"score": sc, "source": source_of(e), "ref": ref, "path": path, + "line": line, "text": e["desc"], + "matched_words": sorted(matched)}, ensure_ascii=False)) + else: + out.append(f"{sc:.1f}\t{source_of(e)}\t{tsv_field(ref)}\t{tsv_field(e['desc'])}") + if out: + sys.stdout.buffer.write(("\n".join(out) + "\n").encode("utf-8", "replace")) return 0 +def tsv_field(s): + """A display field with its separators escaped: a tab or newline in a path + or description must not split a row.""" + return (s.replace("\\", "\\\\").replace("\t", "\\t").replace("\n", "\\n") + .replace("\r", "\\r")) + + +# --- the index writer, shared by write mode and the settle ------------------- +# +# The settle's lock around the writer (2026-12-04, from the settle's review). +# In local mode the nightly settle +# rewrites a pool's MEMORY.md in the checkout sessions work in, and a +# session's own regeneration (the SessionStart hook, `memory-index `) +# could land between the settle's last check and its write and be +# overwritten. Both are this code, so they serialize on the settle's own +# lock ($STATE/memory-settle.lock, which the settle holds for its whole run): +# the writer takes it when local mode is configured and the directory is in +# that checkout's store. Held: it waits up to MEMORY_INDEX_SETTLE_WAIT seconds +# (SETTLE_INDEX_WAIT) and then skips this regeneration with exit 0, since the +# index is derived, the settle regenerates the pools it touched, the next +# session start regenerates the rest, and a session start must never hang or +# fail on the settle. With no local mode configured there is no settle on +# this box (the template ships no other mode), so no lock is taken; the +# settle's own writes go through this function while it already holds the +# lock (a second flock on a new descriptor in the same process would wait on +# itself). The writer takes +# only this lock, never the checkout flock or git's index.lock, so it cannot +# close a cycle with the settle (settle lock, then checkout flock, then +# index.lock) or the team sync (checkout flock, then git). +SETTLE_INDEX_WAIT = 5.0 +_SETTLE_ENV_KEY = r"MEMORY_SETTLE(?:_MODE|_ROOT)?" +_SETTLE_ENV_NAME = re.compile(rf"^[ \t]*(?:export[ \t]+)?{_SETTLE_ENV_KEY}\b") +_SETTLE_PLAIN = re.compile(rf"^[ \t]*({_SETTLE_ENV_KEY})[ \t]*=[ \t]*" + r"(?:\"([^\"\\$`']*)\"|'([^'\\$`\"]*)'|([^\"'\\$`]*?))[ \t]*$") + + +class IndexBusy(Exception): + """The settle holds its lock for this pool's checkout; the write was skipped.""" + + +def settle_state_dir(): + """The settle's state directory (its lock, status and journal).""" + return (os.environ.get("OPS_STATE_DIR") + or os.path.join(os.path.expanduser("~"), ".local", "state", "ops")) + + +def settle_env_file(): + return os.path.join(os.path.expanduser("~"), ".config", "ops", "memory-settle.env") + + +def settle_env_values(path=None): + """{name: value} of the mode, root and off switch in the settle's env + file, the last assignment winning; {} when there is no file or none of + those names appear. Raises ValueError, failing closed, when systemd and + this reader could read those names differently: an assignment with a + backslash, a "$" or backtick, a quote that does not wrap the whole value, + or any other form than NAME=value, and, once a name appears, any + line in the file that ends in a backslash (a continuation) or carries an + unbalanced quote (a value systemd would carry across lines). This is a + check, not a parser: plain single-line assignments are all it reads.""" + path = path or settle_env_file() + try: + with open(path, "r", encoding="utf-8") as fh: + text = fh.read() + except FileNotFoundError: + return {} + except UnicodeError as e: + raise ValueError(f"{path} is not UTF-8 ({e})") from None + lines = text.splitlines() + live = [l for l in lines if l.strip() and l.lstrip()[0] not in "#;"] + ours = [l for l in live if _SETTLE_ENV_NAME.search(l)] + if not ours: + return {} + for l in lines: + if l.rstrip("\r").endswith("\\"): + raise ValueError(f"{path} has a line continued with a backslash; systemd and memory-index " + "would read the settle's settings differently. Use plain NAME=value lines") + for l in live: + if l.count('"') % 2 or l.count("'") % 2: + raise ValueError(f"{path} has a line with an unbalanced quote ({l.strip()[:60]!r}); systemd " + "could read it across lines. Use plain NAME=value lines") + vals = {} + for l in ours: + m = _SETTLE_PLAIN.match(l.rstrip("\r")) + if not m: + raise ValueError(f"{path}: {l.strip()[:80]!r} is not a plain NAME=value assignment the settle " + "reads the same way systemd does (no backslash, $, backtick or partial quote)") + vals[m.group(1)] = next(g for g in m.groups()[1:] if g is not None) + return vals + + +def settle_lock_for(directory): + """The settle lock file a write into directory must hold, or None: only + when the env file configures local mode and directory is in that + checkout's memory store. A session's environment cannot override the + settings the timer and other sessions use. An env file the settle would + refuse means no settle can run, so it asks for no lock.""" + try: + filed = settle_env_values() + except (OSError, ValueError): + return None + root = filed.get("MEMORY_SETTLE_ROOT", "").strip() + if filed.get("MEMORY_SETTLE_MODE", "").strip() != "local" or not os.path.isabs(root): + return None + store = os.path.join(os.path.realpath(root), ".claude-memory") + d = os.path.realpath(directory) + if d != store and not d.startswith(store + os.sep): + return None + return os.path.join(settle_state_dir(), "memory-settle.lock") + + +def take_settle_lock(path): + """The settle lock, open and flock-ed, or None after the bounded wait.""" + import fcntl + try: + wait = float(os.environ.get("MEMORY_INDEX_SETTLE_WAIT", SETTLE_INDEX_WAIT)) + except ValueError: + wait = SETTLE_INDEX_WAIT + os.makedirs(os.path.dirname(path), mode=0o700, exist_ok=True) + fh = open(path, "a+") + deadline = time.monotonic() + max(0.0, wait) + while True: + try: + fcntl.flock(fh.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB) + return fh + except BlockingIOError: + pass + if time.monotonic() >= deadline: + fh.close() + return None + time.sleep(0.1) + + +def write_index(directory): + """Rewrite directory/MEMORY.md from its entries' frontmatter; (lines, + problems) as build_lines gives them. + + Atomic write (WS-5 regen-race fix). Two SessionStart hooks from parallel + sessions sharing this memory dir (e.g. both launched from ~/OPS) can + regenerate MEMORY.md concurrently. A plain open(target, "w") truncates + first, so a reader, or the other writer, can observe a half-written or + empty index. Write a unique temp file in the SAME directory (so + os.replace stays on one filesystem and is atomic on POSIX), then replace + MEMORY.md with it: every observer sees either the old file or a complete + new one, never a torn one. The index is a pure function of the memory + files, so last-writer-wins is harmless: concurrent writers emit identical + bytes. In local mode it first takes the settle's lock (the section + header); raises IndexBusy, nothing written, when the settle holds it past + the wait.""" + lockf = settle_lock_for(directory) + held = None + if lockf: + held = take_settle_lock(lockf) + if held is None: + raise IndexBusy(f"the nightly memory settle holds {lockf}") + try: + return _write_index_unlocked(directory) + finally: + if held is not None: + held.close() + + +def _write_index_unlocked(directory): + lines, problems = build_lines(directory) + content = "\n".join(lines) + ("\n" if lines else "") + target = os.path.join(directory, "MEMORY.md") + fd, tmp = tempfile.mkstemp(prefix=".MEMORY.md.", dir=directory) + try: + with os.fdopen(fd, "w", encoding="utf-8") as fh: + fh.write(content) + os.replace(tmp, target) + except BaseException: + try: + os.unlink(tmp) + except OSError: + pass + raise + return lines, problems + + +# --- the settle, restore and health commands ------------------------------------- +# +# Their code is in memory_settle.py beside this file, loaded only for those +# modes. Why not here: Python compiles a script on every run (no bytecode +# cache for __main__), and this file runs on every prompt (--hint) and every +# boot (--digest). Kept here, the mover's 1,300 lines tripled the compile time +# (18 to 57 ms) and its imports added about 15 ms; measured 2026-11-15 on +# T3-ALEX, the hint ran about 100 ms slower under load. The module is +# executed with this file's names already in its namespace, so it uses +# load_pool, digest_core and the rest unchanged; this file stays the one +# entry point (memory-index --settle, --restore, --health). +_SETTLE = None + + +def settle_module(): + global _SETTLE + if _SETTLE is None: + import types + from importlib.machinery import SourceFileLoader + path = os.path.join(os.path.dirname(os.path.realpath(__file__)), "memory_settle.py") + sys.dont_write_bytecode = True # never a __pycache__ in the checkout + loader = SourceFileLoader("memory_settle", path) + mod = types.ModuleType("memory_settle") + mod.__file__ = path + mod.__dict__.update({k: v for k, v in globals().items() if not k.startswith("__")}) + loader.exec_module(mod) + _SETTLE = mod + return _SETTLE + + def main(argv): check = False directory = None + if len(argv) > 2 and argv[1] == "--digest-fit" and argv[2] == "--cwd": + rest, opts = argv[2:], {"--cwd": None, "--ops": None} + while rest: + if rest[0] in opts and len(rest) > 1: + opts[rest[0]] = rest[1] + rest = rest[2:] + else: + sys.stderr.write(f"memory-index: unexpected digest-fit arg: {rest[0]}\n{USAGE}\n") + return 1 + return digest_fit_cwd_main(opts["--cwd"], opts["--ops"]) if len(argv) > 2 and argv[1] == "--digest-fit": return digest_fit_main(argv[2:]) if len(argv) > 1 and argv[1] == "--pool-for": @@ -1236,14 +1867,38 @@ def main(argv): sys.stderr.write(f"memory-index: unexpected pool-for arg: {rest[0]}\n{USAGE}\n") return 1 return pool_for_main(opts["--cwd"], opts["--ops"]) + if len(argv) > 1 and argv[1] in ("--settle", "--restore", "--health"): + mode, rest, ops = argv[1], list(argv[2:]), None + if "--ops" in rest: + i = rest.index("--ops") + if i + 1 >= len(rest): + sys.stderr.write(f"memory-index: --ops needs a directory\n{USAGE}\n") + return 2 + ops = rest[i + 1] + del rest[i:i + 2] + ms = settle_module() + if mode == "--settle": + return ms.settle_main(rest, ops) + if mode == "--restore": + return ms.restore_main(rest, ops) + if rest: + sys.stderr.write(f"memory-index: unexpected health arg: {rest[0]}\n{USAGE}\n") + return 2 + return ms.health_main(ops) if len(argv) > 1 and argv[1] in ("--digest", "--hint", "--find"): mode = argv[1] - opts = {"--cwd": None, "--ops": None, "--limit": "5"} - rest, words = argv[2:], [] + opts = {"--cwd": None, "--ops": None, "--limit": "5", "--pool": None} + rest, words, excludes, as_json = argv[2:], [], [], False while rest: - if rest[0] in opts and len(rest) > 1: + if rest[0] in opts and len(rest) > 1 and (mode == "--find" or rest[0] in ("--cwd", "--ops")): opts[rest[0]] = rest[1] rest = rest[2:] + elif mode == "--find" and rest[0] == "--exclude" and len(rest) > 1: + excludes.append(rest[1]) + rest = rest[2:] + elif mode == "--find" and rest[0] == "--json": + as_json = True + rest = rest[1:] elif mode == "--find" and not rest[0].startswith("--"): words.append(rest[0]) rest = rest[1:] @@ -1257,15 +1912,20 @@ def main(argv): if not words or not opts["--limit"].isdigit(): sys.stderr.write(f"memory-index: --find needs words and a numeric --limit\n{USAGE}\n") return 1 - return find_main(opts["--cwd"], opts["--ops"], words, int(opts["--limit"])) + return find_main(opts["--cwd"], opts["--ops"], words, int(opts["--limit"]), + as_json=as_json, excludes=excludes, pool_dir=opts["--pool"]) for arg in argv[1:]: if arg in ("-h", "--help"): print(USAGE) - print(" --check print the generated index to stdout; write nothing") - print(" --digest print the memory digest (--cwd, --ops); write nothing") - print(" --hint UserPromptSubmit payload on stdin: print up to three relevant entries") - print(" --find score the pools against ; print the best matches") - print(" --pool-for print the existing pool the digest uses (--cwd, --ops); exit 4 for none") + print(" --check print the generated index to stdout; write nothing") + print(" --digest print the SessionStart memory digest (--cwd, --ops); write nothing") + print(" --hint UserPromptSubmit payload on stdin: print up to three relevant entries") + print(" --find score the pools, their archives and the lessons against ") + print(" --digest-fit per pool (or per source, with --cwd): entries, described, named, not shown") + print(" --pool-for print the existing pool the digest uses (--cwd, --ops); exit 4 for none") + print(" --settle archive what each pool's digest cannot describe (--dry-run: print only)") + print(" --restore move an archived entry back to its live pool") + print(" --health append tonight's row to $STATE/memory-health.tsv") return 0 elif arg == "--check": check = True @@ -1285,36 +1945,20 @@ def main(argv): sys.stderr.write(f"memory-index: not a directory: {directory}\n") return 1 - lines, problems = build_lines(directory) - content = "\n".join(lines) + ("\n" if lines else "") - if check: - sys.stdout.write(content) + lines, problems = build_lines(directory) + sys.stdout.write("\n".join(lines) + ("\n" if lines else "")) else: - target = os.path.join(directory, "MEMORY.md") - # Atomic write (a regen-race fix). Two SessionStart hooks from - # parallel sessions sharing this memory dir (e.g. both launched from - # ~/OPS) can regenerate MEMORY.md concurrently. A plain - # open(target, "w") truncates first, so a reader (or the other writer) - # can observe a half-written or empty index. Write a unique temp file - # in the SAME directory (so os.replace stays on one filesystem and is - # atomic on POSIX), then replace MEMORY.md with it: every observer sees - # either the old file or a complete new one, never a torn one. The - # index is a pure function of the memory files, so last-writer-wins is - # harmless: concurrent writers emit identical bytes. - fd, tmp = tempfile.mkstemp(prefix=".MEMORY.md.", dir=directory) try: - with os.fdopen(fd, "w", encoding="utf-8") as fh: - fh.write(content) - os.replace(tmp, target) - except BaseException: - try: - os.unlink(tmp) - except OSError: - pass - raise + lines, problems = write_index(directory) + except IndexBusy as e: + # Derived file: the next session start regenerates it. A session + # start never waits longer than the bound or fails on the settle. + sys.stderr.write(f"[memory-index] skipped {os.path.join(directory, 'MEMORY.md')}: {e}; " + "the next session start regenerates it\n") + return 0 sys.stderr.write( - f"[memory-index] wrote {len(lines)} line(s) -> {target}\n" + f"[memory-index] wrote {len(lines)} line(s) -> {os.path.join(directory, 'MEMORY.md')}\n" ) pins = count_pinned(directory) @@ -1330,14 +1974,6 @@ def main(argv): ) for fn, reason in problems: sys.stderr.write(f" - {fn}: {reason}\n") - if len(lines) > POOL_CAP: - # A WARN and nothing else (the pool is the owner's): the index above is - # already written, the exit status is untouched, and nothing is removed. - sys.stderr.write( - f"[memory-index] WARN: {len(lines)} entries in {directory}, over the {POOL_CAP}-entry " - "pool cap the digest is sized for; entries past its budget lose their descriptions. " - "Prune the pool (fold, merge or delete entries) when you choose to; nothing was removed\n" - ) return 2 if problems else 0 diff --git a/.claude-config/bin/memory_settle.py b/.claude-config/bin/memory_settle.py new file mode 100644 index 0000000..b43f9c9 --- /dev/null +++ b/.claude-config/bin/memory_settle.py @@ -0,0 +1,1881 @@ +# memory_settle.py - the nightly memory mover (memory-index --settle), its way +# back (--restore) and its nightly row (--health). Not run on its own: +# bin/memory-index loads it for those three modes, with memory-index's own +# names (load_pool, digest_core, canonical_root, write_index, ...) already in +# this module's namespace; see "the settle, restore and health commands" in +# memory-index for why the code lives apart. Tests and +# memory-backfill-modified reach it through memory-index's settle_module(). + +import base64 +import collections +import datetime +import errno +import fcntl +import hashlib +import json +import os +import re +import signal +import socket +import stat +import subprocess +import sys +import tempfile +import time + + +# --- settle: the nightly mover (2026-11-15) ---------------------------------- +# +# Why: a memory pool fills faster than anyone prunes it, and a prune that +# needs the owner's sign-off reaches the owner as work. The settle drains a +# pool by level, not by age: each night it moves out of a pool the +# lowest-ranked entries the pool's real digest cannot describe, until the +# pool's own entries fit or every entry left over the budget is protected. A +# move is byte-for-byte into /_archive/, git-tracked and found by --find +# and --hint, so it is not a delete. +# +# Selection: each pool's own fit, exactly what `--digest-fit ` measures +# (the pool digested alone, no root section). While any own entry is listed +# by name only or not shown, the lowest-ranked one that is not protected is +# taken out and the pool measured again; a described entry is never moved, +# even when every entry below it is protected. Why own fit and not the +# combined digest a project session sees: in a project digest the root +# pool's feedback entries rank above the project's own, so a combined +# setpoint lets the root's volume decide each project pool's size (on its +# first dry run that rule archived 32 of one project pool's 51 entries and +# the pool's described count did not change). Pools are independent, so no +# session directory is needed. +# +# Never moved: a pinned entry; a type user entry; a file with any uncommitted +# change (untracked, staged or not) in the checkout on this box; an +# entry changed in the last SETTLE_FLOOR seconds, by the later of its +# metadata.modified stamp and the last commit that touched it (an old entry +# can carry a recent committed correction); an entry with no valid stamp +# (file times differ between checkouts, so they cannot date a move; the +# memory-backfill-modified script stamps the old ones once); a future stamp or +# commit time; a symlink, a non-regular file or an occupied archive path. +# +# Git. The template runs the settle in local mode only (the "local mode" +# section below): it commits in the owner's checkout through a checked write +# path and never fetches, adds a remote or pushes. Moves are journaled +# ($STATE/memory-settle-journal.json) before they happen, so a failed or +# killed run is finished or put back at the next start, and only paths the +# journal names are touched. One lock ($STATE/memory-settle.lock, a bounded +# wait) keeps two movers (settle, restore) apart, and each session's index +# writer takes it too (memory-index, "the index writer"). +# +# Outcome: $STATE/memory-settle-status.json, written atomically after every +# apply run, schema STATUS_SCHEMA (the gate check and the health reader read +# it): ok (entries moved and committed), noop (nothing to move), failed, or +# disabled (MEMORY_SETTLE=0). Only a landed commit or a valid no-op advances +# last_success_at. pending_delivery is always false here (local mode pushes +# nothing); the field stays so the status schema matches every reader. +SETTLE_FLOOR = 48 * 3600 +SETTLE_LOCK_WAIT = 60.0 +SETTLE_GIT_TIMEOUT = 60 +STATUS_SCHEMA = 1 +STATUS_NAME = "memory-settle-status.json" +JOURNAL_NAME = "memory-settle-journal.json" +LOCK_NAME = "memory-settle.lock" +HEALTH_NAME = "memory-health.tsv" +STORE_NAME = ".claude-memory" + + +class SettleError(Exception): + """A settle or restore that cannot go on; the message is the reason.""" + + +def state_dir(): + return settle_state_dir() # memory-index's, so its index writer finds the same lock + + +_ISO = re.compile(r"^(\d{4})-(\d{2})-(\d{2})(?:[T ](\d{2}):(\d{2})(?::(\d{2})(?:[.,](\d{1,9}))?)?" + r"\s*(Z|z|[+-]\d{2}(?::?\d{2})?)?)?$") +_UTC = datetime.timezone.utc + + +def stamp_latest(raw): + """(epoch seconds, note) for a metadata.modified stamp: the LATEST instant + it can mean, so the 48-hour floor errs toward keeping an entry. A stamp + with a zone is exact (note None). Without a zone it is read as local time + in the westernmost zone (UTC-12), and a bare date as the end of that day + there; the note says so. (None, reason) when there is no stamp or it is not + an ISO date or time.""" + s = (raw or "").strip() + if not s: + return None, "no metadata.modified stamp" + m = _ISO.match(s) + if not m: + return None, f"metadata.modified {clean(s)[:40]!r} is not an ISO date or time" + y, mo, d, hh, mi, ss, frac, zone = m.groups() + try: + if hh is None: + t = datetime.datetime(int(y), int(mo), int(d), 23, 59, 59, tzinfo=_UTC) + return (t + datetime.timedelta(hours=12)).timestamp(), "date only, read as its latest instant" + micro = int((frac or "0")[:6].ljust(6, "0")) + t = datetime.datetime(int(y), int(mo), int(d), int(hh), int(mi), int(ss or 0), micro, tzinfo=_UTC) + except ValueError: + return None, f"metadata.modified {clean(s)[:40]!r} is not a real date or time" + if not zone: + return (t + datetime.timedelta(hours=12)).timestamp(), "no zone, read as its latest instant" + if zone in ("Z", "z"): + return t.timestamp(), None + sign = 1 if zone[0] == "+" else -1 + digits = zone[1:].replace(":", "") + oh, om = int(digits[:2]), int(digits[2:4] or 0) + if oh > 14 or om > 59: + return None, f"metadata.modified {clean(s)[:40]!r} has an impossible zone" + return (t - sign * datetime.timedelta(hours=oh, minutes=om)).timestamp(), None + + +def settle_now(): + """The settle's clock: MEMORY_SETTLE_NOW (an ISO time with a zone; the + tests' fixed clock) or the real time.""" + raw = os.environ.get("MEMORY_SETTLE_NOW") + if not raw: + return time.time() + t, note = stamp_latest(raw) + if t is None or note: + raise SettleError("MEMORY_SETTLE_NOW is not an ISO time with a zone") + return t + + +def iso(t): + return datetime.datetime.fromtimestamp(t, _UTC).strftime("%Y-%m-%dT%H:%M:%SZ") + + +def git_env(read_only=False): + """The environment for every git the settle runs: no inherited repository + pointers (a hook's GIT_DIR must not redirect a command), no prompt that + could wait forever, C locale for parsing. read_only adds + GIT_OPTIONAL_LOCKS=0, so status on the shared checkout never takes its + index lock or rewrites its index.""" + env = {k: v for k, v in os.environ.items() + if k not in ("GIT_DIR", "GIT_WORK_TREE", "GIT_INDEX_FILE", "GIT_COMMON_DIR", + "GIT_OBJECT_DIRECTORY", "GIT_ALTERNATE_OBJECT_DIRECTORIES", + "GIT_NAMESPACE", "GIT_PREFIX")} + env.update(GIT_TERMINAL_PROMPT="0", LC_ALL="C", LANGUAGE="C", + GIT_HTTP_LOW_SPEED_LIMIT="1000", GIT_HTTP_LOW_SPEED_TIME="30") + if read_only: + env["GIT_OPTIONAL_LOCKS"] = "0" + return env + + +def run_git(repo, args, timeout=SETTLE_GIT_TIMEOUT, read_only=False, check=True, + input=None, env_extra=None, raw=False): + """git -C repo with a bounded wait; (returncode, stdout, stderr). + git runs in a session of its own, so a timeout kills git and anything it + started (ssh) by that process group, which this function created and + whose id it holds; a plain kill of git alone can leave ssh holding the + pipes. check raises SettleError on a non-zero exit or a timeout. input + (bytes) is git's stdin, env_extra is added after git_env() strips the + inherited repository pointers (local mode passes its own GIT_INDEX_FILE), + and raw returns stdout as bytes.""" + cmd = ["git", "-C", repo] + list(args) + env = git_env(read_only) + if env_extra: + env.update(env_extra) + try: + p = subprocess.Popen(cmd, stdin=subprocess.DEVNULL if input is None else subprocess.PIPE, + stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env, + start_new_session=True) + except OSError as e: + raise SettleError(f"cannot run git: {e.strerror or e}") from None + try: + out, err = p.communicate(input=input, timeout=timeout) + except subprocess.TimeoutExpired: + try: + if os.getpgid(p.pid) == p.pid: # the group start_new_session made, never ours + os.killpg(p.pid, signal.SIGKILL) + except OSError: + pass + p.kill() + out, err = p.communicate() + raise SettleError(f"git {args[0]} timed out after {timeout} s") from None + if not raw: + out = out.decode("utf-8", "surrogateescape") + err = err.decode("utf-8", "surrogateescape") + if check and p.returncode != 0: + raise SettleError(f"git {' '.join(args[:2])} failed ({p.returncode}): {clean(err)[:300]}") + return p.returncode, out, err + + +def git_top(repo): + rc, out, _e = run_git(repo, ["rev-parse", "--show-toplevel"], read_only=True, check=False) + return os.path.realpath(out.strip()) if rc == 0 and out.strip() else None + + +def inside(path, parent): + """True when realpath(path) is parent or below it (both resolved).""" + p, q = os.path.realpath(path), os.path.realpath(parent) + return p == q or p.startswith(q.rstrip(os.sep) + os.sep) + + +def file_sha(path): + h = hashlib.sha256() + with open(path, "rb") as fh: + for chunk in iter(lambda: fh.read(65536), b""): + h.update(chunk) + return h.hexdigest() + + +def dirty_paths(top): + """{repo-relative path: two-letter status} of every untracked, staged or + unstaged path under the store in the checkout at top. Read-only: no + index lock, no index refresh written.""" + _rc, out, _e = run_git(top, ["status", "--porcelain=v1", "-z", "--untracked-files=all", + "--no-renames", "--ignored=no", "--", STORE_NAME], read_only=True) + found = {} + for rec in out.split("\0"): + if len(rec) > 3: + found[rec[3:]] = rec[:2] + return found + + +def last_changes(top, pools): + """{repo-relative path: latest commit time} of every path under the given + pools in the history at top, from the full log (a --since cut can skip a + commit whose date is skewed). Renames count as changes on both paths.""" + if not pools: + return {} + specs = [f"{STORE_NAME}/{name}/" for name in pools] + _rc, out, _e = run_git(top, ["log", "--format=format:%x01%ct", "--name-only", "--no-renames", + "-z", "--"] + specs, read_only=True, timeout=120) + seen, t = {}, None + for tok in out.split("\0"): + for piece in tok.split("\n"): + if not piece: + continue + if piece.startswith("\x01"): + t = int(piece[1:]) + elif t is not None and piece not in seen: + seen[piece] = t + return seen + + +class Ctx: + """One settle or restore: the shared checkout (authoritative for what a + session sees and for uncommitted work), the tree the pools are read from + (the same checkout in local mode; work_top None means that) and the clock.""" + + def __init__(self, ops, work_top, dry): + self.ops = ops + self.shared_top = git_top(ops) + if not self.shared_top: + raise SettleError(f"{ops} is not a git checkout") + self.work_top = work_top or self.shared_top + self.dry = dry + self.now = settle_now() + self.host = host_key() + if not self.host: + raise SettleError("no memory host key on this machine") + self.shared_store = os.path.join(self.shared_top, STORE_NAME) + self.work_store = os.path.join(self.work_top, STORE_NAME) + self.dirty = {} + self.changes = {} + + def rel(self, path): + return os.path.relpath(os.path.realpath(path), os.path.realpath(self.work_top)) + + def protect_reason(self, e, pool_dir): + """None when e may move, else why it may not (the never-moved list).""" + if e["pinned"]: + return "pinned" + if e["type"] == "user": + return "type user" + rel = self.rel(e["path"]) + if rel in self.dirty: + return f"uncommitted change in the shared checkout ({self.dirty[rel].strip() or '?'})" + stamp, note = stamp_latest(e["modified"]) + if stamp is None: + return note + commit = self.changes.get(rel) + if commit is None: + return "no commit found for it" + latest = max(stamp, commit) + if latest > self.now: + return f"future stamp or commit time ({iso(latest)})" + if self.now - latest < SETTLE_FLOOR: + return f"changed within {SETTLE_FLOOR // 3600} h ({iso(latest)})" + why = move_refusal(e["path"], pool_dir, self.work_store) + if why: + return why + return None + + +def move_refusal(src, pool_dir, store): + """Why src may not be moved to pool_dir/_archive/, or None. The guard every + move passes at selection and again just before it happens: the pool is a + real directory directly in the store, the entry a regular file (not a + link) directly in the pool, the archive a real directory or absent, and + the destination free.""" + if not os.path.isdir(store) or os.path.islink(store): + return "the store is not a real directory" + if os.path.islink(pool_dir) or not os.path.isdir(pool_dir) \ + or os.path.dirname(os.path.realpath(pool_dir)) != os.path.realpath(store): + return "the pool is not a real directory directly in the store" + fn = os.path.basename(src) + if os.path.dirname(os.path.abspath(src)) != os.path.abspath(pool_dir) \ + or not fn.endswith(".md") or fn == "MEMORY.md" or fn.startswith(".") or "\0" in fn: + return "not an entry file directly in the pool" + try: + st = os.lstat(src) + except OSError: + return "the entry is gone" + if not stat.S_ISREG(st.st_mode): + return "a symlink or not a regular file" + adir = os.path.join(pool_dir, ARCHIVE_DIR) + if os.path.lexists(adir) and (os.path.islink(adir) or not os.path.isdir(adir)): + return "the archive path is a symlink or not a directory" + if os.path.lexists(os.path.join(adir, fn)): + return "archive destination occupied" + if not inside(src, store): + return "outside the store" + return None + + +def select_pools(ctx, args): + """[(name, work dir, shown dir)] in name order. args name pool + directories, each of which must be directly in the shared checkout's + store (a path anywhere else is refused, never followed); none means every + live pool of this machine's host key. Retired-host pools are left alone.""" + store = ctx.shared_store + if args: + names = [] + for a in args: + r = os.path.realpath(a) + if os.path.dirname(r) != os.path.realpath(store) or not os.path.isdir(r) or os.path.islink(a): + raise SettleError(f"{a} is not a pool directory directly in {store}; refusing") + names.append(os.path.basename(r)) + names = sorted(set(names)) + else: + try: + names = sorted(d for d in os.listdir(store) + if d.startswith(ctx.host + "-") and not os.path.islink(os.path.join(store, d)) + and os.path.isdir(os.path.join(store, d))) + except OSError as e: + raise SettleError(f"cannot list {store}: {e.strerror or e}") from None + out = [] + for n in names: + work = os.path.join(ctx.work_store, n) + if not os.path.isdir(work) or os.path.islink(work): + continue # not on the remote yet (never committed): nothing of it can move + out.append((n, work, os.path.join(os.path.realpath(ctx.shared_store), n))) + return out + + +def plan_settle(ctx, pools): + """The moves, without making any: {pool name: report}, each report with + "moves" (entries, lowest-ranked first) and the counts the status records. + Each pool is measured alone, as `--digest-fit ` measures it.""" + names = [n for n, _w, _s in pools] + ctx.dirty = dirty_paths(ctx.shared_top) + changes = last_changes(ctx.work_top, names) + if ctx.work_top != ctx.shared_top: + # A commit in the shared checkout that the work tree lacks is a change too. + for k, v in last_changes(ctx.shared_top, names).items(): + changes[k] = max(v, changes.get(k, 0)) + ctx.changes = changes + reports = {} + for name, work, shown in pools: + rep = {"moves": [], "protected_overflow": {}, "error": None} + reports[name] = rep + try: + own, over = load_pool(work, "this", mtime_from=shown if work != shown else None) + except DigestError as e: + rep.update(status="error", error=str(e), entries=None) + continue + rep["entries"] = len(own) + over + if over: + rep.update(status="error", error=f"more than {DIGEST_MAX_FILES} entries; not measured") + continue + try: + while True: + # As digest_fit_main does: the pool is its own directory and its + # own root, so no root section is loaded or shown. + _t, fit, order, k, _j, srcs = digest_core( + work, ctx.ops, work, work, loaded=(own, 0, [], 0), show=(shown, shown)) + outside = [e for e in order[k:] if e["src"] == "this"] + pick = None + for e in reversed(outside): + why = ctx.protect_reason(e, work) + if why: + rep["protected_overflow"][e["fn"]] = why + continue + pick = e + break + if pick is None: + break + own = [e for e in own if e is not pick] + rep["moves"].append(pick) + rep["protected_overflow"].pop(pick["fn"], None) + except DigestError as e: + rep.update(status="error", error=str(e)) + continue + still = {e["fn"] for e in outside} + rep["protected_overflow"] = {fn: why for fn, why in rep["protected_overflow"].items() if fn in still} + row = dict(zip(srcs, fit)).get("this") or (shown, 0, 0, 0, 0) + _p, total, described, named, gone = row + rep.update(after=total, described=described, named=named, not_shown=gone, + fits=not named and not gone, + status="fits" if not rep["moves"] and not named and not gone else + ("settled" if not named and not gone else "protected overflow")) + return reports + + +def reason_class(why): + """A protection reason without its detail (the time in parentheses, a + quoted stamp), for the status counts.""" + return re.sub(r"'[^']*'", "'...'", re.sub(r"\s*\(.*$", "", why)) + + +def status_pools(reports, work_store): + out = {} + for name, r in reports.items(): + classes = collections.Counter(reason_class(w) for w in r["protected_overflow"].values()) + # The per-pool keys (total, described, moved, + # protected_overflow, protected_reasons), then detail: total and + # described are the pool's own fit after this run's moves. + out[name] = { + "total": r.get("after"), "described": r.get("described"), "moved": len(r["moves"]), + "protected_overflow": len(r["protected_overflow"]), + "protected_reasons": dict(sorted(classes.items())), + "named": r.get("named"), "not_shown": r.get("not_shown"), "fits": r.get("fits"), + "entries_before": r.get("entries"), "archived": count_md(os.path.join(work_store, name, ARCHIVE_DIR)), + "status": r.get("status"), "error": r.get("error"), + } + return out + + +def print_plan(ctx, reports, out=sys.stdout): + w = out.write + for name, r in reports.items(): + st = r.get("status") + if st == "error": + w(f"pool {name}: {st}: {r['error']}; {r.get('entries')} entries, nothing moves\n") + continue + n = len(r["moves"]) + w(f"pool {name}: {r['entries']} entries; {n} to archive; after: {r['after']} entries, " + f"{r['described']} described, {r['named']} by name only, {r['not_shown']} not shown" + f"{'' if r['fits'] else ' (still over: protected)'}\n") + for e in r["moves"]: + w(f" move {e['fn']} ({e['type'] or 'no type'}, modified {e['modified'] or 'none'})\n") + for fn, why in sorted(r["protected_overflow"].items()): + w(f" keep {fn}: {why}\n") + + +def settle_result_error(reports): + bad = [f"{n} ({r['status']}: {r['error']})" for n, r in reports.items() + if r.get("status") == "error"] + return ("pools not settled: " + "; ".join(bad)) if bad else None + + +# --- the journal and the status ------------------------------------------------ + + +def journal_path(): + return os.path.join(state_dir(), JOURNAL_NAME) + + +def write_json_atomic(path, obj): + d = os.path.dirname(path) + os.makedirs(d, mode=0o700, exist_ok=True) + fd, tmp = tempfile.mkstemp(prefix="." + os.path.basename(path) + ".", dir=d) + try: + with os.fdopen(fd, "w", encoding="utf-8") as fh: + json.dump(obj, fh, indent=1, sort_keys=True) + fh.write("\n") + fh.flush() + os.fsync(fh.fileno()) + os.replace(tmp, path) + except BaseException: + try: + os.unlink(tmp) + except OSError: + pass + raise + + +def touched_pools(rels): + """The pool directories (repo-relative) a set of moved paths sits in.""" + out = set() + for r in rels: + parts = r.split("/") + if len(parts) >= 3 and parts[0] == STORE_NAME: + out.add(f"{STORE_NAME}/{parts[1]}") + return sorted(out) + + +def restore_refusal(src, dst, store): + """The restore's guard: src a regular file in /_archive/ of a pool + directly in the store, dst that pool's free live path.""" + # As on the archive path, a store symlink could lead outside the + # checkout. Check it before following pools. + if not os.path.isdir(store) or os.path.islink(store): + return "the store is not a real directory" + adir = os.path.dirname(src) + pool_dir = os.path.dirname(adir) + if os.path.basename(adir) != ARCHIVE_DIR or os.path.islink(adir) or os.path.islink(pool_dir) \ + or os.path.dirname(os.path.realpath(pool_dir)) != os.path.realpath(store): + return "not an archived entry of a pool in the store" + try: + st = os.lstat(src) + except OSError: + return "the archived entry is gone" + if not stat.S_ISREG(st.st_mode): + return "a symlink or not a regular file" + if os.path.dirname(dst) != pool_dir or os.path.lexists(dst): + return "the live path is occupied" + return None + + +# --- locking, status ------------------------------------------------------------ + + +def take_lock(): + """An open, flock-ed lock file, or None when another mover still holds it + after MEMORY_SETTLE_LOCK_WAIT seconds (default SETTLE_LOCK_WAIT).""" + try: + wait = float(os.environ.get("MEMORY_SETTLE_LOCK_WAIT", SETTLE_LOCK_WAIT)) + except ValueError: + wait = SETTLE_LOCK_WAIT + d = state_dir() + os.makedirs(d, mode=0o700, exist_ok=True) + fh = open(os.path.join(d, LOCK_NAME), "a+") + deadline = time.monotonic() + max(0.0, wait) + while True: + try: + fcntl.flock(fh.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB) + return fh + except OSError as e: + if e.errno not in (errno.EAGAIN, errno.EACCES): + fh.close() + raise + if time.monotonic() >= deadline: + fh.close() + return None + time.sleep(0.2) + + +def read_status(): + try: + with open(os.path.join(state_dir(), STATUS_NAME), "r", encoding="utf-8") as fh: + s = json.load(fh) + return s if isinstance(s, dict) else {} + except (OSError, ValueError): + return {} + + +def write_status(now, result, error=None, commit=None, pending=False, pools=None): + prev = read_status() + st = { + "schema": STATUS_SCHEMA, + "box": (socket.gethostname() or "").strip().lower() or None, + "last_attempt_at": iso(now), + "last_attempt_result": result, + "last_success_at": iso(now) if result in ("ok", "noop") else prev.get("last_success_at"), + "commit": commit, + "pending_delivery": bool(pending), + "error": error, + "pools": pools or {}, + } + write_json_atomic(os.path.join(state_dir(), STATUS_NAME), st) + return st + + +# --- local mode: the owner's own checkout (team boxes, 2026-12-04) ------------------- +# +# Why: a box owns its pools alone and often has no remote to push to, and an +# owner may keep a backup remote of their own that the settle must never push +# to. So the settle commits in the checkout itself, and the mode is +# configuration, never inferred from the remotes: MEMORY_SETTLE_MODE=local +# and MEMORY_SETTLE_ROOT=, from the process +# environment when the name is set there (systemd loads them from the env +# file) and from the env file otherwise, so a hand run of --settle, +# --dry-run, --restore or --health on the box picks the same mode as the +# timer. No MEMORY_SETTLE_MODE line, or any other value, is refused, never +# guessed. The environment must match the file (each session's index writer +# reads only the file), and a form systemd could read differently is refused +# (memory-index settle_env_values). +# +# Local mode writes the checkout the owner's sessions work in, so its write +# path is checked: the +# settle lock, then an flock on the checkout directory itself (the lock the +# template's box sync takes, so the two never interleave); recovery of a +# journal a stopped run left; a refusal on a detached or unborn HEAD, a git +# operation in progress, unmerged entries or an index format it does not +# write; plan_settle unchanged; then for every path the run can touch (each +# entry, its destination, each regenerated MEMORY.md) the HEAD entry, the +# index entry, the worktree bytes and the status are captured, and a dirty or +# colliding path is refused. The commit is built off to the side: its tree +# is HEAD's tree plus exactly the run's paths (a temporary index file), so +# the owner's staged work can never ride along and a destination new to the +# index needs no `git add` first; the index text is generated from the +# committed entries, so an uncommitted entry's line never lands in a commit. +# Then, with git's own index.lock held (no other git can stage, commit or +# switch branches meanwhile) and SIGTERM, SIGINT and SIGHUP deferred: every +# capture is read again and must be unchanged, the files move, the branch +# ref moves by compare-and-swap from the captured HEAD (a commit that landed +# in between makes the swap fail and the run roll back), and the real index +# is updated for the run's paths only, through a copy renamed into place. +# Each touched pool's worktree MEMORY.md is then what memory-index generates +# from the worktree as the moves left it (an entry the owner has not +# committed keeps its line); the committed one lists committed entries only. +# A session's own index writer takes the settle lock this run holds (see +# memory-index, "the index writer"), so it cannot rewrite the file between +# the last check and the write. A staged or untracked MEMORY.md makes that +# pool's moves refused. The journal names the run's commit before any file +# moves: a stopped run whose commit landed has its index entries finished, +# one that did not has its moves put back, and in both only bytes the run +# itself wrote are changed. The commit is made with plumbing, which runs no +# commit hook; our rule is never to bypass hooks, so a checkout with an +# executable commit hook (COMMIT_HOOKS) is refused +# (local_hook_refusal). Lock order: settle lock, checkout flock, index.lock. +SETTLE_MODES = ("local",) +LOCAL_BUSY = ("MERGE_HEAD", "rebase-merge", "rebase-apply", "CHERRY_PICK_HEAD", "REVERT_HEAD", + "BISECT_LOG", "sequencer") +INDEX_LOCK_WAIT = 10.0 +REGULAR_MODES = ("100644", "100755") +LITERAL = {"GIT_LITERAL_PATHSPECS": "1"} +def settle_env_path(): + return settle_env_file() + + +def read_settle_env(path=None): + """{name: value} of the local-mode settings and off switch, through + memory-index's settle_env_values (one reader for the settle and the index + writer's lock); raises when the file uses a form systemd could read + differently (fail closed).""" + try: + return settle_env_values(path or settle_env_path()) + except (OSError, ValueError) as e: + raise SettleError(f"cannot use {path or settle_env_path()}: {e}") from None + + +def settle_target(ops_arg, filed=None): + """("local", MEMORY_SETTLE_ROOT) for this run. The template ships local + mode only: no MEMORY_SETTLE_MODE, or any value but local, is refused + (never guessed), as are a local mode with no absolute root and an --ops + that names another checkout than the root.""" + if filed is None: + filed = read_settle_env() + + def pick(name): + return os.environ[name] if name in os.environ else filed.get(name) + + # The index writer in every session decides whether to take the settle's + # lock from the env file (sessions do not carry systemd's environment), so + # a run is refused unless the file says the same thing the environment + # does; otherwise the two writers could race unlocked. + names = ("MEMORY_SETTLE_MODE", "MEMORY_SETTLE_ROOT") + differ = [n for n in names if n in os.environ and os.environ[n].strip() != (filed.get(n) or "").strip()] + if differ: + raise SettleError(f"{', '.join(differ)} in the environment differs from {settle_env_path()}; local " + "mode needs them in the file, where each session's index writer reads them") + mode = (pick("MEMORY_SETTLE_MODE") or "").strip() + if mode not in SETTLE_MODES: + raise SettleError(f"MEMORY_SETTLE_MODE is {mode or 'not set'}; this template runs the settle in local " + f"mode only: set MEMORY_SETTLE_MODE=local and MEMORY_SETTLE_ROOT in {settle_env_path()}") + root = (pick("MEMORY_SETTLE_ROOT") or "").strip() + if not root or not os.path.isabs(root): + raise SettleError(f"local mode needs MEMORY_SETTLE_ROOT, the absolute path of this box's harness " + f"checkout (got {root!r}; set it in {settle_env_path()})") + if ops_arg and os.path.realpath(ops_arg) != os.path.realpath(root): + raise SettleError(f"--ops {ops_arg} is not MEMORY_SETTLE_ROOT {root}; local mode writes only " + "the configured checkout") + return "local", root + + +def local_top(root): + """The configured root, which must be the top of its own git checkout + (a subdirectory would make the run write the repository around it).""" + top = git_top(root) + if not top or top != os.path.realpath(root): + raise SettleError(f"MEMORY_SETTLE_ROOT {root} is not the top of a git checkout; refusing") + return top + + +def git_paths(top, names): + """{name: absolute path} of each name in the git directory (per worktree + where git keeps it there).""" + args = ["rev-parse"] + for n in names: + args += ["--git-path", n] + _rc, out, _e = run_git(top, args, read_only=True) + got = out.split("\n")[:len(names)] + if len(got) != len(names): + raise SettleError(f"cannot read the git directory of {top}") + return {n: (p if os.path.isabs(p) else os.path.join(top, p)) for n, p in zip(names, got)} + + +def local_head(top): + """(branch ref, commit) HEAD stands on; raises on a detached or unborn + HEAD, since a commit there would belong to no branch.""" + rc, out, _e = run_git(top, ["symbolic-ref", "-q", "HEAD"], read_only=True, check=False) + ref = out.strip() + if rc != 0 or not ref.startswith("refs/heads/"): + raise SettleError(f"{top} has a detached HEAD; local mode commits only onto a checked-out branch") + rc, out, _e = run_git(top, ["rev-parse", "-q", "--verify", ref + "^{commit}"], read_only=True, check=False) + if rc != 0 or not out.strip(): + raise SettleError(f"{ref} in {top} has no commit yet; nothing to settle against") + return ref, out.strip() + + +def read_small(path): + try: + with open(path, "r", encoding="utf-8", errors="replace") as fh: + return fh.read(4096) + except FileNotFoundError: + return None + + +def local_busy(top, nonce=None, check_lock=True): + """Why the checkout is not ours to write now, or None: a git operation in + progress, unmerged entries, an index format this path does not write, or + an index.lock that is not this run's (nonce). check_lock=False leaves + index.lock to take_index_lock, which waits for a session's git to finish + rather than failing the night on a lock held for a moment.""" + paths = git_paths(top, ["index.lock"] + list(LOCAL_BUSY)) + lock = paths.pop("index.lock") + if check_lock and os.path.lexists(lock) and not (nonce and read_small(lock) == nonce): + return "another git command holds the index (index.lock exists)" + for n, p in paths.items(): + if os.path.lexists(p): + return f"a git operation is in progress ({n})" + _rc, out, _e = run_git(top, ["ls-files", "-u", "-z"], read_only=True) + if out: + return "the index has unmerged entries" + for key in ("core.splitIndex", "index.sparse"): + _rc, out, _e = run_git(top, ["config", "--bool", "--get", key], read_only=True, check=False) + if out.strip() == "true": + return f"{key} is on, an index format local mode does not write" + return None + + +# Every hook `git commit` would run: the three that can reject before the message, the one that can +# reject while it is prepared, and post-commit, whose side effect (a notifier, a mirror) would be +# skipped without a word (reviewer, 2026-12-04). +COMMIT_HOOKS = ("pre-commit", "prepare-commit-msg", "commit-msg", "pre-merge-commit", "post-commit") + + +def local_hook_refusal(top): + """Why local mode will not commit in top because of a git hook, or None. + Its plumbing commit (commit-tree, update-ref) runs no commit hook, and our + rule is never to bypass hooks, so an executable hook named in COMMIT_HOOKS + in the effective hooks directory (core.hooksPath + when set, relative to the checkout's top as git reads it) is refused + rather than skipped. Remove or disable the hook, or leave this box on + hand moves.""" + rc, out, _e = run_git(top, ["config", "--path", "--get", "core.hooksPath"], read_only=True, check=False) + hooks = out.strip() if rc == 0 and out.strip() else None + if hooks: + hooks = hooks if os.path.isabs(hooks) else os.path.join(top, hooks) + else: + hooks = git_paths(top, ["hooks"])["hooks"] + for name in COMMIT_HOOKS: + h = os.path.join(hooks, name) + if os.path.isfile(h) and os.access(h, os.X_OK): + return (f"an executable {name} hook ({h}) would not run for the settle's plumbing commit, " + "and hooks are never bypassed; disable it to settle this checkout") + return None + + +def take_root_lock(top): + """An flock on the checkout directory itself, the lock the template's + box sync takes, so a settle never interleaves with + a sync or another local writer; the open descriptor, or None after the + bounded wait (MEMORY_SETTLE_LOCK_WAIT).""" + try: + wait = float(os.environ.get("MEMORY_SETTLE_LOCK_WAIT", SETTLE_LOCK_WAIT)) + except ValueError: + wait = SETTLE_LOCK_WAIT + fd = os.open(top, os.O_RDONLY | os.O_DIRECTORY) + deadline = time.monotonic() + max(0.0, wait) + while True: + try: + fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB) + return fd + except OSError as e: + if e.errno not in (errno.EAGAIN, errno.EACCES): + os.close(fd) + raise + if time.monotonic() >= deadline: + os.close(fd) + return None + time.sleep(0.2) + + +def _records(out, fields): + """Parse -z output of ls-tree or ls-files into [(field tuple, path)].""" + recs = [] + for rec in out.split("\0"): + if not rec: + continue + meta, path = rec.split("\t", 1) + parts = tuple(meta.split()) + if len(parts) != fields: + raise SettleError(f"unexpected git output: {clean(rec)[:120]}") + recs.append((parts, path)) + return recs + + +def tree_entries(top, commit, paths): + """{path: (mode, type, object)} of each path the commit holds.""" + if not paths: + return {} + _rc, out, _e = run_git(top, ["ls-tree", "-z", commit, "--"] + list(paths), read_only=True, env_extra=LITERAL) + want = set(paths) + return {p: parts for parts, p in _records(out, 3) if p in want} + + +def index_entries(top, paths): + """Return the real index's entries and the paths whose flags hide edits.""" + if not paths: + return {}, set() + _rc, out, _e = run_git(top, ["ls-files", "-v", "-s", "-z", "--"] + list(paths), + read_only=True, env_extra=LITERAL) + found, hidden = {}, set() + for parts, p in _records(out, 4): + flag = parts[0] + found.setdefault(p, []).append(parts[1:]) + if flag == "S" or flag.islower(): + hidden.add(p) + return {p: tuple(sorted(v)) for p, v in found.items()}, hidden + + +def wt_state(path): + """What the worktree holds at path: None, ("file", sha256), ("link", + target) or ("other", file type bits).""" + try: + st = os.lstat(path) + except FileNotFoundError: + return None + if stat.S_ISREG(st.st_mode): + return ("file", file_sha(path)) + if stat.S_ISLNK(st.st_mode): + return ("link", os.readlink(path)) + return ("other", stat.S_IFMT(st.st_mode)) + + +def capture(top, head, paths): + """{path: {tree, index, wt, status}}: the state of every path the run can + touch, compared again under the index lock before anything changes.""" + paths = sorted(set(paths)) + tree = tree_entries(top, head, paths) + idx, hidden = index_entries(top, paths) + _rc, out, _e = run_git(top, ["status", "--porcelain=v1", "-z", "--untracked-files=all", "--no-renames", + "--ignored=no", "--"] + paths, read_only=True, env_extra=LITERAL) + st = {rec[3:]: rec[:2] for rec in out.split("\0") if len(rec) > 3} + return {p: {"tree": tree.get(p), "index": idx.get(p, ()), "wt": wt_state(os.path.join(top, p)), + "status": st.get(p, ""), "hidden": p in hidden} for p in paths} + + +def src_refusal(c, sha): + """Why an entry with capture c may not move in local mode, or None.""" + t = c["tree"] + if t is None: + return "it is not in the last commit" + if t[1] != "blob" or t[0] not in REGULAR_MODES: + return "it is not a regular file in the last commit" + if c["index"] != ((t[0], t[2], "0"),): + return "it has a staged change" + if c["hidden"]: + return "its index entry has skip-worktree or assume-unchanged set" + if c["status"]: + return f"it has an uncommitted change ({c['status'].strip()})" + if c["wt"] != ("file", sha): + return "it changed after it was selected" + return None + + +def dst_refusal(c): + if c["tree"] or c["index"] or c["wt"] is not None or c["status"]: + return "its destination exists in the last commit, the index or the worktree" + return None + + +def index_refusal(c): + """Why a pool's generated MEMORY.md cannot be rewritten, or None.""" + if c["wt"] is not None and c["wt"][0] != "file": + return "the worktree copy is not a regular file" + t = c["tree"] + if t is None: + if not c["index"] and c["wt"] is None and not c["status"]: + return None + return "it is untracked or staged but not committed" + if t[1] != "blob" or t[0] not in REGULAR_MODES: + return "it is not a regular file in the last commit" + if c["index"] != ((t[0], t[2], "0"),): + return "it has a staged change" + if c["hidden"]: + return "its index entry has skip-worktree or assume-unchanged set" + if not c["status"]: + return None if c["wt"] else "the worktree copy is missing" + if c["status"] in (" M", " D"): + return None + return f"it has an uncommitted change ({c['status'].strip()})" + + +def cat_blobs(top, shas): + """{object: bytes} for blob objects, through one git cat-file --batch.""" + want = sorted(set(shas)) + if not want: + return {} + _rc, out, _e = run_git(top, ["cat-file", "--batch"], read_only=True, raw=True, + input=("\n".join(want) + "\n").encode()) + blobs, i = {}, 0 + for sha in want: + nl = out.index(b"\n", i) + head = out[i:nl].decode("ascii", "replace").split() + if len(head) != 3 or head[0] != sha or head[1] != "blob": + raise SettleError(f"cannot read object {sha[:12]} ({' '.join(head)[:80]})") + size = int(head[2]) + blobs[sha] = out[nl + 1:nl + 1 + size] + i = nl + 1 + size + 1 + return blobs + + +def committed_index(top, commit, pool_rel, drop=(), add=None): + """The MEMORY.md text write_index gives for pool_rel as commit holds it, + without the entry names in drop and with add ({name: (mode, object)}): + the run's index from committed entries only, so an entry the owner has + not committed never gets a line in the run's commit.""" + _rc, out, _e = run_git(top, ["ls-tree", "-z", commit, "--", pool_rel + "/"], read_only=True, env_extra=LITERAL) + ents = {} + for (mode, typ, sha), path in _records(out, 3): + name = path.rsplit("/", 1)[-1] + if name.endswith(".md") and name != "MEMORY.md": + ents[name] = (mode, typ, sha) + for n in drop: + ents.pop(n, None) + for n, (mode, sha) in (add or {}).items(): + ents[n] = (mode, "blob", sha) + bad = sorted(n for n, (m, t, _s) in ents.items() if t != "blob" or m not in REGULAR_MODES) + if bad: + raise SettleError(f"{pool_rel}/{bad[0]} is not a regular file in the last commit; " + "local mode does not regenerate that pool's index") + blobs = cat_blobs(top, [s for _m, _t, s in ents.values()]) + with tempfile.TemporaryDirectory(prefix="memory-settle-index-") as d: + for n, (_m, _t, s) in ents.items(): + with open(os.path.join(d, n), "wb") as fh: + fh.write(blobs[s]) + lines, _problems = build_lines(d) + return "\n".join(lines) + ("\n" if lines else "") + + +def index_info(changes): + """`git update-index -z --index-info` input: (mode, object, path), mode + "0" removing the path.""" + return b"".join(f"{m} {s}\t{p}".encode("utf-8", "surrogateescape") + b"\0" for m, s, p in changes) + + +def build_commit(top, old, changes, subject, body): + """The run's commit: old's tree with exactly the changes, built in a + temporary index file (the real index is not read or written), parented on + old. Nothing visible changes: the objects are unreachable until the ref + moves.""" + with tempfile.TemporaryDirectory(prefix="memory-settle-tree-") as d: + env = dict(LITERAL, GIT_INDEX_FILE=os.path.join(d, "index")) + run_git(top, ["read-tree", old], env_extra=env) + run_git(top, ["update-index", "-z", "--index-info"], input=index_info(changes), env_extra=env) + tree = run_git(top, ["write-tree"], env_extra=env)[1].strip() + return run_git(top, ["commit-tree", tree, "-p", old, "-m", subject, "-m", body])[1].strip() + + +def update_real_index(top, changes): + """Set the real index's entries for exactly these paths, leaving every + other entry (the owner's staged work) as it is: a copy of the index is + updated and renamed into place. The caller holds index.lock.""" + ipath = git_paths(top, ["index"])["index"] + fd, tmp = tempfile.mkstemp(prefix=".memory-settle-index.", dir=os.path.dirname(ipath)) + try: + keep_mode(fd, ipath) + finally: + os.close(fd) + try: + with open(ipath, "rb") as src, open(tmp, "wb") as dst: + dst.write(src.read()) + run_git(top, ["update-index", "-z", "--index-info"], input=index_info(changes), + env_extra=dict(LITERAL, GIT_INDEX_FILE=tmp)) + os.replace(tmp, ipath) + except BaseException: + try: + os.unlink(tmp) + except OSError: + pass + raise + + +def take_index_lock(top, nonce): + """Create git's index.lock for the run (the lock every git command that + writes the index takes), holding the run's nonce so a recovery can tell a + lock a stopped run left from another command's. Waits up to + MEMORY_SETTLE_INDEX_WAIT seconds (INDEX_LOCK_WAIT) for a session's git to + finish; raises after.""" + try: + wait = float(os.environ.get("MEMORY_SETTLE_INDEX_WAIT", INDEX_LOCK_WAIT)) + except ValueError: + wait = INDEX_LOCK_WAIT + path = git_paths(top, ["index.lock"])["index.lock"] + deadline = time.monotonic() + max(0.0, wait) + tmp = None + try: + while True: + if not os.path.lexists(path): + if tmp is None: + fd, tmp = tempfile.mkstemp(prefix=".memory-settle-index.", dir=os.path.dirname(path)) + with os.fdopen(fd, "wb") as fh: + fh.write(nonce.encode("utf-8")) + fh.flush() + os.fsync(fh.fileno()) + # Publish a complete lock in one operation. Creating the lock + # first would leave an unidentifiable file after a kill. + try: + os.link(tmp, path) + return path + except FileExistsError: + pass + if time.monotonic() >= deadline: + raise SettleError("another git command holds the index (index.lock); not written") + time.sleep(0.1) + finally: + if tmp is not None: + os.unlink(tmp) + + +def release_index_lock(path, nonce): + """Remove index.lock only when it is the run's own (it holds nonce).""" + if nonce and read_small(path) == nonce: + os.unlink(path) + + +class deferred_signals: + """SIGTERM, SIGINT and SIGHUP held while the run moves files, moves the + ref and holds index.lock, then delivered: a stop mid-section would leave + the owner's checkout locked or half moved. SIGKILL and power loss cannot + be held; the journal covers them.""" + SIGNALS = (signal.SIGTERM, signal.SIGINT, signal.SIGHUP) + + def __enter__(self): + self.got = None + self.old = {s: signal.signal(s, self._held) for s in self.SIGNALS} + return self + + def _held(self, signum, _frame): + self.got = self.got or signum + + def __exit__(self, *_exc): + for s, h in self.old.items(): + signal.signal(s, h) + if self.got: + signal.raise_signal(self.got) + return False + + +def keep_mode(fd, path, default=0o644): + """Give the temp file at fd the permission bits of the file it replaces + (mkstemp makes 0600), or default less the umask for a new file.""" + try: + mode = stat.S_IMODE(os.stat(path).st_mode) + except FileNotFoundError: + mask = os.umask(0) + os.umask(mask) + mode = default & ~mask + os.fchmod(fd, mode) + + +def write_bytes_atomic(path, data): + d = os.path.dirname(path) + fd, tmp = tempfile.mkstemp(prefix="." + os.path.basename(path) + ".", dir=d) + try: + keep_mode(fd, path) + with os.fdopen(fd, "wb") as fh: + fh.write(data) + fh.flush() + os.fsync(fh.fileno()) + os.replace(tmp, path) + except BaseException: + try: + os.unlink(tmp) + except OSError: + pass + raise + + +def local_rename(src, dst): + """Rename an entry without overwriting a path created after the guard.""" + import ctypes + + # Local mode runs on Linux. os.rename would replace an owner's new file, + # and a link/unlink pair would leave two names for an interrupted move. + renameat2 = getattr(ctypes.CDLL(None, use_errno=True), "renameat2", None) + if renameat2 is None: + raise SettleError("local mode requires Linux renameat2 to move entries without replacing files") + at_fdcwd, rename_noreplace = -100, 1 + if renameat2(at_fdcwd, os.fsencode(src), at_fdcwd, os.fsencode(dst), rename_noreplace) != 0: + err = ctypes.get_errno() + raise OSError(err, os.strerror(err), src, None, dst) + + +def local_undo(top, moves, indexes, dirs): + """Put back what a run that did not commit changed in the worktree, + newest first, never deleting a byte: a destination goes back to its + entry path only when that path is free; an index file goes back to its + old text only while it still holds the run's text (a session that + regenerated it since owns it now); an archive directory the run made + goes only when empty. What cannot be put back is named and raises.""" + store = os.path.join(top, STORE_NAME) + parents = set(dirs) + parents.update(os.path.dirname(m[key]) for m in moves for key in ("src", "dst")) + parents.update(os.path.dirname(ip["path"]) for ip in indexes) + for rel in sorted(parents): + parent = os.path.join(top, rel) + # An owner can move a directory while a stopped run waits for + # recovery. Never follow its replacement while undoing old paths. + if os.path.commonpath((store, parent)) != store or os.path.realpath(parent) != parent \ + or (os.path.lexists(parent) and not os.path.isdir(parent)): + raise SettleError(f"{rel} is no longer a directory inside the memory store") + problems = [] + for m in reversed(moves): + s, d = os.path.join(top, m["src"]), os.path.join(top, m["dst"]) + if os.path.lexists(d) and not os.path.lexists(s): + local_rename(d, s) + elif os.path.lexists(s) and not os.path.lexists(d): + continue # never moved + elif os.path.lexists(s): + problems.append(f"{m['src']} and {m['dst']} both exist") + else: + problems.append(f"{m['src']} and {m['dst']} are both gone") + for ip in indexes: + p = os.path.join(top, ip["path"]) + if ip.get("action") == "keep": + continue # an older journal recorded this index but never wrote it + if not ip.get("new_sha256") or wt_state(p) != ("file", ip["new_sha256"]): + continue # never written, or rewritten since by a session (its own now) + if ip.get("old_b64") is None: + os.unlink(p) + else: + write_bytes_atomic(p, base64.b64decode(ip["old_b64"])) + for rel in sorted(dirs, reverse=True): + d = os.path.join(top, rel) + if os.path.isdir(d) and not os.path.islink(d) and not os.listdir(d): + os.rmdir(d) + if problems: + raise SettleError("cannot put back: " + "; ".join(problems)) + + +def local_finish_index(top, j, head): + """A stopped run whose commit landed: set the index entries of its paths + that still hold the state before the run to the commit's, so the index + agrees with HEAD. The caller holds index.lock across the read and write.""" + paths = sorted({m["src"] for m in j["moves"]} | {m["dst"] for m in j["moves"]} + | {ip["path"] for ip in j["indexes"]}) + old_t, new_t = tree_entries(top, j["old"], paths), tree_entries(top, j["new"], paths) + head_t = new_t if head == j["new"] else tree_entries(top, head, paths) + cur, hidden = index_entries(top, paths) + zero = "0" * len(j["old"]) + changes = [] + for p in paths: + o, n = old_t.get(p), new_t.get(p) + if p in hidden or n != head_t.get(p): + continue + if cur.get(p, ()) != (((o[0], o[2], "0"),) if o else ()): + continue + changes.append((n[0], n[2], p) if n else ("0", zero, p)) + if changes: + update_real_index(top, changes) + + +def local_commit_landed(top, new, tip): + if tip == new: + return True + rc, _out, err = run_git(top, ["merge-base", "--is-ancestor", new, tip], read_only=True, check=False) + if rc not in (0, 1): + raise SettleError(f"cannot verify whether commit {new[:12]} landed: {clean(err)[:300]}") + return rc == 0 + + +def local_journal_phase(path, journal, phase): + write_json_atomic(path, dict(journal, phase=phase)) + journal["phase"] = phase + + +def local_recover(top): + """Finish what a stopped local run left, from its journal: an index.lock + holding the run's nonce is removed; a commit that reached the branch has + its index entries finished; one that did not has its worktree changes put + back. A journal of another checkout or of another mode is refused.""" + jp = journal_path() + try: + with open(jp, "r", encoding="utf-8") as fh: + j = json.load(fh) + except FileNotFoundError: + return None + except (OSError, ValueError) as e: + raise SettleError(f"cannot read the journal {jp}: {e}") from None + if not isinstance(j, dict) or j.get("mode") != "local" or j.get("top") != os.path.realpath(top) \ + or not isinstance(j.get("moves"), list) or not isinstance(j.get("indexes"), list) \ + or not isinstance(j.get("nonce"), str) or not j["nonce"]: + raise SettleError(f"the journal {jp} is not this checkout's local run; inspect it by hand") + lock_path = git_paths(top, ["index.lock"])["index.lock"] + # A stopped run may leave a candidate lock or a copy of the index. The + # prefix is this tool's own and the checkout flock excludes another run. + idir = os.path.dirname(lock_path) + for fn in os.listdir(idir): + if fn.startswith(".memory-settle-index."): + os.unlink(os.path.join(idir, fn)) + nonce = j["nonce"] + with deferred_signals(): + if j.get("phase") in ("prepared", "complete"): + release_index_lock(lock_path, nonce) + os.unlink(jp) + return "cleared the journal of a stopped run with no work left to recover" + # Reuse the journal's lock if the stopped run left it. If Git can + # stage meanwhile, take its lock before reading either HEAD or the + # staged paths. A second interruption uses the same recorded nonce. + lock = lock_path if read_small(lock_path) == nonce else take_index_lock(top, nonce) + try: + busy = local_busy(top, nonce) + if busy: + raise SettleError(f"refusing to recover {jp}: {busy}") + ref, head = local_head(top) + if ref != j["ref"]: + raise SettleError(f"refusing to recover {jp} on {ref}; it belongs to {j['ref']}") + if local_commit_landed(top, j["new"], head): + local_finish_index(top, j, head) + note = f"finished the index of commit {j['new'][:12]}, which a stopped run had made" + else: + if head != j["old"]: + raise SettleError(f"refusing to undo {jp}: {ref} moved after the run stopped") + local_undo(top, j["moves"], j["indexes"], j.get("dirs", [])) + note = f"undid {len(j['moves'])} uncommitted move(s) a stopped run left" + local_journal_phase(jp, j, "complete") + finally: + release_index_lock(lock, nonce) + os.unlink(jp) + return note + + +def local_index_plan(top, head, cap, pool_rels, recs): + """[index record] for each touched pool: its committed MEMORY.md (blob, or + None when the committed text already says this) from committed entries + only, and the worktree bytes before the run (old_b64, None when absent) + for a rollback. The worktree text is generated later, under the locks, + from the worktree as the moves leave it. Raises when a pool's MEMORY.md + cannot be written.""" + out = [] + for pr in pool_rels: + idx = f"{pr}/MEMORY.md" + why = index_refusal(cap[idx]) + if why: + raise SettleError(f"refusing to write {idx}: {why}") + drop = [os.path.basename(r["src"]) for r in recs if os.path.dirname(r["src"]) == pr] + add = {os.path.basename(r["dst"]): (cap[r["src"]]["tree"][0], cap[r["src"]]["tree"][2]) + for r in recs if os.path.dirname(r["dst"]) == pr} + data = committed_index(top, head, pr, drop, add).encode("utf-8") + t = cap[idx]["tree"] + blob = run_git(top, ["hash-object", "-w", "--stdin", "--path", idx], input=data)[1].strip() + old = None + if cap[idx]["wt"] is not None: + with open(os.path.join(top, idx), "rb") as fh: + old = base64.b64encode(fh.read()).decode("ascii") + out.append({"path": idx, "mode": t[0] if t else "100644", + "blob": None if t and t[2] == blob else blob, "new_sha256": None, "old_b64": old}) + return out + + +def worktree_index_text(pool_dir): + """What `memory-index ` writes for pool_dir as it now stands (the + settle holds the lock that writer would take, so it is called unlocked).""" + lines, _problems = build_lines(pool_dir) + return ("\n".join(lines) + ("\n" if lines else "")).encode("utf-8") + + +def local_write(ctx, planned_head, pairs, subject, body, restore=False): + """Move each (src, dst) pair (absolute, in the owner's checkout) byte- + identically, regenerate the touched pools' MEMORY.md and commit exactly + those paths onto the checked-out branch, through the checked write path + in this section's header. The caller holds the settle lock and the + checkout lock. Returns the commit id; raises with nothing changed, or + with the journal naming what the next run finishes.""" + top = ctx.shared_top + ref, old = planned_head + # The owner's commit can change whether a selected entry still qualifies + # even when it has no uncommitted edits by the time we capture it. + if local_head(top) != planned_head: + raise SettleError(f"{ref} or HEAD moved while the run planned; nothing written") + busy = local_busy(top, check_lock=False) or local_hook_refusal(top) + if busy: + raise SettleError(f"refusing to write {top}: {busy}") + recs = [{"src": os.path.relpath(s, top), "dst": os.path.relpath(d, top), "sha256": file_sha(s)} + for s, d in pairs] + pools = touched_pools([r["src"] for r in recs] + [r["dst"] for r in recs]) + paths = [r["src"] for r in recs] + [r["dst"] for r in recs] + [f"{p}/MEMORY.md" for p in pools] + cap = capture(top, old, paths) + for (s, d), r in zip(pairs, recs): + why = guard_pair(s, d, ctx.work_store, restore) or src_refusal(cap[r["src"]], r["sha256"]) \ + or dst_refusal(cap[r["dst"]]) + if why: + raise SettleError(f"refusing to move {r['src']}: {why}") + idx_plan = local_index_plan(top, old, cap, pools, recs) + zero = "0" * len(old) + changes = [] + for r in recs: + mode, _t, sha = cap[r["src"]]["tree"] + changes += [("0", zero, r["src"]), (mode, sha, r["dst"])] + changes += [(ip["mode"], ip["blob"], ip["path"]) for ip in idx_plan if ip["blob"]] + new = build_commit(top, old, changes, subject, body) + dirs = sorted({os.path.dirname(r["dst"]) for r in recs + if not os.path.lexists(os.path.join(top, os.path.dirname(r["dst"])))}) + nonce = f"memory-settle {os.getpid()} {os.urandom(8).hex()}\n" + jp = journal_path() + journal = {"v": 1, "mode": "local", "top": os.path.realpath(top), "ref": ref, "old": old, + "new": new, "nonce": nonce, "moves": recs, "dirs": dirs, + "indexes": idx_plan} + local_journal_phase(jp, journal, "prepared") + done, wrote = [], [] + tried_ref = False + with deferred_signals(): + try: + lock = take_index_lock(top, nonce) + except BaseException: + release_index_lock(git_paths(top, ["index.lock"])["index.lock"], nonce) + os.unlink(jp) + raise + try: + try: + # Everything again, under the lock: nothing may have changed since the capture. + if local_head(top) != (ref, old): + raise SettleError(f"{ref} or HEAD moved while the run prepared; nothing written") + busy = local_busy(top, nonce) + if busy: + raise SettleError(f"refusing to write {top}: {busy}") + if capture(top, old, paths) != cap: + raise SettleError("a path the run would touch changed while it prepared; nothing written") + # A run stopped while waiting for a Git writer never moved + # any paths. Recovery consults the moves only after this. + local_journal_phase(jp, journal, "moving") + for (s, d), r in zip(pairs, recs): + why = guard_pair(s, d, ctx.work_store, restore) + if why or file_sha(s) != r["sha256"] or os.path.lexists(d): + raise SettleError(f"refusing to move {r['src']}: {why or 'it changed just before the move'}") + os.makedirs(os.path.dirname(d), exist_ok=True) + local_rename(s, d) + done.append(r) + if file_sha(d) != r["sha256"]: + raise SettleError(f"{r['dst']} does not hold the moved bytes") + # The worktree index: what memory-index generates from the worktree + # as the moves left it, so an entry the owner has not committed keeps + # its line (the commit's index has committed entries only). A + # session's own index writer waits on the settle lock this run + # holds, so it cannot land between this check and this write. + for ip in idx_plan: + p = os.path.join(top, ip["path"]) + if wt_state(p) != cap[ip["path"]]["wt"]: + raise SettleError(f"{ip['path']} changed just before it was written") + data = worktree_index_text(os.path.dirname(p)) + ip["new_sha256"] = hashlib.sha256(data).hexdigest() + if wt_state(p) == ("file", ip["new_sha256"]): + continue + local_journal_phase(jp, journal, "moving") # the journal knows the bytes first + write_bytes_atomic(p, data) + wrote.append(ip) + if local_head(top) != (ref, old): + raise SettleError(f"{ref} or HEAD moved while the run wrote; nothing committed") + tried_ref = True + run_git(top, ["update-ref", "-m", subject, ref, new, old]) + except BaseException as failure: + if tried_ref: + # A timeout in a post-update hook can surface as a Git + # failure after the compare-and-swap wrote the ref. + tip = run_git(top, ["rev-parse", "--verify", ref + "^{commit}"], read_only=True)[1].strip() + if local_commit_landed(top, new, tip): + raise SettleError(f"{failure}; commit {new[:12]} landed on {ref}, " + f"the next run finishes its index from {jp}") from None + if journal["phase"] == "moving": + try: + local_undo(top, done, wrote, dirs) + except (OSError, SettleError) as e: + raise SettleError(f"the run failed and putting its changes back failed too ({e}); " + f"the journal {jp} names them") from None + local_journal_phase(jp, journal, "complete") + raise + try: + update_real_index(top, changes) + except (OSError, SettleError) as e: + raise SettleError(f"commit {new[:12]} is on {ref}, but the index update for its paths failed " + f"({e}); the next run finishes it from the journal {jp}") from None + local_journal_phase(jp, journal, "complete") + finally: + # Recovery needs the nonce until Git's lock has been released. + release_index_lock(lock, nonce) + if journal["phase"] in ("prepared", "complete"): + os.unlink(jp) + return new + + +def guard_pair(src, dst, store, restore): + """The file guards a pair passes at selection and just before the move.""" + if restore: + return restore_refusal(src, dst, store) + if dst != os.path.join(os.path.dirname(src), ARCHIVE_DIR, os.path.basename(src)): + return "the destination is not the entry's own archive path" + return move_refusal(src, os.path.dirname(src), store) + + +def local_pool_refusals(top, head, reports): + """{pool name: why} for pools with moves whose MEMORY.md the run cannot + write (staged, untracked, not a regular file). Those pools move nothing + this run; the rest settle.""" + out = {} + names = [n for n, r in reports.items() if r.get("moves")] + if not names: + return out + idx = {n: f"{STORE_NAME}/{n}/MEMORY.md" for n in names} + cap = capture(top, head, list(idx.values())) + for n, p in idx.items(): + why = index_refusal(cap[p]) + if why: + out[n] = f"{p}: {why}" + return out + + +def refuse_pools(reports, refusals): + for n, why in refusals.items(): + reports[n].update(moves=[], status="error", error=f"not settled: {why}", + after=None, described=None, named=None, not_shown=None, fits=None) + + +def local_settle_apply(root, pool_args): + """The settle in local mode: the run's moves committed onto the + checked-out branch of the owner's checkout; never a fetch, a remote or a + push.""" + notes, reports, commit, now, rlock = [], {}, None, None, None + store = os.path.join(root, STORE_NAME) + try: + now = settle_now() + top = local_top(root) + store = os.path.join(top, STORE_NAME) + rlock = take_root_lock(top) + if rlock is None: + sys.stderr.write(f"memory-index: --settle: another writer (a team sync, settle or restore) holds " + f"{top}; not run\n") + return 75 + note = local_recover(top) + if note: + notes.append(note) + planned_head = local_head(top) + _, head = planned_head + busy = local_busy(top, check_lock=False) or local_hook_refusal(top) + if busy: + raise SettleError(f"refusing to write {top}: {busy}") + ctx = Ctx(top, None, False) + pools = select_pools(ctx, pool_args) + reports = plan_settle(ctx, pools) + refuse_pools(reports, local_pool_refusals(top, head, reports)) + moves = [(e["path"], os.path.join(os.path.dirname(e["path"]), ARCHIVE_DIR, e["fn"])) + for r in reports.values() for e in r["moves"]] + if moves: + n = len(moves) + subject = f"chore(memory): archive {n} {'entry' if n == 1 else 'entries'} past the digest fit" + body = ("The nightly settle (local mode) moved these entries byte-identically into their " + "pool's _archive/, lowest-ranked first, until each pool's own entries fit its digest " + "or the rest were protected (memory-index --settle).\n\n" + + "\n".join(f"- {os.path.relpath(s, top)}" for s, _d in moves)) + commit = local_write(ctx, planned_head, moves, subject, body) + err = settle_result_error(reports) + if err: + raise SettleError(err) + st = write_status(now, "ok" if moves else "noop", commit=commit, pending=False, + pools=status_pools(reports, ctx.work_store)) + except (SettleError, DigestError, OSError, UnicodeError) as e: + return finish_failed(now, str(e), commit, False, reports, notes, store=store) + finally: + if rlock is not None: + os.close(rlock) + for n in notes: + sys.stdout.write(f"memory settle: {n}\n") + moved = sum(p["moved"] for p in st["pools"].values()) + sys.stdout.write(f"memory settle (local mode): {st['last_attempt_result']}; {moved} archived" + f"{', commit ' + commit[:12] if commit else ''}\n") + return 0 + + +def local_preflight(ctx, reports): + """What an apply run in local mode would refuse, read-only: [reason].""" + top = ctx.shared_top + out = [] + try: + _ref, head = local_head(top) + except SettleError as e: + return [str(e)] + for busy in (local_busy(top), local_hook_refusal(top)): + if busy: + out.append(f"{top}: {busy}") + for n, why in sorted(local_pool_refusals(top, head, reports).items()): + out.append(f"pool {n} not settled: {why}") + return out + + +def usable_local(root): + """The owner's checkout when the health row may read it (local mode): + the configured root, the top of its own checkout; else None.""" + try: + return local_top(root) + except SettleError: + return None + + +# --- the settle and restore commands -------------------------------------------- + + +def settle_main(args, ops): + dry = "--dry-run" in args + pool_args = [a for a in args if a != "--dry-run"] + bad = [a for a in pool_args if a.startswith("-")] + if bad: + sys.stderr.write(f"memory-index: unexpected settle arg: {bad[0]}\n{USAGE}\n") + return 2 + filed = {} + try: + filed = read_settle_env() + mode, ops = settle_target(ops, filed) + config_error = None + except SettleError as e: + mode, config_error, ops = None, str(e), resolve_ops(ops) + del mode # local is the only mode + # Hand runs do not inherit systemd's EnvironmentFile. Honor a pause from + # the file even if the invoking shell still has an older setting. + disabled = filed.get("MEMORY_SETTLE") == "0" or os.environ.get("MEMORY_SETTLE") == "0" + if dry: + if config_error: + sys.stderr.write(f"memory-index: --settle --dry-run failed: {config_error}\n") + return 1 + return settle_dry(ops, pool_args, disabled) + if disabled: + try: + write_status(settle_now(), "disabled") + except (OSError, SettleError) as e: + sys.stderr.write(f"memory-index: --settle disabled, and the status could not be written: {e}\n") + return 1 + sys.stdout.write("memory settle: disabled (MEMORY_SETTLE=0); nothing read or moved\n") + record_health(ops, use_root=False) + return 0 + try: + lock = take_lock() + except OSError as e: + sys.stderr.write(f"memory-index: --settle cannot open its lock in {state_dir()}: {e}\n") + return 1 + if lock is None: + # The holder writes the status when it ends; a run that never started + # leaves it alone rather than racing the holder's write. + sys.stderr.write("memory-index: --settle: another settle or restore holds the lock; not run\n") + return 75 + try: + if config_error: + rc = finish_failed(None, config_error, None, False, {}, []) + record_health(ops, use_root=False) + else: + rc = local_settle_apply(ops, pool_args) + record_health(ops) + return rc + finally: + lock.close() + + +def record_health(ops, use_root=True): + """The run's health row. Its failure is reported on stderr and never + changes the settle's exit status (the gate reads the status file). The + owner's checkout is the source: its history and pools are the ones the run + committed to.""" + try: + source = usable_local(ops) if use_root else None + note = append_health(ops, read_status(), source) + sys.stdout.write(f"memory health: {note}\n") + except (OSError, SettleError, DigestError) as e: + sys.stderr.write(f"memory-index: --settle: the health row could not be written: {e}\n") + + +def settle_dry(ops, pool_args, disabled): + """Print the plan from the configured checkout as it stands: no index, + journal, status or cache is written or read for writing, and what an + apply run would refuse there is printed too.""" + refusals = [] + try: + local_top(ops) + ctx = Ctx(ops, None, True) + pools = select_pools(ctx, pool_args) + reports = plan_settle(ctx, pools) + refusals = local_preflight(ctx, reports) + except (SettleError, DigestError) as e: + sys.stderr.write(f"memory-index: --settle --dry-run failed: {e}\n") + return 1 + w = sys.stdout.write + rc, out, _e = run_git(ctx.shared_top, ["symbolic-ref", "-q", "--short", "HEAD"], read_only=True, check=False) + w(f"memory settle, dry run (local mode): read {ctx.shared_top} on " + f"{out.strip() if rc == 0 else 'a detached HEAD'} as it stands; nothing written. " + "Local mode never fetches, adds a remote or pushes\n") + w(f"box {socket.gethostname()}, host key {ctx.host}, now {iso(ctx.now)}, floor {SETTLE_FLOOR // 3600} h" + f"{', MEMORY_SETTLE=0 (an apply run would do nothing)' if disabled else ''}\n") + print_plan(ctx, reports) + moves = sum(len(r["moves"]) for r in reports.values()) + kept = sum(len(r["protected_overflow"]) for r in reports.values()) + w(f"total: {moves} to archive in {sum(1 for r in reports.values() if r['moves'])} pool(s); " + f"{kept} over the budget and protected\n") + if os.path.lexists(journal_path()): + w(f"a journal from a stopped run is waiting ({journal_path()}); an apply run recovers it first\n") + for why in refusals: + w(f"an apply run would refuse: {why}\n") + err = settle_result_error(reports) + if err: + w(f"an apply run would fail: {err}\n") + return 1 + return 1 if refusals else 0 + + +def finish_failed(now, error, commit, pending, reports, notes, store=None): + for n in notes: + sys.stdout.write(f"memory settle: {n}\n") + try: + store = store or os.path.join(os.devnull, STORE_NAME) + pools = status_pools(reports, store) if reports else {} + write_status(now if now is not None else time.time(), "failed", error=clean(error)[:1000], + commit=commit, pending=pending, pools=pools) + except (OSError, SettleError) as e: + sys.stderr.write(f"memory-index: --settle failed and its status could not be written: {e}\n") + sys.stderr.write(f"memory-index: --settle failed: {clean(error)[:1000]}\n") + return 1 + + +def restore_main(args, ops): + """--restore [--pool ] [--dry-run]: move an archived entry + back to its live pool byte-identically, through the lock and the checked + write path the settle uses. The pool is required when two pools' archives + hold the name; an occupied live path is refused. Pin the entry + (metadata.pinned: true) afterwards if it must stay live: an entry the + digest still cannot describe is a candidate again on a later night.""" + dry, pool_arg, name, rest = False, None, None, list(args) + while rest: + a = rest.pop(0) + if a == "--dry-run": + dry = True + elif a == "--pool" and rest: + pool_arg = rest.pop(0) + elif not a.startswith("-") and name is None: + name = a + else: + sys.stderr.write(f"memory-index: unexpected restore arg: {a}\n{USAGE}\n") + return 2 + if not name: + sys.stderr.write(f"memory-index: --restore needs an entry name\n{USAGE}\n") + return 2 + fn = name if name.endswith(".md") else name + ".md" + if "/" in fn or "\0" in fn or fn.startswith(".") or fn == "MEMORY.md": + sys.stderr.write(f"memory-index: --restore: {name!r} is not an entry name\n") + return 2 + lock = rlock = None + try: + mode, ops = settle_target(ops) + del mode # local is the only mode + if dry: + local_top(ops) + ctx = Ctx(ops, None, True) + else: + lock = take_lock() + if lock is None: + sys.stderr.write("memory-index: --restore: another settle or restore holds the lock; not run\n") + return 75 + top = local_top(ops) + rlock = take_root_lock(top) + if rlock is None: + sys.stderr.write(f"memory-index: --restore: another writer (a team sync, settle or restore) holds " + f"{top}; not run\n") + return 75 + note = local_recover(top) + if note: + sys.stdout.write(f"memory restore: {note}\n") + planned_head = local_head(top) + ctx = Ctx(top, None, False) + if pool_arg: + pname = os.path.basename(os.path.realpath(pool_arg)) if "/" in pool_arg else pool_arg + sel = select_pools(ctx, [os.path.join(ctx.shared_store, pname)]) + else: + sel = select_pools(ctx, []) + pools = [n for n, _w, _s in sel] + hits = [p for p in pools if os.path.lexists(os.path.join(ctx.work_store, p, ARCHIVE_DIR, fn))] + if not hits: + raise SettleError(f"no archived entry {fn} in {'pool ' + pools[0] if pool_arg else 'any live pool'}") + if len(hits) > 1: + raise SettleError(f"{fn} is archived in {len(hits)} pools ({', '.join(hits)}); pass --pool") + pool = os.path.join(ctx.work_store, hits[0]) + src, dst = os.path.join(pool, ARCHIVE_DIR, fn), os.path.join(pool, fn) + why = restore_refusal(src, dst, ctx.work_store) + if why: + raise SettleError(f"refusing to restore {hits[0]}/{ARCHIVE_DIR}/{fn}: {why}") + if dry: + sys.stdout.write(f"memory restore, dry run: would move {src} back to {dst}\n") + return 0 + top = ctx.shared_top + commit = local_write(ctx, planned_head, [(src, dst)], "chore(memory): restore 1 archived entry", + f"memory-index --restore (local mode) moved {os.path.relpath(src, top)} back to " + f"{os.path.relpath(dst, top)} byte-identically.", restore=True) + sys.stdout.write(f"memory restore: {hits[0]}/{fn} is live again (commit {commit[:12]}); " + "pin it if it must stay live\n") + return 0 + except (SettleError, DigestError, OSError, UnicodeError) as e: + sys.stderr.write(f"memory-index: --restore failed: {e}\n") + return 1 + finally: + if rlock is not None: + os.close(rlock) + if lock is not None: + lock.close() + + +# --- health: one row a run ----------------------------------------------------- +# +# Every apply run (ok, noop, failed or disabled) ends by appending one row to +# $STATE/memory-health.tsv (tab-separated; the first line names the columns +# and readers go by name): time, box, run id (the status file's +# last_attempt_at), commit, result, entries moved, per-pool live and archived +# counts, and the night's duplicate count. The duplicate count: +# every entry git added to a live pool in the last 24 hours, read from the +# checkout's log (renames are not additions, so a restore is not counted), is +# scored by the --find scorer with itself excluded; it counts when the best +# match shares at least DUPE_MIN_WORDS distinct words and scores DUPE_MIN_SCORE +# or more (the hint's strong-match bar). One line per scored entry goes to +# $STATE/memory-dupes.jsonl with the best ref and score, never a body. A +# column that could not be measured holds "unmeasured", never 0. A second +# row for the same run id is never appended (memory-index --health re-runs it). +HEALTH_VERSION = 1 +HEALTH_COLUMNS = ("v", "timestamp", "box", "run_id", "commit", "outcome", "moved", "pools", + "dupes_scored", "dupes") +DUPES_NAME = "memory-dupes.jsonl" +DUPE_MIN_WORDS = 2 +DUPE_MIN_SCORE = 4.0 + + +def nightly_dupes(clone, ops, now): + """[row] for each entry added to a live pool of this host key in the + checkout's history in the 24 hours before now and still live there.""" + host = host_key() + top = git_top(ops) + if not host or not top: + raise SettleError("no host key or no shared checkout to score against") + _rc, out, _e = run_git(clone, ["log", "-M", "--diff-filter=A", "--name-only", "-z", + "--format=format:%x01%ct", "--", STORE_NAME + "/"], + read_only=True, timeout=120) + added, t = {}, None + for tok in out.split("\0"): + for piece in tok.split("\n"): + if not piece: + continue + if piece.startswith("\x01"): + t = int(piece[1:]) + elif t is not None and piece not in added: + added[piece] = t + root = os.path.join(clone, STORE_NAME, host + claude_key(canonical_root(top))) + lessons = load_lessons(ops) + rows = [] + for rel, ct in sorted(added.items()): + parts = rel.split("/") + if not (now - 86400 <= ct <= now and len(parts) == 3 and parts[1].startswith(host + "-") + and parts[2].endswith(".md") and parts[2] != "MEMORY.md"): + continue + path = os.path.join(clone, rel) + if os.path.islink(path) or not os.path.isfile(path): + continue # archived or removed since: nothing live to score + pool = os.path.dirname(path) + fm = parse_frontmatter(path, limit=FM_READ, errors="replace") + rpool = root if os.path.isdir(root) else None + cands = candidates_for(pool, rpool, rpool is not None and os.path.realpath(rpool) == os.path.realpath(pool)) + cands = [e for e in cands + lessons if os.path.realpath(e["path"]) != os.path.realpath(path)] + scored = score_prompt(tokens(parts[2][:-3] + " " + (fm["description"] or "")), cands) + best = scored[0] if scored else None + ref = None + if best: + bp = os.path.realpath(best[1]["path"]) + if inside(bp, clone): # a pool entry: name it where sessions read it + bp = os.path.join(top, os.path.relpath(bp, os.path.realpath(clone))) + ref = f"{bp}:{best[1]['line']}" if best[1].get("line") else bp + rows.append({"entry": rel, "added_at": iso(ct), "best_ref": ref, + "best_source": source_of(best[1]) if best else None, + "score": best[0] if best else None, + "matched_words": sorted(best[2]) if best else [], + "duplicate": bool(best and len(best[2]) >= DUPE_MIN_WORDS and best[0] >= DUPE_MIN_SCORE)}) + return rows + + +def pool_counts(store): + host = host_key() + out = {} + for d in sorted(os.listdir(store)): + p = os.path.join(store, d) + if host and d.startswith(host + "-") and os.path.isdir(p) and not os.path.islink(p): + out[d] = [count_md(p), count_md(os.path.join(p, ARCHIVE_DIR))] + return out + + +def append_health(ops, status, clone=None): + """Append the row for status (one settle attempt), and its duplicate + lines; nothing when that attempt is already recorded. clone is the + configured checkout when it is usable after a good run (ok or noop): the + duplicate count and the pool counts are read there, the pool counts from + the checkout the arguments name otherwise. Returns a one-line note.""" + run_id = status.get("last_attempt_at") if status.get("schema") == STATUS_SCHEMA else None + path = os.path.join(state_dir(), HEALTH_NAME) + if run_id: + try: + with open(path, "r", encoding="utf-8") as fh: + for line in fh: + cells = line.rstrip("\n").split("\t") + if len(cells) > 3 and cells[0] == str(HEALTH_VERSION) and cells[3] == run_id: + return f"attempt {run_id} already recorded" + except FileNotFoundError: + pass + now = settle_now() + try: + store = os.path.join(clone, STORE_NAME) if clone else os.path.join(git_top(ops) or ops, STORE_NAME) + pools_cell = json.dumps(pool_counts(store), separators=(",", ":"), sort_keys=True) + except (OSError, DigestError, SettleError) as e: + sys.stderr.write(f"memory-index: health: pool counts unmeasured ({e})\n") + pools_cell = "unmeasured" + dupes = None + if clone and status.get("last_attempt_result") in ("ok", "noop"): + try: + dupes = nightly_dupes(clone, ops, now) + except (OSError, DigestError, SettleError) as e: + sys.stderr.write(f"memory-index: health: duplicate count unmeasured ({e})\n") + moved = (str(sum(int(p.get("moved") or 0) for p in status["pools"].values() if isinstance(p, dict))) + if run_id and isinstance(status.get("pools"), dict) else "unmeasured") + row = [str(HEALTH_VERSION), iso(now), (socket.gethostname() or "").lower(), run_id or "none", + (status.get("commit") or "none") if run_id else "unmeasured", + status.get("last_attempt_result") or "unmeasured" if run_id else "unmeasured", + moved, pools_cell, + str(len(dupes)) if dupes is not None else "unmeasured", + str(sum(1 for d in dupes if d["duplicate"])) if dupes is not None else "unmeasured"] + os.makedirs(state_dir(), mode=0o700, exist_ok=True) + if dupes: + with open(os.path.join(state_dir(), DUPES_NAME), "a", encoding="utf-8") as fh: + for d in dupes: + fh.write(json.dumps(dict({"v": 1, "run_id": run_id, "time": iso(now)}, **d), + ensure_ascii=False, sort_keys=True) + "\n") + fd = os.open(path, os.O_WRONLY | os.O_APPEND | os.O_CREAT, 0o600) + with os.fdopen(fd, "a", encoding="utf-8") as fh: + if fh.tell() == 0: + fh.write("\t".join(HEALTH_COLUMNS) + "\n") + fh.write("\t".join(tsv_field(str(c)) for c in row) + "\n") + return f"recorded {row[5]} attempt {row[3]}; duplicates {row[9]} of {row[8]}" + + +def health_main(ops): + """memory-index --health: the row for the latest attempt, when the settle + did not record it (the settle appends its own row at the end of a run).""" + try: + _mode, ops = settle_target(ops) + note = append_health(ops, read_status(), usable_local(ops)) + except (OSError, SettleError) as e: + sys.stderr.write(f"memory-index: --health failed: {e}\n") + return 1 + sys.stdout.write(f"memory health: {note}\n") + return 0 diff --git a/.claude-config/bin/secrets-scan.sh b/.claude-config/bin/secrets-scan.sh index cb9fbdd..3c2165f 100755 --- a/.claude-config/bin/secrets-scan.sh +++ b/.claude-config/bin/secrets-scan.sh @@ -30,7 +30,7 @@ HARD_PATTERNS=( 'gitlab-pat|glpat-[A-Za-z0-9_-]{20,}' 'private-key-block|-----BEGIN [A-Z ]*PRIVATE KEY-----' 'jwt|eyJ[A-Za-z0-9_-]{15,}\.eyJ[A-Za-z0-9_-]{10,}' - 'age-secret-key|AGE-SECRET-KEY-1[A-Z0-9]{20,}' + 'age-secret-key|AGE-SECRET-KEY-(PQ-)?1[A-Z0-9]{20,}' # Flag-form credentials (CLI flags carrying a literal password inline). # Values starting with < or $ are placeholders/vars, deliberately unmatched. 'sshpass-flag-password|sshpass[[:space:]]+-p[[:space:]]*["'"'"'`]?[^<$"'"'"'`[:space:]][^[:space:]]{5,}' diff --git a/.claude-config/bin/tests/card-test.py b/.claude-config/bin/tests/card-test.py index 2b41cb9..d20fb64 100755 --- a/.claude-config/bin/tests/card-test.py +++ b/.claude-config/bin/tests/card-test.py @@ -336,6 +336,16 @@ def test_secret_shapes_are_refused_with_exit_6(self): self.assertIn("secret shape", p.stderr) self.assertEqual(self.snapshot(), before) + def test_an_age_post_quantum_identity_is_refused_with_exit_6(self): + # age 1.4's age-keygen makes AGE-SECRET-KEY-PQ-1... identities by default; the classical shape alone misses them. + self.init() + before = self.snapshot() + for secret in ("AGE-SECRET-KEY-PQ-" + "1ABCDEFGHIJKLMNOPQRSTUVWX", "AGE-SECRET-KEY-" + "1ABCDEFGHIJKLMNOPQRSTUVWX"): + p = self.run_card("add", "use " + secret) + self.assertEqual(p.returncode, 6, (secret[:18], p.stderr)) + self.assertIn("secret shape", p.stderr) + self.assertEqual(self.snapshot(), before) + def test_a_pointer_to_a_secret_is_not_refused(self): self.init() self.ok("how", "add", "password: see the vault entry for the jump box") diff --git a/.claude-config/bin/tests/deploy-trust-test.sh b/.claude-config/bin/tests/deploy-trust-test.sh index 2f7088c..5281a45 100755 --- a/.claude-config/bin/tests/deploy-trust-test.sh +++ b/.claude-config/bin/tests/deploy-trust-test.sh @@ -45,11 +45,11 @@ rm "$TRUST" DEPLOY_FAILED='' # This executes the actual default-path assignment and error handling, rather # than asserting a spelling of an assignment independently of its behavior. -eval "$(awk '/^jf=/ {p=1} p && /^# --- T3 Code/ {exit} p {print}' "$DEPLOY")" +eval "$(awk '/^jf=/ {p=1} p && /^# --- (Nightly memory settle|T3 Code)/ {exit} p {print}' "$DEPLOY")" [[ -f "$TRUST" && ! -e "$CLAUDE_HOME/.claude.json" ]] || fail 'trust caller wrote to the wrong config file' printf 'broken\n' > "$TRUST" DEPLOY_FAILED='' -eval "$(awk '/^jf=/ {p=1} p && /^# --- T3 Code/ {exit} p {print}' "$DEPLOY")" 2>/dev/null +eval "$(awk '/^jf=/ {p=1} p && /^# --- (Nightly memory settle|T3 Code)/ {exit} p {print}' "$DEPLOY")" 2>/dev/null [[ "$DEPLOY_FAILED" == *trust-anchor* ]] || fail 'caller swallowed trust-seeding failure' [[ -z "$(find "$HOME" -name '*.trust.*' -print -quit)" ]] || fail 'trust update left a temporary file' printf 'PASS: trust merge, idempotency, corrupt-state preservation, permissions, symlinks and default path\n' diff --git a/.claude-config/bin/tests/desk-lapse-test.py b/.claude-config/bin/tests/desk-lapse-test.py new file mode 100644 index 0000000..0be356e --- /dev/null +++ b/.claude-config/bin/tests/desk-lapse-test.py @@ -0,0 +1,1340 @@ +#!/usr/bin/env python3 +"""Behavior tests for `desk lapse` and `desk keep` (bin/desk), clean desk piece C. + +Why pin it (AGENTS.md C1): these two commands rewrite a person's own standing rulings, on their box, +from a daily job. Moving a row that should have stayed, losing a row, sweeping an unrelated change into +the commit or disturbing the owner's other work would cost them silently. Every case builds a +throwaway team box (a git repository with a four-column rulings table) under a temp dir inside the +sandbox; nothing names the real checkout, and a sentinel tree beside the box must survive every case. + +Covered: + * the date boundary, both sides: a setup row is in force through its review date and lapses the + day after; the Kind cell form ("setup, review by ...") and the older in-text form; + * the archive: first use (created with its header) and an existing one (its bytes kept as a prefix), + the original row byte for byte, the move date and the reason; + * one commit with exactly the two files' planned bytes (a plumbing commit), an unrelated staged change + still staged and unrelated dirty and untracked files byte for byte; + * the review's three findings: an owner save after desk's rename stays out of the commit and is not + overwritten; an executable commit hook (any of the five) refuses with HEAD, index and files + unchanged; an owner `git commit -a` cannot run inside the write (desk holds index.lock); + * an owner commit before the index lock or before update-ref, and an owner stage before the lock: + a clean refusal with the files as they were; + * an editor's atomic save between desk's last read and its rename (the second review's finding), during + a rollback, and twice in one instant: never overwritten, never deleted; a first archive someone else + created is left intact; no renameat2 (missing or EINVAL) refuses before anything is written; a kill + between the exchange and its comparison is recovered only from verified bytes; + * refusals that change nothing: a dirty or staged rulings or archive file, a symlink, an untracked + archive, an unparseable row, an operation in progress, a detached or unborn HEAD, the checkout + lock held, an identity two rows share, a root that is not the box's without --state-dir; + * a three-column table is never touched, by lapse or by keep; + * interrupted writes (a kill after the first rename, before update-ref, after update-ref): the next + run undoes or finishes them unless a merge, a changed index or a symlinked parent prevents safe + recovery, and only a finished lapse leaves a notice; + * keep: before the date (kind becomes preference, review date gone, text unchanged), after the lapse + (the row back as a preference, the archive entry marked restored), twice (no-op), ambiguous; + * the notice receipt survives a fresh scan, and the counts (record and --counts) carry + rulings_lapsed_recent for 7 days. + +Run: .claude-config/bin/sandbox-run --no-net --ro-bind -- python3 +""" +import os, runpy; runpy.run_path(os.path.join(os.path.dirname(os.path.realpath(__file__)), "..", "sandbox_guard.py"))["require"]() +import fcntl +import hashlib +import json +import shutil +import stat +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path +from unittest.mock import patch + +DESK = Path(os.environ.get("DESK_UNDER_TEST") or Path(__file__).resolve().parent.parent / "desk") +ACTIVE = "CONTEXT/standing-orders.md" +ARCHIVE = "CONTEXT/standing-orders-archive.md" +HEAD = "| Ruling date | Area | Ruling and why | Kind |\n|---|---|---|---|\n" +INTRO = "# Standing orders\n\nThe owner's rulings.\n\n" +OUTRO = "\nA closing paragraph the tool must never touch.\n" +SETUP_ROW = "| 2026-11-20 | Autonomy | Checkpoint mode: pause at each major step. | setup, review by 2026-12-04 |" +PREF_ROW = "| 2026-11-01 | Backups | Keep them nightly. | preference |" +GUARD_ROW = "| 2026-11-02 | Remote | This box has no git remote; never add one (the backup pushes elsewhere). | guardrail |" + + +def sha(path): + return hashlib.sha256(Path(path).read_bytes()).hexdigest() + + +class Box: + """A team box: a git checkout with core.md and a rulings table, plus a sentinel tree beside it.""" + + def __init__(self, tc, rows=(SETUP_ROW, PREF_ROW, GUARD_ROW), table_head=HEAD, extra=None): + self.tc = tc + self.tmp = Path(os.path.realpath(tempfile.mkdtemp(prefix="desk-lapse-"))) + self.root = self.tmp / "OPS" + self.home = self.tmp / "home" + self.state = self.tmp / "state" + self.outside = self.tmp / "outside" + for d in (self.root, self.home, self.outside): + d.mkdir() + self.gitcfg = self.tmp / "gitconfig" + self.gitcfg.write_text("[user]\n\tname = Desk Test\n\temail = desk@example.invalid\n" + "[init]\n\tdefaultBranch = main\n[advice]\n\tdetachedHead = false\n") + # the sentinel tree: a file and a git repo beside the box that no run may touch + (self.outside / "sentinel.md").write_text("outside the box; must survive\n") + self.sentinel = {p: sha(p) for p in [self.outside / "sentinel.md"]} + self.env = {"PATH": os.environ.get("PATH", "/usr/bin:/bin"), "HOME": str(self.home), "LC_ALL": "C", + "GIT_CONFIG_GLOBAL": str(self.gitcfg), "GIT_CONFIG_NOSYSTEM": "1", "DESK_TODAY": "2026-12-05", + "DESK_LOCK_WAIT": "1"} + self.git("init", "-q") + self.write("CONTEXT/core.md", "core\n") + self.write(ACTIVE, INTRO + table_head + "".join(r + "\n" for r in rows) + OUTRO) + for rel, text in (extra or {}).items(): + self.write(rel, text) + self.git("add", "-A") + self.git("commit", "-q", "-m", "box") + + # -- helpers + def write(self, rel, text): + p = self.root / rel + p.parent.mkdir(parents=True, exist_ok=True) + p.write_bytes(text.encode() if isinstance(text, str) else text) + + def read(self, rel): + p = self.root / rel + return p.read_bytes() if p.exists() else None + + def git(self, *args, check=True): + p = subprocess.run(["git", "-C", str(self.root)] + list(args), env=self.env, stdout=subprocess.PIPE, + stderr=subprocess.PIPE) + if check and p.returncode != 0: + raise AssertionError("git %s failed: %s" % (args, p.stderr.decode())) + return p.stdout.decode().rstrip("\n") # rstrip only: status lines start with a space + + def desk(self, *args, today=None, extra_env=None, state=True): + env = dict(self.env) + if today: + env["DESK_TODAY"] = today + env.update(extra_env or {}) + cmd = [sys.executable, "-I", str(DESK)] + list(args) + ["--root", str(self.root)] + if state: + cmd += ["--state-dir", str(self.state)] + p = subprocess.run(cmd, cwd=str(self.tmp), env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + timeout=120) + return p.returncode, p.stdout.decode(), p.stderr.decode() + + def lapse(self, **kw): + return self.desk("lapse", **kw) + + def keep(self, date, area, **kw): + return self.desk("keep", date, area, **kw) + + def head(self): + return self.git("rev-parse", "-q", "--verify", "HEAD", check=False) # "" while unborn + + def commits(self): + return int(self.git("rev-list", "--count", "HEAD")) + + def show(self, rev, rel): + """The exact bytes rev holds at rel.""" + p = subprocess.run(["git", "-C", str(self.root), "cat-file", "blob", "%s:%s" % (rev, rel)], env=self.env, + stdout=subprocess.PIPE, stderr=subprocess.PIPE) + if p.returncode != 0: + raise AssertionError("cannot read %s:%s: %s" % (rev, rel, p.stderr.decode())) + return p.stdout + + def changed_in_head(self): + return sorted(self.git("diff-tree", "--no-commit-id", "--name-only", "-r", "HEAD").split()) + + def notice(self): + p = self.state / "desk-lapse-notice.json" + return json.loads(p.read_text()) if p.exists() else None + + def snapshot(self): + """Every byte the owner could care about: worktree files, the index listing, HEAD and status.""" + files = {} + for dirpath, dirnames, filenames in os.walk(self.root): + if ".git" in dirnames: + dirnames.remove(".git") + for n in filenames: + p = Path(dirpath) / n + files[str(p.relative_to(self.root))] = p.read_bytes() + return {"files": files, "index": self.git("ls-files", "-s"), "head": self.head(), + "status": self.git("status", "--porcelain=v1", "--untracked-files=all")} + + def sentinel_intact(self): + return all(sha(p) == h for p, h in self.sentinel.items()) + + +class Case(unittest.TestCase): + maxDiff = None + + def box(self, **kw): + b = Box(self, **kw) + self.addCleanup(shutil.rmtree, b.tmp, True) + self.addCleanup(lambda: self.assertTrue(b.sentinel_intact(), "the outside sentinel changed")) + return b + + def assertUnchanged(self, box, before, rc_err): + rc, _out, err = rc_err + self.assertEqual(rc, 1, err) + self.assertEqual(box.snapshot(), before) + self.assertIsNone(box.notice()) + self.assertFalse((box.state / "desk-write-journal.json").exists()) + + +class Boundary(Case): + def test_in_force_through_the_review_date(self): + b = self.box() + before = b.snapshot() + rc, out, err = b.lapse(today="2026-12-04") + self.assertEqual(rc, 0, err) + self.assertIn("no setup ruling is past its review date", out) + self.assertEqual(b.snapshot(), before) + self.assertIsNone(b.notice()) + + def test_lapses_the_day_after(self): + b = self.box() + old_active = b.read(ACTIVE).decode() + rc, out, err = b.lapse(today="2026-12-05") + self.assertEqual(rc, 0, err) + self.assertIn("1 setup ruling moved", out) + # the active file is the old one minus exactly that line + self.assertEqual(b.read(ACTIVE).decode(), old_active.replace(SETUP_ROW + "\n", "")) + arch = b.read(ARCHIVE).decode() + self.assertIn("\n~~~text\n" + SETUP_ROW + "\n~~~\n", arch) # byte for byte + self.assertIn("- Reason: lapsed\n- Moved: 2026-12-05\n", arch) + self.assertIn("### 2026-11-20 | Autonomy", arch) + + def test_the_older_in_text_review_form_and_the_scan_agree(self): + row = "| 2026-11-20 | Plans | Show the plan first, review by 2026-12-04. | setup |" + b = self.box(rows=(row, PREF_ROW)) + self.assertEqual(b.lapse(today="2026-12-04")[0], 0) + self.assertIn(row, b.read(ACTIVE).decode()) + rc, _o, err = b.lapse(today="2026-12-05") + self.assertEqual(rc, 0, err) + self.assertNotIn(row, b.read(ACTIVE).decode()) + + def test_a_setup_row_with_no_review_date_stays(self): + b = self.box(rows=("| 2026-11-20 | Dateless | text | setup |", PREF_ROW)) + before = b.snapshot() + self.assertEqual(b.lapse(today="2027-06-01")[0], 0) + self.assertEqual(b.snapshot(), before) + + def test_preference_and_guardrail_rows_never_lapse(self): + rows = ("| 2026-01-01 | P | old, review by 2026-01-02 | preference |", + "| 2026-01-01 | G | old, review by 2026-01-02 | guardrail |") + b = self.box(rows=rows) + before = b.snapshot() + self.assertEqual(b.lapse(today="2027-01-01")[0], 0) + self.assertEqual(b.snapshot(), before) + + +class Archive(Case): + def test_first_use_creates_the_archive_with_its_header(self): + b = self.box() + self.assertIsNone(b.read(ARCHIVE)) + self.assertEqual(b.lapse()[0], 0) + arch = b.read(ARCHIVE).decode() + self.assertTrue(arch.startswith("# Standing orders archive\n")) + self.assertEqual(b.git("ls-files", ARCHIVE), ARCHIVE) + + def test_an_existing_archive_keeps_its_bytes_as_a_prefix(self): + existing = "# Standing orders archive\n\nThe owner's own note, no trailing newline" + b = self.box(extra={ARCHIVE: existing}) + self.assertEqual(b.lapse()[0], 0) + arch = b.read(ARCHIVE).decode() + self.assertTrue(arch.startswith(existing + "\n")) + self.assertEqual(arch.count("- Reason: lapsed"), 1) + + def test_two_due_rows_move_in_one_commit(self): + second = "| 2026-11-21 | Writes | Confirm before any write. | setup (review by 2026-12-01) |" + b = self.box(rows=(SETUP_ROW, second, PREF_ROW)) + n = b.commits() + rc, out, err = b.lapse() + self.assertEqual(rc, 0, err) + self.assertEqual(b.commits(), n + 1) + self.assertIn("2 setup rulings moved", out) + self.assertEqual(b.read(ARCHIVE).decode().count("- Reason: lapsed"), 2) + + def test_crlf_lines_are_kept(self): + b = self.box() + text = b.read(ACTIVE).decode().replace("\n", "\r\n") + b.write(ACTIVE, text) + b.git("commit", "-q", "-am", "crlf") + self.assertEqual(b.lapse()[0], 0) + self.assertEqual(b.read(ACTIVE).decode(), text.replace(SETUP_ROW + "\r\n", "")) + self.assertIn("~~~text\n" + SETUP_ROW + "\r\n~~~", b.read(ARCHIVE).decode()) + + +class Commit(Case): + def test_exactly_the_two_files_and_unrelated_work_survives_byte_for_byte(self): + b = self.box(extra={"notes/staged.md": "base\n", "notes/dirty.md": "base\n"}) + b.write("notes/staged.md", "staged change\n") + b.git("add", "notes/staged.md") + b.write("notes/dirty.md", "dirty, not staged\n") + b.write("notes/untracked.md", "untracked\n") + staged_entry = b.git("ls-files", "-s", "notes/staged.md") + parent = b.head() + rc, _o, err = b.lapse() + self.assertEqual(rc, 0, err) + self.assertEqual(b.git("rev-parse", "HEAD^"), parent) + self.assertEqual(b.changed_in_head(), sorted([ACTIVE, ARCHIVE])) + self.assertEqual(b.read("notes/staged.md"), b"staged change\n") + self.assertEqual(b.read("notes/dirty.md"), b"dirty, not staged\n") + self.assertEqual(b.read("notes/untracked.md"), b"untracked\n") + self.assertEqual(b.git("ls-files", "-s", "notes/staged.md"), staged_entry) + self.assertEqual(b.git("diff", "--cached", "--name-only"), "notes/staged.md") + self.assertEqual(b.git("status", "--porcelain=v1", "--untracked-files=all").splitlines(), + [" M notes/dirty.md", "M notes/staged.md", "?? notes/untracked.md"]) + self.assertTrue(b.git("log", "-1", "--format=%s").startswith("chore(rulings): lapse 1 setup ruling")) + + def test_a_commit_msg_hook_with_an_existing_archive_is_refused(self): + b = self.box(extra={ARCHIVE: "# Standing orders archive\n"}) + hooks = b.tmp / "hooks" + hooks.mkdir() + (hooks / "commit-msg").write_text("#!/bin/sh\nexit 1\n") + (hooks / "commit-msg").chmod(0o755) + b.git("config", "core.hooksPath", str(hooks)) + before = b.snapshot() + self.assertUnchanged(b, before, b.lapse()) + + +class Refusals(Case): + def refuses(self, b, why=None, **kw): + before = b.snapshot() + rc, out, err = b.lapse(**kw) + self.assertUnchanged(b, before, (rc, out, err)) + if why: + self.assertIn(why, err) + return err + + def test_a_dirty_rulings_file(self): + b = self.box() + b.write(ACTIVE, b.read(ACTIVE) + b"an owner edit in progress\n") + self.refuses(b, "uncommitted or staged") + + def test_a_staged_change_in_the_rulings_file(self): + b = self.box() + b.write(ACTIVE, b.read(ACTIVE) + b"staged\n") + b.git("add", ACTIVE) + self.refuses(b, "uncommitted or staged") + + def test_a_staged_change_in_the_archive(self): + b = self.box(extra={ARCHIVE: "# Standing orders archive\n"}) + b.write(ARCHIVE, "# Standing orders archive\n\nstaged note\n") + b.git("add", ARCHIVE) + self.refuses(b, "uncommitted or staged") + + def test_a_new_archive_already_staged(self): + b = self.box() + b.write(ARCHIVE, "# mine\n") + b.git("add", ARCHIVE) + self.refuses(b, "uncommitted or staged") + + def test_an_untracked_archive_in_the_way(self): + b = self.box() + b.write(ARCHIVE, "# the owner's own file\n") + self.refuses(b, "not tracked") + + def test_a_symlinked_rulings_file(self): + b = self.box() + real = b.root / "CONTEXT/real-orders.md" + (b.root / ACTIVE).rename(real) + os.symlink("real-orders.md", b.root / ACTIVE) + b.git("add", "-A") + b.git("commit", "-q", "-m", "link") + self.refuses(b, "symlink") + + def test_a_symlinked_archive(self): + b = self.box(extra={"CONTEXT/elsewhere.md": "x\n"}) + os.symlink("elsewhere.md", b.root / ARCHIVE) + b.git("add", "-A") + b.git("commit", "-q", "-m", "link") + self.refuses(b, "symlink") + + def test_a_row_with_the_wrong_cell_count(self): + b = self.box(rows=(SETUP_ROW, "| 2026-11-03 | Odd | a | b | preference |")) + self.refuses(b, "cells") + + def test_an_unparseable_archive(self): + b = self.box(extra={ARCHIVE: "# A\n\n### broken\n\n- Reason: lapsed\n"}) + self.refuses(b, "Moved") + + def test_a_merge_in_progress(self): + b = self.box() + (b.root / ".git/MERGE_HEAD").write_text(b.head() + "\n") + self.refuses(b, "a merge is in progress") + + def test_a_rebase_in_progress(self): + b = self.box() + (b.root / ".git/rebase-merge").mkdir() + self.refuses(b, "a rebase is in progress") + + def test_a_locked_index(self): + b = self.box() + (b.root / ".git/index.lock").write_text("") + self.refuses(b, "index.lock") + + def test_a_detached_head(self): + b = self.box() + b.git("checkout", "-q", "--detach") + self.refuses(b, "detached") + + def test_an_unborn_head(self): + b = self.box() + b.git("checkout", "-q", "--orphan", "fresh") + self.refuses(b, "unborn") + + def test_the_checkout_lock_held_by_the_team_sync(self): + b = self.box() + fd = os.open(str(b.root), os.O_RDONLY | os.O_DIRECTORY) + self.addCleanup(os.close, fd) + fcntl.flock(fd, fcntl.LOCK_EX) + self.refuses(b, "holds the checkout lock") + + def test_two_rows_with_one_identity(self): + twin = "| 2026-11-20 | autonomy | A second ruling with the same date and area. | preference |" + b = self.box(rows=(SETUP_ROW, twin)) + self.refuses(b, "shares its date and area") + + def test_a_root_that_is_not_the_box_root_needs_a_state_dir(self): + b = self.box() + before = b.snapshot() + rc, _o, err = b.desk("lapse", state=False) + self.assertEqual(rc, 1) + self.assertIn("--state-dir", err) + self.assertEqual(b.snapshot(), before) + + def test_a_dirty_rulings_file_with_nothing_due_is_left_alone_quietly(self): + b = self.box() + b.write(ACTIVE, b.read(ACTIVE) + b"an owner edit in progress\n") + before = b.snapshot() + rc, out, err = b.lapse(today="2026-12-01") + self.assertEqual(rc, 0, err) + self.assertEqual(b.snapshot(), before) + + +class ConcurrentEdit(Case): + """CheckedWrite re-reads each file just before its rename. Driven in process, because the only way to + land an edit between read() and the rename from outside is a race.""" + + def load(self): + import importlib.machinery + import importlib.util + loader = importlib.machinery.SourceFileLoader("desk_mod", str(DESK)) + spec = importlib.util.spec_from_loader("desk_mod", loader) + mod = importlib.util.module_from_spec(spec) + loader.exec_module(mod) + return mod + + def test_an_edit_after_read_refuses_and_both_files_stay_as_found(self): + b = self.box(extra={ARCHIVE: "# Standing orders archive\n"}) + mod = self.load() + saved = dict(os.environ) + self.addCleanup(lambda: (os.environ.clear(), os.environ.update(saved))) + os.environ.update(b.env) + with mod.CheckedWrite(str(b.root), str(b.state), "test") as w: + w.read(ARCHIVE) + w.read(ACTIVE) + b.write(ACTIVE, b"an owner's session saved this meanwhile\n") + with self.assertRaises(mod.Refused) as cm: + # the archive is replaced first, then the active file's re-read finds the edit + w.commit([(ARCHIVE, b"new archive\n"), (ACTIVE, b"new active\n")], "chore: test") + self.assertIn("changed while desk was working", str(cm.exception)) + self.assertEqual(b.read(ARCHIVE), b"# Standing orders archive\n") + self.assertEqual(b.read(ACTIVE), b"an owner's session saved this meanwhile\n") + self.assertFalse((b.state / "desk-write-journal.json").exists()) + self.assertFalse((b.root / "CONTEXT/.standing-orders.md.desk-tmp").exists()) + self.assertEqual(b.commits(), 1) + + def test_a_directory_sync_failure_after_the_active_rename_rolls_back(self): + b = self.box(extra={ARCHIVE: "# Standing orders archive\n"}) + mod = self.load() + before = b.snapshot() + sync = os.fsync + failed = False + + def fail_after_active_rename(fd): + nonlocal failed + if not failed and stat.S_ISDIR(os.fstat(fd).st_mode) and SETUP_ROW.encode() not in b.read(ACTIVE): + failed = True + raise OSError("directory sync failed") + sync(fd) + + with patch.dict(os.environ, b.env), patch.object(os, "fsync", side_effect=fail_after_active_rename): + rc = mod.cmd_lapse(["--root", str(b.root), "--state-dir", str(b.state)]) + self.assertTrue(failed) + self.assertEqual(rc, 1) + self.assertEqual(b.snapshot(), before) + self.assertFalse((b.state / "desk-write-journal.json").exists()) + + +class Plumbing(Case): + """The commit is made from the planned bytes with plumbing, never from the live files, and no git command + of the owner's can slip into desk's write. Each case drives cmd_lapse in process with the fault points + replaced by a stand-in for the owner, acting at that exact moment (the 2026-12-04 review's high + findings, reproduced in fixtures, are the first three).""" + + def run_lapse(self, b, on_fault=None, mod=None): + import contextlib + import io + mod = mod or ConcurrentEdit.load(self) + err = io.StringIO() + with patch.dict(os.environ, b.env), patch.object(mod, "fault", side_effect=on_fault), \ + contextlib.redirect_stderr(err), contextlib.redirect_stdout(io.StringIO()): + rc = mod.cmd_lapse(["--root", str(b.root), "--state-dir", str(b.state)]) + return rc, err.getvalue() + + def planned_active(self, b): + return b.read(ACTIVE).replace(SETUP_ROW.encode() + b"\n", b"") + + def test_an_owner_save_after_the_last_rename_stays_out_of_desks_commit(self): + b = self.box() + planned = self.planned_active(b) + + def owner_saves(point): + if point == "before-commit": + b.write(ACTIVE, b.read(ACTIVE) + b"an owner's unfinished edit\n") + rc, err = self.run_lapse(b, owner_saves) + self.assertEqual(rc, 0, err) + self.assertEqual(b.show("HEAD", ACTIVE), planned) # the planned bytes, exactly + self.assertEqual(b.read(ACTIVE), planned + b"an owner's unfinished edit\n") # never overwritten + self.assertEqual(b.git("status", "--porcelain=v1"), " M " + ACTIVE) # theirs, uncommitted + self.assertIn("changed after desk wrote it", err) + + def test_an_owner_commit_a_cannot_run_inside_the_write(self): + b = self.box(extra={"notes/dirty.md": "base\n"}) + b.write("notes/dirty.md", "the owner's edit\n") + parent, owner = b.head(), [] + + def owner_commits_all(point): + if point == "before-commit": + p = subprocess.run(["git", "-C", str(b.root), "commit", "-a", "-q", "-m", "owner"], env=b.env, + stdout=subprocess.PIPE, stderr=subprocess.PIPE) + owner.append(p.returncode) + rc, err = self.run_lapse(b, owner_commits_all) + self.assertEqual(rc, 0, err) + self.assertEqual(len(owner), 1) + self.assertNotEqual(owner[0], 0, "the owner's commit -a ran in the middle of desk's write") + self.assertEqual(b.git("rev-parse", "HEAD^"), parent) + self.assertEqual(b.changed_in_head(), sorted([ACTIVE, ARCHIVE])) + self.assertEqual(b.git("status", "--porcelain=v1"), " M notes/dirty.md") + + def test_an_owner_commit_between_capture_and_update_ref_refuses_and_rolls_back(self): + b = self.box() + before = b.snapshot() + + def owner_moves_the_branch(point): + if point == "before-commit": + # a writer that does not need the index (plumbing), so desk's index.lock does not stop it + tree = b.git("rev-parse", "HEAD^{tree}") + new = b.git("commit-tree", tree, "-p", "HEAD", "-m", "owner") + b.git("update-ref", "refs/heads/main", new) + rc, err = self.run_lapse(b, owner_moves_the_branch) + self.assertEqual(rc, 1, err) + after = b.snapshot() + self.assertEqual((after["files"], after["index"], after["status"]), + (before["files"], before["index"], before["status"])) + self.assertEqual(b.git("log", "-1", "--format=%s"), "owner") + self.assertIsNone(b.notice()) + self.assertFalse((b.state / "desk-write-journal.json").exists()) + self.assertFalse(os.path.exists(b.root / ".git/index.lock")) + + def test_a_failed_ref_read_cannot_trigger_rollback_after_update_ref(self): + b = self.box() + mod = ConcurrentEdit.load(self) + real_git = mod.CheckedWrite._git + update_returned_error = False + + def update_lands_but_cannot_be_confirmed(w, args, **kwargs): + nonlocal update_returned_error + if args[0] == "update-ref": + rc, out, err = real_git(w, args, **kwargs) + self.assertEqual(rc, 0, err) + update_returned_error = True + return 1, out, "update-ref interrupted after moving the ref" + if update_returned_error and args[:3] == ["rev-parse", "-q", "--verify"]: + return 128, "", "ref temporarily unreadable" + return real_git(w, args, **kwargs) + + planned = self.planned_active(b) + with patch.object(mod.CheckedWrite, "_git", update_lands_but_cannot_be_confirmed): + rc, err = self.run_lapse(b, mod=mod) + self.assertEqual(rc, 1, err) + self.assertIn("ref temporarily unreadable", err) + self.assertEqual(b.show("HEAD", ACTIVE), planned) + self.assertEqual(b.read(ACTIVE), planned) + self.assertIn(SETUP_ROW.encode(), b.read(ARCHIVE)) + self.assertTrue((b.state / "desk-write-journal.json").exists()) + self.assertFalse((b.root / ".git/index.lock").exists()) + self.assertEqual(b.lapse()[0], 0) + self.assertEqual(b.git("status", "--porcelain"), "") + + def test_a_journal_directory_sync_failure_refuses_before_renaming_files(self): + b = self.box() + before = b.snapshot() + mod = ConcurrentEdit.load(self) + real_fsync = os.fsync + state_syncs = 0 + + def fail_writing_phase_sync(fd): + nonlocal state_syncs + opened = os.fstat(fd) + if stat.S_ISDIR(opened.st_mode) and opened.st_ino == b.state.stat().st_ino: + state_syncs += 1 + if state_syncs == 2: + raise OSError("journal directory sync failed") + real_fsync(fd) + + with patch.object(mod.os, "fsync", fail_writing_phase_sync): + rc, err = self.run_lapse(b, mod=mod) + self.assertIn("journal directory sync failed", err) + self.assertUnchanged(b, before, (rc, "", err)) + self.assertFalse((b.root / ".git/index.lock").exists()) + + def test_a_failed_rollback_never_leaves_the_ruling_in_neither_file(self): + b = self.box() + mod = ConcurrentEdit.load(self) + replace = mod.CheckedWrite._replace + + def active_restore_fails(w, rel, data, expect): + # the rollback's restore of the active file (expect is desk's version, without the row) + if rel == ACTIVE and expect is not None and SETUP_ROW.encode() not in expect: + raise OSError("no space left on device") + return replace(w, rel, data, expect) + + def owner_moves_the_branch(point): + if point == "before-commit": + new = b.git("commit-tree", b.git("rev-parse", "HEAD^{tree}"), "-p", "HEAD", "-m", "owner") + b.git("update-ref", "refs/heads/main", new) + import contextlib + import io + err = io.StringIO() + with patch.dict(os.environ, b.env), patch.object(mod, "fault", side_effect=owner_moves_the_branch), \ + patch.object(mod.CheckedWrite, "_replace", active_restore_fails), \ + contextlib.redirect_stderr(err), contextlib.redirect_stdout(io.StringIO()): + rc = mod.cmd_lapse(["--root", str(b.root), "--state-dir", str(b.state)]) + self.assertEqual(rc, 1) + self.assertIn("NOT fully restored", err.getvalue()) + held = [rel for rel in (ACTIVE, ARCHIVE) if b.read(rel) and SETUP_ROW.encode() in b.read(rel)] + self.assertEqual(held, [ARCHIVE]) # the archive copy stays until the row is back + self.assertTrue((b.state / "desk-write-journal.json").exists()) + self.assertFalse(os.path.exists(b.root / ".git/index.lock")) + + def test_the_planned_paths_are_clean_after_a_lapse_and_after_each_keep(self): + # desk undo (piece D) calls CheckedWrite.read right after a commit, and read refuses any path + # with a non-empty status: the real index must match the new HEAD and the files on disk + def clean(): + return b.git("status", "--porcelain=v1", "--untracked-files=all", "--", ACTIVE, ARCHIVE) + b = self.box(rows=(SETUP_ROW, "| 2026-11-21 | Writes | Confirm writes. | setup, review by 2026-12-20 |")) + self.assertIsNone(b.read(ARCHIVE)) + self.assertEqual(b.lapse()[0], 0) # the first-ever archive + self.assertEqual(clean(), "") + for rel in (ACTIVE, ARCHIVE): + self.assertEqual(b.git("ls-files", "-s", rel).split()[1], b.git("rev-parse", "HEAD:" + rel)) + self.assertEqual(b.keep("2026-11-21", "Writes", today="2026-12-05")[0], 0) # promote + self.assertEqual(clean(), "") + self.assertEqual(b.keep("2026-11-20", "Autonomy", today="2026-12-06")[0], 0) # restore + self.assertEqual(clean(), "") + self.assertEqual(b.git("status", "--porcelain=v1", "--untracked-files=all"), "") + + def test_an_owner_commit_before_the_index_lock_refuses_with_nothing_written(self): + b = self.box(extra={"notes/n.md": "base\n"}) + + def owner_commits(point): + if point == "captured": + b.write("notes/n.md", "owner\n") + b.git("commit", "-q", "-am", "owner") + before = (b.read(ACTIVE), b.read(ARCHIVE)) + rc, err = self.run_lapse(b, owner_commits) + self.assertEqual(rc, 1, err) + self.assertIn("the branch moved while desk prepared; nothing was written", err) # before any rename + self.assertEqual((b.read(ACTIVE), b.read(ARCHIVE)), before) + self.assertEqual(b.git("log", "-1", "--format=%s"), "owner") + self.assertEqual(b.git("status", "--porcelain=v1"), "") + + def test_an_owner_merge_before_the_index_lock_refuses_with_nothing_written(self): + b = self.box() + tree = b.git("rev-parse", "HEAD^{tree}") + incoming = b.git("commit-tree", tree, "-p", "HEAD", "-m", "incoming") + before = b.snapshot() + + def owner_starts_merge(point): + if point == "captured": + b.git("merge", "--no-ff", "--no-commit", incoming) + + rc, err = self.run_lapse(b, owner_starts_merge) + self.assertTrue((b.root / ".git/MERGE_HEAD").exists()) + self.assertIn("a merge is in progress", err) + self.assertUnchanged(b, before, (rc, "", err)) + + def test_an_owner_stage_before_the_index_lock_refuses_with_nothing_written(self): + b = self.box(extra={ARCHIVE: "# Standing orders archive\n"}) + + def owner_stages(point): + if point == "captured": + # staged only: the file on disk goes back to its committed bytes, so only the index differs + b.write(ARCHIVE, "# Standing orders archive\n\nthe owner's note\n") + b.git("add", ARCHIVE) + b.write(ARCHIVE, "# Standing orders archive\n") + rc, err = self.run_lapse(b, owner_stages) + self.assertEqual(rc, 1, err) + self.assertIn("has a staged change", err) # the recheck under index.lock + self.assertEqual(b.read(ARCHIVE), b"# Standing orders archive\n") + self.assertIn(SETUP_ROW.encode(), b.read(ACTIVE)) + self.assertEqual(b.git("status", "--porcelain=v1"), "MM " + ARCHIVE) + self.assertEqual(b.git("show", ":" + ARCHIVE), # the owner's staged entry + "# Standing orders archive\n\nthe owner's note") + + +class Swap(Case): + """An editor saves by writing a temp file and renaming it over the rulings file. Such a save landing + between desk's last read and its own rename was overwritten without a word (second review, high). + desk now swaps its file in with renameat2 RENAME_EXCHANGE (RENAME_NOREPLACE for a new file) and + compares what it displaced; an owner's save goes back to the path and desk refuses.""" + + OWNER = b"# the owner's save\n" + + def owner_save(self, b, rel, data): + """An editor's atomic save: a temp file in the same directory renamed over rel.""" + tmp = b.root / os.path.dirname(rel) / (".editor-%d.tmp" % os.getpid()) + tmp.write_bytes(data) + os.replace(tmp, b.root / rel) + + def save_after_read(self, mod, b, rel, nth=1, after=None, data=None): + """Patch CheckedWrite._current so the owner saves rel right after desk's nth read of it (counted + from when after() first says True): the instant between the read and desk's rename.""" + orig = mod.CheckedWrite._current + seen = {"n": 0} + + def current(w, r): + value = orig(w, r) + if r == rel and (after is None or after()): + seen["n"] += 1 + if seen["n"] == nth: + self.owner_save(b, rel, data or self.OWNER) + return value + return patch.object(mod.CheckedWrite, "_current", current) + + def state(self, b): + snap = b.snapshot() + return snap["index"], snap["head"] + + def test_a_save_between_the_last_read_and_the_rename_is_kept_and_desk_refuses(self): + b = self.box() + mod = ConcurrentEdit.load(self) + before = self.state(b) + with self.save_after_read(mod, b, ACTIVE): + rc, err = Plumbing.run_lapse(self, b, mod=mod) + self.assertEqual(rc, 1, err) + self.assertIn("changed while desk was working", err) + self.assertEqual(b.read(ACTIVE), self.OWNER) # the owner's save, at the path + self.assertIsNone(b.read(ARCHIVE)) # the other file rolled back + self.assertEqual(self.state(b), before) # HEAD and the index unchanged + self.assertEqual(sorted(p.name for p in (b.root / "CONTEXT").iterdir()), + ["core.md", "standing-orders.md"]) + self.assertFalse((b.state / "desk-write-journal.json").exists()) + + def test_a_save_during_the_rollback_is_kept(self): + b = self.box() + mod = ConcurrentEdit.load(self) + moved = {"done": False} + + def owner_moves_the_branch(point): + if point == "before-commit": + new = b.git("commit-tree", b.git("rev-parse", "HEAD^{tree}"), "-p", "HEAD", "-m", "owner") + b.git("update-ref", "refs/heads/main", new) + moved["done"] = True + # the rollback reads the active file twice (its check, then the swap's early read): save after the second + with self.save_after_read(mod, b, ACTIVE, nth=2, after=lambda: moved["done"]): + rc, err = Plumbing.run_lapse(self, b, owner_moves_the_branch, mod=mod) + self.assertEqual(rc, 1, err) + self.assertIn("NOT fully restored", err) + self.assertEqual(b.read(ACTIVE), self.OWNER) # not overwritten by the rollback + self.assertIn(SETUP_ROW.encode(), b.read(ARCHIVE)) # the row still has a copy + self.assertTrue((b.state / "desk-write-journal.json").exists()) + + def test_a_second_save_during_the_exchange_back_is_kept_beside_the_file(self): + b = self.box() + mod = ConcurrentEdit.load(self) + second = b"# the owner's second save\n" + + def second_save(point): + if point == "before-swap-back": + self.owner_save(b, ACTIVE, second) + with self.save_after_read(mod, b, ACTIVE): + rc, err = Plumbing.run_lapse(self, b, second_save, mod=mod) + self.assertEqual(rc, 1, err) + kept = sorted((b.root / "CONTEXT").glob("standing-orders.md.desk-displaced-*")) + self.assertEqual(len(kept), 1, err) + self.assertEqual(b.read(ACTIVE), second) # the latest save is at the path + self.assertEqual(kept[0].read_bytes(), self.OWNER) # the one it displaced is kept + self.assertIn(kept[0].name, err) + self.assertIsNone(b.read(ARCHIVE)) + + def test_a_failed_exchange_back_does_not_undo_the_archive(self): + import errno + b = self.box() + mod = ConcurrentEdit.load(self) + original = mod.renameat2 + swaps = 0 + + def exchange(src, dst, flags): + nonlocal swaps + if flags == mod.RENAME_EXCHANGE and dst == str(b.root / ACTIVE): + swaps += 1 + if swaps == 2: + raise OSError(errno.EIO, "exchange back failed") + return original(src, dst, flags) + + with self.save_after_read(mod, b, ACTIVE), patch.object(mod, "renameat2", side_effect=exchange): + rc, err = Plumbing.run_lapse(self, b, mod=mod) + self.assertEqual(rc, 1, err) + self.assertIn("exchange back failed", err) + self.assertIn(SETUP_ROW.encode(), b.read(ARCHIVE) or b"") + self.assertEqual(b.read("CONTEXT/.standing-orders.md.desk-tmp"), self.OWNER) + self.assertTrue((b.state / "desk-write-journal.json").exists()) + self.assertTrue((b.root / ".git/index.lock").exists()) + self.assertEqual(b.commits(), 1) + + def test_a_first_archive_someone_else_created_in_the_window_is_left_intact(self): + b = self.box() + mod = ConcurrentEdit.load(self) + before = self.state(b) + with self.save_after_read(mod, b, ARCHIVE, data=b"# someone else's archive\n"): + rc, err = Plumbing.run_lapse(self, b, mod=mod) + self.assertEqual(rc, 1, err) + self.assertEqual(b.read(ARCHIVE), b"# someone else's archive\n") + self.assertIn(SETUP_ROW.encode(), b.read(ACTIVE)) + self.assertEqual(self.state(b), before) + + def test_without_renameat2_nothing_is_written(self): + b = self.box() + mod = ConcurrentEdit.load(self) + before = b.snapshot() + with patch.object(mod, "libc_renameat2", return_value=None): + rc, err = Plumbing.run_lapse(self, b, mod=mod) + self.assertEqual(rc, 1, err) + self.assertIn("renameat2", err) + self.assertEqual(b.snapshot(), before) + self.assertFalse((b.state / "desk-write-journal.json").exists()) + + def test_a_probe_does_not_delete_an_existing_directory(self): + b = self.box() + notes = "CONTEXT/.desk-probe-notes/owner.md" + b.write(notes, self.OWNER) + rc, _o, err = b.lapse() + self.assertEqual(rc, 0, err) + self.assertEqual(b.read(notes), self.OWNER) + + def test_a_filesystem_that_answers_einval_is_refused_before_any_write(self): + import ctypes + import errno + b = self.box() + mod = ConcurrentEdit.load(self) + before = b.snapshot() + + def einval(*_args): + ctypes.set_errno(errno.EINVAL) + return -1 + with patch.object(mod, "libc_renameat2", return_value=einval): + rc, err = Plumbing.run_lapse(self, b, mod=mod) + self.assertEqual(rc, 1, err) + self.assertIn("renameat2", err) + self.assertEqual(b.snapshot(), before) + self.assertEqual(sorted(p.name for p in (b.root / "CONTEXT").iterdir()), ["core.md", "standing-orders.md"]) + + def test_a_filesystem_without_exchange_never_gets_a_partial_write(self): + # no-replace works, exchange answers EINVAL: the probe must refuse before either rulings file is touched + import ctypes + import errno + b = self.box() + mod = ConcurrentEdit.load(self) + real = mod.libc_renameat2() + calls = [] + + def no_exchange(olddir, src, newdir, dst, flags): + calls.append((os.fsdecode(src), os.fsdecode(dst))) + if flags == 2: + ctypes.set_errno(errno.EINVAL) + return -1 + return real(olddir, src, newdir, dst, flags) + before = b.snapshot() + with patch.object(mod, "libc_renameat2", return_value=no_exchange): + rc, err = Plumbing.run_lapse(self, b, mod=mod) + self.assertEqual(rc, 1, err) + self.assertIn("nothing was written", err) + self.assertTrue(calls) + self.assertTrue(all("/.desk-probe-" in src and "/.desk-probe-" in dst for src, dst in calls), calls) + self.assertEqual(b.snapshot(), before) + self.assertFalse((b.state / "desk-write-journal.json").exists()) + + def test_a_save_to_a_new_archive_during_the_rollback_is_kept(self): + b = self.box() + mod = ConcurrentEdit.load(self) + moved = {"done": False} + + def owner_moves_the_branch(point): + if point == "before-commit": + new = b.git("commit-tree", b.git("rev-parse", "HEAD^{tree}"), "-p", "HEAD", "-m", "owner") + b.git("update-ref", "refs/heads/main", new) + moved["done"] = True + # the rollback checks the new archive, then takes it away: the owner saves in between + with self.save_after_read(mod, b, ARCHIVE, nth=1, after=lambda: moved["done"]): + rc, err = Plumbing.run_lapse(self, b, owner_moves_the_branch, mod=mod) + self.assertEqual(rc, 1, err) + self.assertIn("NOT fully restored", err) + self.assertEqual(b.read(ARCHIVE), self.OWNER) # not deleted by the rollback + self.assertIn(SETUP_ROW.encode(), b.read(ACTIVE)) # the active file was restored first + self.assertTrue((b.state / "desk-write-journal.json").exists()) + + def test_a_kill_between_the_exchange_and_the_comparison(self): + b = self.box() + rc, _o, _e = b.lapse(extra_env={"DESK_FAULT": "after-swap"}) + self.assertEqual(rc, 70) + tmp = b.root / "CONTEXT/.standing-orders.md.desk-tmp" + self.assertTrue(tmp.exists()) # it holds the displaced old bytes + rc, _o, err = b.lapse() + self.assertEqual(rc, 0, err) # verified, removed, undone, redone + self.assertFalse(tmp.exists()) + self.assertEqual(b.changed_in_head(), sorted([ACTIVE, ARCHIVE])) + self.assertEqual(b.git("status", "--porcelain=v1", "--untracked-files=all"), "") + + def test_a_kill_after_an_exchange_that_displaced_an_owner_save(self): + b = self.box() + self.assertEqual(b.lapse(extra_env={"DESK_FAULT": "after-swap"})[0], 70) + tmp = b.root / "CONTEXT/.standing-orders.md.desk-tmp" + tmp.write_bytes(self.OWNER) # what the exchange displaced was a save + rc, _o, err = b.lapse() + self.assertEqual(rc, 1, err) + kept = sorted((b.root / "CONTEXT").glob("standing-orders.md.desk-displaced-*")) + self.assertEqual([k.read_bytes() for k in kept], [self.OWNER]) # never deleted + self.assertIn(kept[0].name, err) + self.assertTrue((b.state / "desk-write-journal.json").exists()) + before = b.snapshot() + rc, _o, err = b.lapse() + self.assertEqual(rc, 1, err) + self.assertIn(kept[0].name, err) + self.assertEqual(b.snapshot(), before) + self.assertTrue((b.state / "desk-write-journal.json").exists()) + self.assertTrue((b.root / ".git/index.lock").exists()) + + def test_recovery_keeps_an_unreadable_displaced_first_archive(self): + b = self.box() + mod = ConcurrentEdit.load(self) + self.assertEqual(b.lapse(extra_env={"DESK_FAULT": "after-first-write"})[0], 70) + self.owner_save(b, ARCHIVE, self.OWNER) + tmp = b.root / "CONTEXT/.standing-orders-archive.md.desk-tmp" + os.replace(b.root / ARCHIVE, tmp) # the move by _remove, before it can inspect the save + original = mod.read_bytes + + def read(path): + if Path(path) == tmp: + raise PermissionError("cannot read displaced archive") + return original(path) + + with patch.object(mod, "read_bytes", side_effect=read): + rc, err = Plumbing.run_lapse(self, b, mod=mod) + self.assertEqual(rc, 1, err) + kept = sorted((b.root / "CONTEXT").glob("standing-orders-archive.md.desk-displaced-*")) + self.assertEqual([k.read_bytes() for k in kept], [self.OWNER]) + self.assertIn(kept[0].name, err) + self.assertTrue((b.root / ".git/index.lock").exists()) + + +class Hooks(Case): + """desk's plumbing commit runs no commit hook and hooks are never bypassed, so a checkout with one is + refused before anything is written (the review's finding: a pre-commit `git add -A` swept the owner's + work into the lapse commit).""" + + def hook(self, b, name, body="#!/bin/sh\ngit add -A\n", where=None, mode=0o755): + d = where or (b.root / ".git/hooks") + d.mkdir(parents=True, exist_ok=True) + (d / name).write_text(body) + (d / name).chmod(mode) + + def test_a_pre_commit_hook_is_refused_with_head_index_and_files_unchanged(self): + b = self.box(extra={"notes/dirty.md": "base\n"}) + b.write("notes/dirty.md", "the owner's edit\n") + b.write("notes/untracked.md", "untracked\n") + self.hook(b, "pre-commit") + before = b.snapshot() + rc, out, err = b.lapse() + self.assertUnchanged(b, before, (rc, out, err)) + self.assertIn("pre-commit hook", err) + + def test_every_commit_hook_under_core_hookspath_is_refused(self): + for name in ("prepare-commit-msg", "commit-msg", "pre-merge-commit", "post-commit"): + with self.subTest(hook=name): + b = self.box() + self.hook(b, name, where=b.root / "githooks") + b.git("config", "core.hooksPath", "githooks") # relative to the checkout's top + before = b.snapshot() + rc, out, err = b.lapse() + self.assertUnchanged(b, before, (rc, out, err)) + self.assertIn(name + " hook", err) + + def test_a_hook_in_a_path_with_trailing_whitespace_is_refused(self): + b = self.box() + directory = "team hooks " + self.hook(b, "pre-commit", where=b.root / directory, body="#!/bin/sh\nexit 1\n") + b.git("config", "core.hooksPath", directory) + before = b.snapshot() + b.git("commit", "--allow-empty", "-qm", "the hook should reject this", check=False) + self.assertEqual(b.head(), before["head"]) + rc, out, err = b.lapse() + self.assertUnchanged(b, before, (rc, out, err)) + self.assertIn("pre-commit hook", err) + + def test_a_hook_that_is_not_executable_or_not_a_commit_hook_is_not_refused(self): + b = self.box() + self.hook(b, "pre-commit", mode=0o644) + self.hook(b, "pre-push") + rc, _o, err = b.lapse() + self.assertEqual(rc, 0, err) + self.assertEqual(b.changed_in_head(), sorted([ACTIVE, ARCHIVE])) + + def test_the_nothing_due_path_refuses_nothing(self): + b = self.box() + self.hook(b, "pre-commit") + rc, out, err = b.lapse(today="2026-12-01") + self.assertEqual(rc, 0, err) + + +class Unmigrated(Case): + LEGACY = "| Ruling date | Area | Ruling and why |\n|---|---|---|\n" + + def test_a_three_column_table_is_never_touched(self): + rows = ("| 2026-11-20 | Autonomy | Checkpoint mode, setup, review by 2026-12-01 |",) + b = self.box(rows=rows, table_head=self.LEGACY) + before = b.snapshot() + rc, out, err = b.lapse(today="2027-01-01") + self.assertEqual(rc, 0, err) + self.assertIn("not migrated", out) + self.assertEqual(b.snapshot(), before) + self.assertIsNone(b.notice()) + rc, _o, err = b.keep("2026-11-20", "Autonomy", today="2027-01-01") + self.assertEqual(rc, 1) + self.assertIn("not migrated", err) + self.assertEqual(b.snapshot(), before) + + def test_no_table_at_all_is_nothing_to_do(self): + b = self.box() + b.write(ACTIVE, "# Standing orders\n\nNo table yet.\n") + b.git("commit", "-q", "-am", "no table") + before = b.snapshot() + rc, out, _e = b.lapse() + self.assertEqual(rc, 0) + self.assertIn("no rulings table", out) + self.assertEqual(b.snapshot(), before) + + +class Interrupted(Case): + def test_a_kill_after_the_first_rename_is_undone_then_redone(self): + b = self.box() + before = b.snapshot() + rc, _o, _e = b.lapse(extra_env={"DESK_FAULT": "after-first-write"}) + self.assertEqual(rc, 70) + # the archive was written first: the row is in both files, never in neither + self.assertIn(SETUP_ROW, b.read(ACTIVE).decode()) + self.assertIn(SETUP_ROW, b.read(ARCHIVE).decode()) + self.assertIsNone(b.notice()) + self.assertEqual(b.head(), before["head"]) + rc, out, err = b.lapse() + self.assertEqual(rc, 0, err) + self.assertIn("interrupted lapse write", err) + self.assertEqual(b.commits(), int(b.git("rev-list", "--count", before["head"])) + 1) + self.assertNotIn(SETUP_ROW, b.read(ACTIVE).decode()) + self.assertEqual(b.read(ARCHIVE).decode().count(SETUP_ROW), 1) + self.assertEqual(len(b.notice()["events"]), 1) + self.assertEqual(b.git("status", "--porcelain"), "") + + def test_a_kill_before_the_commit_is_undone_even_when_nothing_looks_due(self): + b = self.box() + before = b.snapshot() + rc, _o, _e = b.lapse(extra_env={"DESK_FAULT": "before-commit"}) + self.assertEqual(rc, 70) + self.assertNotIn(SETUP_ROW, b.read(ACTIVE).decode()) # both renames done, nothing committed + self.assertIsNone(b.notice()) + # the next run sees no due row in the active file, but the journal sends it through recovery + rc, out, err = b.lapse() + self.assertEqual(rc, 0, err) + self.assertEqual(b.commits(), int(b.git("rev-list", "--count", before["head"])) + 1) + self.assertEqual(b.changed_in_head(), sorted([ACTIVE, ARCHIVE])) + self.assertEqual(b.git("status", "--porcelain"), "") + + def test_recovery_does_not_undo_a_write_during_an_owner_merge(self): + b = self.box() + tree = b.git("rev-parse", "HEAD^{tree}") + incoming = b.git("commit-tree", tree, "-p", "HEAD", "-m", "incoming") + self.assertEqual(b.lapse(extra_env={"DESK_FAULT": "before-commit"})[0], 70) + (b.root / ".git/index.lock").unlink() + b.git("merge", "--no-ff", "--no-commit", incoming) + before = b.snapshot() + + rc, _out, err = b.lapse() + self.assertEqual(rc, 1, err) + self.assertIn("a merge is in progress", err) + self.assertEqual(b.snapshot(), before) + self.assertTrue((b.state / "desk-write-journal.json").exists()) + + def test_a_missing_active_file_does_not_skip_recovery(self): + for command in (("lapse",), ("keep", "2026-11-20", "Autonomy")): + with self.subTest(command=command[0]): + b = self.box() + self.assertEqual(b.lapse(extra_env={"DESK_FAULT": "before-commit"})[0], 70) + (b.root / ACTIVE).unlink() + before = b.snapshot() + + rc, _out, err = b.desk(*command) + self.assertEqual(rc, 1, err) + self.assertIn("could not be undone", err) + self.assertEqual(b.snapshot(), before) + self.assertTrue((b.state / "desk-write-journal.json").exists()) + self.assertFalse((b.root / ".git/index.lock").exists()) + + def test_a_kill_after_the_commit_is_finished_and_its_notice_recovered(self): + b = self.box() + rc, _o, _e = b.lapse(extra_env={"DESK_FAULT": "after-commit"}) + self.assertEqual(rc, 70) + self.assertEqual(b.changed_in_head(), sorted([ACTIVE, ARCHIVE])) + self.assertIsNone(b.notice()) # killed before the receipt + # killed after update-ref and before the index update: desk's index.lock is left and the index + # still holds the old entries for the two paths + self.assertTrue((b.root / ".git/index.lock").exists()) + files = b.snapshot()["files"] + rc, out, err = b.lapse() + self.assertEqual(rc, 0, err) + self.assertIn("finished the index of commit", err) + self.assertEqual(b.snapshot()["files"], files) # recovery keeps the files + self.assertFalse((b.root / ".git/index.lock").exists()) + events = b.notice()["events"] + self.assertEqual(len(events), 1) + self.assertTrue(events[0]["id"].startswith("recovered-")) + self.assertEqual(events[0]["rows"], [{"date": "2026-11-20", "area": "Autonomy"}]) + self.assertFalse((b.state / "desk-write-journal.json").exists()) + self.assertEqual(b.git("status", "--porcelain"), "") + + def test_a_kill_after_commit_keeps_the_archive_when_git_normalizes_it(self): + b = self.box(extra={".gitattributes": "* text=auto eol=lf\n" + ACTIVE + " text eol=crlf\n"}) + (b.root / ACTIVE).unlink() + b.git("checkout-index", "-f", "-u", "--", ACTIVE) + self.assertIn(b"\r\n", b.read(ACTIVE)) + self.assertEqual(b.git("status", "--porcelain"), "") + self.assertEqual(b.lapse(extra_env={"DESK_FAULT": "after-commit"})[0], 70) + after_commit = b.snapshot() + self.assertIn(SETUP_ROW.encode() + b"\r\n", b.read(ARCHIVE)) + + rc, _out, err = b.lapse() + self.assertEqual(rc, 0, err) + after = b.snapshot() + self.assertEqual((after["files"], after["head"]), (after_commit["files"], after_commit["head"])) + self.assertEqual(after["status"], "") # the index finished, nothing to commit + self.assertTrue(b.notice()["events"][0]["id"].startswith("recovered-")) + + def test_recovery_preserves_an_archive_the_owner_staged_after_interruption(self): + b = self.box() + self.assertEqual(b.lapse(extra_env={"DESK_FAULT": "before-commit"})[0], 70) + b.git("add", ARCHIVE, check=False) + self.assertEqual(b.git("ls-files", ARCHIVE), "") # desk's index.lock stopped the add + (b.root / ".git/index.lock").unlink() # the owner follows git's advice + b.git("add", ARCHIVE) + staged = b.git("ls-files", "-s", ARCHIVE) + archive, head = b.read(ARCHIVE), b.head() + + rc, _out, err = b.lapse() + self.assertEqual(rc, 1, err) + self.assertIn("staged", err) + self.assertEqual(b.git("ls-files", "-s", ARCHIVE), staged) + self.assertEqual(b.read(ARCHIVE), archive) + self.assertEqual(b.head(), head) + self.assertTrue((b.state / "desk-write-journal.json").exists()) + + def test_recovery_keeps_the_archive_after_the_owner_commits_only_the_active_file(self): + b = self.box() + self.assertEqual(b.lapse(extra_env={"DESK_FAULT": "before-commit"})[0], 70) + (b.root / ".git/index.lock").unlink() # the owner follows git's advice + b.git("commit", "-q", "-m", "owner commit", "--only", "--", ACTIVE) + self.assertEqual(b.changed_in_head(), [ACTIVE]) + before = b.snapshot() + + rc, _out, err = b.lapse() + self.assertEqual(rc, 1, err) + self.assertIn("the branch moved since", err) + self.assertEqual(b.snapshot(), before) + self.assertIn(SETUP_ROW.encode(), b.read(ARCHIVE)) + self.assertTrue((b.state / "desk-write-journal.json").exists()) + + def test_after_a_kill_past_update_ref_an_entry_the_owner_staged_is_left_as_theirs(self): + b = self.box() + self.assertEqual(b.lapse(extra_env={"DESK_FAULT": "after-commit"})[0], 70) + (b.root / ".git/index.lock").unlink() # the owner follows git's advice + b.write(ACTIVE, b.read(ACTIVE) + b"the owner's staged edit\n") + b.git("add", ACTIVE) + before = b.snapshot() + rc, _o, err = b.lapse() + self.assertEqual(rc, 1, err) + self.assertIn("the index changed after desk started", err) + self.assertEqual(b.snapshot(), before) + self.assertTrue((b.state / "desk-write-journal.json").exists()) + + def test_recovery_cannot_replace_an_explicitly_staged_old_entry(self): + b = self.box() + self.assertEqual(b.lapse(extra_env={"DESK_FAULT": "after-commit"})[0], 70) + (b.root / ".git/index.lock").unlink() + # The owner explicitly selects the pre-lapse entry. Git rewrites the index, but the entry + # is byte-for-byte the one desk captured, even without a save to the working file. + captured_entry = b.git("ls-files", "-s", ACTIVE) + b.git("restore", "--staged", "--source=HEAD^", "--", ACTIVE) + self.assertEqual(b.git("ls-files", "-s", ACTIVE), captured_entry) + before = b.snapshot() + + rc, _out, err = b.lapse() + self.assertEqual(rc, 1, err) + self.assertIn("the index changed after desk started", err) + self.assertEqual(b.snapshot(), before) + self.assertTrue((b.state / "desk-write-journal.json").exists()) + + def test_recovery_does_not_clean_up_through_a_symlinked_parent(self): + b = self.box() + self.assertEqual(b.lapse(extra_env={"DESK_FAULT": "after-first-write"})[0], 70) + # The owner moved the directory and linked it back before retrying. The old temp name + # in the linked directory is outside this checkout. + context = b.root / "CONTEXT" + shared = b.outside / "shared-context" + context.rename(shared) + context.symlink_to(shared, target_is_directory=True) + sentinel = shared / ".standing-orders.md.desk-tmp" + sentinel.write_text("belongs to the owner\n") + + rc, _out, err = b.lapse() + self.assertEqual(rc, 1, err) + self.assertIn("is not a plain directory in the checkout", err) + self.assertEqual(sentinel.read_text(), "belongs to the owner\n") + self.assertTrue((b.state / "desk-write-journal.json").exists()) + + def test_an_owner_edit_after_an_interruption_is_never_overwritten(self): + b = self.box() + b.lapse(extra_env={"DESK_FAULT": "after-first-write"}) + b.write(ARCHIVE, "the owner rewrote this by hand\n") + rc, _o, err = b.lapse() + self.assertEqual(rc, 1) + self.assertIn("could not be undone", err) + self.assertEqual(b.read(ARCHIVE), b"the owner rewrote this by hand\n") + self.assertTrue((b.state / "desk-write-journal.json").exists()) + + +class Keep(Case): + def test_keep_before_the_date_makes_it_a_preference(self): + b = self.box() + old = b.read(ACTIVE).decode() + rc, out, err = b.keep("2026-11-20", "autonomy", today="2026-12-01") + self.assertEqual(rc, 0, err) + new_row = "| 2026-11-20 | Autonomy | Checkpoint mode: pause at each major step. | preference |" + self.assertEqual(b.read(ACTIVE).decode(), old.replace(SETUP_ROW, new_row)) + self.assertEqual(b.changed_in_head(), [ACTIVE]) + n = b.commits() + rc, out, err = b.keep("2026-11-20", "Autonomy", today="2026-12-01") + self.assertEqual(rc, 0, err) + self.assertIn("already a preference", out) + self.assertEqual(b.commits(), n) + self.assertEqual(b.lapse(today="2027-01-01")[0], 0) # never lapses now + self.assertIn(new_row, b.read(ACTIVE).decode()) + + def test_keep_after_the_lapse_restores_it_as_a_preference(self): + b = self.box() + self.assertEqual(b.lapse()[0], 0) + rc, out, err = b.keep("2026-11-20", "Autonomy", today="2026-12-06") + self.assertEqual(rc, 0, err) + self.assertIn("back in force", out) + active = b.read(ACTIVE).decode() + self.assertIn("| 2026-11-20 | Autonomy | Checkpoint mode: pause at each major step. | preference |\n", active) + self.assertTrue(active.endswith(OUTRO)) + arch = b.read(ARCHIVE).decode() + self.assertIn("- Restored: 2026-12-06, by desk keep\n", arch) + self.assertIn("~~~text\n" + SETUP_ROW + "\n~~~", arch) # the original stays in the archive + self.assertEqual(b.changed_in_head(), sorted([ACTIVE, ARCHIVE])) + n = b.commits() + rc, out, err = b.keep("2026-11-20", "Autonomy", today="2026-12-07") + self.assertEqual(rc, 0, err) + self.assertIn("already a preference", out) + self.assertEqual(b.commits(), n) + self.assertEqual(b.lapse(today="2027-01-01")[0], 0) # a preference never lapses + self.assertIn("Autonomy", b.read(ACTIVE).decode()) + + def test_keep_refuses_an_ambiguous_identity(self): + twin = "| 2026-11-20 | Autonomy | Another ruling, same identity. | preference |" + b = self.box(rows=(SETUP_ROW, twin)) + before = b.snapshot() + rc, _o, err = b.keep("2026-11-20", "Autonomy", today="2026-12-01") + self.assertEqual(rc, 1) + self.assertIn("more than one ruling", err) + self.assertEqual(b.snapshot(), before) + + def test_keep_of_an_unknown_identity_refuses(self): + b = self.box() + before = b.snapshot() + rc, _o, err = b.keep("2026-11-20", "Nothing like it") + self.assertEqual(rc, 1) + self.assertIn("no ruling is", err) + self.assertEqual(b.snapshot(), before) + + def test_keep_refuses_a_dirty_rulings_file(self): + b = self.box() + b.write(ACTIVE, b.read(ACTIVE) + b"edit\n") + before = b.snapshot() + rc, _o, err = b.keep("2026-11-20", "Autonomy", today="2026-12-01") + self.assertEqual(rc, 1) + self.assertEqual(b.snapshot(), before) + + +class NoticeAndCounts(Case): + def scan(self, b, today="2026-12-05", *args): + env = dict(b.env, DESK_TODAY=today) + p = subprocess.run([sys.executable, "-I", str(DESK), "--root", str(b.root), "--state-dir", str(b.state)] + + list(args), env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=120) + self.assertEqual(p.returncode, 0, p.stderr.decode()) + return p.stdout.decode() + + def test_one_event_per_lapse_and_a_fresh_scan_does_not_clear_it(self): + b = self.box() + self.assertEqual(b.lapse()[0], 0) + receipt = b.state / "desk-lapse-notice.json" + before = receipt.read_bytes() + rec = json.loads(before) + self.assertEqual(rec["root"], str(b.root)) + self.assertEqual(len(rec["events"]), 1) + ev = rec["events"][0] + self.assertEqual((ev["moved"], ev["commit"], ev["rows"]), + ("2026-12-05", b.head(), [{"date": "2026-11-20", "area": "Autonomy"}])) + self.scan(b, "2026-12-05", "--json") + self.assertEqual(receipt.read_bytes(), before) + self.assertEqual(b.lapse()[0], 0) # a second run adds nothing + self.assertEqual(receipt.read_bytes(), before) + + def test_counts_carry_rulings_lapsed_recent_for_seven_days(self): + b = self.box() + self.assertEqual(b.lapse()[0], 0) + rec = json.loads(self.scan(b, "2026-12-05", "--json")) + self.assertEqual(rec["counts"]["rulings_lapsed_recent"], 1) + view = json.loads(self.scan(b, "2026-12-11", "--counts")) + self.assertEqual(view["counts"]["rulings_lapsed_recent"], 1) + view = json.loads(self.scan(b, "2026-12-12", "--counts")) + self.assertEqual(view["counts"]["rulings_lapsed_recent"], 0) + # a restored ruling still lapsed in the period: the weekly line counts it + self.assertEqual(b.keep("2026-11-20", "Autonomy", today="2026-12-06")[0], 0) + self.assertEqual(json.loads(self.scan(b, "2026-12-06", "--counts"))["counts"]["rulings_lapsed_recent"], 1) + + def test_the_scan_no_longer_calls_a_lapsed_row_overdue(self): + b = self.box() + rec = json.loads(self.scan(b, "2026-12-05", "--json")) + self.assertEqual(rec["counts"]["rulings_setup_overdue"], 1) # the kind-cell form is read + self.assertEqual(rec["findings"]["rulings"]["no_kind"], []) + self.assertEqual(b.lapse()[0], 0) + rec = json.loads(self.scan(b, "2026-12-05", "--json")) + self.assertEqual(rec["counts"]["rulings_setup_overdue"], 0) + + +if __name__ == "__main__": + unittest.main(verbosity=2) diff --git a/.claude-config/bin/tests/desk-review-test.py b/.claude-config/bin/tests/desk-review-test.py new file mode 100644 index 0000000..556c211 --- /dev/null +++ b/.claude-config/bin/tests/desk-review-test.py @@ -0,0 +1,674 @@ +#!/usr/bin/env python3 +"""Behavior tests for the owner review in bin/desk: `desk review`, `desk commit-review`, `desk undo` +(clean desk piece D). + +Why pin it (AGENTS.md C1): commit-review rewrites a person's own rulings on their own box from their +answers, and undo rewrites them back. Changing a ruling the owner did not see, retiring a guardrail in +a batch, sweeping their other work into the commit, or an undo that overwrites a later edit would cost +them silently. Every case builds a throwaway box (a git repository) under a temp dir inside the sandbox; +nothing names the real checkout, and a sentinel file beside the box must survive every case. + +Covered: + * review: at most ten items in a deterministic order over thirteen candidates (setup, then overrides + of a default, absolute words, the worth-a-look collision, a dead reference, then size); a + guardrail shown alone with what it protects; read-only; answered items not shown again; + * the older layout (working-preferences.md, no table): its list items are the items, and a retire + archives the exact lines; + * the owner's layout (the table under "Standing orders" in how-i-work.md); + * a dead reference with a provable correction (one tracked file of that name) and without one; + * commit-review keep, narrow and retire: one commit of exactly the intended paths, with an unrelated + staged file, a dirty file and an untracked file untouched; the archive entry (original row, date, + reason `retired`, the owner's reason); + * refusals that change nothing: a stale item (its text changed since the review), a batch retire + that includes a guardrail (a single guardrail retire is accepted), a retire of a line that is not a + ruling, a malformed request (exit 2); + * undo: exact bytes back (existing archive), the created archive left with its header only, refused + after a later committed or uncommitted owner edit with that edit intact, twice is a no-op. + +Run: .claude-config/bin/sandbox-run --no-net --ro-bind -- python3 +""" +import os, runpy; runpy.run_path(os.path.join(os.path.dirname(os.path.realpath(__file__)), "..", "sandbox_guard.py"))["require"]() +import hashlib +import importlib.machinery +import importlib.util +import json +import shutil +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path + +DESK = Path(os.environ.get("DESK_UNDER_TEST") or Path(__file__).resolve().parent.parent / "desk") +ACTIVE = "CONTEXT/standing-orders.md" +ARCHIVE = "CONTEXT/standing-orders-archive.md" +LEGACY = "CONTEXT/working-preferences.md" +HEAD = "| Ruling date | Area | Ruling and why | Kind |\n|---|---|---|---|\n" +INTRO = "# Standing orders\n\nThe owner's rulings.\n\n" +OUTRO = "\nA closing paragraph the tool must never touch.\n" +SETUP_ROW = "| 2026-11-20 | Autonomy | Checkpoint mode: pause at each major step. | setup, review by 2026-12-04 |" +PREF_ROW = "| 2026-11-01 | Backups | Keep them nightly. | preference |" +GUARD_ROW = ("| 2026-11-02 | Remote | This box has no git remote; do not add one (protects: the backup " + "pushes elsewhere). | guardrail |") +OLD_ARCHIVE = ("# Standing orders archive\n\nAn existing archive the owner already has.\n\n### 2026-10-01 | Old\n\n" + "- Reason: lapsed\n- Moved: 2026-10-20\n- Original row:\n\n~~~text\n" + "| 2026-10-01 | Old | An old setup row. | setup, review by 2026-10-15 |\n~~~\n") + + +def sha(path): + return hashlib.sha256(Path(path).read_bytes()).hexdigest() + + +def load_desk(): + loader = importlib.machinery.SourceFileLoader("desk_review_mod", str(DESK)) + spec = importlib.util.spec_from_loader("desk_review_mod", loader) + mod = importlib.util.module_from_spec(spec) + loader.exec_module(mod) + return mod + + +class Box: + """A box: a git checkout with core.md and a rulings file, and a sentinel file beside it.""" + + def __init__(self, rows=(SETUP_ROW, PREF_ROW, GUARD_ROW), files=None, active=True): + self.tmp = Path(os.path.realpath(tempfile.mkdtemp(prefix="desk-review-"))) + self.root = self.tmp / "OPS" + self.home = self.tmp / "home" + self.state = self.tmp / "state" + self.outside = self.tmp / "outside" + for d in (self.root, self.home, self.outside): + d.mkdir() + self.gitcfg = self.tmp / "gitconfig" + self.gitcfg.write_text("[user]\n\tname = Desk Test\n\temail = desk@example.invalid\n" + "[init]\n\tdefaultBranch = main\n") + (self.outside / "sentinel.md").write_text("outside the box; must survive\n") + self.sentinel = sha(self.outside / "sentinel.md") + self.env = {"PATH": os.environ.get("PATH", "/usr/bin:/bin"), "HOME": str(self.home), "LC_ALL": "C", + "GIT_CONFIG_GLOBAL": str(self.gitcfg), "GIT_CONFIG_NOSYSTEM": "1", "DESK_TODAY": "2026-12-05", + "DESK_LOCK_WAIT": "1"} + self.git("init", "-q") + self.write("CONTEXT/core.md", "core\n") + if active: + self.write(ACTIVE, INTRO + HEAD + "".join(r + "\n" for r in rows) + OUTRO) + for rel, text in (files or {}).items(): + self.write(rel, text) + self.git("add", "-A") + self.git("commit", "-q", "-m", "box") + + def write(self, rel, text): + p = self.root / rel + p.parent.mkdir(parents=True, exist_ok=True) + p.write_bytes(text.encode() if isinstance(text, str) else text) + + def read(self, rel): + p = self.root / rel + return p.read_bytes() if p.exists() else None + + def git(self, *args, check=True): + p = subprocess.run(["git", "-C", str(self.root)] + list(args), env=self.env, stdout=subprocess.PIPE, + stderr=subprocess.PIPE) + if check and p.returncode != 0: + raise AssertionError("git %s failed: %s" % (args, p.stderr.decode())) + return p.stdout.decode().rstrip("\n") + + def desk(self, *args, stdin=None): + cmd = [sys.executable, "-I", str(DESK)] + list(args) + ["--root", str(self.root), "--state-dir", str(self.state)] + p = subprocess.run(cmd, cwd=str(self.tmp), env=self.env, input=(stdin or "").encode(), + stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=120) + return p.returncode, p.stdout.decode(), p.stderr.decode() + + def review(self, *extra): + rc, out, err = self.desk("review", "--json", *extra) + if rc != 0: + raise AssertionError("desk review failed: %s" % err) + return json.loads(out) + + def commit_review(self, answers): + return self.desk("commit-review", stdin=json.dumps({"answers": answers})) + + def undo(self): + return self.desk("undo") + + def head(self): + return self.git("rev-parse", "HEAD") + + def changed_in_head(self): + return sorted(self.git("diff-tree", "--no-commit-id", "--name-only", "-r", "HEAD").split()) + + def snapshot(self): + files = {} + for dirpath, dirnames, filenames in os.walk(self.root): + if ".git" in dirnames: + dirnames.remove(".git") + for n in filenames: + p = Path(dirpath) / n + files[str(p.relative_to(self.root))] = p.read_bytes() + return {"files": files, "index": self.git("ls-files", "-s"), "head": self.head(), + "status": self.git("status", "--porcelain=v1", "--untracked-files=all")} + + def owner_work(self): + """An unrelated staged file, a dirty tracked file and an untracked file, as an owner leaves them.""" + self.write("notes/staged.md", "staged by the owner\n") + self.write("notes/dirty.md", "committed\n") + self.git("add", "notes/dirty.md") + self.git("commit", "-q", "-m", "a tracked note") + self.write("notes/dirty.md", "edited, not committed\n") + self.git("add", "notes/staged.md") + self.write("notes/untracked.md", "never added\n") + + def owner_work_intact(self, tc): + tc.assertEqual(self.git("diff", "--cached", "--name-only"), "notes/staged.md") + tc.assertEqual(self.read("notes/dirty.md"), b"edited, not committed\n") + tc.assertEqual(self.read("notes/untracked.md"), b"never added\n") + st = self.git("status", "--porcelain=v1", "--untracked-files=all") + tc.assertIn("A notes/staged.md", st) + tc.assertIn(" M notes/dirty.md", st) + tc.assertIn("?? notes/untracked.md", st) + + +def item_for(rv, needle): + hits = [it for it in rv["items"] if needle in it["content"]] + assert len(hits) == 1, (needle, [it["content"] for it in rv["items"]]) + return hits[0] + + +class Case(unittest.TestCase): + maxDiff = None + + def box(self, **kw): + b = Box(**kw) + self.addCleanup(shutil.rmtree, b.tmp, True) + self.addCleanup(lambda: self.assertEqual(sha(b.outside / "sentinel.md"), b.sentinel, + "the outside sentinel changed")) + return b + + def assertRefusedUnchanged(self, box, before, result, words): + rc, out, err = result + self.assertEqual(rc, 1, out + err) + self.assertIn(words, err) + self.assertEqual(box.snapshot(), before) + self.assertFalse((box.state / "desk-write-journal.json").exists()) + + +# --------------------------------------------------------------------------------------------------- +# review + +RANK_ROWS = ( + "| 2026-11-21 | Plans | Show the plan first and wait. | setup, review by 2026-12-05 |", + "| 2026-11-22 | Steps | Pause at each step and say what comes next, in detail. | setup, review by 2026-12-06 |", + "| 2026-10-01 | Asks | This overrides the core.md default on asking first. | preference |", + "| 2026-10-02 | Lanes | This overrides the foreman.md default on lanes for every build here. | preference |", + "| 2026-10-03 | Tests | Always run the tests. | preference |", + "| 2026-10-04 | Fridays | Never push on a Friday afternoon after four. | preference |", + "| 2026-10-05 | Vault | Stay signed in to the vault (protects: the lockout of 2026-09-30). | guardrail |", + "| 2026-09-01 | P1 | Plain one. | preference |", + "| 2026-09-02 | P2 | Plain two, a little longer. | preference |", + "| 2026-09-03 | P3 | Plain three, longer again than two. | preference |", + "| 2026-09-04 | P4 | Plain four, the longest plain ruling of them all here. | preference |", + "| 2026-09-05 | P5 | Plain five, mid. | preference |", + "| 2026-09-06 | P6 | Plain six. | preference |", +) + + +class Review(Case): + def test_ten_items_in_a_deterministic_ranked_order(self): + # RED first: no `review` subcommand existed, so the scan rejected the argument (exit 2) + b = self.box(rows=RANK_ROWS) + before = b.snapshot() + first, second = b.review(), b.review() + self.assertEqual(first["candidates"], 13) + self.assertEqual(first["shown"], 10) + self.assertEqual(len(first["items"]), 10) + order = [it["area"] for it in first["items"]] + self.assertEqual(order, [it["area"] for it in second["items"]]) + self.assertEqual([it["id"] for it in first["items"]], [it["id"] for it in second["items"]]) + # setup (longer first), overrides, absolute words, then the rest largest first + self.assertEqual(order[:6], ["Steps", "Plans", "Lanes", "Asks", "Fridays", "Tests"]) + rest = [it for it in first["items"][6:]] + self.assertEqual([it["bytes"] for it in rest], sorted((it["bytes"] for it in rest), reverse=True)) + self.assertEqual([it["rank"] for it in first["items"]], list(range(1, 11))) + self.assertEqual(b.snapshot(), before) # read-only + self.assertFalse(b.state.exists()) # and writes no state + + def test_worth_a_look_and_dead_reference_order_between_absolute_and_size(self): + mod = load_desk() + + def it(area, nbytes, **flags): + f = {"setup": False, "overrides": False, "absolute": False, "worth_a_look": False, "dead_reference": False} + f.update(flags) + return {"flags": f, "bytes": nbytes, "file": "f", "line": nbytes, "content": area, "area": area} + items = [it("plain-big", 900), it("dead", 10, dead_reference=True), it("worth", 20, worth_a_look=True), + it("absolute", 30, absolute=True), it("override", 40, overrides=True), it("setup", 5, setup=True)] + ranked = [x["area"] for x in sorted(items, key=mod.review_key)] + self.assertEqual(ranked, ["setup", "override", "absolute", "worth", "dead", "plain-big"]) + + def test_a_guardrail_is_shown_alone_with_what_it_protects(self): + b = self.box() + g = item_for(b.review(), "no git remote") + self.assertEqual(g["kind"], "guardrail") + self.assertTrue(g["alone"]) + self.assertIn("protects: the backup pushes elsewhere", g["protects"]) + self.assertFalse(item_for(b.review(), "Keep them nightly")["alone"]) + rc, out, _e = b.desk("review") + self.assertIn("(answered alone)", out) + self.assertIn("protects:", out) + + def test_each_item_is_its_file_and_exact_content(self): + b = self.box() + s = item_for(b.review(), "Checkpoint mode") + self.assertEqual(s["file"], ACTIVE) + self.assertEqual(s["content"], SETUP_ROW) + self.assertEqual(s["content_sha256"], hashlib.sha256(SETUP_ROW.encode()).hexdigest()) + self.assertEqual(s["kind"], "setup") + self.assertEqual(s["review_by"], "2026-12-04") + self.assertEqual(s["answers"], ["keep", "narrow", "retire"]) + + def test_answered_items_are_not_shown_again(self): + b = self.box() + rc, _o, err = b.commit_review([{"file": ACTIVE, "content": PREF_ROW, "answer": "keep"}]) + self.assertEqual(rc, 0, err) + rv = b.review() + self.assertEqual(rv["already_answered"], 1) + self.assertNotIn(PREF_ROW, [it["content"] for it in rv["items"]]) + self.assertIn(PREF_ROW, [it["content"] for it in b.review("--all")["items"]]) + + def test_legacy_layout_lists_its_live_preference_lines(self): + prefs = ("# Working preferences\n\nThese are the rules of engagement; a paragraph, never an item.\n\n" + "## Before starting\n\n" + "1. **Read my context files first.** Every time,\n before anything else.\n" + "2. Use the task list for multi-step work.\n\n" + "```text\n- an example inside a fence, never an item\n```\n\n" + "\n\n---\n\n## Output\n\n" + "- Always save outputs in the project folder.\n") + b = self.box(active=False, files={LEGACY: prefs}) + rv = b.review() + self.assertEqual(rv["layout"], "working-preferences") + self.assertEqual(rv["source"]["format"], "legacy") + contents = [it["content"] for it in rv["items"]] + self.assertEqual(sorted(contents), sorted([ + "1. **Read my context files first.** Every time,\n before anything else.", + "2. Use the task list for multi-step work.", + "- Always save outputs in the project folder."])) + first = item_for(rv, "Always save") + self.assertEqual(first["rank"], 1) # absolute words outrank size + self.assertEqual(first["type"], "legacy_preference") + self.assertEqual(first["area"], "Output") + + def test_owner_layout_reads_the_standing_orders_table_in_how_i_work(self): + how = ("# How I work\n\n| Date | Other table | x |\n|---|---|---|\n| 2026-01-01 | not this | no |\n\n" + "## Standing orders\n\nIntro.\n\n| Ruling date | Owner | Distinct context |\n|---|---|---|\n" + "| 2026-12-01 | Every thread | Always say what changed. |\n" + "| 2026-11-01 | Lanes | Keep lanes small. |\n\n## Next section\n") + b = self.box(active=False, files={"CONTEXT/how-i-work.md": how, ".claude-config/ops-port-ref": "x\n"}) + rv = b.review() + self.assertEqual(rv["mode"], "owner") + self.assertEqual(rv["source"]["file"], "CONTEXT/how-i-work.md") + self.assertEqual([it["area"] for it in rv["items"]], ["Every thread", "Lanes"]) + self.assertIsNone(rv["items"][0]["kind"]) + + +class DeadReferences(Case): + def files(self): + return {"CLAUDE.md": "# Box\n\nRead `CONTEXT/old/guide.md` before work.\n\nFollow `CONTEXT/nowhere.md` too.\n", + "CONTEXT/guide.md": "the guide\n"} + + def test_a_provable_correction_and_none(self): + b = self.box(files=self.files()) + rv = b.review() + moved = item_for(rv, "CONTEXT/old/guide.md") + self.assertEqual(moved["type"], "dead_reference") + self.assertEqual(moved["answers"], ["keep", "narrow"]) + ref = moved["dead_references"][0] + self.assertEqual(ref["ref"], "CONTEXT/old/guide.md") + self.assertEqual(ref["correction"], {"ref": "CONTEXT/guide.md", + "content": "Read `CONTEXT/guide.md` before work."}) + gone = item_for(rv, "CONTEXT/nowhere.md") + self.assertIsNone(gone["dead_references"][0]["correction"]) + + def test_two_files_of_that_name_is_not_provable(self): + files = dict(self.files(), **{"SKILLS/x/guide.md": "another\n"}) + b = self.box(files=files) + self.assertIsNone(item_for(b.review(), "CONTEXT/old/guide.md")["dead_references"][0]["correction"]) + + def test_the_correction_commits_only_that_file(self): + b = self.box(files=self.files()) + b.owner_work() + moved = item_for(b.review(), "CONTEXT/old/guide.md") + rc, out, err = b.commit_review([{"file": "CLAUDE.md", "content": moved["content"], "answer": "narrow", + "text": moved["dead_references"][0]["correction"]["content"]}]) + self.assertEqual(rc, 0, err) + self.assertEqual(b.changed_in_head(), ["CLAUDE.md"]) + self.assertIn(b"Read `CONTEXT/guide.md` before work.\n", b.read("CLAUDE.md")) + b.owner_work_intact(self) + + def test_a_dead_reference_line_cannot_be_retired(self): + b = self.box(files=self.files()) + before = b.snapshot() + moved = item_for(b.review(), "CONTEXT/old/guide.md") + self.assertRefusedUnchanged(b, before, b.commit_review( + [{"file": "CLAUDE.md", "content": moved["content"], "answer": "retire", "reason": "x"}]), + "only a ruling can be retired") + + def test_a_dead_reference_in_a_ruling_is_attached_to_it(self): + row = "| 2026-11-03 | Docs | Read `CONTEXT/old/guide.md` first. | preference |" + b = self.box(rows=(PREF_ROW, row), files={"CONTEXT/guide.md": "the guide\n"}) + it = item_for(b.review(), "Read `CONTEXT/old/guide.md`") + self.assertEqual(it["type"], "ruling") + self.assertEqual(it["dead_references"][0]["correction"]["ref"], "CONTEXT/guide.md") + self.assertTrue(it["flags"]["dead_reference"]) + + +# --------------------------------------------------------------------------------------------------- +# commit-review + +class CommitReview(Case): + def test_keep_makes_a_setup_ruling_a_preference_and_commits_only_that_file(self): + b = self.box() + b.owner_work() + rc, out, err = b.commit_review([{"file": ACTIVE, "content": SETUP_ROW, "answer": "keep"}, + {"file": ACTIVE, "content": PREF_ROW, "answer": "keep"}]) + self.assertEqual(rc, 0, err) + self.assertEqual(b.changed_in_head(), [ACTIVE]) + active = b.read(ACTIVE).decode() + self.assertIn("| 2026-11-20 | Autonomy | Checkpoint mode: pause at each major step. | preference |", active) + self.assertIn(PREF_ROW, active) + self.assertIn("kept: 2026-11-20, Autonomy (setup, now a preference)", out) + self.assertIn("unchanged: 2026-11-01, Backups (kept as it is)", out) + msg = b.git("log", "-1", "--format=%B") + self.assertRegex(msg, r"\nDesk-Review: [0-9a-f]{12}\nDesk-Review-Path: CONTEXT/standing-orders.md$") + b.owner_work_intact(self) + + def test_keep_only_on_preferences_makes_no_commit(self): + b = self.box() + head = b.head() + rc, out, err = b.commit_review([{"file": ACTIVE, "content": PREF_ROW, "answer": "keep"}]) + self.assertEqual(rc, 0, err) + self.assertEqual(b.head(), head) + self.assertIn("nothing to change; no commit", out) + + def test_narrow_replaces_only_the_ruling_text(self): + b = self.box() + b.owner_work() + rc, out, err = b.commit_review([{"file": ACTIVE, "content": PREF_ROW, "answer": "narrow", + "text": "Keep them nightly, except | on weekends."}]) + self.assertEqual(rc, 0, err) + self.assertEqual(b.changed_in_head(), [ACTIVE]) + active = b.read(ACTIVE).decode() + self.assertIn("| 2026-11-01 | Backups | Keep them nightly, except \\| on weekends. | preference |", active) + self.assertNotIn(PREF_ROW, active) + self.assertIn(SETUP_ROW, active) + self.assertTrue(active.endswith(OUTRO)) + b.owner_work_intact(self) + + def test_retire_moves_the_row_to_a_new_archive_with_the_owners_reason(self): + b = self.box() + b.owner_work() + old_active = b.read(ACTIVE).decode() + rc, out, err = b.commit_review([{"file": ACTIVE, "content": PREF_ROW, "answer": "retire", + "reason": "Backups moved to the NAS job."}]) + self.assertEqual(rc, 0, err) + self.assertEqual(b.changed_in_head(), [ARCHIVE, ACTIVE]) + self.assertEqual(b.read(ACTIVE).decode(), old_active.replace(PREF_ROW + "\n", "")) + arch = b.read(ARCHIVE).decode() + self.assertTrue(arch.startswith("# Standing orders archive\n")) + self.assertIn("### 2026-11-01 | Backups\n\n- Reason: retired\n- Moved: 2026-12-05\n", arch) + self.assertIn("\n~~~text\n" + PREF_ROW + "\n~~~\n- Owner's reason: Backups moved to the NAS job.\n", arch) + b.owner_work_intact(self) + # C's parser still reads the archive, and the scan's lapsed count ignores a retire + entries = load_desk().parse_archive(arch) + self.assertEqual([(e["reason"], e["date"], e["area"]) for e in entries], [("retired", "2026-11-01", "Backups")]) + + def test_keep_narrow_and_retire_in_one_commit(self): + b = self.box(files={ARCHIVE: OLD_ARCHIVE}) + b.owner_work() + rc, out, err = b.commit_review([ + {"file": ACTIVE, "content": SETUP_ROW, "answer": "keep"}, + {"file": ACTIVE, "content": PREF_ROW, "answer": "retire", "reason": "No longer needed."}, + {"file": ACTIVE, "content": GUARD_ROW, "answer": "narrow", "text": "No git remote on this box."}]) + self.assertEqual(rc, 0, err) + self.assertEqual(b.changed_in_head(), [ARCHIVE, ACTIVE]) + self.assertTrue(b.read(ARCHIVE).decode().startswith(OLD_ARCHIVE)) + self.assertEqual(int(b.git("rev-list", "--count", "HEAD")), 3) + b.owner_work_intact(self) + + def test_retire_of_a_legacy_line_archives_its_exact_lines(self): + prefs = "# Prefs\n\n## Output\n\n- Save to the project.\n- Ask before\n sending anything.\n" + b = self.box(active=False, files={LEGACY: prefs}) + content = "- Ask before\n sending anything." + rc, out, err = b.commit_review([{"file": LEGACY, "content": content, "answer": "retire", "reason": "Done."}]) + self.assertEqual(rc, 0, err) + self.assertEqual(b.read(LEGACY).decode(), "# Prefs\n\n## Output\n\n- Save to the project.\n") + arch = b.read(ARCHIVE).decode() + self.assertIn("~~~markdown\n" + content + "\n~~~\n", arch) + self.assertIn("- Reason: retired\n", arch) + self.assertIn("- Owner's reason: Done.\n", arch) + self.assertEqual(len(load_desk().parse_archive(arch)), 1) + + def test_retire_cannot_strip_the_parent_rule_from_its_nested_list(self): + parent = "- Never restart these services:" + prefs = f"# Prefs\n\n{parent}\n - VPN during open hours.\n - Database during backups.\n" + b = self.box(active=False, files={LEGACY: prefs}) + before = b.snapshot() + self.assertRefusedUnchanged(b, before, b.commit_review( + [{"file": LEGACY, "content": parent, "answer": "retire", "reason": "No longer in force."}]), + "no longer a review item") + self.assertNotIn(parent, [it["content"] for it in b.review()["items"]]) + + def test_a_stale_item_is_refused(self): + # RED PROOF case: without the exact-content check the old text would be written over the edit + b = self.box() + stale = item_for(b.review(), "Keep them nightly")["content"] + b.write(ACTIVE, b.read(ACTIVE).decode().replace("Keep them nightly.", "Keep them nightly and weekly.")) + b.git("commit", "-q", "-am", "owner edits a ruling after the review") + before = b.snapshot() + self.assertRefusedUnchanged(b, before, b.commit_review( + [{"file": ACTIVE, "content": stale, "answer": "retire", "reason": "x"}]), "no longer in") + + def test_a_ruling_moved_to_a_fence_cannot_be_narrowed(self): + b = self.box() + item = item_for(b.review(), "Keep them nightly") + lines = b.read(ACTIVE).decode().replace(PREF_ROW + "\n", "") + b.write(ACTIVE, lines + "\n~~~text\n" + PREF_ROW + "\n~~~\n") + b.git("commit", "-q", "-am", "owner moves the ruling into an example") + before = b.snapshot() + self.assertRefusedUnchanged(b, before, b.commit_review( + [{"file": item["file"], "content": item["content"], "answer": "narrow", "text": "Weekly."}]), + "no longer a review item") + + def test_a_batch_retire_that_includes_a_guardrail_is_refused(self): + # RED PROOF case: a guardrail retires only alone + b = self.box() + before = b.snapshot() + self.assertRefusedUnchanged(b, before, b.commit_review([ + {"file": ACTIVE, "content": PREF_ROW, "answer": "retire", "reason": "x"}, + {"file": ACTIVE, "content": GUARD_ROW, "answer": "retire", "reason": "y"}]), + "a guardrail is retired only alone") + self.assertRefusedUnchanged(b, before, b.commit_review([ + {"file": ACTIVE, "content": PREF_ROW, "answer": "keep"}, + {"file": ACTIVE, "content": GUARD_ROW, "answer": "retire", "reason": "y"}]), + "a guardrail is retired only alone") + + def test_a_single_guardrail_retire_is_accepted(self): + b = self.box() + rc, out, err = b.commit_review([{"file": ACTIVE, "content": GUARD_ROW, "answer": "retire", + "reason": "The box has a backup remote now."}]) + self.assertEqual(rc, 0, err) + self.assertNotIn(GUARD_ROW, b.read(ACTIVE).decode()) + self.assertIn(GUARD_ROW, b.read(ARCHIVE).decode()) + + def test_a_dirty_rulings_file_is_refused(self): + b = self.box() + b.write(ACTIVE, b.read(ACTIVE) + b"an uncommitted owner line\n") + before = b.snapshot() + self.assertRefusedUnchanged(b, before, b.commit_review( + [{"file": ACTIVE, "content": PREF_ROW, "answer": "retire", "reason": "x"}]), "uncommitted or staged") + + def test_paths_outside_the_rules_are_refused(self): + b = self.box() + before = b.snapshot() + for rel in ("../outside/sentinel.md", ARCHIVE, "CONTEXT/core.md", ".git/config.md"): + self.assertRefusedUnchanged(b, before, b.commit_review( + [{"file": rel, "content": "core", "answer": "narrow", "text": "x"}]), rel) + + def test_a_malformed_request_is_a_usage_error(self): + b = self.box() + before = b.snapshot() + for raw in ("not json", json.dumps({"answers": []}), + json.dumps({"answers": [{"file": ACTIVE, "content": PREF_ROW, "answer": "drop"}]}), + json.dumps({"answers": [{"file": ACTIVE, "content": PREF_ROW, "answer": "retire"}]}), + json.dumps({"answers": [{"file": ACTIVE, "content": PREF_ROW, "answer": "narrow"}]})): + rc, _o, err = b.desk("commit-review", stdin=raw) + self.assertEqual(rc, 2, raw + err) + self.assertEqual(b.snapshot(), before) + + +# --------------------------------------------------------------------------------------------------- +# undo + +class Undo(Case): + def test_undo_refuses_a_commit_on_a_checkout_with_no_matching_review_record(self): + b = self.box() + self.assertEqual(b.commit_review( + [{"file": ACTIVE, "content": PREF_ROW, "answer": "narrow", "text": "Weekly."}])[0], 0) + # git commit -C reuses the review message when the owner adds a correction. + b.write(ACTIVE, b.read(ACTIVE) + b"\nThe owner added this paragraph.\n") + b.git("commit", "-q", "-a", "-C", "HEAD") + b.state = b.tmp / "other-checkout-state" + before = b.snapshot() + self.assertRefusedUnchanged(b, before, b.undo(), "no matching local review record") + + def test_undo_after_an_interrupted_next_review_keeps_the_previous_binding(self): + b = self.box() + original = b.read(ACTIVE) + self.assertEqual(b.commit_review( + [{"file": ACTIVE, "content": PREF_ROW, "answer": "narrow", "text": "Weekly."}])[0], 0) + b.env["DESK_FAULT"] = "before-commit" + self.assertEqual(b.commit_review([{"file": ACTIVE, "content": SETUP_ROW, "answer": "keep"}])[0], 70) + del b.env["DESK_FAULT"] + rc, out, err = b.undo() + self.assertEqual(rc, 0, out + err) + self.assertEqual(b.read(ACTIVE), original) + + def test_undo_can_prove_a_review_that_committed_before_its_state_was_finalized(self): + b = self.box() + original = b.read(ACTIVE) + b.env["DESK_FAULT"] = "after-commit" + self.assertEqual(b.commit_review( + [{"file": ACTIVE, "content": PREF_ROW, "answer": "narrow", "text": "Weekly."}])[0], 70) + del b.env["DESK_FAULT"] + rc, out, err = b.undo() + self.assertEqual(rc, 0, out + err) + self.assertEqual(b.read(ACTIVE), original) + + def test_undo_refuses_an_amended_review_with_only_pending_state(self): + b = self.box() + self.assertEqual(b.commit_review( + [{"file": ACTIVE, "content": PREF_ROW, "answer": "narrow", "text": "Weekly."}])[0], 0) + # Model a kill after CheckedWrite finished and before commit-review finalized the record. + path = b.state / "desk-review-last.json" + state = json.loads(path.read_text()) + path.write_text(json.dumps({**state, "status": "pending", "commit": None})) + b.write(ACTIVE, b.read(ACTIVE) + b"\nOwner's correction.\n") + b.git("commit", "-q", "-a", "--amend", "--no-edit") + before = b.snapshot() + self.assertRefusedUnchanged(b, before, b.undo(), "does not have the planned review bytes") + + def test_failed_archive_tree_read_is_not_an_absent_archive(self): + mod = load_desk() + mod.review_git = lambda *_args: (128, b"", "tree could not be read") + with self.assertRaisesRegex(mod.Refused, "tree could not be read"): + mod.blob_at("fixture", "a" * 40, ARCHIVE) + + def test_undo_restores_exact_bytes(self): + b = self.box(files={ARCHIVE: OLD_ARCHIVE}) + b.owner_work() + active, archive = b.read(ACTIVE), b.read(ARCHIVE) + rc, _o, err = b.commit_review([ + {"file": ACTIVE, "content": SETUP_ROW, "answer": "keep"}, + {"file": ACTIVE, "content": PREF_ROW, "answer": "retire", "reason": "x"}]) + self.assertEqual(rc, 0, err) + review = b.head() + rc, out, err = b.undo() + self.assertEqual(rc, 0, err) + self.assertIn("undone in commit", out) + self.assertEqual(b.read(ACTIVE), active) + self.assertEqual(b.read(ARCHIVE), archive) + self.assertEqual(b.git("rev-parse", "HEAD^"), review) + self.assertEqual(b.changed_in_head(), [ARCHIVE, ACTIVE]) + self.assertIn("Desk-Review-Undo: ", b.git("log", "-1", "--format=%B")) + b.owner_work_intact(self) + state = json.loads((b.state / "desk-review-last.json").read_text()) + self.assertEqual((state["status"], state["commit"], state["undone_by"]), ("undone", review, b.head())) + + def test_undo_leaves_an_archive_the_review_created_with_its_header_only(self): + b = self.box() + active = b.read(ACTIVE) + rc, _o, err = b.commit_review([{"file": ACTIVE, "content": PREF_ROW, "answer": "retire", "reason": "x"}]) + self.assertEqual(rc, 0, err) + rc, _o, err = b.undo() + self.assertEqual(rc, 0, err) + self.assertEqual(b.read(ACTIVE), active) + self.assertEqual(b.read(ARCHIVE).decode(), load_desk().ARCHIVE_HEADER) + + def test_undo_twice_is_a_no_op(self): + b = self.box() + rc, _o, err = b.commit_review([{"file": ACTIVE, "content": PREF_ROW, "answer": "narrow", "text": "Weekly."}]) + self.assertEqual(rc, 0, err) + self.assertEqual(b.undo()[0], 0) + before = b.snapshot() + rc, out, err = b.undo() + self.assertEqual(rc, 0, err) + self.assertIn("nothing to undo", out) + self.assertIn("already undone", out) + self.assertEqual(b.snapshot(), before) + + def test_undo_with_no_review_is_a_no_op(self): + b = self.box() + before = b.snapshot() + rc, out, err = b.undo() + self.assertEqual(rc, 0, err) + self.assertIn("nothing to undo", out) + self.assertEqual(b.snapshot(), before) + + def test_undo_refused_after_a_later_owner_commit_and_the_edit_survives(self): + b = self.box() + rc, _o, err = b.commit_review([{"file": ACTIVE, "content": PREF_ROW, "answer": "narrow", "text": "Weekly."}]) + self.assertEqual(rc, 0, err) + b.write(ACTIVE, b.read(ACTIVE) + b"\nThe owner's own later paragraph.\n") + b.git("commit", "-q", "-am", "owner: a later edit") + edited = b.read(ACTIVE) + before = b.snapshot() + rc, out, err = b.undo() + self.assertEqual(rc, 1, out + err) + self.assertIn("CONTEXT/standing-orders.md changed since the review", err) + self.assertIn("owner: a later edit", err) + self.assertEqual(b.snapshot(), before) + self.assertEqual(b.read(ACTIVE), edited) + + def test_undo_refused_over_an_uncommitted_owner_edit(self): + b = self.box() + rc, _o, err = b.commit_review([{"file": ACTIVE, "content": PREF_ROW, "answer": "narrow", "text": "Weekly."}]) + self.assertEqual(rc, 0, err) + b.write(ACTIVE, b.read(ACTIVE) + b"pending owner work\n") + before = b.snapshot() + rc, out, err = b.undo() + self.assertEqual(rc, 1, out + err) + self.assertIn("uncommitted or staged", err) + self.assertEqual(b.snapshot(), before) + + def test_undo_ignores_an_unrelated_later_commit(self): + b = self.box() + active = b.read(ACTIVE) + rc, _o, err = b.commit_review([{"file": ACTIVE, "content": PREF_ROW, "answer": "narrow", "text": "Weekly."}]) + self.assertEqual(rc, 0, err) + b.write("notes/later.md", "unrelated\n") + b.git("add", "notes/later.md") + b.git("commit", "-q", "-m", "unrelated") + rc, _o, err = b.undo() + self.assertEqual(rc, 0, err) + self.assertEqual(b.read(ACTIVE), active) + self.assertEqual(b.read("notes/later.md"), b"unrelated\n") + + +if __name__ == "__main__": + unittest.main() diff --git a/.claude-config/bin/tests/desk-test.py b/.claude-config/bin/tests/desk-test.py new file mode 100644 index 0000000..9b8be74 --- /dev/null +++ b/.claude-config/bin/tests/desk-test.py @@ -0,0 +1,967 @@ +#!/usr/bin/env python3 +"""Behavior tests for bin/desk, the read-only check of the AI context on a box. + +desk reports only what it can prove, and its one-line result reaches every teammate's session +briefing, so a false alarm or a false "clean" costs the whole team's trust in it. These cases +test the rules a wrong desk would break: + + * the stale-core proof: the five shared proof cases (the same list the team sync's suite + replays), plus current, the owner's box, and a pin supplied by a controller; + * dead references: a required missing path, an exact retired model id and a missing skill are + found; examples, optional paths, placeholders, bans, history and on-demand folders are not; + * rulings: kinds, review dates at their boundary, the unmigrated table, worth a look; + * duplicate memory pools, and that memory never reaches the briefing line or the counts; + * both older layouts and an unknown one: recognized or unread, never a crash, never "clean"; + * the cache: atomic, stale after 8 days, another root's ignored, a failed scan leaves the + last success alone, counts-only never writes; + * read-only: no write into the checkout, no fetch, no remote, and no import from the repo. + +Every case runs the real script against fixture trees under a temp dir (a fake template git +repo with history, boxes cloned from it, a fake HOME). The environment is rebuilt from scratch, +so nothing reads the real ~ or the real checkout. desk lapse and desk keep move rulings between +files (tests/desk-lapse-test.py covers them), so this suite runs inside sandbox-run too (the guard +below, AGENTS.md C1): the daily-sync cases here run the lapse stage. +""" +import os, runpy; runpy.run_path(os.path.join(os.path.dirname(os.path.realpath(__file__)), "..", "sandbox_guard.py"))["require"]() +import ast +import hashlib +import importlib.machinery +import importlib.util +import json +import os +import shutil +import stat +import subprocess +import sys +import tempfile +import time +import unittest +from pathlib import Path + +# DESK_UNDER_TEST points the suite at a mutated copy (the injected-defect run); unset in the gate. +DESK = Path(os.environ.get("DESK_UNDER_TEST") or Path(__file__).resolve().parent.parent / "desk") +NOW = "2026-12-04" # the date every case pretends it is + + +def sh(cmd, cwd=None, env=None, check=True): + p = subprocess.run(cmd, cwd=cwd, env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE) + if check and p.returncode != 0: + raise AssertionError("%s failed: %s" % (cmd, p.stderr.decode())) + return p + + +GIT_ENV = {"PATH": os.environ.get("PATH", "/usr/bin:/bin"), "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_CONFIG_SYSTEM": os.devnull, "GIT_AUTHOR_NAME": "t", "GIT_AUTHOR_EMAIL": "t@example.invalid", + "GIT_COMMITTER_NAME": "t", "GIT_COMMITTER_EMAIL": "t@example.invalid", "HOME": "/nonexistent"} + + +def git(repo, *args, date=None, check=True): + env = dict(GIT_ENV) + if date: + env["GIT_AUTHOR_DATE"] = env["GIT_COMMITTER_DATE"] = date + return sh(["git", "-C", str(repo)] + list(args), env=env, check=check).stdout.decode().strip() + + +def write(path, text, mode=None): + path = Path(path) + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(text.encode() if isinstance(text, str) else text) + if mode: + path.chmod(mode) + + +# --- the template fixture: one core file, three template commits, edits far apart ------------------- + +def base_lines(): + return ["paragraph %02d: stable template text that no edit touches" % i for i in range(1, 25)] + + +EDITS = {"A": (2, "paragraph 03: EDIT A from the first template commit"), + "B": (11, "paragraph 12: EDIT B from the second template commit"), + "C": (20, "paragraph 21: EDIT C from the third template commit")} + + +def doc(*edits, extra=None): + lines = base_lines() + for e in edits: + idx, text = EDITS[e] + lines[idx] = text + if extra: + lines.append(extra) + return "\n".join(lines) + "\n" + + +class Template: + """A template repo: V0 = base, V1 = +A, V2 = +A+B, V3 = +A+B+C (the pin).""" + + def __init__(self, root): + self.path = Path(root) / "template" + self.path.mkdir() + git(self.path, "init", "-q", "-b", "main") + self.commits = [] + for n, edits in enumerate([(), ("A",), ("A", "B"), ("A", "B", "C")]): + write(self.path / "CONTEXT/core.md", doc(*edits)) + write(self.path / "CONTEXT/foreman.md", "foreman doctrine\n") + write(self.path / "CONTEXT/how-i-work.md", "how i work\n") + git(self.path, "add", "-A") + git(self.path, "commit", "-q", "-m", "v%d" % n, date="2026-11-%02dT12:00:00+00:00" % (10 + n * 5)) + self.commits.append(git(self.path, "rev-parse", "HEAD")) + self.pin = self.commits[-1] + + +class DeskCase(unittest.TestCase): + maxDiff = None + + def setUp(self): + self.tmp = Path(tempfile.mkdtemp(prefix="desk-test-")) + self.home = self.tmp / "home" + self.home.mkdir() + self.state = self.tmp / "state" + self.addCleanup(shutil.rmtree, self.tmp, True) + + # -- helpers + def env(self, **extra): + env = {"PATH": os.environ.get("PATH", "/usr/bin:/bin"), "HOME": str(self.home), "LC_ALL": "C", + "DESK_TODAY": NOW} + env.update(extra) + return env + + def desk(self, root, *args, extra_env=None, cwd=None, python_flags=("-I",)): + cmd = [sys.executable] + list(python_flags) + [str(DESK), "--root", str(root)] + list(args) + p = subprocess.run(cmd, cwd=str(cwd or self.tmp), env=self.env(**(extra_env or {})), + stdout=subprocess.PIPE, stderr=subprocess.PIPE) + return p.returncode, p.stdout.decode(), p.stderr.decode() + + def scan(self, root, *args, extra_env=None): + rc, out, err = self.desk(root, "--json", "--cache", str(self.state / "c.json"), *args, extra_env=extra_env) + self.assertEqual(rc, 0, err) + return json.loads(out) + + def box(self, tpl, core_text, layout="standing-orders", extra=None, pin=None): + """A team box cloned from the template, with its own core.md committed on top.""" + root = self.tmp / ("box%d" % len(list(self.tmp.glob("box*")))) + sh(["git", "clone", "-q", "--no-hardlinks", str(tpl.path), str(root)], env=GIT_ENV) + write(root / "CONTEXT/core.md", core_text) + write(root / ".claude-config/ops-upstream-ref", "upstream=example/tpl\nlast_synced=%s\n" % (pin or tpl.pin)) + if layout == "standing-orders": + write(root / "CONTEXT/standing-orders.md", + "# Standing orders\n\n| Ruling date | Area | Ruling and why | Kind |\n|---|---|---|---|\n") + elif layout == "working-preferences": + write(root / "CONTEXT/working-preferences.md", "# Working preferences\n") + for rel, text in (extra or {}).items(): + write(root / rel, text) + git(root, "add", "-A") + git(root, "commit", "-q", "-m", "local state") + return root + + def plain_root(self, files, owner=False, at=None): + """A harness tree with no git: enough for every check except the stale-core proof, which a team + box with no pin reports as unread. owner=True marks the owner's box, where that check does not apply.""" + root = Path(at) if at else self.tmp / ("plain%d" % len(list(self.tmp.glob("plain*")))) + for rel, text in files.items(): + write(root / rel, text) + if owner: + write(root / ".claude-config/ops-port-ref", "ops_commit=x\n") + return root + + def core_state(self, rec, rel="CONTEXT/core.md"): + return next(r for r in rec["core"] if r["path"] == rel) + + +class StaleCoreProof(DeskCase): + """The five proof cases shared with the team sync's suite, plus the cases around them.""" + + def setUp(self): + super().setUp() + self.tpl = Template(self.tmp) + + def test_current_file_is_not_stale(self): + rec = self.scan(self.box(self.tpl, doc("A", "B", "C"))) + self.assertEqual(self.core_state(rec)["state"], "current") + self.assertEqual(rec["findings"]["stale_core"], []) + + def test_case1_local_equals_an_older_template_version(self): + rec = self.scan(self.box(self.tpl, doc("A"))) + st = self.core_state(rec) + self.assertEqual((st["state"], st["match"]), ("stale", "older_version")) + self.assertEqual(st["template_commit"], self.tpl.commits[1]) + self.assertEqual(rec["counts"]["stale_core"], 1) + + def test_case2_older_version_with_one_later_patch_replayed_is_proven(self): + # the 2026-12-02 shape: the box was behind, and one template change was copied in by hand + rec = self.scan(self.box(self.tpl, doc("C"))) + st = self.core_state(rec) + self.assertEqual((st["state"], st["match"]), ("stale", "rebuild")) + self.assertEqual(st["template_commit"], self.tpl.commits[3]) + self.assertEqual(st["base_commit"], self.tpl.commits[0]) + + def test_case3_proven_shape_plus_one_line_no_version_holds_is_not_proven(self): + rec = self.scan(self.box(self.tpl, doc("C", extra="a line the owner added"))) + self.assertEqual(self.core_state(rec)["state"], "unresolved") + self.assertEqual(rec["findings"]["stale_core"], []) + self.assertEqual(rec["counts"]["stale_core"], 0) + self.assertEqual(rec["counts"]["unresolved_core"], 1) + self.assertEqual(rec["line"], "") # an owner edit is possible, so the briefing says nothing + + def test_case4_needing_two_separate_later_patches_is_not_proven(self): + rec = self.scan(self.box(self.tpl, doc("B", "C"))) + self.assertEqual(self.core_state(rec)["state"], "unresolved") + self.assertEqual(rec["counts"]["stale_core"], 0) + + def test_case5_history_that_cannot_be_read_is_unread_never_stale(self): + # a checkout that holds no template objects at all: the pin names a commit it does not have + root = self.tmp / "noobjects" + write(root / "CONTEXT/core.md", doc("A")) + write(root / "CONTEXT/standing-orders.md", "# s\n") + write(root / ".claude-config/ops-upstream-ref", "last_synced=%s\n" % self.tpl.pin) + git(root.parent, "init", "-q", str(root)) + git(root, "add", "-A") + git(root, "commit", "-q", "-m", "x") + rec = self.scan(root) + self.assertEqual(self.core_state(rec)["state"], "unread") + self.assertEqual(rec["counts"]["stale_core"], 0) + self.assertEqual(rec["coverage"]["status"], "incomplete") + self.assertTrue(any(u["check"] == "stale_core" and "never fetches" in u["reason"] for u in rec["coverage"]["unread"])) + self.assertIn("not checked", rec["line"]) + self.assertIn("not a clean result", rec["line"]) + + def test_case5b_a_shallow_checkout_is_unread(self): + shallow = self.tmp / "shallow" + sh(["git", "clone", "-q", "--depth", "1", "file://%s" % self.tpl.path, str(shallow)], env=GIT_ENV) + write(shallow / "CONTEXT/core.md", doc("A")) + write(shallow / ".claude-config/ops-upstream-ref", "last_synced=%s\n" % self.tpl.pin) + write(shallow / "CONTEXT/standing-orders.md", "# s\n") + git(shallow, "add", "-A") + git(shallow, "commit", "-q", "-m", "local") + rec = self.scan(shallow) + st = self.core_state(rec) + self.assertEqual(st["state"], "unread") + self.assertIn("shallow", st["reason"]) + + def test_no_pin_is_unread(self): + root = self.box(self.tpl, doc("A")) + os.unlink(root / ".claude-config/ops-upstream-ref") + rec = self.scan(root) + self.assertEqual(self.core_state(rec)["state"], "unread") + self.assertEqual(rec["pin"]["source"], "none") + + def test_a_controller_pin_wins_over_the_marker(self): + root = self.box(self.tpl, doc("A", "B")) + rec = self.scan(root, "--pin", self.tpl.commits[2]) + self.assertEqual(self.core_state(rec)["state"], "current") + self.assertEqual(rec["pin"], {"sha": self.tpl.commits[2], "source": "supplied"}) + rec = self.scan(root, extra_env={"DESK_PIN": self.tpl.commits[2]}) + self.assertEqual(self.core_state(rec)["state"], "current") + + def test_a_malformed_pin_is_refused_without_a_scan(self): + rc, _out, err = self.desk(self.box(self.tpl, doc("A")), "--pin", "not-a-sha", "--cache", str(self.state / "c.json")) + self.assertEqual(rc, 1) + self.assertIn("pin", err) + self.assertFalse((self.state / "c.json").exists()) + + def test_untracked_core_is_unread(self): + root = self.box(self.tpl, doc("A")) + git(root, "rm", "-q", "--cached", "CONTEXT/core.md") + git(root, "commit", "-q", "-m", "untrack") + rec = self.scan(root) + self.assertEqual(self.core_state(rec)["state"], "unread") + self.assertIn("not tracked", self.core_state(rec)["reason"]) + + def test_symlinked_core_is_unread(self): + root = self.box(self.tpl, doc("A")) + real = root / "CONTEXT/core-real.md" + shutil.move(str(root / "CONTEXT/core.md"), str(real)) + os.symlink(real, root / "CONTEXT/core.md") + rec = self.scan(root) + self.assertEqual(self.core_state(rec)["state"], "unread") + + def test_the_owner_box_has_no_stale_core_check(self): + root = self.box(self.tpl, doc("A")) + write(root / ".claude-config/ops-port-ref", "ops_commit=%s\n" % self.tpl.pin) + rec = self.scan(root) + self.assertEqual(rec["mode"], "owner") + self.assertEqual({r["state"] for r in rec["core"]}, {"not_applicable"}) + self.assertEqual(rec["findings"]["stale_core"], []) + self.assertEqual(rec["pin"]["sha"], None) + + def test_the_proof_does_not_touch_the_checkout(self): + root = self.box(self.tpl, doc("C")) + before = tree_state(root) + self.scan(root) + self.assertEqual(tree_state(root), before) + self.assertEqual(git(root, "status", "--porcelain"), "") + + def test_a_missing_core_file_is_not_applicable(self): + root = self.box(self.tpl, doc("A")) + os.unlink(root / "CONTEXT/how-i-work.md") + rec = self.scan(root) + self.assertEqual(self.core_state(rec, "CONTEXT/how-i-work.md")["state"], "not_applicable") + + +def tree_state(root): + """Every path under root with size and mtime, .git included: a read must leave this unchanged.""" + out = {} + for dirpath, dirnames, filenames in os.walk(root): + for name in filenames + dirnames: + p = os.path.join(dirpath, name) + st = os.lstat(p) + out[p] = (st.st_size, st.st_mtime_ns, stat.S_IFMT(st.st_mode)) + return out + + +class DeadReferences(DeskCase): + CORE = "\n".join([ + "# Core", + "The doctrine lives in `CONTEXT/missing-required.md` and nowhere else.", + "Read `CONTEXT/present.md` first.", + "Example only: write the note to `CONTEXT/example-missing.md`.", + "```", + "cat CONTEXT/in-a-fence.md", + "```", + "| Machines | `CONTEXT/machines.md` (when the Operator keeps one) |", + "If that file exists, read `CONTEXT/maybe.md`.", + "Lessons go to `CONTEXT/projects/-lessons.md`.", + "Notes land in `NOTES/MASTER/anything.md`.", + "A link [the plan](plan-missing.md) points nowhere.", + "The old layout kept `CONTEXT/was-removed.md`, which was removed in 2026.", + "", + "Pin the lane to `claude-sonnet-5[1m]` for builds.", + "Banned everywhere: Opus 5 (the exact id `claude-opus-5`, not 5.5).", + "The current foreman is `claude-opus-5-5[1m]`.", + "Cheap reading runs on `claude-haiku-5-5` only.", + "Cheap lanes pin `claude-haiku-4-5-20251001` for summaries.", + "Use `claude-haiku-4-5` for summaries.", + "Follow the `ghost` skill for intake.", + "Follow the `present-skill` skill for intake.", + "The `draft-skill` skill is a draft and not built yet.", + ]) + "\n" + + def root(self, extra=None): + files = {"CONTEXT/core.md": self.CORE, "CONTEXT/present.md": "x\n", + "SKILLS/present-skill/SKILL.md": "---\nname: present-skill\n---\n"} + files.update(extra or {}) + return self.plain_root(files) + + def refs(self, rec): + return {(d["kind"], d["ref"]) for d in rec["findings"]["dead_references"]} + + def test_finds_what_is_provably_dead(self): + refs = self.refs(self.scan(self.root())) + self.assertIn(("missing_path", "CONTEXT/missing-required.md"), refs) + self.assertIn(("missing_path", "plan-missing.md"), refs) + self.assertIn(("retired_model", "claude-sonnet-5"), refs) + self.assertIn(("retired_model", "claude-haiku-4-5"), refs) + self.assertIn(("retired_model", "claude-haiku-4-5-20251001"), refs) # the dated form is its own id + self.assertIn(("missing_skill", "ghost"), refs) + + def test_leaves_examples_optional_paths_and_history_alone(self): + refs = {r for _k, r in self.refs(self.scan(self.root()))} + for quiet in ("CONTEXT/example-missing.md", "CONTEXT/in-a-fence.md", "CONTEXT/machines.md", "CONTEXT/maybe.md", + "CONTEXT/was-removed.md", "CONTEXT/in-a-comment.md", "CONTEXT/present.md", + "NOTES/MASTER/anything.md", "draft-skill", "present-skill"): + self.assertNotIn(quiet, refs) + self.assertFalse([r for r in refs if "lessons" in r]) # a placeholder is not a path + + def test_a_ban_is_not_a_use_and_the_allowed_ids_are_not_flagged(self): + refs = {r for _k, r in self.refs(self.scan(self.root()))} + self.assertNotIn("claude-opus-5", refs) # "Banned everywhere: ... not 5.5" + self.assertNotIn("claude-opus-5-5", refs) # the boundary rule: -5-5 is the current id + self.assertNotIn("claude-haiku-5-5", refs) + + def test_findings_carry_file_and_line(self): + rec = self.scan(self.root()) + hit = next(d for d in rec["findings"]["dead_references"] if d["ref"] == "CONTEXT/missing-required.md") + self.assertEqual((hit["file"], hit["line"]), ("CONTEXT/core.md", 2)) + self.assertEqual(rec["counts"]["dead_references"], len(rec["findings"]["dead_references"])) + self.assertIn("dead reference", rec["line"]) + + def test_the_retired_list_comes_from_model_roles(self): + roles = ("| Role | Model | Id | How |\n|---|---|---|---|\n" + "| Retired | Old One | `claude-test-9`; `claude-opus-4-8` | pinned nowhere |\n" + "| Banned | Opus 5; every Haiku except 5.5 | `claude-opus-5` (the exact id); every haiku id except " + "`claude-haiku-5-5` | see Bans |\n") + core = "Pin builds to `claude-test-9` today.\nPin builds to `claude-sonnet-5` today.\n" + rec = self.scan(self.root({"CONTEXT/model-roles.md": roles, "CONTEXT/core.md": core})) + refs = {r for _k, r in self.refs(rec)} + self.assertIn("claude-test-9", refs) + self.assertNotIn("claude-sonnet-5", refs) # not in this fixture's Retired row + self.assertEqual(rec["coverage"]["checks"]["dead_references"]["model_list"], "model-roles.md") + + def test_without_model_roles_the_builtin_list_is_used_and_says_so(self): + rec = self.scan(self.root()) + self.assertEqual(rec["coverage"]["checks"]["dead_references"]["model_list"], "builtin") + self.assertTrue(any("built-in list" in n for n in rec["coverage"]["notes"])) + + def test_imports_are_followed_and_unresolved_ones_are_honest(self): + glob = self.home / ".claude/CLAUDE.md" + write(glob, "@~/OPS/CONTEXT/imported.md\n@~/COWORK/CONTEXT/gone.md\n") + write(self.home / "OPS/CONTEXT/imported.md", "Pin `claude-sonnet-5` here.\n") + rec = self.scan(self.root()) + self.assertTrue(any(d["file"].endswith("imported.md") for d in rec["findings"]["dead_references"])) + unread = [u for u in rec["coverage"]["unread"] if u["check"] == "always_loaded"] + self.assertTrue(any("gone.md" in u["reason"] for u in unread)) # no fallback named: unread + self.assertIn("not checked", rec["line"]) + + def test_an_unresolved_import_with_a_named_fallback_is_a_note_not_unread(self): + write(self.home / ".claude/CLAUDE.md", + "@~/COWORK/CONTEXT/core.md\nIf that is unavailable read ~/OPS/CONTEXT/core.md if it exists.\n") + write(self.home / "OPS/CONTEXT/core.md", "x\n") + rec = self.scan(self.root()) + self.assertFalse([u for u in rec["coverage"]["unread"] if u["check"] == "always_loaded"]) + self.assertTrue(any("fallback" in n for n in rec["coverage"]["notes"])) + + def test_a_named_fallback_that_is_absent_is_still_unread(self): + write(self.home / ".claude/CLAUDE.md", + "@~/COWORK/CONTEXT/core.md\nIf that is unavailable read ~/OPS/CONTEXT/core.md if it exists.\n") + rec = self.scan(self.root()) # ~/OPS/CONTEXT/core.md is not there either + unread = [u for u in rec["coverage"]["unread"] if u["check"] == "always_loaded"] + self.assertTrue(any("core.md" in u["reason"] for u in unread)) + + def test_a_broken_rules_link_is_a_dead_reference_and_a_live_one_is_loaded(self): + # a team box loads core through ~/.claude/rules/ops-core.md; a link whose target is gone means + # sessions start without it (found on a team box 2026-11-16), so it is never passed over as clean + rules = self.home / ".claude/rules" + rules.mkdir(parents=True) + os.symlink(str(self.home / "OPS/CONTEXT/core.md"), rules / "ops-core.md") # target absent + write(self.home / "elsewhere/extra.md", "Pin `claude-sonnet-5` here.\n") + os.symlink(str(self.home / "elsewhere/extra.md"), rules / "extra.md") + rec = self.scan(self.root()) + broken = [d for d in rec["findings"]["dead_references"] if d["kind"] == "broken_link"] + self.assertEqual([(d["file"], d["ref"]) for d in broken], + [("~/.claude/rules/ops-core.md", str(self.home / "OPS/CONTEXT/core.md"))]) + self.assertTrue(any(d["kind"] == "retired_model" and d["file"].endswith("extra.md") + for d in rec["findings"]["dead_references"])) # the live link was read + self.assertIn("dead reference", rec["line"]) + self.assertIn("broken link", self.desk(rec["root"], "--no-cache")[1]) + + def test_an_unreadable_rules_folder_is_unread(self): + if os.geteuid() == 0: + self.skipTest("root reads everything") + rules = self.home / ".claude/rules" + rules.mkdir(parents=True) + os.chmod(rules, 0) + self.addCleanup(os.chmod, rules, 0o755) + rec = self.scan(self.root()) + self.assertTrue(any(u["check"] == "always_loaded" and "rules" in u["subject"] for u in rec["coverage"]["unread"])) + self.assertIn("not checked", rec["line"]) + + def test_an_unreadable_file_is_unread_not_clean(self): + if os.geteuid() == 0: + self.skipTest("root reads everything") + root = self.root({"AGENTS.md": "text\n"}) + os.chmod(root / "AGENTS.md", 0) + self.addCleanup(os.chmod, root / "AGENTS.md", 0o644) + rec = self.scan(root) + self.assertTrue(any("AGENTS.md" in u["subject"] for u in rec["coverage"]["unread"])) + self.assertEqual(rec["coverage"]["status"], "incomplete") + + def test_a_clean_tree_has_an_empty_line(self): + rec = self.scan(self.plain_root({"CONTEXT/core.md": "Plain text with `CONTEXT/core.md` in it.\n", + "CONTEXT/standing-orders.md": "# s\n"})) + self.assertEqual(rec["findings"]["dead_references"], []) + self.assertEqual(rec["counts"]["dead_references"], 0) + + +class Rulings(DeskCase): + HEAD = "| Ruling date | Area | Ruling and why | Kind |\n|---|---|---|---|\n" + + def rec(self, table, extra=None): + files = {"CONTEXT/standing-orders.md": "# Standing orders\n\n" + table} + files.update(extra or {}) + tpl = getattr(self, "_tpl", None) or Template(self.tmp) + self._tpl = tpl + return self.scan(self.box(tpl, doc("A", "B", "C"), extra=files)) + + def test_rows_without_a_valid_kind_are_found(self): + rec = self.rec(self.HEAD + "| 2026-11-01 | Backups | Keep them. | preference |\n" + "| 2026-11-02 | Plans | Show the plan. | |\n" + "| 2026-11-03 | Odd | Something. | whatever |\n") + self.assertEqual([r["line"] for r in rec["findings"]["rulings"]["no_kind"]], [6, 7]) + self.assertEqual(rec["counts"]["rulings_no_kind"], 2) + self.assertIn("2 rulings with no kind", rec["line"]) + + def test_a_setup_row_is_overdue_only_after_its_review_date(self): + rows = ("| 2026-11-20 | Past | x review by 2026-12-03 | setup |\n" + "| 2026-11-20 | On the day | x review by 2026-12-04 | setup |\n" + "| 2026-11-20 | Future | x review by 2026-12-05 | setup |\n" + "| 2026-11-20 | Pref | x review by 2026-11-01 | preference |\n" + "| 2026-11-20 | Guard | x review by 2026-11-01 | guardrail |\n") + rec = self.rec(self.HEAD + rows) + over = rec["findings"]["rulings"]["setup_overdue"] + self.assertEqual([r["area"] for r in over], ["Past"]) + self.assertEqual(over[0]["review_by"], "2026-12-03") + self.assertEqual(rec["findings"]["rulings"]["no_kind"], []) + self.assertIn("1 setup ruling past its review date", rec["line"]) + + def test_the_review_date_in_the_kind_cell_is_read(self): + rows = ("| 2026-11-20 | Cell past | x | setup, review by 2026-12-03 |\n" + "| 2026-11-20 | Cell today | x | setup (review by 2026-12-04) |\n" + "| 2026-11-20 | Junk | x | setupish |\n") + rec = self.rec(self.HEAD + rows) + self.assertEqual([r["area"] for r in rec["findings"]["rulings"]["setup_overdue"]], ["Cell past"]) + self.assertEqual([r["area"] for r in rec["findings"]["rulings"]["no_kind"]], ["Junk"]) + + def test_a_setup_row_with_no_review_date_is_unread(self): + rec = self.rec(self.HEAD + "| 2026-11-20 | Dateless | text | setup |\n") + self.assertTrue(any("no review date" in u["reason"] for u in rec["coverage"]["unread"])) + self.assertEqual(rec["findings"]["rulings"]["setup_overdue"], []) + + def test_an_unmigrated_table_is_not_judged(self): + rec = self.rec("| Ruling date | Area | Ruling and why |\n|---|---|---|\n| 2026-11-01 | A | text |\n") + self.assertEqual(rec["coverage"]["checks"]["rulings"]["status"], "unmigrated") + self.assertEqual(rec["counts"]["rulings_no_kind"], 0) + self.assertEqual(rec["line"], "") + + def test_the_template_example_row_is_skipped(self): + rec = self.rec(self.HEAD + "| YYYY-MM-DD | EXAMPLE: permission mode | Keep the defaults. | |\n") + self.assertEqual(rec["findings"]["rulings"]["no_kind"], []) + + def test_a_table_inside_a_fence_or_comment_is_not_the_table(self): + rec = self.rec("\n" + "```\n| Ruling date | Area | Text | Kind |\n|---|---|---|---|\n| 2026-01-01 | A | b | |\n```\n") + self.assertEqual(rec["coverage"]["checks"]["rulings"]["status"], "unread") + + def test_a_missing_table_is_unread(self): + rec = self.rec("No table here.\n") + self.assertEqual(rec["coverage"]["checks"]["rulings"]["status"], "unread") + self.assertIn("not checked", rec["line"]) + + def test_worth_a_look_is_separate_and_never_counted(self): + tpl = getattr(self, "_tpl", None) or Template(self.tmp) # its last change to core.md is 2026-11-25 + self._tpl = tpl + rows = ("| 2026-11-01 | Old override | This overrides the `core.md` default for plans. | preference |\n" + "| 2026-11-30 | New override | This overrides the `core.md` default for plans. | preference |\n" + "| 2026-11-01 | No override | Keep it. | preference |\n") + root = self.box(tpl, doc("A", "B", "C"), extra={"CONTEXT/standing-orders.md": + "# Standing orders\n\n" + self.HEAD + rows}) + rec = self.scan(root) + self.assertEqual([w["area"] for w in rec["worth_a_look"]], ["Old override"]) + self.assertEqual(rec["worth_a_look"][0]["template_changed"], "2026-11-25") + self.assertEqual(rec["counts"]["worth_a_look"], 1) + self.assertEqual(rec["line"], "") # not a defect: no briefing text + + def test_parse_rulings_table_is_reusable(self): + loader = importlib.machinery.SourceFileLoader("desk_mod", str(DESK)) + spec = importlib.util.spec_from_loader("desk_mod", loader) + mod = importlib.util.module_from_spec(spec) + loader.exec_module(mod) + text = ("intro\n\n| Ruling date | Area | Ruling and why | Kind |\n|---|---|---|---|\n" + "| 2026-11-01 | A \\| B | a `x | y` b | setup |\n| 2026-11-02 | C | d | preference |\n\nafter\n") + table = mod.parse_rulings_table(text) + self.assertEqual(table["columns"]["kind"], 3) + self.assertEqual([r["line"] for r in table["rows"]], [5, 6]) + self.assertEqual(table["rows"][0]["cells"][1], "A | B") + self.assertIsNone(mod.parse_rulings_table("no table\n")) + legacy = mod.parse_rulings_table("| Ruling date | Area | Ruling and why |\n|---|---|---|\n| 2026-01-01 | A | b |\n") + self.assertIsNone(legacy["columns"]["kind"]) + + +class MemoryPools(DeskCase): + def pools(self, spec): + files = {"CONTEXT/core.md": "core\n"} + for pool, entries in spec.items(): + files[".claude-memory/%s/MEMORY.md" % pool] = "index of %s\n" % pool # differs per pool + for name, text in entries.items(): + files[".claude-memory/%s/%s" % (pool, name)] = text + return self.plain_root(files) + + def test_identical_pools_are_found_and_stay_out_of_the_line(self): + same = {"a.md": "alpha\n", "b.md": "beta\n", "c.md": "gamma\n"} + rec = self.scan(self.pools({"pool-one": same, "pool-two": dict(same), "pool-three": {"a.md": "other\n", "b.md": "x\n"}})) + self.assertEqual(len(rec["findings"]["duplicate_pools"]), 1) + self.assertEqual(len(rec["findings"]["duplicate_pools"][0]["pools"]), 2) + self.assertEqual(rec["counts"]["duplicate_pools"], 1) + self.assertNotIn("pool", rec["line"]) + self.assertNotIn("duplicate_pools", json.loads(self.desk(rec["root"], "--counts")[1])["counts"]) + + def test_one_changed_byte_is_not_a_duplicate(self): + rec = self.scan(self.pools({"p1": {"a.md": "alpha\n", "b.md": "beta\n"}, "p2": {"a.md": "alpha\n", "b.md": "beta!\n"}})) + self.assertEqual(rec["findings"]["duplicate_pools"], []) + + def test_a_missing_entry_is_not_a_duplicate(self): + rec = self.scan(self.pools({"p1": {"a.md": "alpha\n", "b.md": "beta\n"}, "p2": {"a.md": "alpha\n", "b.md": "beta\n", "c.md": "c\n"}})) + self.assertEqual(rec["findings"]["duplicate_pools"], []) + + def test_tiny_pools_are_not_called_duplicates(self): + rec = self.scan(self.pools({"p1": {"a.md": "alpha\n"}, "p2": {"a.md": "alpha\n"}})) + self.assertEqual(rec["findings"]["duplicate_pools"], []) + + def test_a_symlink_to_a_pool_is_not_a_second_pool(self): + root = self.pools({"p1": {"a.md": "alpha\n", "b.md": "beta\n"}}) + os.symlink(root / ".claude-memory/p1", root / ".claude-memory/p1-link") + rec = self.scan(root) + self.assertEqual(rec["findings"]["duplicate_pools"], []) + + def test_a_profile_pool_that_duplicates_a_store_pool_is_found(self): + same = {"a.md": "alpha\n", "b.md": "beta\n"} + root = self.pools({"p1": same}) + for n, t in same.items(): + write(self.home / ".claude/projects/-home-x/memory" / n, t) + rec = self.scan(root) + self.assertEqual(len(rec["findings"]["duplicate_pools"]), 1) + + +class Layouts(DeskCase): + def test_the_older_preferences_layout_is_recognized(self): + root = self.plain_root({"CONTEXT/core.md": "core\n", "CONTEXT/working-preferences.md": "Pin `claude-opus-4-8`.\n", + "CONTEXT/about-me.md": "me\n"}) + rec = self.scan(root) + self.assertEqual(rec["layout"], "working-preferences") + self.assertEqual(rec["coverage"]["checks"]["rulings"]["status"], "not_applicable") + self.assertTrue(any(d["ref"] == "claude-opus-4-8" for d in rec["findings"]["dead_references"])) + self.assertTrue(any(f["path"].endswith("working-preferences.md") for f in rec["size"]["files"])) + + def test_a_fork_with_no_core_file_is_recognized(self): + root = self.plain_root({"CONTEXT/working-preferences.md": "prefs\n", "CLAUDE.md": "Read `CONTEXT/missing-doc.md` now.\n"}) + rec = self.scan(root) + self.assertEqual(rec["layout"], "fork") + self.assertEqual({r["state"] for r in rec["core"]}, {"not_applicable"}) + self.assertEqual(rec["coverage"]["unread_count"], 0) # recognized, so not "unread" + self.assertTrue(any(d["ref"] == "CONTEXT/missing-doc.md" for d in rec["findings"]["dead_references"])) + + def test_an_unknown_layout_is_unread_not_clean_and_not_a_crash(self): + root = self.plain_root({"CONTEXT/notes.md": "something\n"}) + rec = self.scan(root) + self.assertEqual(rec["layout"], "unknown") + self.assertEqual(rec["coverage"]["status"], "incomplete") + self.assertTrue(any(u["check"] == "rulings" for u in rec["coverage"]["unread"])) + self.assertIn("not checked", rec["line"]) + self.assertIn("not a clean result", rec["line"]) + + def test_a_directory_that_is_not_a_harness_root_is_an_error(self): + empty = self.tmp / "empty" + empty.mkdir() + rc, _out, err = self.desk(empty, "--cache", str(self.state / "c.json")) + self.assertEqual(rc, 1) + self.assertIn("not a harness root", err) + self.assertFalse((self.state / "c.json").exists()) + rc, _out, err = self.desk(self.tmp / "nope", "--cache", str(self.state / "c.json")) + self.assertEqual(rc, 1) + + def test_roster_is_not_checked_in_this_release(self): + rec = self.scan(self.plain_root({"CONTEXT/core.md": "x\n", "CONTEXT/standing-orders.md": "# s\n"})) + self.assertEqual(rec["coverage"]["roster"], "not checked") + self.assertFalse([d for d in rec["findings"]["dead_references"] if d["kind"] == "person"]) + + +class SizeReport(DeskCase): + def test_bytes_per_file_and_total_with_no_judgment(self): + core = "c" * 700 + "\n" + rec = self.scan(self.plain_root({"CONTEXT/core.md": core, "AGENTS.md": "a" * 50}, owner=True)) + sizes = {f["path"]: f["bytes"] for f in rec["size"]["files"]} + self.assertEqual(sizes["CONTEXT/core.md"], 701) + self.assertEqual(sizes["AGENTS.md"], 50) + self.assertEqual(rec["size"]["total"], 701 + 50) + self.assertIsNone(rec["size"]["threshold"]) + self.assertIsNone(rec["size"]["over_threshold"]) + self.assertEqual(rec["line"], "") # size never speaks in the briefing + + def test_a_threshold_is_reported_but_never_a_finding_or_a_count(self): + rec = self.scan(self.plain_root({"CONTEXT/core.md": "c" * 700}, owner=True), + extra_env={"DESK_SIZE_THRESHOLD": "100"}) + self.assertTrue(rec["size"]["over_threshold"]) + self.assertEqual(rec["line"], "") + self.assertNotIn("size", rec["counts"]) + + +class CacheAndLine(DeskCase): + def root(self): + return self.plain_root({"CONTEXT/core.md": "See `CONTEXT/gone.md` first.\n", "CONTEXT/standing-orders.md": "# s\n"}) + + def run_default(self, root, *extra): + return self.desk(root, "--state-dir", str(self.state), *extra) + + def test_a_scan_writes_only_desk_last_json_atomically(self): + root = self.root() + before = tree_state(root) + rc, out, _err = self.run_default(root) + self.assertEqual(rc, 0) + self.assertEqual(sorted(p.name for p in self.state.iterdir()), ["desk-last.json"]) # no temp file left + cache = json.loads((self.state / "desk-last.json").read_text()) + self.assertEqual(cache["root"], str(root.resolve())) + self.assertEqual(cache["schema"], 1) + self.assertIn("scanned_at", cache) + self.assertEqual(tree_state(root), before) # nothing written inside the harness tree + self.assertIn("Result:", out) + + def test_line_reads_the_cache_and_never_scans(self): + root = self.root() + self.run_default(root) + rc, out, _e = self.run_default(root, "--line") + self.assertEqual(rc, 0) + self.assertIn("1 dead reference", out) + write(root / "CONTEXT/core.md", "clean now\n") # the tree changes; --line must still say the old thing + rc, out2, _e = self.run_default(root, "--line") + self.assertEqual(out2, out) + cache = json.loads((self.state / "desk-last.json").read_text()) + self.assertEqual(out.strip(), cache["line"]) + + def test_line_is_empty_when_the_cache_is_absent_stale_or_another_roots(self): + root = self.root() + rc, out, _e = self.run_default(root, "--line") + self.assertEqual((rc, out), (0, "")) # absent + self.run_default(root) + path = self.state / "desk-last.json" + cache = json.loads(path.read_text()) + cache["scanned_epoch"] = int(time.time()) - 8 * 86400 - 60 + path.write_text(json.dumps(cache)) + self.assertEqual(self.run_default(root, "--line")[1], "") # older than 8 days + cache["scanned_epoch"] = int(time.time()) - 7 * 86400 + path.write_text(json.dumps(cache)) + self.assertIn("dead reference", self.run_default(root, "--line")[1]) # 7 days is still fresh + other = self.root() + self.assertEqual(self.run_default(other, "--line")[1], "") # a cache for a different root + path.write_text("{not json") + self.assertEqual(self.run_default(root, "--line")[1], "") + + def test_line_is_empty_when_there_is_nothing_to_show(self): + root = self.plain_root({"CONTEXT/core.md": "fine\n"}, owner=True) + self.run_default(root) + self.assertEqual(self.run_default(root, "--line")[1], "") + cache = json.loads((self.state / "desk-last.json").read_text()) + self.assertEqual(cache["line"], "") + + def test_a_failed_scan_leaves_the_last_success_alone(self): + root = self.root() + self.run_default(root) + path = self.state / "desk-last.json" + before = path.read_bytes() + rc, _o, err = self.desk(self.tmp / "gone", "--state-dir", str(self.state)) + self.assertEqual(rc, 1) + self.assertEqual(path.read_bytes(), before) + rc, _o, _e = self.run_default(root, "--pin", "zzz") + self.assertEqual(rc, 1) + self.assertEqual(path.read_bytes(), before) + + def test_counts_and_no_cache_never_write_the_cache(self): + root = self.root() + rc, out, _e = self.run_default(root, "--counts") + self.assertEqual(rc, 0) + self.assertFalse(self.state.exists()) + counts = json.loads(out) + self.assertEqual(set(counts["counts"]), {"stale_core", "dead_references", "rulings_setup_overdue", + "rulings_lapsed_recent"}) + self.assertTrue(all(isinstance(v, int) for v in counts["counts"].values())) + self.assertIn(counts["coverage"], ("complete", "incomplete")) + self.assertNotIn("findings", counts) + self.assertNotIn("gone.md", out) # content never leaves the box in counts + self.run_default(root, "--no-cache") + self.assertFalse(self.state.exists()) + + def test_the_cache_cannot_be_written_inside_the_checkout(self): + root = self.root() + rc, _o, err = self.desk(root, "--cache", str(root / "desk-last.json")) + self.assertEqual(rc, 1) + self.assertIn("inside the checkout", err) + self.assertFalse((root / "desk-last.json").exists()) + + def test_state_dir_defaults_by_box(self): + team = self.plain_root({"CONTEXT/core.md": "x\n"}, at=self.home / "OPS") + rc, _o, _e = self.desk(team) + self.assertEqual(rc, 0) + self.assertTrue((self.home / ".local/state/ops/desk-last.json").is_file()) + rc, _o, _e = self.desk(team, extra_env={"OPS_STATE_DIR": str(self.tmp / "ops-state")}) + self.assertTrue((self.tmp / "ops-state/desk-last.json").is_file()) + owner = self.plain_root({"CONTEXT/core.md": "x\n"}, owner=True, at=self.home / "COWORK") + self.desk(owner) + self.assertTrue((self.home / ".local/state/cowork/desk-last.json").is_file()) + self.desk(owner, extra_env={"COWORK_STATE_DIR": str(self.tmp / "cw-state")}) + self.assertTrue((self.tmp / "cw-state/desk-last.json").is_file()) + + def test_a_worktree_or_scratch_copy_never_replaces_the_boxs_cache(self): + box = self.plain_root({"CONTEXT/core.md": "See `CONTEXT/gone.md` first.\n"}, owner=True, at=self.home / "COWORK") + self.desk(box) + path = self.home / ".local/state/cowork/desk-last.json" + before = path.read_bytes() + scratch = self.plain_root({"CONTEXT/core.md": "fine\n"}, owner=True) + rc, out, err = self.desk(scratch) + self.assertEqual(rc, 0) + self.assertIn("Result:", out) # it still scans and prints + self.assertIn("cache not refreshed", err) + self.assertEqual(path.read_bytes(), before) + rc, _o, _e = self.desk(scratch, "--cache", str(self.tmp / "mine.json")) # an explicit cache is the caller's choice + self.assertTrue((self.tmp / "mine.json").is_file()) + + +class DailySync(DeskCase): + """Stage 6 of backup/daily-sync.sh. Only run_lapse and run_desk are cut out and run: the other stages + pull, stash and push, and a test must never reach them.""" + SYNC = Path(__file__).resolve().parent.parent.parent / "backup" / "daily-sync.sh" + HOOKLIB = Path(__file__).resolve().parent.parent.parent / "hooks" / "hooklib.sh" + + def run_stage(self, root, desk_text=None, stages=("run_desk",)): + import re as _re + text = self.SYNC.read_text() + function = "\n".join(_re.search(r"^%s\(\) \{.*?^\}" % name, text, _re.M | _re.S).group() + for name in ("run_lapse", "run_desk")) + (root / ".claude-config/bin").mkdir(parents=True, exist_ok=True) + (root / ".claude-config/hooks").mkdir(parents=True, exist_ok=True) + shutil.copy(self.HOOKLIB, root / ".claude-config/hooks/hooklib.sh") + if desk_text is not False: + (root / ".claude-config/bin/desk").write_text(DESK.read_text() if desk_text is None else desk_text) + log = self.tmp / "sync.log" + # Both roots: the owner's daily-sync reads COWORK_DIR, the template's OPS_DIR. + command = ('COWORK_DIR="$1"; OPS_DIR="$1"; LOG_FILE="$2"; log() { printf "%s\\n" "$*" >> "$LOG_FILE"; };\n' + + function + "\n" + "; ".join(stages) + '; echo "stage-exit=$?"') + p = subprocess.run(["bash", "-c", command, "_", str(root), str(log)], env=self.env(), timeout=120, + stdout=subprocess.PIPE, stderr=subprocess.PIPE) + return p.stdout.decode(), log.read_text() if log.exists() else "" + + def test_the_stage_refreshes_the_cache_and_logs_one_line(self): + root = self.plain_root({"CONTEXT/core.md": "See `CONTEXT/gone.md` first.\n", "CONTEXT/standing-orders.md": "# s\n"}, + at=self.home / "OPS") + out, log = self.run_stage(root) + self.assertIn("stage-exit=0", out) + self.assertTrue((self.home / ".local/state/ops/desk-last.json").is_file()) + self.assertIn("DESK: 1 dead reference", log) + + def test_a_clean_result_is_logged_as_nothing_to_show(self): + root = self.plain_root({"CONTEXT/core.md": "fine\n"}, owner=True, at=self.home / "COWORK") + out, log = self.run_stage(root) + self.assertIn("DESK: nothing to show", log) + + def test_a_desk_that_errors_never_fails_the_sync_and_keeps_the_old_cache(self): + root = self.plain_root({"CONTEXT/core.md": "fine\n"}, owner=True, at=self.home / "COWORK") + self.run_stage(root) + cache = self.home / ".local/state/cowork/desk-last.json" + before = cache.read_bytes() + out, log = self.run_stage(root, desk_text="import sys\nprint('boom', file=sys.stderr)\nsys.exit(3)\n") + self.assertIn("stage-exit=0", out) + self.assertIn("WARN desk exited 3", log) + self.assertIn("boom", log) + self.assertEqual(cache.read_bytes(), before) + + def lapse_box(self, legacy=False): + """A team box at ~/OPS (the box root, so desk uses its default state dir) with one setup ruling + past its review date, committed with the fixture HOME's git identity.""" + write(self.home / ".gitconfig", "[user]\n\tname = t\n\temail = t@example.invalid\n") + head = "| Ruling date | Area | Ruling and why |%s\n|---|---|---|%s\n" % (("", "") if legacy else (" Kind |", "---|")) + row = ("| 2026-11-20 | Autonomy | Pause at each step, setup, review by 2026-12-01 |\n" if legacy else + "| 2026-11-20 | Autonomy | Pause at each step. | setup, review by 2026-12-01 |\n") + root = self.plain_root({"CONTEXT/core.md": "core\n", "CONTEXT/standing-orders.md": "# s\n\n" + head + row}, + at=self.home / "OPS") + env = dict(GIT_ENV, HOME=str(self.home)) + env.pop("GIT_CONFIG_GLOBAL", None) + for args in (["init", "-q", "-b", "main"], ["add", "-A"], ["commit", "-q", "-m", "box"]): + sh(["git", "-C", str(root)] + args, env=env) + return root + + def test_the_lapse_stage_moves_a_due_ruling_before_the_check(self): + root = self.lapse_box() + out, log = self.run_stage(root, stages=("run_lapse", "run_desk")) + self.assertIn("stage-exit=0", out) + self.assertIn("LAPSE: desk lapse: 1 setup ruling moved", log) + self.assertTrue((root / "CONTEXT/standing-orders-archive.md").is_file()) + self.assertTrue((self.home / ".local/state/ops/desk-lapse-notice.json").is_file()) + cache = json.loads((self.home / ".local/state/ops/desk-last.json").read_text()) + self.assertEqual(cache["counts"]["rulings_setup_overdue"], 0) # the check ran after the move + self.assertEqual(cache["counts"]["rulings_lapsed_recent"], 1) + self.assertLess(log.index("LAPSE:"), log.index("DESK: running desk")) + + def test_the_lapse_stage_leaves_an_unmigrated_table_alone(self): + root = self.lapse_box(legacy=True) + before = (tree_state(root / "CONTEXT"), tree_state(root / ".git")) # run_stage adds .claude-config itself + out, log = self.run_stage(root, stages=("run_lapse",)) + self.assertIn("stage-exit=0", out) + self.assertIn("not migrated", log) + self.assertEqual((tree_state(root / "CONTEXT"), tree_state(root / ".git")), before) + self.assertFalse((self.home / ".local/state/ops/desk-lapse-notice.json").exists()) + + def test_a_refused_lapse_never_fails_the_sync(self): + root = self.lapse_box() + orders = root / "CONTEXT/standing-orders.md" + orders.write_text(orders.read_text() + "an owner edit not yet committed\n") + before = orders.read_bytes() + out, log = self.run_stage(root, stages=("run_lapse", "run_desk")) + self.assertIn("stage-exit=0", out) + self.assertIn("LAPSE: WARN desk lapse exited 1", log) + self.assertEqual(orders.read_bytes(), before) + cache = json.loads((self.home / ".local/state/ops/desk-last.json").read_text()) + self.assertEqual(cache["counts"]["rulings_setup_overdue"], 1) # still in force, and visible + + def test_a_missing_desk_is_skipped_with_a_warning(self): + root = self.plain_root({"CONTEXT/core.md": "fine\n"}, owner=True) + out, log = self.run_stage(root, desk_text=False) + self.assertIn("stage-exit=0", out) + self.assertIn("WARN desk unreadable", log) + + +class ReadOnlyAndSelfContained(DeskCase): + def test_a_scan_changes_nothing_in_a_git_checkout_and_never_fetches(self): + tpl = Template(self.tmp) + root = self.box(tpl, doc("A")) + git(root, "remote", "add", "ops-template", str(tpl.path)) + remotes = git(root, "remote", "-v") + before = tree_state(root) + rec = self.scan(root) + self.assertEqual(self.core_state(rec)["state"], "stale") + self.assertEqual(tree_state(root), before) # .git included: index, refs, objects + self.assertEqual(git(root, "remote", "-v"), remotes) + self.assertFalse((root / ".git/FETCH_HEAD").exists()) + self.assertEqual(git(root, "status", "--porcelain"), "") + + def test_an_absent_pin_object_is_not_fetched(self): + tpl = Template(self.tmp) + root = self.tmp / "lonely" + write(root / "CONTEXT/core.md", doc("A")) + write(root / ".claude-config/ops-upstream-ref", "last_synced=%s\n" % tpl.pin) + git(root.parent, "init", "-q", str(root)) + git(root, "add", "-A") + git(root, "commit", "-q", "-m", "x") + git(root, "remote", "add", "ops-template", str(tpl.path)) # a reachable remote that desk must not use + self.scan(root) + self.assertFalse((root / ".git/FETCH_HEAD").exists()) + self.assertEqual(git(root, "cat-file", "-t", tpl.pin, check=False), "") + + def test_it_imports_nothing_from_the_repo(self): + tree = ast.parse(DESK.read_text()) + names = set() + for node in ast.walk(tree): + if isinstance(node, ast.Import): + names.update(a.name.split(".")[0] for a in node.names) + elif isinstance(node, ast.ImportFrom): + self.assertEqual(node.level, 0, "a relative import") + names.add((node.module or "").split(".")[0]) + stdlib = set(sys.stdlib_module_names) if hasattr(sys, "stdlib_module_names") else None + if stdlib is not None: + self.assertEqual(names - stdlib, set()) + self.assertFalse([n for n in names if n in ("sandbox_guard", "hooklib")]) + + def test_it_runs_isolated_from_an_empty_directory_and_from_a_pipe(self): + root = self.plain_root({"CONTEXT/core.md": "x\n", "CONTEXT/standing-orders.md": "# s\n"}) + empty = self.tmp / "emptycwd" + empty.mkdir() + rc, out, _e = self.desk(root, "--no-cache", cwd=empty) + self.assertEqual(rc, 0) + # piped to the interpreter, as the fleet read does: no __file__, no repo + p = subprocess.run([sys.executable, "-I", "-", "--root", str(root), "--no-cache", "--json"], + input=DESK.read_bytes(), cwd=str(empty), env=self.env(), stdout=subprocess.PIPE, + stderr=subprocess.PIPE) + self.assertEqual(p.returncode, 0, p.stderr.decode()) + self.assertEqual(json.loads(p.stdout)["schema"], 1) + + +class Record(DeskCase): + def test_the_json_record_has_the_documented_shape(self): + tpl = Template(self.tmp) + rec = self.scan(self.box(tpl, doc("C"))) + for key in ("schema", "scanned_at", "scanned_epoch", "root", "mode", "layout", "pin", "findings", "worth_a_look", + "core", "size", "coverage", "counts", "line"): + self.assertIn(key, rec) + self.assertEqual(rec["mode"], "team") + self.assertEqual(rec["pin"]["source"], "ops-upstream-ref") + self.assertEqual(set(rec["coverage"]), {"status", "unread_count", "unread", "roster", "checks", "notes", "indeterminate_skipped"}) + self.assertIn("1 core file behind the template", rec["line"]) + self.assertIn("worth_a_look", rec["counts"]) + + def test_text_output_names_unread_coverage_and_is_not_json(self): + root = self.plain_root({"CONTEXT/notes.md": "x\n"}) + rc, out, _e = self.desk(root, "--no-cache") + self.assertEqual(rc, 0) + self.assertIn("NOT CHECKED", out) + self.assertIn("not a clean result", out) + self.assertFalse(out.lstrip().startswith("{")) + + +if __name__ == "__main__": + unittest.main(verbosity=2) diff --git a/.claude-config/bin/tests/memory-boundary-test.py b/.claude-config/bin/tests/memory-boundary-test.py index d498063..fa2f41b 100755 --- a/.claude-config/bin/tests/memory-boundary-test.py +++ b/.claude-config/bin/tests/memory-boundary-test.py @@ -92,10 +92,12 @@ def test_the_home_account_name_is_not_a_project_word(self): self.assertNotIn("alice", words) self.assertNotIn("ops", words) - def test_the_pool_cap_warns_and_never_fails(self): - self.assertEqual(MEMORY["POOL_CAP"], 60) + def test_a_large_pool_has_no_cap(self): + # The 60-entry warning went with the nightly settle (2026-12-04): a large + # pool writes its whole index, exits 0 and prints nothing on stderr. + self.assertNotIn("POOL_CAP", MEMORY) with tempfile.TemporaryDirectory(prefix="memory-cap-") as pool: - for i in range(MEMORY["POOL_CAP"] + 1): + for i in range(61): Path(pool, f"entry-{i:03d}.md").write_text( f"---\nname: entry-{i:03d}\ndescription: entry {i}\nmetadata:\n type: feedback\n---\n" ) @@ -104,8 +106,8 @@ def test_the_pool_cap_warns_and_never_fails(self): capture_output=True, text=True, check=False, ) self.assertEqual(run.returncode, 0, run.stderr) - self.assertIn("WARN", run.stderr) - self.assertEqual(len(run.stdout.splitlines()), MEMORY["POOL_CAP"] + 1) + self.assertEqual(run.stderr, "") + self.assertEqual(len(run.stdout.splitlines()), 61) @unittest.skipUnless(HINT_HOOK.is_file(), "hooks/memory-hint.sh is not in this copy") diff --git a/.claude-config/bin/tests/memory-hint-test.sh b/.claude-config/bin/tests/memory-hint-test.sh index f7df6ee..30ed3c9 100755 --- a/.claude-config/bin/tests/memory-hint-test.sh +++ b/.claude-config/bin/tests/memory-hint-test.sh @@ -256,6 +256,47 @@ o="$(mirror_run)"; rc=$? [ "$rc" = 0 ] && [ -z "$o" ] && [ ! -e "$ST/memory-hint.log" ] \ && ok "an indexer with no --hint: nothing printed, exit 0 and no log line" || bad "indexer without --hint" "rc=$rc o=$o log=$(cat "$ST/memory-hint.log" 2>&1)" +# 9. the archives: an entry the nightly settle archived is still +# hinted, from this pool's archive and the root's, under its archive path (not a +# name that reads as a live entry); the root archive keeps the root's project +# exclusion; lessons paragraphs never reach the hint (--find reads them). +AP="$T/arch-pool"; AR="$T/arch-root"; mkdir -p "$AP/_archive" "$AR/_archive" "$CW/CONTEXT/projects" +for n in 1 2 3 4 5 6 7 8; do + entry "$AP" "reference-apfill-$n" reference "Unrelated note $n about badges kiosks and docks" "2026-09-0${n}T10:00:00Z" + entry "$AR" "reference-arfill-$n" reference "General note $n about monitors routers and modems" "2026-08-0${n}T10:00:00Z" +done +entry "$AP/_archive" feedback-print-spooler-laser-stall feedback "Restart the print spooler service after a laser driver push stalls the queue" 2026-09-20T10:00:00Z +entry "$AR/_archive" reference-firewall-split-tunnel-vpn reference "Firewall mobile VPN split tunnel needs the allowed subnets listed per user group" 2026-09-21T10:00:00Z +entry "$AR/_archive" project-quokka-migration-cutover project "Quokka migration workstream cutover list and the quokka freeze window" 2026-09-22T10:00:00Z +longd="Restart the walrus gateway firmware after a walrus rollback, $(python3 -I -c 'print("then check the walrus logs again and again " * 8)')" +entry "$AP/_archive" reference-walrus-gateway-rollback-firmware reference "$longd" 2026-09-23T10:00:00Z +printf '## Narwhal tusk\n\nNarwhal tusk calibration: hold the narwhal tusk sensor for ten seconds.\n' > "$CW/CONTEXT/projects/zz-narwhal-lessons.md" +ahint() { hint "$1" MEMORY_INDEX_DIR="$AP" MEMORY_DIGEST_ROOT_DIR="$AR"; } +APR="$(cd "$AP" && pwd -P)"; ARR="$(cd "$AR" && pwd -P)" +out="$(ahint "the print spooler is stalled again after the laser driver push, restart the spooler service?")" +# (A long temp path leaves the description little room: only its start is checked.) +[[ "$out" == "Relevant memory: $APR/_archive/feedback-print-spooler-laser-stall.md: Re"* ]] \ + && ok "archive: this pool's archived entry is hinted under its archive path" || bad "this-pool archive hint" "$out" +out="$(ahint "how do I set the firewall mobile VPN split tunnel allowed subnets for a user group")" +[[ "$out" == *"Relevant memory: $ARR/_archive/reference-firewall-split-tunnel-vpn.md: Fi"* ]] \ + && ok "archive: the root pool's archived entry is hinted under its archive path" || bad "root archive hint" "$out" +out="$(ahint "what is on the quokka migration cutover list and when is the quokka freeze window")" +! grep -q 'quokka' <<< "$out" && ok "archive: the root archive's type project entry is not hinted from a project cwd" \ + || bad "root archive project entry hinted" "$out" +out="$(ahint "walrus gateway firmware rollback, restart the walrus gateway and check the walrus logs")" +wpre="Relevant memory: $APR/_archive/reference-walrus-gateway-rollback-firmware.md: " +if [[ "$out" == "$wpre"* ]] && [[ "$out" == *"..." ]] \ + && { [ "$(printf '%s' "$out" | wc -m)" -le 200 ] || [ "${#wpre}" -gt 186 ]; }; then + ok "a long description is cut to the 200-character line; the archive path stays whole" +else bad "line cut" "$out"; fi +out="$(ahint "narwhal tusk calibration, how long do I hold the narwhal tusk sensor")" +fnd="$(env HOME="$T/home" OPS_DIR="$CW" MEMORY_DIGEST_HOST="$HOST" OPS_STATE_DIR="$ST" MEMORY_INDEX_DIR="$AP" MEMORY_DIGEST_ROOT_DIR="$AR" \ + python3 -I "$HERE/../memory-index" --find --ops "$CW" --cwd "$PROJ" narwhal tusk calibration sensor)" +if [ -z "$out" ] && grep -q $'\tlessons\t.*zz-narwhal-lessons.md:3\t' <<< "$fnd"; then + ok "lessons: a strong lessons paragraph is never hinted (--find finds it)" +else bad "lessons in the hint" "hint=$out find=$fnd"; fi +rm -f "$CW/CONTEXT/projects/zz-narwhal-lessons.md" + # 11. each entry once per session (the same few entries otherwise repeat on every prompt). # RED PROOF: the previous hook printed the same line # for the same session every time, so the second and third checks below fail on it. diff --git a/.claude-config/bin/tests/memory-index-test.sh b/.claude-config/bin/tests/memory-index-test.sh index d2d69ef..f38df85 100755 --- a/.claude-config/bin/tests/memory-index-test.sh +++ b/.claude-config/bin/tests/memory-index-test.sh @@ -13,11 +13,17 @@ # - labels a title-less entry by its `name:` (the pool entry format has no # `title:`, so a large pool used to fail --check) and flags only a file # with neither -# - WARNS, and only warns, on a pool of more than 60 entries: the index is -# still written and the exit status is unchanged (a pool is its owner's) +# - has no pool cap (2026-12-04, with the nightly settle): a large pool +# exits 0, and one with a broken file still exits 2 and names it # - warns, without failing, on more than 20 pinned entries -# - --find ranks the entry a query is about first -# - --pool-for prints the pool the digest uses and creates nothing (exit 4 for none) +# - --find ranks the entry a query is about first, refs it by path +# - the archive: /_archive/ never reaches the live index or a count, +# and gets no index of its own +# - --find reads this pool, the root pool, both archives and the lessons +# paragraphs (sources, refs, --json shape and precision, --exclude by +# path, no match, failures) +# - --pool-for prints the pool --digest uses (worktree, host-key file, +# profile dir) and exits 4 without creating one where there is none # # Run: bash ~/OPS/.claude-config/bin/tests/memory-index-test.sh # Exit: 0 = all pass; non-zero on first failure. @@ -199,16 +205,16 @@ for i in range(139): open(f"{sys.argv[1]}/{stem}.md", "w").write( f"---\nname: {stem}\ndescription: entry {i}\nmetadata:\n type: reference\n---\nbody\n") PY -# 139 is over the 60-entry warning line; the point here is that not one of the 139 -# is flagged as missing a title, and that the warning does not change the exit. +# The point here is that not one of the 139 is flagged as missing a title (and, +# with the cap gone, that 139 entries exit 0). OUT="$("$GEN" --check "$N" 2>"$ERRFILE")"; rc=$? -[ "$rc" -eq 0 ] || fail "139 name:-only entries: expected exit 0 (a warning, not a failure), got $rc" +[ "$rc" -eq 0 ] || fail "139 entries: expected exit 0 (no pool cap), got $rc" ! grep -q 'need backfill\|missing title' "$ERRFILE" || fail "a name:-only entry was flagged as missing a title: $(head -3 "$ERRFILE")" [ "$(printf '%s\n' "$OUT" | wc -l)" -eq 139 ] || fail "expected 139 index lines" rm -rf "$N" pass "139 name:-only entries: none flagged as missing a title" -# --- Test 10: the 60-entry pool cap is a WARN, never an error. --------------------- +# --- Test 10: no pool cap; a large pool still reports malformed entries. ---------- mkpool() { # mkpool [pinned count] python3 - "$1" "$2" "${3:-0}" <<'PY' import os, sys @@ -227,19 +233,18 @@ mkpool "$C/ok" 60 [ "$rc" -eq 0 ] && [ ! -s "$ERRFILE" ] || fail "60 entries is at the cap and must be silent (rc=$rc): $(cat "$ERRFILE")" mkpool "$C/over" 61 OUT="$("$GEN" --check "$C/over" 2>"$ERRFILE")"; rc=$? -[ "$rc" -eq 0 ] || fail "61 entries must still exit 0 (a warning only), got $rc" -grep -q 'WARN: 61 entries in .*over the 60-entry pool cap' "$ERRFILE" || fail "cap warning must carry the count: $(cat "$ERRFILE")" -grep -q 'nothing was removed' "$ERRFILE" || fail "cap warning must say nothing was removed: $(cat "$ERRFILE")" -[ "$(printf '%s\n' "$OUT" | wc -l)" -eq 61 ] || fail "--check still prints the whole index over the cap" +[ "$rc" -eq 0 ] && [ ! -s "$ERRFILE" ] || fail "61 entries: no cap any more, expected a silent exit 0, got $rc: $(cat "$ERRFILE")" +[ "$(printf '%s\n' "$OUT" | wc -l)" -eq 61 ] || fail "--check prints the whole index" "$GEN" "$C/over" 2>"$ERRFILE"; rc=$? [ "$rc" -eq 0 ] && [ -f "$C/over/MEMORY.md" ] && [ "$(wc -l < "$C/over/MEMORY.md")" -eq 61 ] \ - || fail "write mode over the cap must write the index and exit 0 (rc=$rc)" -[ "$(find "$C/over" -name 'entry-*.md' | wc -l)" -eq 61 ] || fail "an over-cap pool lost entries" -# A broken file still reports its own exit status; the cap never outranks it. + || fail "write mode on 61 entries writes the index and exits 0 (rc=$rc)" +# A malformed entry in a large pool is still reported (exit 2, named), not hidden. printf 'no frontmatter\n' > "$C/over/bare.md" -"$GEN" --check "$C/over" >/dev/null 2>&1; rc=$? -[ "$rc" -eq 2 ] || fail "over the cap with a broken file must exit 2 (the broken file), got $rc" -pass "pool cap: 60 is silent; 61 warns with the count, exits 0, writes the index and removes nothing" +"$GEN" --check "$C/over" >/dev/null 2>"$ERRFILE"; rc=$? +[ "$rc" -eq 2 ] && grep -q 'bare.md: missing title: and name:' "$ERRFILE" \ + || fail "a large pool with a broken file must exit 2 and name it, got $rc: $(cat "$ERRFILE")" +! grep -q 'cap' "$ERRFILE" || fail "no cap message any more: $(cat "$ERRFILE")" +pass "no pool cap: 60 and 61 entries exit 0; a broken file in a large pool still exits 2 and is named" # --- Test 11: more than 20 pinned entries warn, never fail. ------------------------- mkpool "$C/pins" 30 21 @@ -273,8 +278,8 @@ for i in 1 2 3 4 5 6 7 8 9 10; do done OUT="$(MEMORY_INDEX_DIR="$F" MEMORY_DIGEST_ROOT_DIR="$C/none" MEMORY_DIGEST_HOST=t "$GEN" --find --ops "$C" --cwd "$C" rounding on invoice billing 2>&1)" first="$(printf '%s\n' "$OUT" | head -1 | cut -f3)" -[ "$first" = feedback-invoice-rounding-let-it-be ] || fail "--find ranked the wrong entry first: $OUT" -printf '%s\n' "$OUT" | head -1 | grep -qP '^\d+\.\d\tthis\t' || fail "--find line shape is score, pool, name, description: $OUT" +[ "$first" = "$(cd "$F" && pwd -P)/feedback-invoice-rounding-let-it-be.md" ] || fail "--find ranked the wrong entry first (ref is the entry's path): $OUT" +printf '%s\n' "$OUT" | head -1 | grep -qP '^\d+\.\d\tthis\t/' || fail "--find line shape is score, source, ref, text: $OUT" "$GEN" --find >/dev/null 2>&1 && fail "--find with no words must fail" pass "--find: the entry the words are about ranks first; no words is an error" @@ -283,36 +288,165 @@ if grep -q -e "$(printf '\342\200\224')" -e "$(printf '\342\200\223')" "$GEN"; t pass "memory-index has no em or en dash character" rm -rf "$C" -# --- Test 14: --pool-for prints the pool the digest uses and creates nothing. ----------- -# session-end rebuilds this directory's index through it, so it must agree with -# --digest for a linked worktree, the host-key file and a profile's +# --- Test 13: the archive is not a live entry anywhere. --------------------------- +A="$(mktemp -d "${TMPDIR:-/tmp}/memory-index-arch.XXXXXX")" +mkpool "$A/pool" 3 +mkpool "$A/pool/_archive" 2 +OUT="$("$GEN" --check "$A/pool" 2>"$ERRFILE")"; rc=$? +[ "$rc" -eq 0 ] && [ "$(printf '%s\n' "$OUT" | wc -l)" -eq 3 ] && ! grep -q '_archive' <<< "$OUT" \ + || fail "the live index must hold the 3 live entries only (rc=$rc): $OUT" +"$GEN" "$A/pool" 2>/dev/null +[ "$(wc -l < "$A/pool/MEMORY.md")" -eq 3 ] && [ ! -e "$A/pool/_archive/MEMORY.md" ] \ + || fail "the live index holds the live entries; the archive gets no index" +python3 -I -c 'import sys; from importlib.machinery import SourceFileLoader as L +sys.dont_write_bytecode = True +m = L("mi", sys.argv[1]).load_module() +assert m.count_md(sys.argv[2]) == 3, m.count_md(sys.argv[2]) +assert len(m.load_pool(sys.argv[2], "this")[0]) == 3 +assert m.count_pinned(sys.argv[2]) == 0' "$GEN" "$A/pool" || fail "counts must leave the archive out" +pass "archive: /_archive/ stays out of the live index and the counts, and has no index" + +# --- Test 14: one search over pools, archives and lessons. ------------------------ +# An OPS tree with a root pool, a project pool, an archive in each holding the +# same name, and a lessons file. Every ref is a path; an archived name names its pool. +W="$A/cw"; mkdir -p "$W/CONTEXT/projects" "$W/proj" +RP="$W/rootpool"; PP="$W/projpool"; mkdir -p "$RP/_archive" "$PP/_archive" +entry() { # entry + printf -- '---\nname: %s\ndescription: "%s"\nmetadata:\n type: %s\n modified: 2026-10-01T00:00:00Z\n---\nbody\n' "$2" "$4" "$3" > "$1" +} +entry "$PP/live-zebra.md" live-zebra reference "zebra crossings near the depot need a permit" +entry "$RP/root-zebra.md" root-zebra feedback "zebra paint dries slowly in winter" +entry "$PP/_archive/same-zebra.md" same-zebra reference "archived zebra fact from the project" +entry "$RP/_archive/same-zebra.md" same-zebra feedback "archived zebra fact from the root" +entry "$RP/_archive/root-project-zebra.md" root-project-zebra project "root workstream zebra state" +for i in 1 2 3 4 5 6; do entry "$PP/filler-$i.md" "filler-$i" reference "unrelated filler $i about printers"; done +cat > "$W/CONTEXT/projects/zoo-lessons.md" <<'EOF' +# Zoo lessons + +## Zebra handling + +First paragraph mentions nothing relevant. + +A zebra crossing permit is filed with the depot office, +and the permit number goes on the gate. + +```bash +# zebra comment inside a fence, not a heading + +echo zebra permit depot +``` + +## Other + +Unrelated words only. +EOF +fx() { MEMORY_INDEX_DIR="$PP" MEMORY_DIGEST_ROOT_DIR="$RP" MEMORY_DIGEST_HOST=t OPS_STATE_DIR="$A/state" \ + "$GEN" --find --ops "$W" --cwd "$W/proj" "$@"; } +OUT="$(fx --limit 20 zebra permit depot crossing)"; rc=$? +[ "$rc" -eq 0 ] || fail "--find failed: $OUT" +cut -f2 <<< "$OUT" | sort -u | tr '\n' ' ' | grep -qx 'archive lessons root this ' || fail "every source must appear: $OUT" +grep -qP "^\d+\.\d\tthis\t$(cd "$PP" && pwd -P)/live-zebra\.md\tzebra crossings" <<< "$OUT" || fail "this-pool row: $OUT" +grep -qP "\tarchive\t$(cd "$PP" && pwd -P)/_archive/same-zebra\.md\t" <<< "$OUT" \ + && grep -qP "\tarchive\t$(cd "$RP" && pwd -P)/_archive/same-zebra\.md\t" <<< "$OUT" \ + || fail "two archives holding one name: each ref names its pool: $OUT" +! grep -q 'root-project-zebra' <<< "$OUT" || fail "the root archive keeps the root pool's project exclusion: $OUT" +LF="$(cd "$W/CONTEXT/projects" && pwd -P)/zoo-lessons.md" +grep -qP "\tlessons\t$LF:7\tZebra handling: A zebra crossing permit" <<< "$OUT" \ + || fail "a lessons paragraph: path:line of its first line, its heading's words carried: $OUT" +grep -qP "\tlessons\t$LF:10\tZebra handling: \x60\x60\x60bash # zebra comment" <<< "$OUT" \ + || fail "a fenced block is one paragraph under the heading above it (its # line is no heading): $OUT" +grep -q "$LF:5 " <<< "$OUT" || fail "a paragraph carries its heading's words (zebra): $OUT" +! grep -q "$LF:18" <<< "$OUT" || fail "a paragraph under another heading without the words does not match: $OUT" +pass "--find: this, root, archive and lessons rows; refs are paths, archive refs name their pool, paragraphs carry path:line" + +# JSON: one object per row, the frozen keys, unrounded score, line null for an entry. +J="$(fx --json --limit 20 zebra permit depot crossing)" +python3 -I -c ' +import json, sys +rows = [json.loads(l) for l in sys.stdin.read().splitlines()] +tsv = sys.argv[1].splitlines() +assert len(rows) == len(tsv), (len(rows), len(tsv)) +for r, t in zip(rows, tsv): + assert set(r) == {"score", "source", "ref", "path", "line", "text", "matched_words"}, r + assert isinstance(r["score"], float) and "%.1f" % r["score"] == t.split(" ")[0], (r["score"], t) + assert r["path"].startswith("/") and r["ref"].startswith(r["path"]), r + if r["source"] == "lessons": + assert isinstance(r["line"], int) and r["ref"] == "%s:%d" % (r["path"], r["line"]), r + else: + assert r["line"] is None and r["ref"] == r["path"], r + assert r["matched_words"] == sorted(set(r["matched_words"])) and r["matched_words"], r +assert any(r["score"] != round(r["score"], 1) for r in rows), "scores are unrounded" +assert "crossing" in rows[0]["matched_words"] or "permit" in rows[0]["matched_words"], rows[0] +' "$(fx --limit 20 zebra permit depot crossing)" <<< "$J" || fail "--json shape: $J" +pass "--find --json: one object per row; score unrounded; path, line (null for an entry), matched_words" + +# --exclude drops that file (by path, before the word counts), never a same-named entry elsewhere. +X="$(fx --json --limit 20 --exclude "$PP/_archive/same-zebra.md" zebra archived fact)" +! grep -q "$(cd "$PP" && pwd -P)/_archive/same-zebra.md" <<< "$X" && grep -q "$(cd "$RP" && pwd -P)/_archive/same-zebra.md" <<< "$X" \ + || fail "--exclude must drop exactly the named file: $X" +s1="$(fx --json zebra archived fact | python3 -I -c 'import json,sys; print([json.loads(l) for l in sys.stdin if json.loads(l)["path"].endswith("rootpool/_archive/same-zebra.md")][0]["score"])')" +s2="$(python3 -I -c 'import json,sys; print([json.loads(l) for l in sys.stdin if json.loads(l)["path"].endswith("rootpool/_archive/same-zebra.md")][0]["score"])' <<< "$X")" +[ "$s1" != "$s2" ] || fail "--exclude must act before the word counts (scores unchanged: $s1)" +pass "--exclude: drops the file by path before scoring; the same name in another pool stays" + +# No match is empty and exits 0; a search that cannot read a source exits 1. +OUT="$(fx quokka marsupial 2>&1)"; rc=$? +[ "$rc" -eq 0 ] && [ -z "$OUT" ] || fail "no match: empty output, exit 0 (rc=$rc): $OUT" +if [ "$(id -u)" != 0 ]; then + chmod 000 "$RP/_archive"; OUT="$(fx zebra permit 2>&1)"; rc=$?; chmod 755 "$RP/_archive" + [ "$rc" -eq 1 ] && grep -q 'find failed' <<< "$OUT" || fail "an unreadable archive must fail the search (rc=$rc): $OUT" + chmod 000 "$W/CONTEXT/projects"; OUT="$(fx zebra permit 2>&1)"; rc=$?; chmod 755 "$W/CONTEXT/projects" + [ "$rc" -eq 1 ] || fail "an unreadable lessons dir must fail the search (rc=$rc): $OUT" + pass "--find: no match is empty with exit 0; an unreadable archive or lessons dir exits 1" +else + echo "SKIP: unreadable-source cases (running as root reads mode 000 dirs)" +fi + +# Display fields escape tab and newline: a lessons file whose name holds a tab. +printf '## Tab\n\nzebra permit depot tabbed\n' > "$W/CONTEXT/projects/tab$(printf '\t')name.md" +OUT="$(fx --limit 30 zebra permit depot tabbed)" +grep -q 'tab\\tname.md:3' <<< "$OUT" && ! grep -qP "tab\tname" <<< "$OUT" || fail "a tab in a ref must be escaped: $OUT" +[ "$(cut -f1-4 <<< "$OUT" | awk -F'\t' 'NF != 4' | wc -l)" = 0 ] || fail "every row has exactly four fields: $OUT" +pass "--find: a tab in a path is escaped, every row keeps four fields" + +# The lessons cache is a speed-up only: a corrupt cache gives the same result. +before="$(fx --json --limit 5 zebra permit depot crossing)" +for c in "$A/state/memory-lessons-index/"*.json; do printf 'garbage' > "$c"; done +after="$(fx --json --limit 5 zebra permit depot crossing)" +[ -n "$before" ] && [ "$before" = "$after" ] || fail "a corrupt lessons cache must not change the result" +pass "--find: the lessons cache is rebuilt when corrupt; the result does not depend on it" +rm -rf "$A" + +# --- Test 15: --pool-for prints the pool the digest uses and creates nothing. ----------- +# session-end rebuilds this directory's index through it (2026-11-17), so it must +# agree with --digest for a linked worktree, the host-key file and a profile's # projects//memory, and must never create a pool for a directory without one. P="$(mktemp -d "${TMPDIR:-/tmp}/memory-index-poolfor.XXXXXX")"; P="$(cd "$P" && pwd -P)" -PH="$P/home"; mkdir -p "$PH/.config/ops" "$P/ops/.claude-memory" "$P/elsewhere" +PH="$P/home"; mkdir -p "$PH/.config/ops" "$P/cw/.claude-memory" "$P/elsewhere" gx() { git -c init.defaultBranch=main -c user.name=t -c user.email=t@example.invalid "$@"; } gx init -q "$P/proj" && gx -C "$P/proj" commit -q --allow-empty -m base \ && gx -C "$P/proj" worktree add -q -b lane "$P/proj-wt" 2>/dev/null || fail "--pool-for: cannot build the fixture repo" printf 'fixhost\n' > "$PH/.config/ops/memory-host" PKEY="$(printf '%s' "$P/proj" | sed 's/[^A-Za-z0-9]/-/g')" -PPOOL="$P/ops/.claude-memory/fixhost$PKEY"; mkdir -p "$PPOOL" +PPOOL="$P/cw/.claude-memory/fixhost$PKEY"; mkdir -p "$PPOOL" printf -- '---\nname: pool-entry\ndescription: an entry\nmetadata:\n type: project\n---\nbody\n' > "$PPOOL/pool-entry.md" PCFG="" # a profile dir for one case; empty means none pf() { env -u MEMORY_DIGEST_HOST -u MEMORY_INDEX_DIR -u MEMORY_DIGEST_ROOT_DIR -u CLAUDE_CONFIG_DIR \ -u CLAUDE_PROJECT_DIR -u OPS_DIR HOME="$PH" ${PCFG:+CLAUDE_CONFIG_DIR="$PCFG"} "$GEN" "$@"; } -OUT="$(pf --pool-for --cwd "$P/proj-wt" --ops "$P/ops")"; rc=$? +OUT="$(pf --pool-for --cwd "$P/proj-wt" --ops "$P/cw")"; rc=$? [ "$rc" = 0 ] && [ "$OUT" = "$PPOOL" ] || fail "--pool-for from a worktree with the host-key file: rc=$rc out=$OUT, want $PPOOL" -pf --digest --cwd "$P/proj-wt" --ops "$P/ops" | grep -qF "$PPOOL" \ +pf --digest --cwd "$P/proj-wt" --ops "$P/cw" | grep -qF "$PPOOL" \ || fail "--digest does not name the pool --pool-for printed ($PPOOL)" mkdir -p "$P/cfg/projects/$PKEY/memory" cp "$PPOOL/pool-entry.md" "$P/cfg/projects/$PKEY/memory/profile-entry.md" PCFG="$P/cfg" -OUT="$(pf --pool-for --cwd "$P/proj-wt" --ops "$P/ops")" +OUT="$(pf --pool-for --cwd "$P/proj-wt" --ops "$P/cw")" [ "$OUT" = "$P/cfg/projects/$PKEY/memory" ] || fail "--pool-for with a profile's projects//memory: got $OUT" -pf --digest --cwd "$P/proj-wt" --ops "$P/ops" | grep -qF "$OUT" \ +pf --digest --cwd "$P/proj-wt" --ops "$P/cw" | grep -qF "$OUT" \ || fail "--digest does not name the profile pool --pool-for printed ($OUT)" PCFG="" before="$(find "$P" | sort)" -OUT="$(pf --pool-for --cwd "$P/elsewhere" --ops "$P/ops" 2>"$ERRFILE")"; rc=$? +OUT="$(pf --pool-for --cwd "$P/elsewhere" --ops "$P/cw" 2>"$ERRFILE")"; rc=$? [ "$rc" = 4 ] && [ -z "$OUT" ] || fail "--pool-for without a pool must exit 4 and print nothing: rc=$rc out=$OUT" [ "$before" = "$(find "$P" | sort)" ] || fail "--pool-for created something for a directory without a pool" pf --pool-for --bogus x >/dev/null 2>&1; rc=$? diff --git a/.claude-config/bin/tests/memory-settle-test.py b/.claude-config/bin/tests/memory-settle-test.py new file mode 100644 index 0000000..833fdd5 --- /dev/null +++ b/.claude-config/bin/tests/memory-settle-test.py @@ -0,0 +1,1630 @@ +#!/usr/bin/env python3 +"""memory-settle-test.py - the nightly memory mover (memory-index --settle and +--restore) in local mode, its status file, --health and memory-backfill-modified. + +Why pin it (a test of a move tool cannot reach real files): the settle moves +files in the git checkout the owner's sessions write all day, and its digest +code runs at every boot. A mover that reached outside its store, followed a +link out of it, lost a concurrent edit or swept the owner's staged work into +its commit would cost real work silently. Every case builds throwaway +repositories inside the sandbox; nothing names the real checkout, and an +outside sentinel tree must survive every case. + +The template runs the settle in local mode only, so every World writes a +local-mode env file naming its own throwaway checkout. Selection is checked +through --dry-run (the planner with no mover) and the eligibility functions +(memory_settle.py, through memory-index); the write path through real runs, +with a git wrapper at the process boundary that stops the mover at chosen +points. + +Run: .claude-config/bin/sandbox-run --no-net --ro-bind -- python3 +""" +import os, runpy; runpy.run_path(os.path.join(os.path.dirname(os.path.realpath(__file__)), "..", "sandbox_guard.py"))["require"]() +import fcntl +import hashlib +import json +import re +import shutil +import stat +import subprocess +import sys +import tempfile +import time +import unittest +from importlib.machinery import SourceFileLoader +from unittest.mock import patch + +sys.dont_write_bytecode = True +BIN = os.path.realpath(os.path.join(os.path.dirname(os.path.realpath(__file__)), "..")) +IDX = os.path.join(BIN, "memory-index") +BACKFILL = os.path.join(BIN, "memory-backfill-modified") +MI = SourceFileLoader("memory_index_under_test", IDX).load_module() +MS = MI.settle_module() # the mover's code, memory_settle.py, as memory-index loads it +REAL_GIT = shutil.which("git") +HOST = "hk" +NOW = "2026-11-20T03:10:00Z" +STATUS_KEYS = {"schema", "box", "last_attempt_at", "last_attempt_result", "last_success_at", + "commit", "pending_delivery", "error", "pools"} + +FAKE_GIT = r"""#!/usr/bin/env bash +# A git at the process boundary. FAKE_GIT holds the modes; REAL_GIT the real one. +args=("$@"); i=0; sub="" +while [ $i -lt ${#args[@]} ]; do + a="${args[$i]}" + if [ "$a" = "-C" ] || [ "$a" = "-c" ]; then i=$((i+2)); continue; fi + case "$a" in -*) i=$((i+1)); continue ;; esac + sub="$a"; break +done +case ",${FAKE_GIT:-}," in + *,push-reject,*) [ "$sub" = push ] && { echo " ! [rejected] HEAD -> master (fetch first)" >&2; exit 1; } ;; +esac +case ",${FAKE_GIT:-}," in + *,push-lost,*) if [ "$sub" = push ]; then "$REAL_GIT" "$@" >/dev/null 2>&1; echo "fatal: the remote end hung up unexpectedly" >&2; exit 128; fi ;; +esac +case ",${FAKE_GIT:-}," in + *,commit-fail,*) [ "$sub" = commit ] && { echo "fatal: simulated commit failure" >&2; exit 1; } ;; +esac +case ",${FAKE_GIT:-}," in + *,push-hook-once,*) if [ "$sub" = push ] && [ ! -e "$FAKE_GIT_MARK" ]; then : > "$FAKE_GIT_MARK"; bash "$FAKE_GIT_HOOK" || exit 97; fi ;; +esac +exec "$REAL_GIT" "$@" +""" + + +def slurp(path, mode="r"): + with open(path, mode) as fh: + return fh.read() + + +def key(path): + return re.sub(r"[^A-Za-z0-9]", "-", path) + + +def sha(path): + with open(path, "rb") as fh: + return hashlib.sha256(fh.read()).hexdigest() + + +def entry_text(stem, desc, typ="reference", modified=None, pinned=False, body="body text\n"): + lines = ["---", f"name: {stem}", f'description: "{desc}"', "metadata:", f" type: {typ}"] + if modified: + lines.append(f" modified: {modified}") + if pinned: + lines.append(" pinned: true") + return "\n".join(lines) + "\n---\n" + body + + +def long_desc(i): + return (f"Lesson number {i:03d} about a gotcha seen on a client box, written down with the fix, " + f"the date it was found and enough words to fill the line cap {i:03d}") + + +class World: + """A bare remote, the shared checkout's stand-in, and helpers.""" + + def __init__(self, tc): + self.tc = tc + self.tmp = os.path.realpath(tempfile.mkdtemp(prefix="settle-")) + self.home = os.path.join(self.tmp, "home") + self.state = os.path.join(self.tmp, "state") + self.remote = os.path.join(self.tmp, "remote.git") + self.shared = os.path.join(self.tmp, "shared") + self.outside = os.path.join(self.tmp, "outside") + self.fakebin = os.path.join(self.tmp, "fakebin") + for d in (self.home, self.outside, self.fakebin): + os.makedirs(d) + self.gitcfg = os.path.join(self.tmp, "gitconfig") + with open(self.gitcfg, "w") as fh: + fh.write("[user]\n\tname = Settle Test\n\temail = settle@example.invalid\n" + "[init]\n\tdefaultBranch = master\n[advice]\n\tdetachedHead = false\n") + # The sentinel tree: files beside the store that no run may touch. + self.sentinel = os.path.join(self.outside, "sentinel.md") + with open(self.sentinel, "w") as fh: + fh.write(entry_text("sentinel", "outside the store; must survive", modified="2020-01-01T00:00:00Z")) + self.sentinel_sha = sha(self.sentinel) + with open(os.path.join(self.fakebin, "git"), "w") as fh: + fh.write(FAKE_GIT) + os.chmod(os.path.join(self.fakebin, "git"), 0o755) + self.env = {k: v for k, v in os.environ.items() + if not k.startswith(("GIT_", "MEMORY_", "OPS_", "CLAUDE_"))} + self.env.update(HOME=self.home, OPS_STATE_DIR=self.state, OPS_DIR=self.shared, + MEMORY_DIGEST_HOST=HOST, MEMORY_SETTLE_NOW=NOW, GIT_CONFIG_GLOBAL=self.gitcfg, + GIT_CONFIG_NOSYSTEM="1", CLAUDE_CONFIG_DIR=os.path.join(self.home, ".claude"), + REAL_GIT=REAL_GIT, PYTHONDONTWRITEBYTECODE="1", TZ="UTC") + self.clone = os.path.join(self.home, ".local", "share", "ops", "memory-settle", "OPS") + self.git(self.tmp, "init", "--quiet", "--bare", self.remote) + self.git(self.tmp, "clone", "--quiet", self.remote, self.shared) + self.git(self.shared, "commit", "--quiet", "--allow-empty", "-m", "init", date="2026-09-01T00:00:00Z") + self.git(self.shared, "push", "--quiet", "origin", "HEAD:master") + self.store = os.path.join(self.shared, ".claude-memory") + self.root = os.path.join(self.store, HOST + key(self.shared)) + # The template ships local mode only (memory_settle.py settle_target). + self.write(os.path.join(self.home, ".config", "ops", "memory-settle.env"), + f"MEMORY_SETTLE_OWNER=1\nMEMORY_SETTLE_MODE=local\nMEMORY_SETTLE_ROOT={self.shared}\n") + + def git(self, repo, *args, date=None, check=True, env=None): + e = dict(self.env) + e.pop("PATH", None) + e["PATH"] = os.environ.get("PATH", "/usr/bin:/bin") + if date: + e.update(GIT_AUTHOR_DATE=date, GIT_COMMITTER_DATE=date) + if env: + e.update(env) + r = subprocess.run([REAL_GIT, "-C", repo] + list(args), env=e, capture_output=True, text=True, + timeout=60) + if check and r.returncode != 0: + raise AssertionError(f"git {args} failed: {r.stderr}") + return r.stdout + + def write(self, path, text): + os.makedirs(os.path.dirname(path), exist_ok=True) + with open(path, "w") as fh: + fh.write(text) + + def entry(self, pool, stem, desc, **kw): + p = os.path.join(pool, stem + ".md") + self.write(p, entry_text(stem, desc, **kw)) + return p + + def commit_push(self, repo, msg, date="2026-10-01T00:00:00Z", paths=(".",)): + self.git(repo, "add", "-A", "--", *paths) + self.git(repo, "commit", "--quiet", "-m", msg, date=date) + self.git(repo, "push", "--quiet", "origin", "HEAD:master") + + def overflow_root(self, n=72, start=0, typ="reference", prefix="reference-r"): + """n old entries in the root pool, entry i dated day i from 2026-09-01.""" + for i in range(start, start + n): + day = 1 + i + month, d = (9, day) if day <= 30 else ((10, day - 30) if day <= 61 else (11, day - 61)) + self.entry(self.root, f"{prefix}{i:03d}", long_desc(i), typ=typ, + modified=f"2026-{month:02d}-{d:02d}T12:00:00Z") + MI_index(self.root) + + def other_clone(self, name="other"): + path = os.path.join(self.tmp, name) + self.git(self.tmp, "clone", "--quiet", self.remote, path) + return path + + def run(self, *args, fake=None, extra=None, timeout=300): + e = dict(self.env) + if fake: + e["PATH"] = self.fakebin + os.pathsep + os.environ.get("PATH", "/usr/bin:/bin") + e["FAKE_GIT"] = fake + e["FAKE_GIT_MARK"] = os.path.join(self.tmp, "fake-mark") + if extra: + e.update(extra) + return subprocess.run([sys.executable, "-I", "-B", IDX] + list(args), env=e, capture_output=True, + text=True, timeout=timeout, cwd=self.tmp) + + def status(self): + with open(os.path.join(self.state, "memory-settle-status.json")) as fh: + return json.load(fh) + + def remote_ls(self, rel_dir): + out = self.git(self.remote, "ls-tree", "--name-only", "master", rel_dir + "/") + return sorted(os.path.basename(x) for x in out.split("\n") if x) + + def remote_show(self, rel): + return self.git(self.remote, "show", f"master:{rel}") + + def rel(self, path): + return os.path.relpath(path, self.shared) + + def snapshot(self, top): + out = [] + for r, ds, fs in os.walk(top): + ds.sort() + for f in sorted(fs) + ds: + p = os.path.join(r, f) + st = os.lstat(p) + data = "" + if stat.S_ISREG(st.st_mode): + data = sha(p) + elif stat.S_ISLNK(st.st_mode): + data = os.readlink(p) + out.append((os.path.relpath(p, top), st.st_mode, st.st_mtime_ns, data)) + return out + + +def MI_index(pool): + MI.write_index(pool) + + +def dry_moves(out): + return [m.group(1) for m in re.finditer(r"^ move (\S+)", out, re.M)] + + +def dry_keeps(out): + return {m.group(1): m.group(2) for m in re.finditer(r"^ keep (\S+): (.*)$", out, re.M)} + + +class Base(unittest.TestCase): + def setUp(self): + self.w = World(self) + + def tearDown(self): + # C1 oracle: the outside sentinel is byte-identical after every case. + try: + self.assertEqual(sha(self.w.sentinel), self.w.sentinel_sha, "the outside sentinel changed") + finally: + for r, ds, fs in os.walk(self.w.tmp): + for d in ds: + try: + os.chmod(os.path.join(r, d), 0o755) + except OSError: + pass + shutil.rmtree(self.w.tmp, ignore_errors=True) + + def seed_root(self, n=72): + self.w.overflow_root(n) + self.w.commit_push(self.w.shared, "seed root pool") + + +class Eligibility(unittest.TestCase): + """The never-moved classes and the 48-hour floor, on the functions the + settle uses (no repository, no moves).""" + + def setUp(self): + self.tmp = tempfile.mkdtemp(prefix="elig-") + self.store = os.path.join(self.tmp, "store") + self.pool = os.path.join(self.store, "hk-pool") + os.makedirs(os.path.join(self.pool, "_archive")) + self.now = MS.stamp_latest(NOW)[0] + + def tearDown(self): + shutil.rmtree(self.tmp, ignore_errors=True) + + def ctx(self, dirty=None, changes=None): + c = MS.Ctx.__new__(MS.Ctx) + c.now, c.work_top, c.work_store = self.now, self.tmp, self.store + c.dirty, c.changes = dirty or {}, changes or {} + return c + + def ent(self, fn="e.md", typ="reference", pinned=False, modified="2026-10-01T00:00:00Z"): + p = os.path.join(self.pool, fn) + with open(p, "w") as fh: + fh.write("x") + return {"path": p, "fn": fn, "type": typ, "pinned": pinned, "modified": modified} + + def rel(self, e): + return os.path.relpath(e["path"], self.tmp) + + def test_every_never_moved_class(self): + old = MS.stamp_latest("2026-10-01T00:00:00Z")[0] + e = self.ent() + ok = {self.rel(e): old} + self.assertIsNone(self.ctx(changes=ok).protect_reason(e, self.pool), "an old, clean, stamped entry may move") + self.assertEqual(self.ctx(changes=ok).protect_reason(self.ent(pinned=True), self.pool), "pinned") + self.assertEqual(self.ctx(changes=ok).protect_reason(self.ent(typ="user"), self.pool), "type user") + for code in ("??", " M", "M ", "A ", " D"): + why = self.ctx(dirty={self.rel(e): code}, changes=ok).protect_reason(e, self.pool) + self.assertTrue(why and why.startswith("uncommitted change"), (code, why)) + self.assertEqual(self.ctx(changes=ok).protect_reason(self.ent(modified=None), self.pool), + "no metadata.modified stamp") + why = self.ctx(changes=ok).protect_reason(self.ent(modified="last tuesday"), self.pool) + self.assertIn("is not an ISO date or time", why) + why = self.ctx(changes=ok).protect_reason(self.ent(modified="2026-02-30T00:00:00Z"), self.pool) + self.assertIn("is not a real date", why) + why = self.ctx(changes=ok).protect_reason(self.ent(modified="2026-11-21T00:00:00Z"), self.pool) + self.assertTrue(why.startswith("future stamp"), why) + self.assertEqual(self.ctx(changes={}).protect_reason(e, self.pool), "no commit found for it") + # a fresh committed edit under a stale stamp + why = self.ctx(changes={self.rel(e): self.now - 3600}).protect_reason(e, self.pool) + self.assertTrue(why.startswith("changed within 48 h"), why) + # an occupied archive path + with open(os.path.join(self.pool, "_archive", "e.md"), "w") as fh: + fh.write("other") + self.assertEqual(self.ctx(changes=ok).protect_reason(e, self.pool), "archive destination occupied") + + def test_floor_and_zone_boundaries(self): + cases = [ + ("2026-11-18T03:10:01Z", True), ("2026-11-18T03:10:00Z", False), ("2026-11-18T03:09:59Z", False), + ("2026-11-17T22:10:01-05:00", True), ("2026-11-17T22:09:59-05:00", False), + ("2026-11-18T17:10:01+14:00", True), ("2026-11-18T17:09:59+14:00", False), + ("2026-11-17T15:10:01", True), ("2026-11-17T15:09:59", False), # no zone: read as UTC-12 + ("2026-11-17", True), ("2026-11-16", False), # a date: its last instant at UTC-12 + ("2026-11-18T03:10:01.5Z", True), ("2026-11-18 03:10:01Z", True), + ] + for stamp, protected in cases: + e = self.ent(modified=stamp) + why = self.ctx(changes={self.rel(e): 0}).protect_reason(e, self.pool) + if protected: + self.assertTrue(why and why.startswith("changed within 48 h"), (stamp, why)) + else: + self.assertIsNone(why, (stamp, why)) + self.assertIsNone(MS.stamp_latest("2026-11-18T03:10:01+15:00")[0], "an impossible zone is invalid") + + def test_move_guard_refuses_escapes(self): + e = self.ent() + outside = os.path.join(self.tmp, "outside.md") + with open(outside, "w") as fh: + fh.write("outside") + link = os.path.join(self.pool, "link.md") + os.symlink(outside, link) + self.assertEqual(MS.move_refusal(link, self.pool, self.store), "a symlink or not a regular file") + self.assertEqual(MS.move_refusal(outside, self.pool, self.store), "not an entry file directly in the pool") + other = os.path.join(self.tmp, "elsewhere") + os.makedirs(other) + shutil.copy(e["path"], os.path.join(other, "e.md")) + self.assertEqual(MS.move_refusal(os.path.join(other, "e.md"), other, self.store), + "the pool is not a real directory directly in the store") + os.rmdir(os.path.join(self.pool, "_archive")) + os.symlink(other, os.path.join(self.pool, "_archive")) + self.assertEqual(MS.move_refusal(e["path"], self.pool, self.store), + "the archive path is a symlink or not a directory") + + +class Selection(Base): + """What moves, from the dry run (the planner with no mover).""" + + def test_lowest_ranked_first_by_tier_then_age(self): + # 20 feedback entries (tier 1) dated after 52 reference entries (tier 2): + # the references go first, oldest first, and no feedback entry moves. + self.w.overflow_root(52) + self.w.overflow_root(20, start=52, typ="feedback", prefix="feedback-f") + self.w.commit_push(self.w.shared, "seed root pool") + r = self.w.run("--settle", "--dry-run") + self.assertEqual(r.returncode, 0, r.stderr + r.stdout) + moves = dry_moves(r.stdout) + self.assertTrue(moves, r.stdout) + self.assertEqual(moves, [f"reference-r{i:03d}.md" for i in range(len(moves))]) + + def test_protected_overflow_never_moves_a_described_entry(self): + self.seed_root() + # Make every entry below the budget line (the oldest, all one tier) + # uncommitted in the shared checkout; the described ones stay eligible. + fit = subprocess.run([sys.executable, "-I", "-B", IDX, "--digest-fit", self.w.root], + env=self.w.env, capture_output=True, text=True, timeout=60).stdout.split("\t") + described = int(fit[2]) + over = [f"reference-r{i:03d}.md" for i in range(72 - described)] + for fn in over: + with open(os.path.join(self.w.root, fn), "a") as fh: + fh.write("local edit, not committed\n") + r = self.w.run("--settle", "--dry-run") + self.assertEqual(r.returncode, 0, r.stderr) + self.assertEqual(dry_moves(r.stdout), [], "nothing below the line may move, and nothing above it") + keeps = dry_keeps(r.stdout) + self.assertTrue(set(over) <= set(keeps), keeps) + self.assertTrue(all(v.startswith("uncommitted change") for v in keeps.values()), keeps) + r = self.w.run("--settle") + self.assertEqual(r.returncode, 0, r.stderr) + st = self.w.status() + self.assertEqual(st["last_attempt_result"], "noop") + pool = st["pools"][os.path.basename(self.w.root)] + self.assertEqual(pool["moved"], 0) + self.assertGreaterEqual(pool["protected_overflow"], len(over)) + self.assertFalse(pool["fits"]) + self.assertEqual(self.w.remote_ls(self.w.rel(self.w.root) + "/_archive"), []) + + def test_project_pool_settles_to_its_own_fit_whatever_the_root_holds(self): + """The setpoint is each pool's own fit (what --digest-fit + measures), so a project's moves do not depend on the root pool: 30 + root feedback entries, which outrank a project's own references in + its session digest, change nothing.""" + proj = os.path.join(self.w.shared, "PROJECTS", "Org", "proj") + os.makedirs(proj) + self.w.git(proj, "init", "--quiet") + ppool = os.path.join(self.w.store, HOST + key(proj)) + for i in range(70): + self.w.entry(ppool, f"reference-p{i:03d}", long_desc(500 + i), + modified=f"2026-{9 + i // 28:02d}-{1 + i % 28:02d}T08:00:00Z") + self.w.entry(self.w.root, "reference-small-root", "one root entry", modified="2026-09-01T00:00:00Z") + self.w.commit_push(self.w.shared, "seed pools", paths=(".claude-memory",)) + alone = self.w.run("--settle", "--dry-run", ppool) + self.assertEqual(alone.returncode, 0, alone.stderr + alone.stdout) + small_root = dry_moves(alone.stdout) + self.assertTrue(small_root, alone.stdout) + self.w.overflow_root(30, start=40, typ="feedback", prefix="feedback-f") + self.w.commit_push(self.w.shared, "a busy root", paths=(".claude-memory",)) + busy = self.w.run("--settle", "--dry-run", ppool) + self.assertEqual(dry_moves(busy.stdout), small_root, "the root pool's volume never sizes a project pool") + self.assertTrue(all(m.startswith("reference-p") for m in small_root)) + # Applied: --digest-fit (the gate's own measure) reports the pool fits, + # and with the last-moved entry back it would not. + r = self.w.run("--settle") + self.assertEqual(r.returncode, 0, r.stderr + r.stdout) + self.w.git(self.w.shared, "pull", "-q", "--ff-only") + + def fit(): + out = subprocess.run([sys.executable, "-I", "-B", IDX, "--digest-fit", ppool], + env=self.w.env, capture_output=True, text=True, timeout=60).stdout + return out.strip().split("\t")[3:] + self.assertEqual(fit(), ["0", "0"]) + os.rename(os.path.join(ppool, "_archive", small_root[-1]), os.path.join(ppool, small_root[-1])) + self.assertNotEqual(fit(), ["0", "0"], "one move fewer would not fit") + os.rename(os.path.join(ppool, small_root[-1]), os.path.join(ppool, "_archive", small_root[-1])) + + def test_fresh_committed_edit_and_missing_stamp_protect(self): + self.seed_root() + r = self.w.run("--settle", "--dry-run") + low = dry_moves(r.stdout) + a, b = low[0], low[1] + with open(os.path.join(self.w.root, a), "a") as fh: + fh.write("a committed correction yesterday\n") + p = os.path.join(self.w.root, b) + text = slurp(p) + with open(p, "w") as fh: + fh.write(re.sub(r" modified: .*\n", "", text)) + self.w.commit_push(self.w.shared, "edit two old entries", date="2026-11-19T03:00:00Z") + r = self.w.run("--settle", "--dry-run") + self.assertEqual(r.returncode, 0, r.stderr) + moves = dry_moves(r.stdout) + # a keeps its old stamp (so it still ranks lowest) but its last commit + # is a day old; b lost its stamp. Neither moves; the next ones do. + self.assertNotIn(a, moves) + self.assertNotIn(b, moves) + self.assertEqual(moves[0], low[2], r.stdout) + # Seen from the planner: a was weighed and kept for its commit time. + self.assertIn(f" keep {a}: changed within 48 h (2026-11-19T03:00:00Z)", r.stdout + self.keep_trace(a)) + + def keep_trace(self, fn): + """The planner's reason for fn, read from the module (the dry run lists + only what is still over the budget at the end).""" + ctx = MS.Ctx.__new__(MS.Ctx) + ctx.now = MS.stamp_latest(NOW)[0] + ctx.work_top = self.w.shared + ctx.work_store = self.w.store + old = dict(os.environ) + try: + os.environ.update(self.w.env) + ctx.dirty = MS.dirty_paths(self.w.shared) + ctx.changes = MS.last_changes(self.w.shared, [os.path.basename(self.w.root)]) + e = [x for x in MI.load_pool(self.w.root, "this")[0] if x["fn"] == fn][0] + return f" keep {fn}: {ctx.protect_reason(e, self.w.root)}" + finally: + os.environ.clear() + os.environ.update(old) + + def test_pool_arguments_outside_the_store_are_refused(self): + self.seed_root() + for bad in (self.w.outside, os.path.join(self.w.shared, ".claude-memory"), self.w.tmp): + r = self.w.run("--settle", "--dry-run", bad) + self.assertEqual(r.returncode, 1, (bad, r.stdout)) + self.assertIn("not a pool directory directly in", r.stderr) + link = os.path.join(self.w.store, HOST + "-linked") + os.symlink(self.w.outside, link) + r = self.w.run("--settle", "--dry-run", link) + self.assertEqual(r.returncode, 1, r.stdout) + r = self.w.run("--settle", "--dry-run") + self.assertNotIn("-linked", r.stdout, "a symlinked pool is never listed") + + def test_a_pool_no_directory_maps_to_is_still_settled(self): + """Own fit needs no session directory: a pool named for a directory + that exists nowhere settles like any other.""" + ghost = os.path.join(self.w.store, HOST + key("/nowhere/at/all")) + for i in range(70): + self.w.entry(ghost, f"g{i:03d}", long_desc(i), modified=f"2026-09-{1 + i % 28:02d}T00:00:00Z") + self.w.commit_push(self.w.shared, "ghost pool") + r = self.w.run("--settle", "--dry-run") + self.assertEqual(r.returncode, 0, r.stdout + r.stderr) + self.assertTrue(dry_moves(r.stdout)) + r = self.w.run("--settle") + self.assertEqual(r.returncode, 0, r.stdout + r.stderr) + self.assertEqual(self.w.status()["last_attempt_result"], "ok") + self.assertTrue(self.w.status()["pools"][os.path.basename(ghost)]["moved"]) + + +class DryRun(Base): + def test_dry_run_writes_nothing(self): + self.seed_root() + before = self.w.snapshot(self.w.tmp) + refs = self.w.git(self.w.remote, "for-each-ref") + r = self.w.run("--settle", "--dry-run") + self.assertEqual(r.returncode, 0, r.stderr) + self.assertTrue(dry_moves(r.stdout)) + self.assertEqual(self.w.snapshot(self.w.tmp), before, "the dry run changed a file") + self.assertEqual(self.w.git(self.w.remote, "for-each-ref"), refs) + self.assertFalse(os.path.exists(self.w.state)) + self.assertFalse(os.path.exists(self.w.clone)) + + +class Controls(Base): + def test_disabled(self): + self.seed_root() + r = self.w.run("--settle", extra={"MEMORY_SETTLE": "0"}) + self.assertEqual(r.returncode, 0, r.stderr) + st = self.w.status() + self.assertEqual(set(st), STATUS_KEYS) + self.assertEqual(st["last_attempt_result"], "disabled") + self.assertFalse(os.path.exists(self.w.clone)) + + def test_manual_settle_honors_the_env_file_off_switch(self): + self.seed_root() + env_file = os.path.join(self.w.home, ".config", "ops", "memory-settle.env") + with open(env_file, "a", encoding="utf-8") as fh: + fh.write('MEMORY_SETTLE=1\nMEMORY_SETTLE="0"\n') + head = self.w.git(self.w.shared, "rev-parse", "HEAD") + before = self.w.snapshot(self.w.store) + dry = self.w.run("--settle", "--dry-run") + self.assertEqual(dry.returncode, 0, dry.stderr) + self.assertIn("MEMORY_SETTLE=0 (an apply run would do nothing)", dry.stdout) + self.assertTrue(dry_moves(dry.stdout), "the fixture must contain entries eligible to move") + for extra in (None, {"MEMORY_SETTLE": "1"}): + with self.subTest(extra=extra): + run = self.w.run("--settle", extra=extra) + self.assertEqual(run.returncode, 0, run.stderr) + self.assertEqual(self.w.status()["last_attempt_result"], "disabled") + self.assertEqual(self.w.git(self.w.shared, "rev-parse", "HEAD"), head) + self.assertEqual(self.w.snapshot(self.w.store), before) + + def test_lock_held_by_another_mover(self): + self.seed_root() + os.makedirs(self.w.state) + with open(os.path.join(self.w.state, "memory-settle.lock"), "a+") as fh: + fcntl.flock(fh.fileno(), fcntl.LOCK_EX) + r = self.w.run("--settle", extra={"MEMORY_SETTLE_LOCK_WAIT": "0"}) + r2 = self.w.run("--restore", "x", extra={"MEMORY_SETTLE_LOCK_WAIT": "0"}) + self.assertEqual(r.returncode, 75, r.stderr) + self.assertEqual(r2.returncode, 75, r2.stderr) + self.assertFalse(os.path.exists(os.path.join(self.w.state, "memory-settle-status.json"))) + self.assertFalse(os.path.exists(self.w.clone)) + +class Status(Base): + """The status file as the gate reads it (Lane B's check): schema 1, + last_attempt_at on every run, last_success_at refreshed by ok, noop and + protected-only runs, ISO 8601 with Z, and the per-pool counts.""" + + ISO = r"^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(Z|[+-]\d\d:\d\d)$" + + def test_success_refreshes_on_ok_noop_and_protected_only(self): + self.seed_root() + for when, extra in (("2026-11-20T03:10:00Z", None), ("2026-11-21T03:10:00Z", None)): + r = self.w.run("--settle", extra=dict({"MEMORY_SETTLE_NOW": when}, **(extra or {}))) + self.assertEqual(r.returncode, 0, r.stderr) + st = self.w.status() + self.assertIs(type(st["schema"]), int) + self.assertEqual(st["schema"], 1) + self.assertEqual((st["last_attempt_at"], st["last_success_at"]), (when, when), st["last_attempt_result"]) + self.assertRegex(st["last_attempt_at"], self.ISO) + self.assertEqual(st["last_attempt_result"], "noop") + pool = st["pools"][os.path.basename(self.w.root)] + self.assertTrue({"total", "described", "moved", "protected_overflow", "protected_reasons"} <= set(pool), pool) + # Protected-only: a new overflow whose only movable candidates are uncommitted. + self.w.git(self.w.shared, "pull", "-q", "--ff-only") + for i in range(20): + self.w.entry(self.w.root, f"reference-a{i:03d}", long_desc(900 + i), modified="2026-08-01T00:00:00Z") + self.w.commit_push(self.w.shared, "more") + # Every live entry gets an uncommitted edit, so no overflow entry may move. + for fn in os.listdir(self.w.root): + if fn.endswith(".md") and fn != "MEMORY.md": + with open(os.path.join(self.w.root, fn), "a") as fh: + fh.write("uncommitted\n") + r = self.w.run("--settle", extra={"MEMORY_SETTLE_NOW": "2026-11-22T03:10:00Z"}) + self.assertEqual(r.returncode, 0, r.stderr) + st = self.w.status() + pool = st["pools"][os.path.basename(self.w.root)] + self.assertEqual((st["last_attempt_result"], pool["moved"]), ("noop", 0)) + self.assertGreater(pool["protected_overflow"], 0) + self.assertEqual(pool["protected_reasons"], {"uncommitted change in the shared checkout": pool["protected_overflow"]}) + self.assertEqual(st["last_success_at"], "2026-11-22T03:10:00Z", "a protected-only run is a success") + + def test_disabled_writes_the_attempt_and_keeps_the_last_success(self): + self.seed_root() + self.assertEqual(self.w.run("--settle").returncode, 0) + r = self.w.run("--settle", extra={"MEMORY_SETTLE": "0", "MEMORY_SETTLE_NOW": "2026-11-21T03:10:00Z"}) + self.assertEqual(r.returncode, 0) + st = self.w.status() + self.assertEqual((st["last_attempt_result"], st["last_attempt_at"], st["last_success_at"]), + ("disabled", "2026-11-21T03:10:00Z", "2026-11-20T03:10:00Z")) + + +class Health(Base): + def rows(self): + with open(os.path.join(self.w.state, "memory-health.tsv")) as fh: + lines = fh.read().splitlines() + head = lines[0].split("\t") + return [dict(zip(head, l.split("\t"))) for l in lines[1:]] + + def test_each_run_appends_one_row_with_the_nights_duplicates(self): + self.seed_root() + # A lessons paragraph in the shared checkout, and two entries added in + # the last 24 hours: one repeats the paragraph, one is new. + les = os.path.join(self.w.shared, "CONTEXT", "projects", "zoo-lessons.md") + self.w.write(les, "## Walrus gateway\n\nWalrus gateway firmware rollback: hold the walrus reset button " + "for ten seconds, then reflash the walrus gateway firmware.\n") + self.w.entry(self.w.root, "feedback-walrus-gateway-firmware-rollback", + "Walrus gateway firmware rollback needs the walrus reset button held ten seconds", + typ="feedback", modified="2026-11-19T12:00:00Z") + self.w.entry(self.w.root, "feedback-quokka-badge-printer", "Quokka badge printer jams on glossy stock", + typ="feedback", modified="2026-11-19T12:00:00Z") + self.w.commit_push(self.w.shared, "two new entries", date="2026-11-19T12:00:00Z", + paths=(".claude-memory",)) + r = self.w.run("--settle") + self.assertEqual(r.returncode, 0, r.stderr + r.stdout) + rows = self.rows() + self.assertEqual(len(rows), 1, "the settle appends its own row") + row, st = rows[0], self.w.status() + self.assertEqual((row["v"], row["run_id"], row["outcome"], row["commit"]), + ("1", st["last_attempt_at"], "ok", st["commit"])) + moved = st["pools"][os.path.basename(self.w.root)]["moved"] + self.assertEqual(row["moved"], str(moved)) + self.assertEqual(json.loads(row["pools"])[os.path.basename(self.w.root)], [74 - moved, moved]) + self.assertEqual((row["dupes_scored"], row["dupes"]), ("2", "1")) + with open(os.path.join(self.w.state, "memory-dupes.jsonl")) as fh: + dl = [json.loads(l) for l in fh] + self.assertEqual(len(dl), 2) + hit = [d for d in dl if d["duplicate"]][0] + self.assertTrue(hit["entry"].endswith("/feedback-walrus-gateway-firmware-rollback.md")) + self.assertEqual(hit["best_ref"], os.path.realpath(les) + ":3") + self.assertEqual(hit["best_source"], "lessons") + self.assertGreaterEqual(hit["score"], 4.0) + self.assertGreaterEqual(len(hit["matched_words"]), 2) + for d in dl: + self.assertEqual(set(d), {"v", "run_id", "time", "entry", "added_at", "best_ref", "best_source", + "score", "matched_words", "duplicate"}, "refs and scores, never bodies") + # The entries added more than 24 hours before the next run are not scored again. + r = self.w.run("--settle", extra={"MEMORY_SETTLE_NOW": "2026-11-21T03:10:00Z"}) + row = self.rows()[-1] + self.assertEqual((row["outcome"], row["dupes_scored"], row["dupes"]), ("noop", "0", "0")) + r = self.w.run("--health", extra={"MEMORY_SETTLE_NOW": "2026-11-21T03:10:00Z"}) + self.assertIn("already recorded", r.stdout) + self.assertEqual(len(self.rows()), 2, "one row per attempt") + + def test_unmeasured_never_zero(self): + r = self.w.run("--health") + self.assertEqual(r.returncode, 0, r.stderr) + row = self.rows()[0] + for col in ("outcome", "moved", "dupes_scored", "dupes", "pools"): + self.assertEqual(row[col], "unmeasured", col) + self.seed_root() + r = self.w.run("--settle", extra={"MEMORY_SETTLE": "0"}) + row = self.rows()[-1] + self.assertEqual((row["outcome"], row["dupes_scored"], row["dupes"]), ("disabled", "unmeasured", "unmeasured")) + + +class Backfill(Base): + def test_backfill_preserves_a_metadata_block_with_comments(self): + originals = ( + "---\nname: commented\nmetadata: # provenance\n type: feedback\n---\nbody\n", + "---\nname: indented-comment\nmetadata:\n # provenance\n type: feedback\n---\nbody\n", + ) + for i, original in enumerate(originals): + self.w.write(os.path.join(self.w.root, f"comment-{i}.md"), original) + self.w.commit_push(self.w.shared, "commented metadata", date="2026-10-05T10:20:30-04:00") + r = subprocess.run([sys.executable, "-I", "-B", BACKFILL, "--apply", self.w.root], env=self.w.env, + capture_output=True, text=True) + self.assertEqual(r.returncode, 0, r.stderr + r.stdout) + for i, original in enumerate(originals): + path = os.path.join(self.w.root, f"comment-{i}.md") + self.assertEqual(slurp(path), original.replace( + " type: feedback\n", " type: feedback\n modified: 2026-10-05T10:20:30-04:00\n"), + "add one child to the existing map, retaining its indentation and comments") + self.assertEqual(MI.parse_frontmatter(path)["type"], "feedback") + + def test_backfill_dry_run_apply_and_idempotence(self): + pool = self.w.root + stamped = self.w.entry(pool, "has-stamp", "stamped", modified="2026-10-01T00:00:00Z") + bare = self.w.entry(pool, "no-stamp", "unstamped") + nometa = os.path.join(pool, "no-meta.md") + self.w.write(nometa, '---\nname: no-meta\ndescription: "no metadata block"\n---\nbody\n') + crlf = os.path.join(pool, "crlf.md") + with open(crlf, "wb") as fh: + fh.write(b'---\r\nname: crlf\r\ndescription: "windows endings"\r\nmetadata:\r\n type: feedback\r\n---\r\nbody\r\n') + invalid = self.w.entry(pool, "bad-stamp", "bad", modified="soon") + self.w.commit_push(self.w.shared, "entries", date="2026-10-05T10:20:30-04:00") + untracked = self.w.entry(pool, "untracked", "never committed") + os.makedirs(os.path.join(pool, "_archive")) + archived = self.w.entry(os.path.join(pool, "_archive"), "archived", "not live") + snap = self.w.snapshot(self.w.shared) + r = subprocess.run([sys.executable, "-I", "-B", BACKFILL, pool], env=self.w.env, capture_output=True, text=True) + self.assertEqual(r.returncode, 0, r.stderr) + self.assertEqual(self.w.snapshot(self.w.shared), snap, "the dry run writes nothing") + self.assertIn(f"would-stamp\t{bare}\t2026-10-05T10:20:30-04:00", r.stdout) + self.assertIn("left alone", r.stdout) + self.assertIn(f"skip\t{untracked}\tno commit changes it", r.stdout) + self.assertNotIn("archived", r.stdout) + old = {p: slurp(p, "rb") for p in (stamped, bare, nometa, crlf, invalid)} + r = subprocess.run([sys.executable, "-I", "-B", BACKFILL, "--apply", pool], env=self.w.env, + capture_output=True, text=True) + self.assertEqual(r.returncode, 0, r.stderr) + self.assertEqual(slurp(stamped, "rb"), old[stamped]) + self.assertEqual(slurp(invalid, "rb"), old[invalid]) + new = slurp(bare, "rb") + self.assertEqual(new, old[bare].replace(b" type: reference\n", + b" type: reference\n modified: 2026-10-05T10:20:30-04:00\n")) + self.assertEqual(slurp(nometa, "rb"), old[nometa].replace( + b'"no metadata block"\n---', b'"no metadata block"\nmetadata:\n modified: 2026-10-05T10:20:30-04:00\n---')) + self.assertEqual(slurp(crlf, "rb"), old[crlf].replace( + b" type: feedback\r\n", b" type: feedback\r\n modified: 2026-10-05T10:20:30-04:00\r\n")) + self.assertEqual(MI.parse_frontmatter(bare)["modified"], "2026-10-05T10:20:30-04:00") + self.assertNotIn(b"modified", slurp(archived, "rb")) + snap = self.w.snapshot(self.w.shared) + r = subprocess.run([sys.executable, "-I", "-B", BACKFILL, "--apply", pool], env=self.w.env, + capture_output=True, text=True) + self.assertEqual(self.w.snapshot(self.w.shared), snap, "a second apply changes nothing") + + +# --- local mode (2026-12-04) -------------------------------------------------------------- +# +# Why pin it: on a team box the settle commits in the checkout the owner's own sessions work +# in, on whatever branch is checked out, with or without a remote. What would go wrong +# without these cases, and not be seen until an owner lost work: an unrelated staged or dirty +# file swept into the settle's commit or changed on disk; a dirty MEMORY.md or entry +# overwritten; a write during a merge or rebase; a first archive path that a path-limited +# commit silently leaves out; a killed run that leaves index.lock behind or half-moved files; +# a fetch, a push or a new remote (one owner's own backup remote must never receive a push); +# restore or health reading the wrong tree. Every case runs in throwaway repositories under +# the sandbox, with the outside sentinel checked after each (Base.tearDown). + +LOCAL_GIT = r"""#!/usr/bin/env bash +# A git at the process boundary for local mode: logs each subcommand to GIT_LOG, and in +# FAKE_LOCAL's modes stops the mover (kill -9 of the python that ran git) or runs a hook. +args=("$@"); i=0; sub="" +while [ $i -lt ${#args[@]} ]; do + a="${args[$i]}" + if [ "$a" = "-C" ] || [ "$a" = "-c" ]; then i=$((i+2)); continue; fi + case "$a" in -*) i=$((i+1)); continue ;; esac + sub="$a"; break +done +[ -n "${GIT_LOG:-}" ] && printf '%s\n' "$sub" >> "$GIT_LOG" +case ",${FAKE_LOCAL:-}," in + *,kill-at-update-ref,*) [ "$sub" = update-ref ] && { kill -9 "$PPID"; exit 1; } ;; +esac +case ",${FAKE_LOCAL:-}," in + *,ref-updated-but-failed,*) + if [ "$sub" = update-ref ]; then "$REAL_GIT" "$@" || exit $?; exit 128; fi ;; +esac +case ",${FAKE_LOCAL:-}," in + *,kill-after-update-ref,*) + if [ "$sub" = update-ref ]; then "$REAL_GIT" "$@" || exit $?; : > "$FAKE_MARK"; exit 0; fi + if [ "$sub" = update-index ] && [ -e "$FAKE_MARK" ]; then kill -9 "$PPID"; exit 1; fi ;; +esac +case ",${FAKE_LOCAL:-}," in + *,hook-at-update-ref,*) [ "$sub" = update-ref ] && { bash "$FAKE_HOOK" || exit 97; } ;; +esac +case ",${FAKE_LOCAL:-}," in + *,hook-at-commit-tree,*) [ "$sub" = commit-tree ] && { bash "$FAKE_HOOK" || exit 97; } ;; +esac +exec "$REAL_GIT" "$@" +""" + + +class LocalBase(Base): + """The owner's checkout (the World's shared repo) as the configured harness root.""" + + def setUp(self): + super().setUp() + self.top = self.w.shared + self.envf = os.path.join(self.w.home, ".config", "ops", "memory-settle.env") + self.rel_pool = self.w.rel(self.w.root) + self.configure() + self.lgit = os.path.join(self.w.tmp, "lbin") + os.makedirs(self.lgit) + self.w.write(os.path.join(self.lgit, "git"), LOCAL_GIT) + os.chmod(os.path.join(self.lgit, "git"), 0o755) + self.gitlog = os.path.join(self.w.tmp, "git-log") + + def configure(self, body=None): + self.w.write(self.envf, body if body is not None else + f"MEMORY_SETTLE_OWNER=1\nMEMORY_SETTLE_MODE=local\nMEMORY_SETTLE_ROOT={self.top}\n") + + def on_main(self, origin=False): + self.w.git(self.top, "checkout", "-q", "-b", "main") + if not origin: + self.w.git(self.top, "remote", "remove", "origin") + + def commit(self, msg, date="2026-10-01T00:00:00Z", paths=(".",)): + self.w.git(self.top, "add", "-A", "--", *paths) + self.w.git(self.top, "commit", "--quiet", "-m", msg, date=date) + + def seed(self, n=72): + self.w.overflow_root(n) + self.commit("seed root pool") + + def mi(self, *args, fake=None, extra=None): + e = {"PATH": self.lgit + os.pathsep + os.environ.get("PATH", "/usr/bin:/bin"), "GIT_LOG": self.gitlog, + "FAKE_MARK": os.path.join(self.w.tmp, "fake-mark")} + if fake: + e["FAKE_LOCAL"] = fake + e.update(extra or {}) + return self.w.run(*args, extra=e) + + def head(self, rev="HEAD"): + return self.w.git(self.top, "rev-parse", rev).strip() + + def porcelain(self): + return self.w.git(self.top, "status", "--porcelain=v1", "--untracked-files=all") + + def changed(self, rev="HEAD"): + return set(self.w.git(self.top, "show", "--name-only", "--no-renames", "--format=", rev).split()) + + def tree(self, rev, rel_dir): + out = self.w.git(self.top, "ls-tree", "--name-only", rev, rel_dir + "/") + return sorted(os.path.basename(x) for x in out.split("\n") if x) + + def journal(self): + return os.path.join(self.w.state, "memory-settle-journal.json") + + def index_lock(self): + return os.path.join(self.top, ".git", "index.lock") + + def plan(self): + r = self.mi("--settle", "--dry-run") + self.assertEqual(r.returncode, 0, r.stdout + r.stderr) + moves = dry_moves(r.stdout) + self.assertTrue(moves, r.stdout) + return moves + + def committed_check(self, rev="HEAD"): + """memory-index --check of the pool exactly as rev holds it.""" + dest = tempfile.mkdtemp(dir=self.w.tmp, prefix="export-") + arch = subprocess.run([REAL_GIT, "-C", self.top, "archive", "--format=tar", rev, self.rel_pool], + capture_output=True, check=True) + subprocess.run(["tar", "-x", "-C", dest], input=arch.stdout, check=True) + r = subprocess.run([sys.executable, "-I", "-B", IDX, "--check", os.path.join(dest, self.rel_pool)], + capture_output=True, text=True) + return r.stdout, slurp(os.path.join(dest, self.rel_pool, "MEMORY.md")) + + def owner_snapshot(self): + """The checkout as the owner sees it: everything but .git/objects, where a refused run + may leave unreachable objects (never a ref, the index or a file).""" + return [r for r in self.w.snapshot(self.top) if not r[0].startswith(os.path.join(".git", "objects"))] + + def assert_untouched(self, before_head, snap, why): + self.assertEqual(self.head(), before_head, why + ": HEAD moved") + self.assertEqual(self.w.snapshot(self.top), snap, why + ": the checkout changed") + self.assertFalse(os.path.exists(self.journal()), why + ": a journal was left") + + +class LocalMode(LocalBase): + def test_without_origin_on_main_commits_only_its_paths(self): + self.on_main(origin=False) + self.seed() + self.assertFalse(os.path.exists(os.path.join(self.w.root, "_archive")), "the archive is new") + plan = self.plan() + before = {fn: sha(os.path.join(self.w.root, fn)) for fn in plan} + old = self.head() + master = self.head("master") + idx, gidx = os.path.join(self.w.root, "MEMORY.md"), os.path.join(self.top, ".git", "index") + os.chmod(idx, 0o644) + modes = (stat.S_IMODE(os.stat(idx).st_mode), stat.S_IMODE(os.stat(gidx).st_mode)) + r = self.mi("--settle") + self.assertEqual(r.returncode, 0, r.stdout + r.stderr) + self.assertIn("memory settle (local mode): ok", r.stdout) + st = self.w.status() + self.assertEqual(set(st), STATUS_KEYS) + self.assertEqual(st["last_attempt_result"], "ok") + self.assertEqual(st["commit"], self.head()) + self.assertFalse(st["pending_delivery"]) + self.assertEqual(self.head("HEAD^"), old, "one commit, on top of the owner's HEAD") + self.assertEqual(self.w.git(self.top, "symbolic-ref", "--short", "HEAD").strip(), "main") + self.assertEqual(self.w.git(self.top, "for-each-ref", "--format=%(refname)", "refs/heads"), + "refs/heads/main\nrefs/heads/master\n", "no other branch was made") + self.assertEqual(self.head("master"), master, "the branch not checked out is not moved") + self.assertEqual(self.changed(), {f"{self.rel_pool}/{fn}" for fn in plan} + | {f"{self.rel_pool}/_archive/{fn}" for fn in plan} | {f"{self.rel_pool}/MEMORY.md"}) + self.assertEqual(self.w.git(self.top, "log", "-1", "--format=%s").strip(), + f"chore(memory): archive {len(plan)} entries past the digest fit") + # The new archive path is committed and staged as HEAD has it: the tree is clean. + self.assertEqual(self.tree("HEAD", self.rel_pool + "/_archive"), sorted(plan)) + self.assertEqual(self.porcelain(), "", "index and worktree agree with the new HEAD") + for fn, h in before.items(): + self.assertFalse(os.path.lexists(os.path.join(self.w.root, fn))) + self.assertEqual(sha(os.path.join(self.w.root, "_archive", fn)), h, "byte-identical move") + check, committed = self.committed_check() + self.assertEqual(committed, check, "the committed index is the generated one") + self.assertEqual(slurp(os.path.join(self.w.root, "MEMORY.md")), committed) + self.assertEqual((stat.S_IMODE(os.stat(idx).st_mode), stat.S_IMODE(os.stat(gidx).st_mode)), modes, + "the rewritten MEMORY.md and index keep their permission bits") + self.assertEqual(self.w.git(self.top, "remote"), "", "no remote was added") + self.assertFalse(os.path.exists(self.w.clone), "local mode makes no clone") + self.assertFalse(os.path.exists(self.index_lock())) + self.assertFalse(os.path.exists(self.journal())) + r = self.mi("--settle", extra={"MEMORY_SETTLE_NOW": "2026-11-21T03:10:00Z"}) + self.assertEqual(r.returncode, 0, r.stderr) + self.assertEqual(self.w.status()["last_attempt_result"], "noop") + + def test_with_origin_never_fetches_adds_a_remote_or_pushes(self): + self.on_main(origin=True) + self.seed() + remote_refs = self.w.git(self.w.remote, "for-each-ref") + remotes = self.w.git(self.top, "remote", "-v") + r = self.mi("--settle", "--dry-run") + self.assertIn("(local mode)", r.stdout) + self.assertIn("on main", r.stdout) + r = self.mi("--settle") + self.assertEqual(r.returncode, 0, r.stdout + r.stderr) + self.assertEqual(self.w.status()["last_attempt_result"], "ok") + self.assertEqual(self.w.git(self.w.remote, "for-each-ref"), remote_refs, "the remote is untouched") + self.assertEqual(self.w.git(self.top, "remote", "-v"), remotes) + self.assertFalse(os.path.exists(os.path.join(self.top, ".git", "FETCH_HEAD"))) + self.assertFalse(os.path.exists(self.w.clone)) + used = set(slurp(self.gitlog).split()) + self.assertFalse(used & {"fetch", "push", "pull", "clone", "remote", "ls-remote", "merge", "rebase"}, used) + self.assertEqual(self.w.git(self.top, "rev-parse", "origin/master").strip(), + self.w.git(self.w.remote, "rev-parse", "master").strip()) + + def test_unrelated_staged_and_dirty_work_survives_byte_for_byte(self): + self.on_main() + self.seed() + t = self.top + for name in ("notes.txt", "both.txt"): + self.w.write(os.path.join(t, name), "committed\n") + self.commit("owner files") + self.w.write(os.path.join(t, "notes.txt"), "edited, not staged\n") + self.w.write(os.path.join(t, "staged.txt"), "a new file, staged\n") + self.w.git(t, "add", "staged.txt") + self.w.write(os.path.join(t, "both.txt"), "staged version\n") + self.w.git(t, "add", "both.txt") + self.w.write(os.path.join(t, "both.txt"), "worktree version on top\n") + self.w.write(os.path.join(t, "untracked.txt"), "untracked\n") + # In the pool: a committed entry with an unstaged edit, a new untracked entry, and the + # MEMORY.md a session start regenerated from both (an unstaged change). + edited = os.path.join(self.w.root, "reference-r071.md") + with open(edited, "a") as fh: + fh.write("an owner's edit in progress\n") + newe = self.w.entry(self.w.root, "reference-zz-owner-new", "an entry the owner has not committed", + modified="2026-11-19T00:00:00Z") + MI_index(self.w.root) + plan = self.plan() + mine = ["notes.txt", "both.txt", "staged.txt", "untracked.txt", self.w.rel(edited), self.w.rel(newe)] + bytes_before = {p: slurp(os.path.join(t, p), "rb") for p in mine} + cached = self.w.git(t, "diff", "--cached", "--name-status") + stages = self.w.git(t, "ls-files", "-s", "--", "notes.txt", "both.txt", "staged.txt") + unstaged = self.w.git(t, "diff", "--name-status") + old = self.head() + r = self.mi("--settle") + self.assertEqual(r.returncode, 0, r.stdout + r.stderr) + self.assertEqual(self.head("HEAD^"), old) + moved = {f"{self.rel_pool}/{fn}" for fn in plan if fn != "reference-r071.md"} + self.assertTrue(moved) + changed = self.changed() + self.assertEqual(changed - {f"{self.rel_pool}/MEMORY.md"}, + moved | {p.replace(self.rel_pool + "/", self.rel_pool + "/_archive/") for p in moved}, + "the commit holds the moves and the index, nothing of the owner's") + for p in mine: + self.assertEqual(slurp(os.path.join(t, p), "rb"), bytes_before[p], f"{p} changed on disk") + self.assertEqual(self.w.git(t, "diff", "--cached", "--name-status"), cached, "the staged set changed") + self.assertEqual(self.w.git(t, "ls-files", "-s", "--", "notes.txt", "both.txt", "staged.txt"), stages) + self.assertEqual(self.w.git(t, "diff", "--name-status", "--", "notes.txt", "both.txt", self.w.rel(edited)), + "\n".join(l for l in unstaged.splitlines() if not l.endswith("MEMORY.md")) + "\n") + committed = self.w.git(t, "show", f"HEAD:{self.rel_pool}/MEMORY.md") + self.assertNotIn("reference-zz-owner-new", committed, "an uncommitted entry never gets a committed line") + self.assertNotIn("owner's edit", self.w.git(t, "show", f"HEAD:{self.w.rel(edited)}")) + check, _c = self.committed_check() + self.assertEqual(committed, check) + # The worktree index is what memory-index generates from the worktree as it now stands + # (the owner's uncommitted entry keeps its line; the moved entries have none), while the + # committed one holds committed entries only (from the settle's review). + idx = os.path.join(self.w.root, "MEMORY.md") + wt_check = subprocess.run([sys.executable, "-I", "-B", IDX, "--check", self.w.root], + capture_output=True, text=True).stdout + self.assertEqual(slurp(idx), wt_check) + self.assertIn("reference-zz-owner-new", slurp(idx)) + self.assertIn(f" M {self.rel_pool}/MEMORY.md", self.porcelain()) + + def test_a_staged_index_refuses_its_pool_and_changes_nothing(self): + self.on_main() + self.seed() + idx = os.path.join(self.w.root, "MEMORY.md") + with open(idx, "a") as fh: + fh.write("an owner's staged line\n") + self.w.git(self.top, "add", self.w.rel(idx)) + cached = self.w.git(self.top, "diff", "--cached") + r = self.mi("--settle", "--dry-run") + self.assertEqual(r.returncode, 1, r.stdout) + self.assertIn(f"an apply run would refuse: pool {os.path.basename(self.w.root)} not settled", r.stdout) + snap, old = self.w.snapshot(self.top), self.head() + r = self.mi("--settle") + self.assertEqual(r.returncode, 1, r.stdout + r.stderr) + st = self.w.status() + self.assertEqual(st["last_attempt_result"], "failed") + self.assertIn("MEMORY.md: it has a staged change", st["error"]) + self.assertEqual(st["pools"][os.path.basename(self.w.root)]["moved"], 0) + self.assert_untouched(old, snap, "a staged index") + self.assertEqual(self.w.git(self.top, "diff", "--cached"), cached) + + def test_a_worktree_index_symlink_is_left_in_place(self): + self.on_main() + self.seed() + idx = os.path.join(self.w.root, "MEMORY.md") + target = os.path.join(self.w.outside, "owner-index.md") + self.w.write(target, "owner's index\n") + os.unlink(idx) + os.symlink(target, idx) + old, snap = self.head(), self.owner_snapshot() + for args in (("--settle", "--dry-run"), ("--settle",)): + with self.subTest(args=args): + r = self.mi(*args) + self.assertEqual(r.returncode, 1, r.stdout + r.stderr) + self.assertIn("MEMORY.md: the worktree copy is not a regular file", r.stdout + r.stderr) + self.assertEqual(os.readlink(idx), target) + self.assertEqual((self.head(), self.owner_snapshot()), (old, snap)) + self.assertEqual(slurp(target), "owner's index\n") + + def test_a_hidden_worktree_change_does_not_get_overwritten(self): + self.on_main() + self.seed() + idx = os.path.join(self.w.root, "MEMORY.md") + path = self.w.rel(idx) + old = self.head() + for flag in ("assume-unchanged", "skip-worktree"): + with self.subTest(flag=flag): + self.w.git(self.top, "update-index", "--" + flag, path) + with open(idx, "ab") as fh: + fh.write(b"the owner's local text\n") + before = slurp(idx, "rb") + self.assertEqual(self.porcelain(), "") + r = self.mi("--settle") + self.assertEqual(r.returncode, 1, r.stdout + r.stderr) + self.assertEqual(slurp(idx, "rb"), before) + self.assertEqual(self.head(), old) + self.assertIn("skip-worktree or assume-unchanged", r.stderr) + self.w.git(self.top, "update-index", "--no-" + flag, path) + + def test_a_git_operation_in_progress_or_a_detached_head_refuses(self): + self.on_main() + self.seed() + gd = os.path.join(self.top, ".git") + head = self.head() + cases = { + "MERGE_HEAD": lambda: self.w.write(os.path.join(gd, "MERGE_HEAD"), head + "\n"), + "rebase-merge": lambda: os.makedirs(os.path.join(gd, "rebase-merge")), + "CHERRY_PICK_HEAD": lambda: self.w.write(os.path.join(gd, "CHERRY_PICK_HEAD"), head + "\n"), + "BISECT_LOG": lambda: self.w.write(os.path.join(gd, "BISECT_LOG"), "git bisect start\n"), + "index.lock": lambda: self.w.write(os.path.join(gd, "index.lock"), "another git\n"), + "detached HEAD": lambda: self.w.git(self.top, "checkout", "-q", "--detach"), + } + undo = { + "MERGE_HEAD": lambda: os.unlink(os.path.join(gd, "MERGE_HEAD")), + "rebase-merge": lambda: os.rmdir(os.path.join(gd, "rebase-merge")), + "CHERRY_PICK_HEAD": lambda: os.unlink(os.path.join(gd, "CHERRY_PICK_HEAD")), + "BISECT_LOG": lambda: os.unlink(os.path.join(gd, "BISECT_LOG")), + "index.lock": lambda: os.unlink(os.path.join(gd, "index.lock")), + "detached HEAD": lambda: self.w.git(self.top, "checkout", "-q", "main"), + } + for name, make in cases.items(): + with self.subTest(name): + make() + snap = self.owner_snapshot() + r = self.mi("--settle", extra={"MEMORY_SETTLE_INDEX_WAIT": "0"}) + self.assertEqual(r.returncode, 1, r.stdout + r.stderr) + self.assertEqual(self.w.status()["last_attempt_result"], "failed") + self.assertIn("detached HEAD" if name == "detached HEAD" else name, self.w.status()["error"]) + self.assertEqual(self.head(), head) + self.assertEqual(self.owner_snapshot(), snap, f"{name}: the checkout changed") + self.assertFalse(os.path.exists(self.journal()), f"{name}: a journal was left") + if name == "index.lock": + self.assertEqual(slurp(os.path.join(gd, "index.lock")), "another git\n", + "another command's lock is never removed") + undo[name]() + r = self.mi("--settle") + self.assertEqual(r.returncode, 0, r.stdout + r.stderr) + + def test_a_session_lock_held_for_a_moment_is_waited_out(self): + self.on_main() + self.seed() + lock = self.index_lock() + self.w.write(lock, "a session's git\n") + hook = os.path.join(self.w.tmp, "hook.sh") + # The lock is there through the preflight and the plan, and goes a second after the + # run starts waiting for it, as a session's commit would. + self.w.write(hook, f'( sleep 1; rm -f "{lock}" ) >/dev/null 2>&1 &\n') + r = self.mi("--settle", fake="hook-at-commit-tree", + extra={"FAKE_HOOK": hook, "MEMORY_SETTLE_INDEX_WAIT": "30"}) + self.assertEqual(r.returncode, 0, r.stdout + r.stderr) + self.assertEqual(self.w.status()["last_attempt_result"], "ok") + self.assertEqual(self.porcelain(), "") + self.assertFalse(os.path.exists(lock)) + + def test_a_change_while_preparing_refuses_and_keeps_the_owner_edit(self): + self.on_main() + self.seed() + plan = self.plan() + victim = os.path.join(self.w.root, plan[0]) + hook = os.path.join(self.w.tmp, "hook.sh") + self.w.write(hook, f'printf "an edit while the settle prepared\\n" >> "{victim}"\n') + old = self.head() + r = self.mi("--settle", fake="hook-at-commit-tree", extra={"FAKE_HOOK": hook}) + self.assertEqual(r.returncode, 1, r.stdout + r.stderr) + self.assertIn("changed while it prepared", self.w.status()["error"]) + self.assertEqual(self.head(), old) + self.assertTrue(slurp(victim).endswith("an edit while the settle prepared\n")) + self.assertEqual(self.porcelain(), f" M {self.w.rel(victim)}\n", "only the owner's edit is left") + self.assertFalse(os.path.exists(os.path.join(self.w.root, "_archive"))) + self.assertFalse(os.path.exists(self.journal())) + self.assertFalse(os.path.exists(self.index_lock())) + + def test_an_entry_pinned_and_committed_after_selection_stays_live(self): + self.on_main() + self.seed() + first = self.plan()[0] + path = os.path.join(self.w.root, first) + plan_settle = MS.plan_settle + + def plan_before_owner_commits(ctx, pools): + reports = plan_settle(ctx, pools) + self.w.write(path, slurp(path).replace("metadata:\n", "metadata:\n pinned: true\n")) + self.commit("owner pins an entry", paths=(self.w.rel(path),)) + return reports + + with patch.dict(os.environ, self.w.env, clear=True), patch.object( + MS, "plan_settle", side_effect=plan_before_owner_commits): + self.assertEqual(MS.local_settle_apply(self.top, []), 1) + self.assertIn("moved while the run planned", self.w.status()["error"]) + self.assertEqual(self.w.git(self.top, "log", "-1", "--format=%s").strip(), "owner pins an entry") + self.assertIn("pinned: true", slurp(path)) + self.assertEqual(self.porcelain(), "") + + def test_a_branch_that_moved_before_the_swap_rolls_back(self): + self.on_main() + self.seed() + plan = self.plan() + before = {fn: sha(os.path.join(self.w.root, fn)) for fn in plan} + hook = os.path.join(self.w.tmp, "hook.sh") + # Another writer moves the branch without the index (which the settle holds locked). + self.w.write(hook, f'cd "{self.top}"\nc=$("$REAL_GIT" commit-tree "HEAD^{{tree}}" -p HEAD -m concurrent)\n' + f'"$REAL_GIT" update-ref refs/heads/main "$c"\n') + porcelain = self.porcelain() + r = self.mi("--settle", fake="hook-at-update-ref", extra={"FAKE_HOOK": hook}) + self.assertEqual(r.returncode, 1, r.stdout + r.stderr) + self.assertIn("update-ref", self.w.status()["error"]) + self.assertEqual(self.w.git(self.top, "log", "-1", "--format=%s").strip(), "concurrent", + "the other writer's commit stands") + for fn, h in before.items(): + self.assertEqual(sha(os.path.join(self.w.root, fn)), h, f"{fn} is back, byte-identical") + self.assertFalse(os.path.exists(os.path.join(self.w.root, "_archive")), "the archive the run made is gone") + self.assertEqual(self.porcelain(), porcelain) + self.assertFalse(os.path.exists(self.journal())) + self.assertFalse(os.path.exists(self.index_lock())) + + def test_a_run_killed_before_its_commit_is_undone_next_time(self): + self.on_main() + self.seed() + plan = self.plan() + before = {fn: sha(os.path.join(self.w.root, fn)) for fn in plan} + old = self.head() + r = self.mi("--settle", fake="kill-at-update-ref") + self.assertEqual(r.returncode, -9, r.stdout + r.stderr) + self.assertTrue(os.path.exists(self.journal())) + self.assertTrue(os.path.exists(self.index_lock()), "the stopped run's index.lock is left") + self.assertTrue(os.path.exists(os.path.join(self.w.root, "_archive", plan[0])), "moves were made") + self.assertEqual(self.head(), old) + # The owner keeps working meanwhile: an unrelated edit and a new entry. + self.w.write(os.path.join(self.top, "owner.txt"), "written after the stop\n") + r = self.mi("--settle") + self.assertEqual(r.returncode, 0, r.stdout + r.stderr) + self.assertIn(f"undid {len(plan)} uncommitted move(s)", r.stdout) + self.assertEqual(self.head("HEAD^"), old, "one settle commit after the recovery") + for fn, h in before.items(): + self.assertEqual(sha(os.path.join(self.w.root, "_archive", fn)), h) + self.assertEqual(slurp(os.path.join(self.top, "owner.txt")), "written after the stop\n") + self.assertEqual(self.porcelain(), "?? owner.txt\n") + self.assertFalse(os.path.exists(self.journal())) + self.assertFalse(os.path.exists(self.index_lock())) + + def test_recovery_refuses_an_archive_redirected_after_the_stop(self): + self.on_main() + self.seed() + name = self.plan()[0] + r = self.mi("--settle", fake="kill-at-update-ref") + self.assertEqual(r.returncode, -9, r.stdout + r.stderr) + archive = os.path.join(self.w.root, "_archive") + external_dir = os.path.join(self.w.outside, "relocated-archive") + os.rename(archive, external_dir) + os.symlink(external_dir, archive) + external_entry = os.path.join(external_dir, name) + before = sha(external_entry) + old = self.head() + r = self.mi("--settle") + self.assertEqual(r.returncode, 1, r.stdout + r.stderr) + self.assertIn("is no longer a directory inside the memory store", r.stderr) + self.assertEqual(sha(external_entry), before) + self.assertFalse(os.path.lexists(os.path.join(self.w.root, name))) + self.assertEqual(self.head(), old) + self.assertTrue(os.path.exists(self.journal())) + + def test_a_run_killed_after_its_commit_has_its_index_finished(self): + self.on_main() + self.seed() + plan = self.plan() + old = self.head() + r = self.mi("--settle", fake="kill-after-update-ref") + self.assertEqual(r.returncode, -9, r.stdout + r.stderr) + new = self.head() + self.assertNotEqual(new, old, "the commit landed") + self.assertTrue(os.path.exists(self.journal())) + r = self.mi("--settle", extra={"MEMORY_SETTLE_NOW": "2026-11-21T03:10:00Z"}) + self.assertEqual(r.returncode, 0, r.stdout + r.stderr) + self.assertIn(f"finished the index of commit {new[:12]}", r.stdout) + self.assertEqual(self.head(), new, "nothing more to move") + self.assertEqual(self.w.status()["last_attempt_result"], "noop") + self.assertEqual(self.porcelain(), "", "the index agrees with HEAD again") + self.assertEqual(self.w.git(self.top, "ls-files", f"{self.rel_pool}/_archive").split(), + [f"{self.rel_pool}/_archive/{fn}" for fn in sorted(plan)]) + self.assertFalse(os.path.exists(self.index_lock())) + + def test_a_ref_update_reported_as_failed_after_landing_is_recovered(self): + self.on_main() + self.seed() + plan = self.plan() + old = self.head() + r = self.mi("--settle", fake="ref-updated-but-failed") + self.assertEqual(r.returncode, 1, r.stdout + r.stderr) + new = self.head() + self.assertNotEqual(new, old, "the ref moved despite the reported failure") + self.assertTrue(os.path.isfile(os.path.join(self.w.root, "_archive", plan[0]))) + self.assertTrue(os.path.exists(self.journal())) + r = self.mi("--settle") + self.assertEqual(r.returncode, 0, r.stdout + r.stderr) + self.assertEqual(self.head(), new) + self.assertEqual(self.porcelain(), "") + self.assertFalse(os.path.exists(self.journal())) + + def test_recovery_preserves_work_staged_while_waiting_for_the_index(self): + self.on_main() + self.seed() + plan = self.plan() + r = self.mi("--settle", fake="kill-after-update-ref") + self.assertEqual(r.returncode, -9, r.stdout + r.stderr) + # Simulate a session that can stage while recovering from a failure + # that left the journal but released index.lock. + os.unlink(self.index_lock()) + entry = os.path.join(self.w.root, "_archive", plan[0]) + path = self.w.rel(entry) + real_take = MS.take_index_lock + + def take_after_owner_stages(top, nonce): + with open(entry, "ab") as fh: + fh.write(b"the owner's follow-up\n") + self.w.git(top, "add", path) + return real_take(top, nonce) + + with patch.dict(os.environ, self.w.env, clear=True), patch.object( + MS, "take_index_lock", side_effect=take_after_owner_stages): + MS.local_recover(self.top) + self.assertTrue(self.w.git(self.top, "show", ":" + path).endswith("the owner's follow-up\n")) + self.assertEqual(self.porcelain(), f"M {path}\n") + + def test_recovery_can_release_a_lock_after_interrupted_cleanup(self): + self.on_main() + self.seed() + old = self.head() + with patch.dict(os.environ, self.w.env, clear=True), patch.object( + MS, "release_index_lock", side_effect=OSError("interrupted during lock cleanup")): + self.assertEqual(MS.local_settle_apply(self.top, []), 1) + new = self.head() + self.assertNotEqual(new, old) + self.assertTrue(os.path.exists(self.index_lock())) + r = self.mi("--settle", extra={"MEMORY_SETTLE_INDEX_WAIT": "0"}) + self.assertEqual(r.returncode, 0, r.stdout + r.stderr) + self.assertEqual(self.head(), new) + self.assertEqual(self.porcelain(), "") + self.assertFalse(os.path.exists(self.index_lock())) + self.assertFalse(os.path.exists(self.journal())) + + def test_restore_in_local_mode_and_an_occupied_live_path(self): + self.on_main() + self.seed() + plan = self.plan() + self.assertEqual(self.mi("--settle").returncode, 0) + self.w.write(os.path.join(self.top, "staged.txt"), "staged across the restore\n") + self.w.git(self.top, "add", "staged.txt") + arch = os.path.join(self.w.root, "_archive", plan[0]) + h = sha(arch) + r = self.mi("--restore", plan[0][:-3], "--dry-run") + self.assertEqual(r.returncode, 0, r.stderr) + self.assertIn("would move", r.stdout) + settled = self.head() + r = self.mi("--restore", plan[0][:-3]) + self.assertEqual(r.returncode, 0, r.stdout + r.stderr) + self.assertEqual(self.head("HEAD^"), settled) + self.assertEqual(self.w.git(self.top, "log", "-1", "--format=%s").strip(), "chore(memory): restore 1 archived entry") + self.assertEqual(self.changed(), {f"{self.rel_pool}/_archive/{plan[0]}", f"{self.rel_pool}/{plan[0]}", + f"{self.rel_pool}/MEMORY.md"}) + self.assertEqual(sha(os.path.join(self.w.root, plan[0])), h) + self.assertEqual(self.porcelain(), "A staged.txt\n", "the owner's staged file is still staged, alone") + # An occupied live path is refused and both files keep their bytes. + live = os.path.join(self.w.root, plan[1]) + self.w.write(live, "the owner wrote this name again\n") + h1 = sha(os.path.join(self.w.root, "_archive", plan[1])) + r = self.mi("--restore", plan[1][:-3]) + self.assertEqual(r.returncode, 1, r.stdout) + self.assertIn("the live path is occupied", r.stderr) + self.assertEqual(slurp(live), "the owner wrote this name again\n") + self.assertEqual(sha(os.path.join(self.w.root, "_archive", plan[1])), h1) + self.assertEqual(self.head("HEAD^"), settled) + + def test_restore_does_not_replace_a_live_path_created_after_the_guard(self): + self.on_main() + self.seed() + name = self.plan()[0] + r = self.mi("--settle") + self.assertEqual(r.returncode, 0, r.stderr) + settled = self.head() + live = os.path.join(self.w.root, name) + archived = os.path.join(self.w.root, "_archive", name) + archive_sha = sha(archived) + makedirs = os.makedirs + + def owner_creates_live_path(path, *args, **kwargs): + makedirs(path, *args, **kwargs) + if path == self.w.root: + with open(live, "x") as fh: + fh.write("the owner recreated this memory\n") + + with patch.dict(os.environ, self.w.env, clear=True), patch.object( + MS.os, "makedirs", side_effect=owner_creates_live_path): + self.assertEqual(MS.restore_main([name], self.top), 1) + self.assertEqual(slurp(live), "the owner recreated this memory\n") + self.assertEqual(sha(archived), archive_sha) + self.assertEqual(self.head(), settled) + + def test_a_session_index_write_during_the_settle_is_not_overwritten(self): + """A review finding: a session's index writer rewrote MEMORY.md after the settle's + last check, and the settle then overwrote it, dropping the line of an entry the owner + had not committed. The writer now waits on the settle's lock and skips; the settle + leaves the worktree index as memory-index generates it from the worktree.""" + self.on_main() + self.seed() + self.w.entry(self.w.root, "reference-zz-owner-new", "an entry the owner has not committed", + modified="2026-11-19T00:00:00Z") + idx = os.path.join(self.w.root, "MEMORY.md") + real_write = MS.write_bytes_atomic + session = {} + + def a_session_starts_first(path, data): + if path == idx and not session: + # A session start regenerates this pool's index right after the settle's + # final check of the file, through the same CLI the SessionStart hook runs. + session["r"] = subprocess.run([sys.executable, "-I", "-B", IDX, self.w.root], + env=dict(self.w.env, MEMORY_INDEX_SETTLE_WAIT="1"), + capture_output=True, text=True, timeout=60) + return real_write(path, data) + + with patch.dict(os.environ, self.w.env, clear=True), patch.object( + MS, "write_bytes_atomic", side_effect=a_session_starts_first): + self.assertEqual(MS.settle_main([], None), 0) + self.assertTrue(session, "the settle wrote the index") + self.assertEqual(session["r"].returncode, 0, session["r"].stderr) + self.assertIn("skipped", session["r"].stderr, "the session's writer waited on the settle's lock, then skipped") + check = subprocess.run([sys.executable, "-I", "-B", IDX, "--check", self.w.root], + capture_output=True, text=True).stdout + self.assertEqual(slurp(idx), check, "the worktree index is what memory-index generates from the worktree") + self.assertIn("reference-zz-owner-new", slurp(idx), "an uncommitted entry keeps its line") + self.assertNotIn("reference-zz-owner-new", self.w.git(self.top, "show", f"HEAD:{self.rel_pool}/MEMORY.md")) + + def test_health_reads_the_owner_checkout(self): + self.on_main() + self.seed() + self.w.entry(self.w.root, "feedback-quokka-badge-printer", "Quokka badge printer jams on glossy stock", + typ="feedback", modified="2026-11-19T12:00:00Z") + self.commit("a new entry", date="2026-11-19T12:00:00Z") + r = self.mi("--settle") + self.assertEqual(r.returncode, 0, r.stdout + r.stderr) + with open(os.path.join(self.w.state, "memory-health.tsv")) as fh: + lines = fh.read().splitlines() + row = dict(zip(lines[0].split("\t"), lines[1].split("\t"))) + st = self.w.status() + self.assertEqual((row["outcome"], row["commit"], row["run_id"]), ("ok", st["commit"], st["last_attempt_at"])) + moved = st["pools"][os.path.basename(self.w.root)]["moved"] + self.assertEqual(json.loads(row["pools"])[os.path.basename(self.w.root)], [73 - moved, moved]) + self.assertEqual(row["dupes_scored"], "1", "the night's new entry is scored from the owner's history") + r = self.mi("--health") + self.assertEqual(r.returncode, 0, r.stderr) + self.assertIn("already recorded", r.stdout) + + +class LocalConfig(LocalBase): + def test_bad_configuration_is_refused_never_guessed(self): + # The template has no other mode to fall back to: a missing, empty or other mode is refused. + self.on_main(origin=True) + self.seed() + sub = os.path.join(self.top, "sub") + os.makedirs(sub) + cases = [ + ("", "this template runs the settle in local mode only"), + ("MEMORY_SETTLE_MODE=clone\n", "this template runs the settle in local mode only"), + ("MEMORY_SETTLE_MODE=bogus\n", "this template runs the settle in local mode only"), + ("MEMORY_SETTLE_MODE=\n", "this template runs the settle in local mode only"), + ("MEMORY_SETTLE_MODE=local\n", "local mode needs MEMORY_SETTLE_ROOT"), + ("MEMORY_SETTLE_MODE=local\nMEMORY_SETTLE_ROOT=relative/path\n", "local mode needs MEMORY_SETTLE_ROOT"), + (f"MEMORY_SETTLE_MODE=local\nMEMORY_SETTLE_ROOT={sub}\n", "is not the top of a git checkout"), + ] + snap, old = self.w.snapshot(self.top), self.head() + for body, want in cases: + with self.subTest(body): + self.configure("MEMORY_SETTLE_OWNER=1\n" + body) + r = self.mi("--settle", "--dry-run") + self.assertEqual(r.returncode, 1, r.stdout) + self.assertIn(want, r.stderr) + r = self.mi("--settle") + self.assertEqual(r.returncode, 1, r.stdout) + self.assertEqual(self.w.status()["last_attempt_result"], "failed") + self.assertIn(want, self.w.status()["error"]) + r = self.mi("--restore", "anything") + self.assertEqual(r.returncode, 1) + self.assertIn(want, r.stderr) + self.assertFalse(os.path.exists(self.w.clone), "never fell back to the clone and its push") + self.assertEqual((self.head(), self.w.snapshot(self.top)), (old, snap)) + self.configure() + r = self.mi("--settle", "--ops", self.w.outside) + self.assertEqual(r.returncode, 1) + self.assertIn("is not MEMORY_SETTLE_ROOT", self.w.status()["error"]) + + def test_the_environment_selects_local_mode_as_systemd_passes_it(self): + self.on_main() + self.seed() + # systemd passes the file's lines as the environment: the two agree, and the run goes. + r = self.mi("--settle", extra={"MEMORY_SETTLE_MODE": "local", "MEMORY_SETTLE_ROOT": self.top}) + self.assertEqual(r.returncode, 0, r.stdout + r.stderr) + self.assertIn("(local mode)", r.stdout) + self.assertFalse(os.path.exists(self.w.clone)) + + def test_an_environment_the_file_does_not_match_is_refused(self): + """Each session's index writer reads the file, not systemd's environment, to decide + whether to take the settle's lock; a local run the file does not describe could race + it unlocked.""" + self.on_main() + self.seed() + snap, old = self.owner_snapshot(), self.head() + for body in ("MEMORY_SETTLE_OWNER=1\n", f"MEMORY_SETTLE_MODE=local\nMEMORY_SETTLE_ROOT={self.w.outside}\n"): + with self.subTest(body): + self.configure(body) + r = self.mi("--settle", extra={"MEMORY_SETTLE_MODE": "local", "MEMORY_SETTLE_ROOT": self.top}) + self.assertEqual(r.returncode, 1, r.stdout + r.stderr) + self.assertIn("differs from", self.w.status()["error"]) + self.assertEqual((self.head(), self.owner_snapshot()), (old, snap)) + + def test_env_forms_systemd_reads_differently_are_refused(self): + """Fail closed (a review finding): a hand run must never read the settle's settings + differently from systemd, so any escaped, expanded, partly quoted or continued form + of them is refused; plain lines, whole-value quotes included, still work.""" + self.on_main() + self.seed() + t = self.top + bad = [ + f"MEMORY_SETTLE_MODE=local\nMEMORY_SETTLE_ROOT={t}\\ \n", + f"MEMORY_SETTLE_MODE=local\nMEMORY_SETTLE_ROOT=\\{t}\n", + f"MEMORY_SETTLE_MODE=lo\\\ncal\nMEMORY_SETTLE_ROOT={t}\n", + f'MEMORY_SETTLE_MODE="local\nMEMORY_SETTLE_ROOT={t}\n', + f"MEMORY_SETTLE_MODE='lo'cal\nMEMORY_SETTLE_ROOT={t}\n", + "MEMORY_SETTLE_MODE=local\nMEMORY_SETTLE_ROOT=$HOME/OPS\n", + f"MEMORY_SETTLE_MODE=local\nMEMORY_SETTLE_ROOT=`echo {t}`\n", + f'OTHER="a\nMEMORY_SETTLE_MODE=local\n"\nMEMORY_SETTLE_ROOT={t}\n', + f"OTHER=a\\\nMEMORY_SETTLE_MODE=local\nMEMORY_SETTLE_ROOT={t}\n", + f"export MEMORY_SETTLE_MODE=local\nMEMORY_SETTLE_ROOT={t}\n", + ] + snap, old = self.owner_snapshot(), self.head() + for body in bad: + with self.subTest(body): + self.configure("MEMORY_SETTLE_OWNER=1\n" + body) + r = self.mi("--settle", "--dry-run") + self.assertEqual(r.returncode, 1, r.stdout + r.stderr) + self.assertIn("systemd", r.stderr) + r = self.mi("--settle") + self.assertEqual(r.returncode, 1, r.stdout + r.stderr) + self.assertIn("systemd", self.w.status()["error"]) + self.assertFalse(os.path.exists(self.w.clone), "never read as clone mode") + self.assertEqual((self.head(), self.owner_snapshot()), (old, snap)) + for body in (f'MEMORY_SETTLE_MODE="local"\nMEMORY_SETTLE_ROOT=\'{t}\'\n', + f"# a comment with a \\ and a ' quote\nMEMORY_SETTLE_MODE = local\nMEMORY_SETTLE_ROOT={t} \n"): + with self.subTest(body): + self.configure("MEMORY_SETTLE_OWNER=1\n" + body) + r = self.mi("--settle", "--dry-run") + self.assertEqual(r.returncode, 0, r.stdout + r.stderr) + self.assertIn("(local mode)", r.stdout) + + def test_an_executable_commit_hook_is_refused_not_skipped(self): + """Our rule is never to bypass hooks, and local mode commits with plumbing, which runs + none: a checkout with a commit hook is refused, in the dry run and the apply run.""" + self.on_main() + self.seed() + hooks = os.path.join(self.top, ".git", "hooks") + os.makedirs(hooks, exist_ok=True) + self.w.write(os.path.join(hooks, "pre-commit.sample"), "#!/bin/sh\nexit 0\n") + os.chmod(os.path.join(hooks, "pre-commit.sample"), 0o755) + self.w.write(os.path.join(hooks, "commit-msg"), "#!/bin/sh\nexit 0\n") # present, not executable + alt = os.path.join(self.w.tmp, "hookdir") + cases = [("pre-commit", hooks, None), ("commit-msg", hooks, None), ("pre-merge-commit", hooks, None), + ("prepare-commit-msg", hooks, None), ("post-commit", hooks, None), + ("pre-commit", alt, alt)] + for name, d, hooks_path in cases: + with self.subTest(f"{name} in {d}"): + os.makedirs(d, exist_ok=True) + h = os.path.join(d, name) + self.w.write(h, "#!/bin/sh\nexit 0\n") + os.chmod(h, 0o755) + if hooks_path: + self.w.git(self.top, "config", "core.hooksPath", hooks_path) + snap, old = self.owner_snapshot(), self.head() + r = self.mi("--settle", "--dry-run") + self.assertEqual(r.returncode, 1, r.stdout + r.stderr) + self.assertIn(f"an apply run would refuse: {self.top}: an executable {name} hook", r.stdout) + r = self.mi("--settle") + self.assertEqual(r.returncode, 1, r.stdout + r.stderr) + self.assertIn(f"executable {name} hook", self.w.status()["error"]) + self.assertEqual((self.head(), self.owner_snapshot()), (old, snap)) + os.chmod(h, 0o644) + if hooks_path: + self.w.git(self.top, "config", "--unset", "core.hooksPath") + r = self.mi("--settle") + self.assertEqual(r.returncode, 0, r.stdout + r.stderr) + + def test_spaces_before_env_assignments_match_systemd(self): + self.on_main(origin=True) + self.seed() + self.configure(f"MEMORY_SETTLE_OWNER=1\nMEMORY_SETTLE_MODE = local\nMEMORY_SETTLE_ROOT = {self.top}\n") + r = self.mi("--settle") + self.assertEqual(r.returncode, 0, r.stdout + r.stderr) + self.assertIn("(local mode)", r.stdout) + self.assertFalse(os.path.exists(self.w.clone)) + self.assertNotIn("fetch", slurp(self.gitlog).splitlines()) + + def test_a_journal_from_the_other_mode_is_refused(self): + self.on_main() + self.seed() + self.w.write(self.journal(), json.dumps({"v": 1, "clone": self.w.clone, "head": self.head(), "moves": []})) + snap, old = self.w.snapshot(self.top), self.head() + r = self.mi("--settle") + self.assertEqual(r.returncode, 1) + self.assertIn("not this checkout's local run", self.w.status()["error"]) + self.assertEqual((self.head(), self.w.snapshot(self.top)), (old, snap)) + + def test_the_index_writer_waits_then_skips_while_the_settle_holds_its_lock(self): + self.on_main() + self.seed(5) + idx = os.path.join(self.w.root, "MEMORY.md") + os.makedirs(self.w.state, exist_ok=True) + outside_pool = os.path.join(self.w.outside, "pool") + self.w.entry(outside_pool, "o1", "a pool outside the configured checkout", modified="2026-09-01T00:00:00Z") + + def write(directory, wait="1", **extra): + return subprocess.run([sys.executable, "-I", "-B", IDX, directory], + env=dict(self.w.env, MEMORY_INDEX_SETTLE_WAIT=wait, **extra), + capture_output=True, text=True, timeout=60) + + fd = os.open(os.path.join(self.w.state, "memory-settle.lock"), os.O_RDWR | os.O_CREAT, 0o600) + try: + fcntl.flock(fd, fcntl.LOCK_EX) + self.w.write(idx, "stale\n") + t0 = time.monotonic() + r = write(self.w.root) + took = time.monotonic() - t0 + self.assertEqual(r.returncode, 0, r.stderr) + self.assertIn("skipped", r.stderr) + self.assertEqual(slurp(idx), "stale\n", "nothing written while the settle holds its lock") + self.assertGreaterEqual(took, 0.9, "it waited for the lock first") + self.assertLess(took, 30) + # A session can inherit overrides from its shell. The timer still + # runs with the settings in the file, and the session must serialize with it. + for extra in ({"MEMORY_SETTLE_MODE": "clone"}, {"MEMORY_SETTLE_ROOT": self.w.outside}): + with self.subTest(extra=extra): + r = write(self.w.root, wait="0", **extra) + self.assertEqual(r.returncode, 0, r.stderr) + self.assertIn("skipped", r.stderr) + self.assertEqual(slurp(idx), "stale\n") + r = write(outside_pool) + self.assertEqual(r.returncode, 0, r.stderr) + self.assertIn("o1", slurp(os.path.join(outside_pool, "MEMORY.md")), "no lock outside the checkout") + # A box with no local mode configured has no settle, so the writer takes no lock. + self.configure("MEMORY_SETTLE_OWNER=1\n") + r = write(self.w.root, wait="0") + self.assertEqual(r.returncode, 0, r.stderr) + self.assertNotEqual(slurp(idx), "stale\n", "no settle configured: writes as before") + self.configure() + finally: + os.close(fd) + self.w.write(idx, "stale\n") + r = write(self.w.root) + self.assertEqual(r.returncode, 0, r.stderr) + self.assertNotIn("skipped", r.stderr) + self.assertNotEqual(slurp(idx), "stale\n", "the lock free, it writes") + + def test_a_held_checkout_lock_waits_then_does_not_run(self): + self.on_main() + self.seed() + fd = os.open(self.top, os.O_RDONLY | os.O_DIRECTORY) + try: + fcntl.flock(fd, fcntl.LOCK_EX) + r = self.mi("--settle", extra={"MEMORY_SETTLE_LOCK_WAIT": "0"}) + r2 = self.mi("--restore", "x", extra={"MEMORY_SETTLE_LOCK_WAIT": "0"}) + finally: + os.close(fd) + self.assertEqual(r.returncode, 75, r.stderr) + self.assertIn("holds", r.stderr) + self.assertEqual(r2.returncode, 75, r2.stderr) + + +if __name__ == "__main__": + unittest.main(verbosity=2) diff --git a/.claude-config/bin/tests/memory-settle-timer-test.sh b/.claude-config/bin/tests/memory-settle-timer-test.sh new file mode 100644 index 0000000..504018c --- /dev/null +++ b/.claude-config/bin/tests/memory-settle-timer-test.sh @@ -0,0 +1,326 @@ +#!/usr/bin/env bash +# memory-settle-timer-test.sh - behavior tests for the wiring of the nightly memory mover +# (memory-index --settle): the two tracked units, the local-mode drop-in, the env template, +# and deploy.sh's keep_memory_settle_units(). The gate's own cases for check 6b +# (check_memory_settle) live in verify-ops-selftest.sh. +# +# Why pin these: the timer commits archive moves into the owner's checkout every night and +# runs unattended. What would go wrong without a test, and not be seen: +# - the service running on a box that never opted in, or its condition failing the unit +# instead of skipping it, which paints a red unit on every box that did not opt in; +# - the unit swallowing the mover's exit status (a "-" prefix, a shell wrapper that exits 0, a +# SuccessExitStatus), so a failed settle reads as success in systemd while the gate, which +# reads the status file, disagrees; +# - a oneshot bounded by RuntimeMaxSec, which systemd ignores for Type=oneshot, so a hung run +# would hold the timer's next start forever (the bound is TimeoutStartSec); +# - the schedule drifting off 03:10 (ahead of the 03:30 drift gate that reads its status) or +# losing Persistent=true; +# - deploy.sh installing a first copy of a unit or the drop-in, creating the env file, +# enabling or starting the timer, running a reload while t3code.service awaits one +# (arming its pending version switch), or aborting the whole deploy on a failure here; +# - the shipped template opting every box in (MEMORY_SETTLE_OWNER=1). +# +# Exit-status propagation is pinned from the unit text (systemd's documented behaviour for an +# ExecStart without "-", with no wrapper and no SuccessExitStatus). It is not run through a live +# unit: this suite starts no unit, writes no ~/.config, and never reaches the real user manager. +# The first live run is the activation step, read back by hand. +# +# Every path under test is a temp dir (HOME, OPS_DIR); systemctl is a shim. +# +# Usage: memory-settle-timer-test.sh (exit 0 all pass, 1 otherwise) +# shellcheck disable=SC2016 +. "$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd -P)/../sandbox-guard.sh" && sandbox_guard || exit 97 +set -uo pipefail +HERE="$(cd "$(dirname "$0")" && pwd -P)" +REPO="$(cd "$HERE/../../.." && pwd -P)" +DEPLOY="$REPO/.claude-config/deploy.sh" +SRC="$REPO/.claude-config/systemd" +SVC="$SRC/memory-settle.service" +TMR="$SRC/memory-settle.timer" +TPL="$SRC/memory-settle.env" +DROP="$SRC/memory-settle.service.d/local-mode.conf" +[ -f "$DEPLOY" ] || { echo "FAIL: deploy.sh missing"; exit 1; } + +T="$(mktemp -d)"; trap 'rm -rf "$T"' EXIT +pass=0; fail=0 +ok() { pass=$((pass+1)); echo "PASS: $1"; } +bad() { fail=$((fail+1)); echo "FAIL: $1"; [ $# -gt 1 ] && printf ' %s\n' "$2"; } + +echo "memory-settle-timer-test:" + +# --- the units --------------------------------------------------------------------------------- +# unit_value FILE KEY: every value of KEY= in FILE, comment lines excluded. +unit_value() { grep -E "^$2=" "$1" | sed -E "s/^$2=//"; } + +[ -f "$SVC" ] && [ -f "$TMR" ] && [ -f "$TPL" ] && ok "both units and the env template are tracked" \ + || bad "memory-settle.service, .timer or .env missing from .claude-config/systemd" + +[ "$(unit_value "$SVC" Type)" = oneshot ] && ok "service: Type=oneshot" || bad "service: Type is not oneshot" +exec_start="$(unit_value "$SVC" ExecStart)" +[ "$exec_start" = '%h/OPS/.claude-config/bin/memory-index --settle' ] \ + && ok "service: ExecStart is memory-index --settle from the OPS checkout" \ + || bad "service: ExecStart is not '%h/OPS/.claude-config/bin/memory-index --settle'" "$exec_start" + +# The unit's result must be the mover's own exit status: no "-" prefix (which ignores failure), no +# shell wrapper (whose `; exit 0` or `||` would mask it), no SuccessExitStatus or restart mask. +case "$exec_start" in -*|@*|:*|'!'*) bad "service: ExecStart prefix ignores or changes the exit status" "$exec_start" ;; *) ok "service: ExecStart has no ignore-failure prefix" ;; esac +case "$exec_start" in *'|'*|*';'*|*'&'*|*'sh -c'*|*bash*) bad "service: ExecStart goes through a shell or a pipeline, which can mask the exit status" "$exec_start" ;; *) ok "service: ExecStart is the mover itself, no shell wrapper" ;; esac +grep -vE '^[[:space:]]*#' "$SVC" | grep -qE '^(SuccessExitStatus|RestartPreventExitStatus|RestartForceExitStatus)=' \ + && bad "service: an exit-status directive changes what counts as success" "$(grep -E '^(SuccessExitStatus|RestartPreventExitStatus|RestartForceExitStatus)=' "$SVC")" \ + || ok "service: no SuccessExitStatus, so any non-zero exit of the mover marks the unit failed" + +# A oneshot ignores RuntimeMaxSec (systemd-analyze verify: "RuntimeMaxSec= has no effect in +# combination with Type=oneshot"), so a run is bounded by TimeoutStartSec, and the bound is finite. +grep -vE '^[[:space:]]*#' "$SVC" | grep -qE '^RuntimeMaxSec=' \ + && bad "service: RuntimeMaxSec is ignored for Type=oneshot; bound the run with TimeoutStartSec" \ + || ok "service: no RuntimeMaxSec (a oneshot ignores it)" +tmo="$(unit_value "$SVC" TimeoutStartSec)" +case "$tmo" in + *min) n="${tmo%min}"; { [[ "$n" =~ ^[0-9]+$ ]] && [ "$n" -ge 1 ] && [ "$n" -le 120 ]; } && ok "service: TimeoutStartSec=$tmo bounds a hung run" || bad "service: TimeoutStartSec is not a sane bound" "$tmo" ;; + *h) n="${tmo%h}"; { [[ "$n" =~ ^[0-9]+$ ]] && [ "$n" -ge 1 ] && [ "$n" -le 2 ]; } && ok "service: TimeoutStartSec=$tmo bounds a hung run" || bad "service: TimeoutStartSec is not a sane bound" "$tmo" ;; + *) bad "service: TimeoutStartSec is missing or not in minutes or hours" "${tmo:-none}" ;; +esac +[ "$(unit_value "$SVC" Nice)" = 10 ] && ok "service: Nice=10" || bad "service: Nice is not 10" +if grep -qE '^\[Install\]' "$SVC"; then bad "service: has an [Install] section (only the timer is enabled)"; else ok "service: no [Install] section"; fi + +# The env file the unit, the gate check and deploy.sh share. +[ "$(unit_value "$SVC" EnvironmentFile)" = '-%h/.config/ops/memory-settle.env' ] \ + && ok "service: EnvironmentFile is the optional (-) ~/.config/ops/memory-settle.env, the path the gate and deploy use" \ + || bad "service: EnvironmentFile is not '-%h/.config/ops/memory-settle.env'" "$(unit_value "$SVC" EnvironmentFile)" + +# The owner condition, run as systemd would run it ("$$" is systemd's escape for "$"). A condition +# failure must exit 1 to 254 (the unit is skipped, not failed); 255 or a signal would fail the unit. +cond="$(unit_value "$SVC" ExecCondition)" +if [ -z "$cond" ]; then + bad "service: no ExecCondition, so the unit would run on a box that is not the memory owner" +else + cond_sh="${cond//\$\$/\$}" + run_cond() { env -i PATH=/usr/bin:/bin "$@" bash -c "$cond_sh"; } + run_cond MEMORY_SETTLE_OWNER=1; rc1=$? + run_cond MEMORY_SETTLE_OWNER=0; rc0=$? + run_cond MEMORY_SETTLE_OWNER=; rce=$? + run_cond A=b; rcu=$? + run_cond MEMORY_SETTLE_OWNER=10; rcl=$? + run_cond 'MEMORY_SETTLE_OWNER=1 '; rcs=$? + [ "$rc1" = 0 ] && ok "ExecCondition: MEMORY_SETTLE_OWNER=1 lets the unit run" || bad "ExecCondition: an owner box is skipped (rc=$rc1)" "$cond" + skipped=yes + for rc in "$rc0" "$rce" "$rcu" "$rcl" "$rcs"; do { [ "$rc" -ge 1 ] && [ "$rc" -le 254 ]; } || skipped=no; done + [ "$skipped" = yes ] && ok "ExecCondition: 0, empty, unset, 10 and '1 ' all skip the unit with an exit of 1 to 254, never 0 or 255 (rc $rc0 $rce $rcu $rcl $rcs)" \ + || bad "ExecCondition: a non-owner value does not exit 1 to 254" "rc0=$rc0 empty=$rce unset=$rcu ten=$rcl spaced=$rcs" +fi + +# systemd's own static check of both units (documented behaviour: it warns on a directive that has no +# effect, such as RuntimeMaxSec on a oneshot, and fails on an unknown or malformed one). %h resolves to +# the temp HOME, so the stub below stands in for the mover and the check never reads a real checkout. +if command -v systemd-analyze >/dev/null 2>&1; then + VH="$T/vhome"; mkdir -p "$VH/OPS/.claude-config/bin" "$VH/units" + printf '#!/bin/sh\nexit 0\n' > "$VH/OPS/.claude-config/bin/memory-index"; chmod +x "$VH/OPS/.claude-config/bin/memory-index" + cp "$SVC" "$TMR" "$VH/units/" + vout="$(HOME="$VH" systemd-analyze --user verify "$VH/units/memory-settle.service" "$VH/units/memory-settle.timer" 2>&1)"; vrc=$? + if [ "$vrc" = 0 ] && ! printf '%s' "$vout" | grep -qiE 'no effect|ignoring|unknown|bad setting|invalid'; then + ok "systemd-analyze verify accepts both units with no ignored directive" + elif printf '%s' "$vout" | grep -qiE 'bus|connect|permission denied|not permitted|operation not'; then + echo "SKIP: systemd-analyze cannot run here (the static unit check): $(printf '%s' "$vout" | head -1)" + else + bad "systemd-analyze verify reports a problem with the units (rc=$vrc)" "$(printf '%s' "$vout" | head -5)" + fi + # The same check with the local-mode drop-in beside the service (systemd-analyze reads a + # .d directory next to the unit file it is given). + if [ -f "$DROP" ]; then + mkdir -p "$VH/units/memory-settle.service.d"; cp "$DROP" "$VH/units/memory-settle.service.d/" + vout="$(HOME="$VH" systemd-analyze --user verify "$VH/units/memory-settle.service" "$VH/units/memory-settle.timer" 2>&1)"; vrc=$? + if [ "$vrc" = 0 ] && ! printf '%s' "$vout" | grep -qiE 'no effect|ignoring|unknown|bad setting|invalid'; then + ok "systemd-analyze verify accepts the service with the local-mode drop-in, no ignored directive" + elif printf '%s' "$vout" | grep -qiE 'bus|connect|permission denied|not permitted|operation not'; then + echo "SKIP: systemd-analyze cannot run here (the drop-in check): $(printf '%s' "$vout" | head -1)" + else + bad "systemd-analyze verify reports a problem with the local-mode drop-in (rc=$vrc)" "$(printf '%s' "$vout" | head -5)" + fi + fi +else echo "SKIP: systemd-analyze not installed (the static unit check)"; fi + +oncal="$(unit_value "$TMR" OnCalendar)" +[ "$oncal" = '*-*-* 03:10' ] && ok "timer: OnCalendar is every day at 03:10, ahead of the 03:30 drift gate" || bad "timer: OnCalendar is not '*-*-* 03:10'" "$oncal" +[ "$(unit_value "$TMR" Persistent)" = true ] && ok "timer: Persistent=true" || bad "timer: Persistent is not true" +[ "$(unit_value "$TMR" WantedBy)" = timers.target ] && ok "timer: WantedBy=timers.target" || bad "timer: WantedBy is not timers.target" +if command -v systemd-analyze >/dev/null 2>&1; then + cal="$(systemd-analyze calendar "$oncal" 2>&1)" + if printf '%s\n' "$cal" | grep -q 'Normalized form: \*-\*-\* 03:10:00' && printf '%s\n' "$cal" | grep -q '03:10:00'; then ok "timer: systemd parses the schedule as daily 03:10:00" + else bad "timer: systemd-analyze does not read a daily 03:10 schedule" "$cal"; fi +fi + +# The template. A shipped =1 would opt every box in once a rollout copies it unedited. +owner_lines="$(grep -E '^MEMORY_SETTLE_OWNER=' "$TPL")" +[ "$owner_lines" = 'MEMORY_SETTLE_OWNER=0' ] && ok "template: the one active MEMORY_SETTLE_OWNER line is 0, so a copied template opts nothing in" \ + || bad "template: MEMORY_SETTLE_OWNER lines are not exactly one '=0'" "$owner_lines" +grep -qE '^MEMORY_SETTLE=' "$TPL" && bad "template: MEMORY_SETTLE is active, so a box ships with the mover off" "$(grep -E '^MEMORY_SETTLE=' "$TPL")" \ + || ok "template: MEMORY_SETTLE is only a commented example" +# Local mode is the template's only mode, so it ships active; the root is the rollout's to fill in. +[ "$(grep -E '^[[:space:]]*MEMORY_SETTLE_MODE=' "$TPL")" = 'MEMORY_SETTLE_MODE=local' ] \ + && ok "template: MEMORY_SETTLE_MODE=local is the one active mode line" \ + || bad "template: the active mode line is not exactly MEMORY_SETTLE_MODE=local" "$(grep -E 'MEMORY_SETTLE_MODE' "$TPL")" +! grep -qE '^[[:space:]]*MEMORY_SETTLE_ROOT=' "$TPL" && grep -qE '^#MEMORY_SETTLE_ROOT=/' "$TPL" \ + && ok "template: MEMORY_SETTLE_ROOT is a commented example the rollout fills in" \ + || bad "template: MEMORY_SETTLE_ROOT is active or its example is missing" "$(grep -E 'MEMORY_SETTLE_ROOT' "$TPL")" +# memory-index reads the template the way it reads a real env file: it must parse, fail-closed rules and all. +TPLV="$(python3 -I -c 'import sys +from importlib.machinery import SourceFileLoader as L +sys.dont_write_bytecode = True +m = L("mi", sys.argv[1]).load_module() +print(m.settle_env_values(sys.argv[2]))' "$REPO/.claude-config/bin/memory-index" "$TPL" 2>&1)" +[ "$TPLV" = "{'MEMORY_SETTLE_MODE': 'local'}" ] && ok "template: memory-index reads it as local mode with no root (refused until the rollout fills it in)" \ + || bad "template: memory-index does not read the template as local mode with no root" "$TPLV" + +# --- the local-mode drop-in ------------------------------------------------------------------- +# What would go wrong unseen: the drop-in adding a second ExecStart or ExecCondition to the base +# unit's instead of replacing them (systemd appends to a list unless it is reset first), so a box +# would also run the base unit's command; a condition that lets the unit run without local mode or +# an absolute root; an ExecStart behind a shell that masks the mover's exit status. +if [ ! -f "$DROP" ]; then + bad "the local-mode drop-in systemd/memory-settle.service.d/local-mode.conf is missing" +else + drop_body="$(grep -vE '^[[:space:]]*(#|$)' "$DROP")" + [ "$(printf '%s\n' "$drop_body" | grep -E '^(ExecCondition|ExecStart)=' | sed -E 's/=.*/=/' | tr '\n' ' ')" = 'ExecCondition= ExecCondition= ExecStart= ExecStart= ' ] \ + && [ "$(printf '%s\n' "$drop_body" | grep -cE '^(ExecCondition|ExecStart)=$')" = 2 ] \ + && [ "$(printf '%s\n' "$drop_body" | grep -E '^ExecCondition=' | head -1)" = 'ExecCondition=' ] \ + && [ "$(printf '%s\n' "$drop_body" | grep -E '^ExecStart=' | head -1)" = 'ExecStart=' ] \ + && ok "drop-in: resets ExecCondition and ExecStart before setting one of each" \ + || bad "drop-in: ExecCondition and ExecStart are not each reset and then set once" "$drop_body" + [ "$(printf '%s\n' "$drop_body" | grep -cvE '^(\[Service\]|ExecCondition=.*|ExecStart=.*)$')" = 0 ] \ + && ok "drop-in: changes nothing else in the base unit" || bad "drop-in: sets more than the condition and the command" "$drop_body" + d_start="$(printf '%s\n' "$drop_body" | grep -E '^ExecStart=.' | sed -E 's/^ExecStart=//')" + [ "$d_start" = '/usr/bin/env python3 ${MEMORY_SETTLE_ROOT}/.claude-config/bin/memory-index --settle' ] \ + && ok "drop-in: ExecStart runs the configured root's memory-index --settle, no shell, no ignore prefix" \ + || bad "drop-in: ExecStart is not the root's memory-index --settle" "$d_start" + d_cond="$(printf '%s\n' "$drop_body" | grep -E '^ExecCondition=.' | sed -E 's/^ExecCondition=//')" + d_cond_sh="${d_cond//\$\$/\$}" + d_run() { env -i PATH=/usr/bin:/bin "$@" bash -c "$d_cond_sh"; } + d_run MEMORY_SETTLE_OWNER=1 MEMORY_SETTLE_MODE=local MEMORY_SETTLE_ROOT=/home/x/OPS; d_ok=$? + d_skips="" + for combo in "MEMORY_SETTLE_OWNER=0 MEMORY_SETTLE_MODE=local MEMORY_SETTLE_ROOT=/home/x/OPS" \ + "MEMORY_SETTLE_OWNER=1 MEMORY_SETTLE_ROOT=/home/x/OPS" \ + "MEMORY_SETTLE_OWNER=1 MEMORY_SETTLE_MODE=clone MEMORY_SETTLE_ROOT=/home/x/OPS" \ + "MEMORY_SETTLE_OWNER=1 MEMORY_SETTLE_MODE=local" \ + "MEMORY_SETTLE_OWNER=1 MEMORY_SETTLE_MODE=local MEMORY_SETTLE_ROOT=" \ + "MEMORY_SETTLE_OWNER=1 MEMORY_SETTLE_MODE=local MEMORY_SETTLE_ROOT=relative/OPS" \ + "MEMORY_SETTLE_OWNER=1 MEMORY_SETTLE_MODE=local MEMORY_SETTLE_ROOT=/"; do + # shellcheck disable=SC2086 + d_run $combo; rc=$? + { [ "$rc" -ge 1 ] && [ "$rc" -le 254 ]; } || d_skips="$d_skips [$combo -> $rc]" + done + [ "$d_ok" = 0 ] && [ -z "$d_skips" ] \ + && ok "drop-in ExecCondition: runs only with owner 1, mode local and an absolute root; every other combination skips (exit 1 to 254)" \ + || bad "drop-in ExecCondition: wrong verdict" "ok-case rc=$d_ok; not skipped:$d_skips" +fi + +# --- deploy.sh's keep_memory_settle_units() ------------------------------------------------------- +DFN="$(awk '/^keep_memory_settle_units\(\) \{/,/^}/' "$DEPLOY")" +DH="$T/dhome"; mkdir -p "$DH" +# run_deploy_fn: the real function, evaluated with its message helpers and systemctl shimmed. +# SYSTEMD_USER=0 makes `show-environment` fail (no user manager on the box). +run_deploy_fn() { + ( + export HOME="$DH"; unset XDG_CONFIG_HOME + # Consumed by the real function evaluated below. + # shellcheck disable=SC2034 + CONFIG_DIR="$REPO/.claude-config"; DEPLOY_FAILED="" + msg_ok() { echo "OK $*"; }; msg_warn() { echo "WARN $*"; }; msg_bad() { echo "BAD $*"; }; msg_action() { echo "ACT $*"; } + systemctl() { + echo "systemctl $*" >> "$T/dcalls" + case "$*" in + *show-environment*) [ "${SYSTEMD_USER:-1}" = 1 ]; return $? ;; + *NeedDaemonReload*) + [ "${SYSTEMD_T3_QUERY_FAIL:-0}" = 0 ] || return 1 + cat "$T/dneed" 2>/dev/null || echo no ;; + *is-enabled*) return 1 ;; + esac + } + eval "$DFN" + keep_memory_settle_units + echo "FAILED=[$DEPLOY_FAILED]" + ) > "$T/dout" 2>&1 +} +UD="$DH/.config/systemd/user"; ENVF="$DH/.config/ops/memory-settle.env" +no_enable() { ! grep -qE 'systemctl --user (enable|start|restart|stop|disable|mask|link)|--now' "$T/dcalls"; } +if [ -z "$DFN" ]; then + bad "deploy.sh: keep_memory_settle_units() not found" +else + # A box that never opted in: nothing is installed, created, reloaded or enabled. + : > "$T/dcalls"; run_deploy_fn + if [ ! -e "$UD" ] && [ ! -e "$ENVF" ] && [ ! -s "$T/dcalls" ] && grep -q '^OK Nightly memory settle not installed on this box' "$T/dout" \ + && grep -q '^FAILED=\[\]' "$T/dout"; then + ok "a box that never opted in: no unit, drop-in or env file is created, systemctl is never called" + else bad "a deploy installed something on a box that never opted in" "$(tr '\n' ' ' < "$T/dout") :: $(tr '\n' ' ' < "$T/dcalls") :: $(ls -R "$DH/.config" 2>&1 | tr '\n' ' ')"; fi + : > "$T/dcalls"; run_deploy_fn + [ ! -e "$UD" ] && [ ! -s "$T/dcalls" ] && ok "a second run on that box is the same no-op" || bad "second run on a box that never opted in" "$(tr '\n' ' ' < "$T/dout")" + + # An installed box (the rollout's copies, here older than the tracked ones): each is brought current, + # one reload, nothing enabled; the env file is the owner's and never touched. + mkdir -p "$UD/memory-settle.service.d" "$(dirname "$ENVF")" + for f in memory-settle.service memory-settle.timer memory-settle.service.d/local-mode.conf; do printf '# an older copy\n' > "$UD/$f"; done + printf 'MEMORY_SETTLE_OWNER=1\nMEMORY_SETTLE_MODE=local\nMEMORY_SETTLE_ROOT=/home/x/OPS\n# owner edit\n' > "$ENVF" + env_before="$(sha256sum < "$ENVF")" + : > "$T/dcalls"; run_deploy_fn + if cmp -s "$SRC/memory-settle.service" "$UD/memory-settle.service" && cmp -s "$SRC/memory-settle.timer" "$UD/memory-settle.timer" \ + && cmp -s "$DROP" "$UD/memory-settle.service.d/local-mode.conf" \ + && [ "$(grep -c 'systemctl --user daemon-reload' "$T/dcalls")" = 1 ] && no_enable \ + && [ "$env_before" = "$(sha256sum < "$ENVF")" ] && grep -q '^FAILED=\[\]' "$T/dout"; then + ok "an installed box: both units and the drop-in brought current, one reload, nothing enabled, the env file untouched" + else bad "keeping an installed box current" "$(tr '\n' ' ' < "$T/dout") :: $(tr '\n' ' ' < "$T/dcalls")"; fi + sum_before="$(cat "$UD/memory-settle.service" "$UD/memory-settle.timer" "$UD/memory-settle.service.d/local-mode.conf" | sha256sum)" + : > "$T/dcalls"; run_deploy_fn + if grep -q '^OK memory-settle units already current' "$T/dout" && ! grep -q daemon-reload "$T/dcalls" && no_enable \ + && [ "$sum_before" = "$(cat "$UD/memory-settle.service" "$UD/memory-settle.timer" "$UD/memory-settle.service.d/local-mode.conf" | sha256sum)" ]; then + ok "a second run on an installed box changes nothing: no reload, nothing enabled" + else bad "second run on an installed box is not idempotent" "$(tr '\n' ' ' < "$T/dout") :: $(tr '\n' ' ' < "$T/dcalls")"; fi + + # Only what is installed is kept: a box with the units but no drop-in never gets the drop-in. + rm -rf "${UD:?}/memory-settle.service.d"; echo "# drift" >> "$UD/memory-settle.timer" + : > "$T/dcalls"; run_deploy_fn + if [ ! -e "$UD/memory-settle.service.d" ] && cmp -s "$SRC/memory-settle.timer" "$UD/memory-settle.timer" && no_enable; then + ok "a drifted unit is re-copied, and a drop-in the rollout did not install is never added" + else bad "the drop-in was added, or the drifted unit was not re-copied" "$(ls -la "$UD" 2>&1 | tr '\n' ' ')"; fi + + # While t3code.service awaits a reload, a deploy must not run one (it would arm the pending T3 version switch). + echo "# drift" >> "$UD/memory-settle.timer"; echo yes > "$T/dneed"; : > "$T/dcalls"; run_deploy_fn + if cmp -s "$SRC/memory-settle.timer" "$UD/memory-settle.timer" && ! grep -q "daemon-reload" "$T/dcalls" \ + && grep -q "^WARN t3code.service changed on disk" "$T/dout" && no_enable; then + ok "re-copies a drifted unit but skips the reload while t3code.service awaits one" + else bad "reload guard" "$(tr '\n' ' ' < "$T/dout") :: $(tr '\n' ' ' < "$T/dcalls")"; fi + rm -f "$T/dneed" + + # A failed property read cannot rule out a pending T3 version switch. + echo "# drift" >> "$UD/memory-settle.timer"; : > "$T/dcalls"; SYSTEMD_T3_QUERY_FAIL=1 run_deploy_fn + if cmp -s "$SRC/memory-settle.timer" "$UD/memory-settle.timer" && ! grep -q 'systemctl --user daemon-reload' "$T/dcalls" \ + && grep -q '^WARN Could not check whether t3code.service needs a daemon-reload' "$T/dout" && no_enable; then + ok "a failed T3 property read defers the reload and keeps the updated unit" + else bad "failed T3 property read" "$(tr '\n' ' ' < "$T/dout") :: $(tr '\n' ' ' < "$T/dcalls")"; fi + + # A symlinked unit is the owner's (systemctl link): never written through or replaced. + ln -sf "$T/nowhere.service" "$UD/memory-settle.service" + : > "$T/dcalls"; run_deploy_fn + [ -L "$UD/memory-settle.service" ] && [ ! -e "$T/nowhere.service" ] && no_enable \ + && ok "a symlinked unit is left alone, never written through" || bad "a symlinked unit was followed or replaced" "$(ls -l "$UD" 2>&1 | tr '\n' ' ')" + + # No systemd user manager after a change: a WARN, the files current, and never an aborted deploy. + DH="$T/dhome5"; UD="$DH/.config/systemd/user"; mkdir -p "$UD"; printf '# old\n' > "$UD/memory-settle.timer" + ( set -e; SYSTEMD_USER=0 run_deploy_fn ); [ $? -eq 0 ] && cont=yes || cont=no + if [ "$cont" = yes ] && grep -q "^WARN No systemd user manager here" "$T/dout" && cmp -s "$SRC/memory-settle.timer" "$UD/memory-settle.timer" \ + && [ ! -e "$UD/memory-settle.service" ]; then + ok "no systemd user manager: the installed unit is brought current with a WARN, nothing else is added" + else bad "no-manager case (cont=$cont)" "$(tr '\n' ' ' < "$T/dout")"; fi + + # A copy that cannot be written is a [XX] line and a deploy failure, never a silent pass. + DH="$T/dhome6"; UD="$DH/.config/systemd/user"; mkdir -p "$UD"; printf '# old\n' > "$UD/memory-settle.timer"; chmod 444 "$UD/memory-settle.timer"; chmod 555 "$UD" + if [ "$(id -u)" != 0 ]; then + ( set -e; run_deploy_fn ); [ $? -eq 0 ] && cont=yes || cont=no + if [ "$cont" = yes ] && grep -q '^BAD Could not update' "$T/dout" && grep -q '^FAILED=\[ memory-settle\]' "$T/dout"; then + ok "an installed unit that cannot be updated is reported and marks the deploy failed" + else bad "unwritable unit (cont=$cont)" "$(tr '\n' ' ' < "$T/dout")"; fi + else echo "SKIP: unwritable-unit case (root writes a read-only directory)"; fi + chmod 755 "$UD" +fi + +echo +echo "memory-settle-timer-test: $pass passed, $fail failed" +[ "$fail" -eq 0 ] diff --git a/.claude-config/bin/tests/secrets-guard-test.sh b/.claude-config/bin/tests/secrets-guard-test.sh index dacc6a1..99f2f93 100755 --- a/.claude-config/bin/tests/secrets-guard-test.sh +++ b/.claude-config/bin/tests/secrets-guard-test.sh @@ -174,6 +174,13 @@ printf '%s\n' "$CRED" > "$ODDFILE" ERR="$(bash "$SCAN" "$SCANDIR" 2>&1)"; RC=$? [ "$RC" = 1 ] && grep -q 'github-token' <<< "$ERR" \ && ok "scanner: newline in a file name still reaches the credential scan" || bad "newline file was skipped" "rc=$RC $ERR" +# age 1.4's age-keygen makes post-quantum identities (AGE-SECRET-KEY-PQ-1...) by default; the +# classical shape alone missed them. Built from parts so this file holds no matchable key. +for AGEKEY in "AGE-SECRET-KEY-PQ-""1ABCDEFGHIJKLMNOPQRST" "AGE-SECRET-KEY-""1ABCDEFGHIJKLMNOPQRST"; do + ERR="$(printf '%s\n' "$AGEKEY" | bash "$SCAN" --stdin agekey 2>&1)"; RC=$? + [ "$RC" = 1 ] && grep -q 'age-secret-key' <<< "$ERR" \ + && ok "scanner: an age identity (${AGEKEY:0:18}) is a hard hit" || bad "age identity passed" "rc=$RC $ERR" +done printf '%s\n' "$CRED" > "$SCANDIR/clean.md" ERR="$(PATH="$BADFIND:$PATH" bash "$SCAN" "$SCANDIR" 2>&1)"; RC=$? [ "$RC" = 1 ] && grep -q 'github-token' <<< "$ERR" && grep -q 'directory walk failed' <<< "$ERR" \ diff --git a/.claude-config/bin/tests/session-briefing-desk-test.sh b/.claude-config/bin/tests/session-briefing-desk-test.sh new file mode 100644 index 0000000..c4956b4 --- /dev/null +++ b/.claude-config/bin/tests/session-briefing-desk-test.sh @@ -0,0 +1,186 @@ +#!/usr/bin/env bash +# session-briefing-desk-test.sh - behavior tests for desk_line in hooks/session-briefing.sh, the +# briefing line that shows what `desk` (bin/desk) last proved wrong with the AI context on this box. +# +# Why: the line reaches every teammate's session start. A false alarm teaches people to skip the +# briefing, a stale one keeps alarming after the check stopped running, a memory finding in it puts +# memory size or duplicates in the briefing, which it never carries, and a scan at session start would make every session wait on git history. So the line reads the +# cache only. +# +# Pinned: +# a fresh cache with a line: one ` Desk:` line, exactly as cached (end to end from a real desk run); +# no cache, a cache older than 8 days, a cache written for another checkout, an empty line, a +# schema the hook does not know: no Desk line at all; +# a cache that exists but cannot be parsed: one line naming the file and `desk`, never silence; +# the line never carries memory findings, even when the cache record holds them; +# the hook never runs desk: a stub desk that would write a sentinel is left alone; +# a lane session prints no Desk line (the lane gate exits first); a resumed session prints the +# full briefing (this hook has no resume short form) with the line once; +# unread coverage reaches the line and is never worded as clean; +# the lapse notice (desk lapse's receipt, end to end from a real lapse): shown once, then recorded as +# shown; a fresh scan does not revive it; another checkout's receipt is quiet; a broken one says so; +# an unwritable shown list repeats it rather than hiding it; a lane neither shows nor uses it up. +# +# Every path is under a temp dir. The suite refuses to run outside the sandbox because +# session-briefing.sh deletes and moves state files (the sandbox guard below). +# +# Usage: session-briefing-desk-test.sh (exit 0 all pass, 1 otherwise) +. "$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd -P)/../sandbox-guard.sh" && sandbox_guard || exit 97 +set -uo pipefail +HERE="$(cd "$(dirname "$0")" && pwd -P)" +BRIEF_HOOK="$HERE/../../hooks/session-briefing.sh" +DESK="$HERE/../desk" +[ -f "$BRIEF_HOOK" ] && [ -f "$DESK" ] || { echo "FAIL: the hook or desk is missing"; exit 1; } +command -v jq >/dev/null || { echo "FAIL: jq required (the hooks' own parser)"; exit 1; } + +T="$(mktemp -d)"; trap 'rm -rf "$T"' EXIT +pass=0; fail=0 +ok() { pass=$((pass+1)); echo "PASS: $1"; } +bad() { fail=$((fail+1)); echo "FAIL: $1"; [ $# -gt 1 ] && printf ' %s\n' "$2"; } + +echo "session-briefing-desk-test:" +mkdir -p "$T/home" "$T/run" "$T/cycle" "$T/state" "$T/work" "$T/cfg/projects" +CW="$T/ops"; mkdir -p "$CW/NOTES/MASTER/AI" "$CW/PROJECTS" "$CW/CONTEXT" "$CW/.claude-config/bin" +CWR="$(cd "$CW" && pwd -P)" +# the owner's box marker, so desk judges this fixture as the owner's tree (no stale-core check) +printf 'ops_commit=x\n' > "$CW/.claude-config/ops-port-ref" +# a stub desk the hook must never run +SENT="$T/desk-ran" +printf '#!/bin/sh\ntouch %s\n' "$SENT" > "$CW/.claude-config/bin/desk"; chmod +x "$CW/.claude-config/bin/desk" +CACHE="$T/state/desk-last.json" + +# run [VAR=value ...]: stdout in $out, exit code in $rc. +run() { + local payload="$1"; shift + out="$(cd "$T/work" && printf '%s' "$payload" | env -u OPS_CYCLE_RUNDIR -u CC_CYCLE_RUNDIR -u OPS_STATE_DIR -u TMUX -u HERDR_SESSION \ + -u T3CODE_THREAD_ID -u CLAUDE_CODE_SESSION_ID -u OPS_LANE_CLASS -u CODEX_USAGE \ + HOME="$T/home" OPS_DIR="$CW" CLAUDE_CONFIG_DIR="$T/cfg" LANE_CLASS_NO_DB=1 \ + CC_CYCLE_RUNDIR="$T/run" OPS_CYCLE_RUNDIR="$T/cycle" OPS_STATE_DIR="$T/state" "$@" bash "$BRIEF_HOOK" 2>"$T/err")" + rc=$? +} +has() { case "$out" in *"$1"*) return 0 ;; esac; return 1; } +desk_lines() { printf '%s\n' "$out" | grep -c '^ Desk:' || true; } +PAYLOAD='{"hook_event_name":"SessionStart","source":"startup","session_id":"sess-desk-test"}' +now="$(date +%s)" + +# write_cache [extra jq object merged into the record] +write_cache() { + jq -n --arg root "$1" --argjson epoch "$2" --arg line "$3" --argjson extra "${4:-{\}}" \ + '{schema: 1, root: $root, scanned_epoch: $epoch, line: $line} + $extra' > "$CACHE" +} + +# --- no cache: no line ------------------------------------------------------------- +rm -f "$CACHE" +run "$PAYLOAD" +{ has 'SESSION BRIEFING' && [ "$(desk_lines)" -eq 0 ] && [ "$rc" -eq 0 ]; } && ok "no cache: the briefing has no Desk line" || bad "no cache printed a Desk line" "$out" + +# --- end to end from a real scan -------------------------------------------------------- +printf 'Read `CONTEXT/does-not-exist.md` before starting.\n' > "$CW/CONTEXT/core.md" +HOME="$T/home" python3 -I "$DESK" --root "$CW" --state-dir "$T/state" >/dev/null 2>"$T/err" || bad "the real desk scan failed" "$(cat "$T/err")" +cached="$(jq -r .line "$CACHE")" +run "$PAYLOAD" +{ [ -n "$cached" ] && has " Desk: $cached" && [ "$(desk_lines)" -eq 1 ]; } && ok "a real scan's cached line is shown once, exactly as cached" || bad "end-to-end line" "cached=[$cached] out=$out" +has '1 dead reference' && ok "the shown line names the finding" || bad "line lost the finding" "$out" + +# --- stale, foreign, empty and unknown caches stay quiet -------------------------------- +write_cache "$CWR" "$((now - 8*86400 - 120))" "3 dead references in always-loaded files. Run desk for the list." +run "$PAYLOAD" +[ "$(desk_lines)" -eq 0 ] && ok "a cache older than 8 days is not shown" || bad "stale cache shown" "$out" +write_cache "$CWR" "$((now - 7*86400))" "3 dead references in always-loaded files. Run desk for the list." +run "$PAYLOAD" +[ "$(desk_lines)" -eq 1 ] && ok "a 7-day-old cache is still shown" || bad "7-day cache hidden" "$out" +write_cache "$T/some-other-checkout" "$now" "3 dead references in always-loaded files. Run desk for the list." +run "$PAYLOAD" +[ "$(desk_lines)" -eq 0 ] && ok "a cache written for another checkout is not shown" || bad "foreign cache shown" "$out" +write_cache "$CWR" "$now" "" +run "$PAYLOAD" +[ "$(desk_lines)" -eq 0 ] && ok "an empty line (nothing to show) prints nothing" || bad "empty line printed" "$out" +write_cache "$CWR" "$((now + 3600))" "a line from the future" +run "$PAYLOAD" +[ "$(desk_lines)" -eq 0 ] && ok "a cache dated in the future is not shown" || bad "future cache shown" "$out" +jq -n --arg root "$CWR" --argjson epoch "$now" '{schema: 99, root: $root, scanned_epoch: $epoch, line: "unknown schema"}' > "$CACHE" +run "$PAYLOAD" +[ "$(desk_lines)" -eq 0 ] && ok "a schema this hook does not know prints nothing" || bad "unknown schema shown" "$out" + +# --- a broken cache is never silence ------------------------------------------------- +printf '{not json' > "$CACHE" +run "$PAYLOAD" +{ has ' Desk: cache unreadable' && has 'run desk' && [ "$rc" -eq 0 ]; } && ok "an unparseable cache says so, and the hook still exits 0" || bad "broken cache" "$out" + +# --- memory never reaches the briefing --------------------------------------------------- +write_cache "$CWR" "$now" "1 core file behind the template with no local edit. Run desk for the list." \ + '{"findings": {"duplicate_pools": [{"pools": ["pool-alpha", "pool-beta"], "entries": 125}]}, "counts": {"duplicate_pools": 1}}' +run "$PAYLOAD" +{ has ' Desk: 1 core file behind' && ! has 'pool-alpha' && ! has '125' && ! has 'duplicate'; } \ + && ok "memory findings in the record never reach the briefing" || bad "memory leaked into the briefing" "$out" + +# --- unread coverage reaches the line and is not worded as clean -------------------------- +write_cache "$CWR" "$now" "2 areas not checked, so this is not a clean result. Run desk for details." +run "$PAYLOAD" +{ has 'not a clean result' && ! has 'nothing wrong' && ! has 'all clear'; } && ok "unread coverage is shown as not checked, never as clean" || bad "unread wording" "$out" + +# --- the hook never scans ---------------------------------------------------------------- +rm -f "$SENT" +run "$PAYLOAD" +[ ! -e "$SENT" ] && ok "the hook never runs desk at session start" || bad "the hook ran desk" +rm -f "$CACHE"; run "$PAYLOAD" +[ ! -e "$SENT" ] && [ ! -e "$CACHE" ] && ok "with no cache the hook still does not scan or create one" || bad "the hook scanned or wrote a cache" + +# --- lane and resume ------------------------------------------------------------------------ +write_cache "$CWR" "$now" "3 dead references in always-loaded files. Run desk for the list." +run "$PAYLOAD" T3CODE_THREAD_ID='thread:delegated-task:command%3Amcp%3Aabc%3Adelegate-task%3Ax' +[ "$(desk_lines)" -eq 0 ] && ok "a lane session prints no Desk line" || bad "lane printed Desk" "$out" +run '{"hook_event_name":"SessionStart","source":"startup","session_id":"sess-resume"}' +run '{"hook_event_name":"SessionStart","source":"resume","session_id":"sess-resume"}' +# This template's hook has no resume short form: a resumed session gets the full briefing, Desk line once. +[ "$(desk_lines)" -eq 1 ] && ok "a resumed session gets the full briefing with one Desk line" || bad "resume Desk line count" "$out" + +# --- the lapse notice: shown once, end to end from a real desk lapse ------------------------------- +# A team box (no owner marker) with a migrated table and one setup row past its review date. +BOX="$T/box"; mkdir -p "$BOX/CONTEXT" "$BOX/NOTES/MASTER/AI" "$BOX/PROJECTS" +BOXR="$(cd "$BOX" && pwd -P)" +printf '[user]\n\tname = t\n\temail = t@example.invalid\n' > "$T/gitconfig" +printf 'core\n' > "$BOX/CONTEXT/core.md" +printf '# Standing orders\n\n| Ruling date | Area | Ruling and why | Kind |\n|---|---|---|---|\n| 2026-11-20 | Autonomy | Pause at each step. | setup, review by 2026-12-04 |\n| 2026-11-01 | Backups | Nightly. | preference |\n' \ + > "$BOX/CONTEXT/standing-orders.md" +gitb() { env HOME="$T/home" GIT_CONFIG_GLOBAL="$T/gitconfig" GIT_CONFIG_NOSYSTEM=1 git -C "$BOX" "$@"; } +gitb init -q -b main && gitb add -A && gitb commit -q -m box || bad "the fixture box could not be committed" +LSTATE="$T/lapse-state" +env HOME="$T/home" GIT_CONFIG_GLOBAL="$T/gitconfig" GIT_CONFIG_NOSYSTEM=1 DESK_TODAY=2026-12-05 \ + python3 -I "$DESK" lapse --root "$BOX" --state-dir "$LSTATE" >"$T/lapse-out" 2>&1 \ + || bad "desk lapse failed on the fixture box" "$(cat "$T/lapse-out")" +[ -f "$LSTATE/desk-lapse-notice.json" ] && ok "desk lapse wrote a pending notice" || bad "no notice receipt" "$(cat "$T/lapse-out")" +notice_lines() { printf '%s\n' "$out" | grep -c 'lapsed on' || true; } +run "$PAYLOAD" OPS_DIR="$BOX" OPS_STATE_DIR="$LSTATE" +{ has ' Desk: 1 setup ruling lapsed on 2026-12-05; say keep to restore' && [ "$(notice_lines)" -eq 1 ] && [ "$rc" -eq 0 ]; } \ + && ok "the next briefing shows the lapse notice once" || bad "lapse notice missing" "$out" +grep -Fxq "$(jq -r '.events[0].id' "$LSTATE/desk-lapse-notice.json")" "$LSTATE/desk-lapse-shown" 2>/dev/null \ + && ok "the shown event is recorded in desk-lapse-shown" || bad "shown list not written" +run "$PAYLOAD" OPS_DIR="$BOX" OPS_STATE_DIR="$LSTATE" +[ "$(notice_lines)" -eq 0 ] && ok "the briefing after that does not repeat it" || bad "notice repeated" "$out" +# a fresh scan rewrites desk-last.json and must not bring the notice back or erase a new one +env HOME="$T/home" DESK_TODAY=2026-12-05 python3 -I "$DESK" --root "$BOX" --state-dir "$LSTATE" >/dev/null 2>&1 +run "$PAYLOAD" OPS_DIR="$BOX" OPS_STATE_DIR="$LSTATE" +[ "$(notice_lines)" -eq 0 ] && ok "a fresh scan does not bring a shown notice back" || bad "scan revived the notice" "$out" +# a receipt for another checkout, or a broken one +jq --arg r "$T/elsewhere" '.root = $r | .events[0].id = "lapse-other"' "$LSTATE/desk-lapse-notice.json" > "$T/other.json" +cp "$T/other.json" "$LSTATE/desk-lapse-notice.json" +run "$PAYLOAD" OPS_DIR="$BOX" OPS_STATE_DIR="$LSTATE" +[ "$(notice_lines)" -eq 0 ] && ok "a receipt written for another checkout is not shown" || bad "foreign receipt shown" "$out" +printf '{broken' > "$LSTATE/desk-lapse-notice.json" +run "$PAYLOAD" OPS_DIR="$BOX" OPS_STATE_DIR="$LSTATE" +{ has 'lapse notice unreadable' && [ "$rc" -eq 0 ]; } && ok "an unreadable receipt says so, never silence" || bad "broken receipt" "$out" +# the shown list cannot be written: the notice repeats rather than vanishing +jq -n --arg r "$BOXR" '{schema: 1, root: $r, events: [{id: "lapse-two", moved: "2026-12-06", commit: null, + rows: [{date: "a", area: "b"}, {date: "c", area: "d"}]}]}' > "$LSTATE/desk-lapse-notice.json" +rm -f "$LSTATE/desk-lapse-shown"; mkdir "$LSTATE/desk-lapse-shown" +run "$PAYLOAD" OPS_DIR="$BOX" OPS_STATE_DIR="$LSTATE" +run "$PAYLOAD" OPS_DIR="$BOX" OPS_STATE_DIR="$LSTATE" +{ has '2 setup rulings lapsed on 2026-12-06' && [ "$rc" -eq 0 ]; } && ok "an unwritable shown list repeats the notice, never hides it" || bad "unwritable shown list" "$out" +rmdir "$LSTATE/desk-lapse-shown" +run "$PAYLOAD" OPS_DIR="$BOX" OPS_STATE_DIR="$LSTATE" T3CODE_THREAD_ID='thread:delegated-task:command%3Amcp%3Aabc%3Adelegate-task%3Ax' +[ "$(notice_lines)" -eq 0 ] && [ ! -e "$LSTATE/desk-lapse-shown" ] && ok "a lane session neither shows nor uses up the notice" || bad "lane consumed the notice" "$out" + +echo +echo "session-briefing-desk-test: $pass passed, $fail failed" +[ "$fail" -eq 0 ] diff --git a/.claude-config/bin/tests/t3-api-test.sh b/.claude-config/bin/tests/t3-api-test.sh index 8ee14cb..c1335f0 100755 --- a/.claude-config/bin/tests/t3-api-test.sh +++ b/.claude-config/bin/tests/t3-api-test.sh @@ -419,6 +419,15 @@ assert b["message"]["attachments"]==[] assert b["runtimeMode"]=="auto-accept-edits" PYCOMPACT [ $? -eq 0 ] && pass || faild "native compact must send bare command and return its messageId" +# V1 compact --arm-record reads the thread afresh just before the POST and holds on any answer it cannot +# check: this stub's thread read names another thread and carries no messages, so exit 6, no dispatch. +python3 -c 'import json,sys; json.dump({"thread": "thread-aaaa", "armed_at": "2026-12-02T15:00:00Z"}, open(sys.argv[1], "w"))' "$TMP/arm-v1.json" +NB="$(wc -l < "$STUB_LOG")" +OUT="$(run compact thread-aaaa --arm-record "$TMP/arm-v1.json")"; rc=$? +REQS="$(tail -n +"$((NB + 1))" "$STUB_LOG" | python3 -c 'import json,sys; print(" ".join("%s %s" % (r["method"], r["path"].split("?")[0]) for r in map(json.loads, sys.stdin)))')" +[ "$rc" -eq 6 ] && printf '%s' "$OUT" | grep -q 'the thread answer does not identify the armed thread' \ + && printf '%s' "$REQS" | grep -q 'GET /api/orchestration/threads/thread-aaaa' && ! printf '%s' "$REQS" | grep -q 'POST /api/orchestration/dispatch' \ + && pass || faild "V1 compact with an arm record must read the thread before the POST and send nothing on an uncheckable answer (rc=$rc)" "out=$OUT reqs=$REQS" # V1 archive is unchanged by the V2 refusal (section 3e): one thread.archive POST. OUT="$(run archive thread-aaaa)"; rc=$? @@ -1648,6 +1657,34 @@ h = hashlib.sha256(b"/compact").hexdigest()[:12] assert p["text"] == "/compact" and p["dispatchMode"] == {"type": "queue_after_active"} and "deliveryIntent" not in p assert p["commandId"].startswith("t3-api:compact:wt-idle:%s:" % h) and p["messageId"].startswith("t3-api:msg:wt-idle:%s:" % h)' \ && pass || faild "V2 compact must send exact /compact queued and print its messageId (rc=$rc)" "out=$OUT err=$ERR" +# compact --arm-record: the armed compactor's last check, on the /bounded read v2_message already made. +# A clean arm dispatches as before; a run started after the arming, or an active run, exits 9 with the +# reason on stdout and nothing sent; a record for another thread is a bad answer (6), nothing sent. +w3_arm() { # + python3 -c 'import json,sys; json.dump({"thread": sys.argv[2], "armed_at": sys.argv[3]}, open(sys.argv[1], "w"))' "$@" +} +w3_arm "$TMP/arm-clean.json" wt-idle 2026-10-17T19:00:00Z +w3_reset; B="$(w3_mark)"; w3 compact wt-idle --arm-record "$TMP/arm-clean.json"; rc=$? +P="$(ws_payloads "$B")" +[ "$rc" -eq 0 ] && [ "$(printf '%s\n' "$P" | grep -c .)" = 1 ] \ + && [ "$OUT" = "$(printf '%s' "$P" | python3 -c 'import json,sys; print(json.load(sys.stdin)["messageId"])')" ] \ + && pass || faild "V2 compact with a clean arm record must dispatch one /compact and print its messageId (rc=$rc)" "out=$OUT err=$ERR" +w3_arm "$TMP/arm-late.json" wt-idle 2026-10-17T18:00:00Z +w3_reset; B="$(w3_mark)"; w3 compact wt-idle --arm-record "$TMP/arm-late.json"; rc=$? +[ "$rc" -eq 9 ] && printf '%s' "$OUT" | grep -q '^another run started after the arming: ' && [ "$(ws_count "$B")" = 0 ] \ + && pass || faild "V2 compact must stand down (exit 9, reason on stdout, nothing sent) on a run after the arming, got rc=$rc" "out=$OUT err=$ERR" +w3_arm "$TMP/arm-running.json" wt-running 2026-10-17T19:00:00Z +w3_reset; B="$(w3_mark)"; w3 compact wt-running --arm-record "$TMP/arm-running.json"; rc=$? +[ "$rc" -eq 9 ] && [ "$OUT" = "the thread has an active run" ] && [ "$(ws_count "$B")" = 0 ] \ + && pass || faild "V2 compact must stand down (exit 9, nothing sent) on an active run, got rc=$rc" "out=$OUT err=$ERR" +w3_reset; B="$(w3_mark)"; w3 compact wt-running --arm-record "$TMP/arm-clean.json"; rc=$? +[ "$rc" -eq 6 ] && printf '%s' "$ERR" | grep -q 'the arm record is for another thread' && [ "$(ws_count "$B")" = 0 ] \ + && pass || faild "V2 compact with another thread's arm record must exit 6, nothing sent, got rc=$rc" "out=$OUT err=$ERR" +for args in "wt-idle --arm-record" "wt-idle --arm $TMP/arm-clean.json" "wt-idle --arm-record ''" "wt-idle extra"; do + w3_reset; B="$(w3_mark)"; eval "w3 compact $args"; rc=$? + [ "$rc" -eq 2 ] && printf '%s' "$ERR" | grep -qF 'compact [--arm-record FILE]' && [ "$(ws_count "$B")" = 0 ] \ + && pass || faild "compact $args must be a usage error (exit 2), nothing sent, got rc=$rc" "err=$ERR" +done # An exact '/compact' through send is allowed; it is the compact verb. w3_reset; B="$(w3_mark)"; w3 send wt-idle /compact; rc=$? [ "$rc" -eq 0 ] && ws_since "$B" | grep -q '^message.dispatch t3-api:compact:wt-idle:' && pass || faild "send of an exact /compact must go out (rc=$rc)" "$ERR" diff --git a/.claude-config/bin/tests/t3-api-v2-safety-test.py b/.claude-config/bin/tests/t3-api-v2-safety-test.py index 8e7e6b5..8df33f2 100644 --- a/.claude-config/bin/tests/t3-api-v2-safety-test.py +++ b/.claude-config/bin/tests/t3-api-v2-safety-test.py @@ -254,6 +254,78 @@ def test_only_a_compaction_attributed_to_the_selected_run_proves_completion(self self.assertEqual(api.compact_evidence(bounded, "t", "compact-message")[0], "completed") +class CompactArmGuardTests(unittest.TestCase): + """compact-arm-check: the armed compactor's last look before /compact (compact-cycle.sh + ARMED BY REST-STOP). The owner's message or another run after the arming, or a run still + active, stands it down; an answer it cannot check raises, so nothing is sent.""" + ARM = {"thread": "t", "armed_at": "2026-12-02T15:00:00Z", "armed_turn": "armed-run"} + + def v2(self, messages=(), runs=()): + return {"projection": {"thread": {"id": "t"}, "messages": list(messages), "runs": list(runs)}} + + def v1(self, messages=(), **thread): + return {"thread": dict({"id": "t", "messages": list(messages), "latestTurn": None}, **thread)} + + def test_a_clean_v2_thread_is_not_superseded(self): + answer = self.v2([{"id": "u", "role": "user", "creationSource": "web", "createdAt": "2026-12-02T14:59:00Z"}], + [{"id": "r0", "status": "completed", "requestedAt": "2026-12-02T14:59:00Z"}]) + self.assertIsNone(api.compact_arm_guard(answer, "t", self.ARM, "2")) + + def test_a_harness_message_after_the_arming_is_not_the_owner(self): + for src in ("server", "mcp"): + answer = self.v2([{"id": "h", "role": "user", "creationSource": src, "createdAt": "2026-12-02T15:00:05Z"}]) + self.assertIsNone(api.compact_arm_guard(answer, "t", self.ARM, "2"), src) + + def test_the_owner_typing_after_the_arming_stands_it_down_on_both_protocols(self): + late = {"id": "late", "role": "user", "creationSource": "web", "createdAt": "2026-12-02T15:00:01Z"} + self.assertIn("the owner typed after the arming: message late", api.compact_arm_guard(self.v2([late]), "t", self.ARM, "2")) + # V1 threads carry no creationSource: any user message counts as the owner's. + v1_late = {k: v for k, v in late.items() if k != "creationSource"} + self.assertIn("the owner typed after the arming", api.compact_arm_guard(self.v1([v1_late]), "t", self.ARM, "1")) + + def test_an_unreadable_time_reads_as_a_change(self): + bad_msg = {"id": "u", "role": "user", "creationSource": "web", "createdAt": "yesterday"} + self.assertIn("unreadable createdAt", api.compact_arm_guard(self.v2([bad_msg]), "t", self.ARM, "2")) + bad_run = {"id": "r", "status": "completed", "requestedAt": "2026-12-02T14:00:00Z", "startedAt": 12} + self.assertIn("unreadable startedAt", api.compact_arm_guard(self.v2(runs=[bad_run]), "t", self.ARM, "2")) + + def test_a_run_after_the_arming_stands_it_down_but_the_arming_turn_does_not(self): + armed = {"id": "armed-run", "status": "completed", "startedAt": "2026-12-02T15:00:02Z"} + self.assertIsNone(api.compact_arm_guard(self.v2(runs=[armed]), "t", self.ARM, "2")) + late = {"id": "late-run", "status": "queued", "requestedAt": "2026-12-02T15:00:01Z"} + self.assertIn("another run started after the arming: late-run", + api.compact_arm_guard(self.v2(runs=[armed, late]), "t", self.ARM, "2")) + + def test_validation_started_at_wins_over_armed_at(self): + arm = dict(self.ARM, validation_started_at="2026-12-02T15:00:10Z") + msg = {"id": "u", "role": "user", "creationSource": "web", "createdAt": "2026-12-02T15:00:05Z"} + self.assertIsNone(api.compact_arm_guard(self.v2([msg]), "t", arm, "2")) + + def test_an_active_run_or_a_question_card_stands_it_down(self): + running = {"id": "armed-run", "status": "running", "startedAt": "2026-12-02T14:59:00Z"} + self.assertEqual(api.compact_arm_guard(self.v2(runs=[running]), "t", self.ARM, "2"), "the thread has an active run") + self.assertEqual(api.compact_arm_guard(self.v1(session={"activeTurnId": "turn-x"}), "t", self.ARM, "1"), + "the thread has an active run") + self.assertEqual(api.compact_arm_guard(self.v1(hasPendingUserInput=True), "t", self.ARM, "1"), + "the thread has a pending question card") + self.assertIsNone(api.compact_arm_guard(self.v1(session={"activeTurnId": None}), "t", self.ARM, "1")) + + def test_an_answer_or_record_it_cannot_check_raises(self): + cases = ( + ({"thread": {"id": "other", "messages": []}}, self.ARM, "1"), + ({"thread": {"id": "t"}}, self.ARM, "1"), + ({"projection": {"thread": {"id": "other"}, "messages": [], "runs": []}}, self.ARM, "2"), + (self.v2(), dict(self.ARM, thread="other"), "2"), + (self.v2(), dict(self.ARM, armed_at="not a time"), "2"), + (self.v2(), {"thread": "t"}, "2"), + ({"thread": {"id": "t", "messages": []}}, self.ARM, "1"), # neither runs nor latestTurn + ) + for answer, arm, proto in cases: + with self.subTest(answer=answer, arm=arm, proto=proto): + with self.assertRaises(api.ShapeError): + api.compact_arm_guard(answer, "t", arm, proto) + + class TransportBaseTests(unittest.TestCase): def test_a_non_origin_base_never_dispatches_at_the_root_route(self): for base in ("http://127.0.0.1:1/other-server", "http://127.0.0.1:1?server=other", diff --git a/.claude-config/bin/verify-ops-selftest.sh b/.claude-config/bin/verify-ops-selftest.sh index 18386c2..98f3791 100755 --- a/.claude-config/bin/verify-ops-selftest.sh +++ b/.claude-config/bin/verify-ops-selftest.sh @@ -4,7 +4,7 @@ # SessionStart matcher check (18), the boot checks (1b root instructions, 5 # citations, 16 the always-loaded core, 17 retired hooks, 21 and 21b the # identity layer), the identity-exclusion check (23), the sandbox guards (24), -# dangling memory links (25), the memory digest fit and pool cap (6, 6b), and +# dangling memory links (25), the memory digest fit and the settle (6, 6b), and # the skill index and size checks (9, 9b), and the secrets scan exits (8) pass the shipped tree # against current Stage-1-shaped settings, and fail on each class they exist to # catch. It also pins the shipped .gitattributes rule that merges pool @@ -469,10 +469,7 @@ mkdir -p "$OPS/SKILLS/unindexed-local-skill" run check_skills_index chk "real unindexed skill dir -> WARN naming it" "$([ "$WARNS" = 1 ] && printf '%s' "$OUT" | grep -q 'unindexed-local-skill'; echo $?)" -# 27. Memory pool entry cap (6b): WARN only, never FAIL (a pool is the -# Operator's content). The shipped memory-index counts the entries, so the cap -# and the --check exit codes come from the real indexer, never a stub, except -# where a broken indexer is the case under test. +# Fixture pools for the digest-fit cases below; the shipped memory-index reads them. mk_pool() { # pool_name n_entries local d="$OPS/.claude-memory/$1" i mkdir -p "$d" @@ -485,37 +482,133 @@ cap_case() { mkdir -p "$OPS/.claude-config/bin" "$OPS/.claude-memory" cp "$SRC_OPS/.claude-config/bin/memory-index" "$OPS/.claude-config/bin/memory-index" } -cap_case cap-none -run check_memory_pool_cap -chk "no pools -> OK" "$([ "$FAILS" = 0 ] && [ "$WARNS" = 0 ] && printf '%s' "$OUT" | grep -q 'no memory pools to cap'; echo $?)" -cap_case cap-at -mk_pool host-a-home-op-OPS 60; mk_pool host-a-home-op-OPS-PROJECTS-ExampleOrg-app 3 -run check_memory_pool_cap -chk "a pool at exactly 60 entries -> OK naming the cap and pool count" \ - "$([ "$FAILS" = 0 ] && [ "$WARNS" = 0 ] && printf '%s' "$OUT" | grep -qF 'within the 60-entry cap (2 pools)'; echo $?)" -cap_case cap-over -mk_pool host-a-home-op-OPS 61 -run check_memory_pool_cap -chk "a pool at 61 entries -> WARN naming pool and count, no FAIL" \ - "$([ "$FAILS" = 0 ] && [ "$WARNS" = 1 ] && printf '%s' "$OUT" | grep -qF 'host-a-home-op-OPS(61)'; echo $?)" -mk_pool host-b-home-op-OPS 65 -run check_memory_pool_cap -chk "two pools over the cap -> one WARN naming both" \ - "$([ "$FAILS" = 0 ] && [ "$WARNS" = 1 ] && printf '%s' "$OUT" | grep -qF 'host-a-home-op-OPS(61)' && printf '%s' "$OUT" | grep -qF 'host-b-home-op-OPS(65)'; echo $?)" -cap_case cap-backfill -mk_pool host-a-home-op-OPS 3 -printf 'no frontmatter\n' > "$OPS/.claude-memory/host-a-home-op-OPS/bad.md" -run check_memory_pool_cap -chk "an entry needing a backfill is not a cap finding -> OK" "$([ "$FAILS" = 0 ] && [ "$WARNS" = 0 ]; echo $?)" -cap_case cap-broken -mk_pool host-a-home-op-OPS 3 -printf '#!/usr/bin/env python3\nimport sys\nsys.exit(1)\n' > "$OPS/.claude-config/bin/memory-index" -run check_memory_pool_cap -chk "an indexer that cannot read a pool -> FAIL, never a pass" \ - "$([ "$FAILS" = 1 ] && printf '%s' "$OUT" | grep -qF 'host-a-home-op-OPS(exit 1)'; echo $?)" -rm -f "$OPS/.claude-config/bin/memory-index" -run check_memory_pool_cap -chk "memory-index missing -> FAIL" "$([ "$FAILS" = 1 ] && printf '%s' "$OUT" | grep -q 'memory-index missing'; echo $?)" +# 27. The memory settle runs (6b). The case's HOME holds the opt-in env file; OPS_STATE_DIR holds +# the status file. Each verdict is exactly one OK or one FAIL line, and every FAIL names the two +# repair commands (the point of the check is that its red line is actionable). +# ms_status [attempt-hours-ago]: a schema 1 status file. The attempt +# defaults to the success time, or to 1 hour ago when there is no success. +ms_status() { + python3 - "$MS_ST" "$1" "$2" "${3:-$2}" <<'PY' +import datetime as dt, json, sys +path, result, success, attempt = sys.argv[1:5] +now = dt.datetime.now(dt.timezone.utc) +ago = lambda h: (now - dt.timedelta(hours=float(h))).isoformat() +if attempt == "null": + attempt = "1" +json.dump({"schema": 1, "box": "fixture", "last_attempt_at": ago(attempt), "last_attempt_result": result, + "last_success_at": None if success == "null" else ago(success), "commit": "0123abc", + "pending_delivery": False, "error": None, "pools": {}}, open(path, "w")) +PY +} +# ms_farm: a box that opted in, last run an ok 2 hours ago. +ms_farm() { + HOME="$WORK/ms-farm"; rm -rf "${HOME:?}"; MS_STATE="$HOME/ms-state"; MS_ENV="$HOME/.config/ops/memory-settle.env"; MS_ST="$MS_STATE/memory-settle-status.json" + mkdir -p "$MS_STATE" "$HOME/.config/ops" + printf '# memory-settle.env +MEMORY_SETTLE_OWNER=1 +' > "$MS_ENV"; ms_status ok 2 +} +ms_out() { OPS_STATE_DIR="$MS_STATE" run check_memory_settle; printf '%s' "$OUT"; } +# ms_expect