From a85e1fc2cee84dd539fa6e9a55aeef9bef852e84 Mon Sep 17 00:00:00 2001 From: Alex Ivantsov Date: Wed, 2 Dec 2026 18:06:01 -0500 Subject: [PATCH] feat(card): port the thread card, rest stop and harness fixes Carries the thread card (bin/card, hooks/thread-card.sh), the two-step rest stop (bin/rest-stop prep and arm), the armed compactor cycle and its live-lock interlock, the reminder-only context ladder (a stop is blocked only at 92%), two GET-only T3 reads, the smaller hook fixes and the doctrine and docs changes made since the last port (2026-11-18). Review edits: the armed thread is rechecked at dispatch, the recovery baton is kept when the /compact receipt is uncertain, and the reply tail is scanned for secret shapes before it is trimmed. --- .claude-config/backup/daily-sync.sh | 7 +- .claude-config/bin/README.md | 235 ++- .claude-config/bin/asks | 5 + .claude-config/bin/card | 1324 +++++++++++++++++ .claude-config/bin/compact-cycle.sh | 687 ++++++++- .claude-config/bin/lib/t3_api_v2.py | 256 +++- .claude-config/bin/lib/thread_messages.py | 482 ++++++ .claude-config/bin/rest-stop | 655 ++++++++ .claude-config/bin/session-end | 26 +- .claude-config/bin/t3-api.sh | 145 +- .claude-config/bin/tests/asks-test.py | 11 + .claude-config/bin/tests/card-test.py | 926 ++++++++++++ .../bin/tests/compact-cycle-t3-test.sh | 624 +++++++- .claude-config/bin/tests/memory-hint-test.sh | 51 +- .../bin/tests/post-compact-resume-test.sh | 23 +- .claude-config/bin/tests/pre-compact-test.sh | 11 +- .claude-config/bin/tests/rest-stop-test.py | 789 ++++++++++ .../bin/tests/secrets-guard-test.sh | 19 +- .claude-config/bin/tests/session-end-test.py | 51 + .claude-config/bin/tests/sync-check-test.sh | 105 ++ .../bin/tests/t3-api-v2-safety-test.py | 213 +++ .claude-config/bin/verify-ops.sh | 3 + .../hooks/context-watch-selftest.sh | 254 +++- .claude-config/hooks/context-watch.sh | 224 ++- .claude-config/hooks/git-guard.sh | 56 +- .claude-config/hooks/guard-selftest.sh | 33 + .claude-config/hooks/memory-hint.sh | 41 + .claude-config/hooks/post-compact-resume.sh | 41 +- .claude-config/hooks/pre-compact.sh | 31 +- .../hooks/report-lint-regression-test.py | 25 + .claude-config/hooks/report-lint.py | 32 +- .claude-config/hooks/secrets-guard.sh | 40 +- .claude-config/hooks/thread-card-selftest.sh | 176 +++ .claude-config/hooks/thread-card.sh | 90 ++ AGENTS.md | 2 +- CHANGELOG.md | 57 + CONTEXT/core.md | 38 +- CONTEXT/foreman.md | 109 +- CONTEXT/how-i-work.md | 50 +- CONTEXT/project-kata.md | 39 +- DEPLOYMENT.md | 43 +- PROJECTS/Sync-Check.ps1 | 21 +- PROJECTS/sync-check.sh | 31 +- README.md | 4 +- SKILLS/harness/SKILL.md | 8 +- 45 files changed, 7696 insertions(+), 397 deletions(-) create mode 100755 .claude-config/bin/card create mode 100644 .claude-config/bin/lib/thread_messages.py create mode 100755 .claude-config/bin/rest-stop create mode 100755 .claude-config/bin/tests/card-test.py create mode 100644 .claude-config/bin/tests/rest-stop-test.py create mode 100755 .claude-config/bin/tests/sync-check-test.sh create mode 100755 .claude-config/hooks/thread-card-selftest.sh create mode 100755 .claude-config/hooks/thread-card.sh diff --git a/.claude-config/backup/daily-sync.sh b/.claude-config/backup/daily-sync.sh index 7f6ac55..46f27e6 100755 --- a/.claude-config/backup/daily-sync.sh +++ b/.claude-config/backup/daily-sync.sh @@ -18,8 +18,11 @@ # stranded the work in a stash when a run was killed between the two, and # stash/pop dropped empty directories and reset file modes every day. # - Project stage delegates to PROJECTS/sync-check.sh --auto: it walks every -# repo, fast-forwards / rebases the clean ones, and SKIPS dirty repos -# (never touches uncommitted work). Pull-only: it never pushes projects. +# main checkout, fast-forwards / rebases the clean ones, and SKIPS dirty +# repos (never touches uncommitted work). Pull-only: it never pushes +# projects. It leaves linked worktrees alone (a lane's private branch): a +# rebase there rewrote commit ids daily, which broke branch-gc's +# reflog-coverage proof and kept landed worktrees looking active. # - Push gate: the backup sends the whole copy (memory, CONTEXT, notes) to # origin, so it pushes only when bin/origin-private-check verifies origin # private: exit 0 and its own "private" verdict line (gate_proved). A public diff --git a/.claude-config/bin/README.md b/.claude-config/bin/README.md index 10953d6..780a802 100644 --- a/.claude-config/bin/README.md +++ b/.claude-config/bin/README.md @@ -343,7 +343,10 @@ hand from three skills run the same way every time. Python standard library only memory-digest hook passes), lints when the thread named a file under `.claude-config/` or `SKILLS/`, lists the thread's open asks (`asks list`), and prints what is left for the agent: lessons, documents, the five-field resume note, the memory entries touched in the thread's - window, and by mode the compact line (`compact-cycle.sh --target `), the baton path + window, and by mode the compact line (`compact-cycle.sh --target `; on a pause in a + Claude T3 thread with `rest-stop` beside it and `CC_THREAD_CARD` not 0, the `rest-stop prep` + then `rest-stop arm` route instead, with a line to keep the thread card current and to put a + question to the Operator in the `asks` register first), the baton path (`.claude-handoffs/key.sh` under `${OPS_DIR:-~/OPS}/.claude-handoffs/pending/`, where `hooks/handoff-check.sh` looks), or, for a close, the measured time as evidence (`active-minutes`), the scratch files, worktrees and named Docker objects the thread created @@ -553,7 +556,11 @@ header says which event. a prompt too short or too long to be a request, and a lane (`agent_id` in the payload, or `bin/lane-class` answering `t3-lane` or `agent-lane`). A 3 s cap on the scorer; a failure is one line in `${OPS_STATE_DIR:-~/.local/state/ops}/memory-hint.log`, - never a message to the model. `MEMORY_HINT=0` turns it off. + never a message to the model. Each line is shown once per session: the lines already printed + to a session id are kept in `${OPS_STATE_DIR:-~/.local/state/ops}/memory-hint-seen/` (files older than two days are pruned when a new session starts), so the same few + entries do not repeat on every prompt; a payload with no session id, or a state file that + cannot be written, prints every time. `MEMORY_HINT=0` turns it off. - `hooks/report-lint.sh` (Stop; the work is in `report-lint.py`): when a foreman's FINAL message asks the Operator to decide more than three things, carries a decision table, or names things only by ID in its asks, it blocks @@ -563,7 +570,8 @@ header says which event. narration in the turn is never judged, and nothing in it reads for deferral. It never blocks a message under 400 characters, a stop that is already the rewrite (`stop_hook_active`), a lane, the same message twice, or anything it - cannot read. `REPORT_LINT=0` turns it off; `REPORT_LINT_MAX_ASKS` (default 3) + cannot read. A run of list items that are each a name with only a link beside it (a set of + approval links) counts as one ask, not one per link. `REPORT_LINT=0` turns it off; `REPORT_LINT_MAX_ASKS` (default 3) moves the threshold. Each judged Stop leaves one line of counts and a hash, never text, in `${OPS_STATE_DIR:-~/.local/state/ops}/report-lint.jsonl`. Tests: `hooks/report-lint-selftest.sh`, `hooks/report-lint-regression-test.py`. @@ -726,7 +734,13 @@ an absent key or a 404 is the older protocol 1) and speaks both. Reads go over HTTP: `snapshot`, `shell`, `thread `, `active-turn `, `thread-for-session ` (T3's `statev2.sqlite`, read-only; an ambiguous mapping is refused), `compact-status ` (pending, completed, failed, or -nothing-to-compact) and `server-busy`. On protocol 2 the answers are translated to +nothing-to-compact), `server-busy`, `thread-messages ` (the messages and page of +`thread` without its run state, so it skips the whole-thread-list read that makes +`thread` slow on a busy box) and `history [--until ] [--max-pages N]` +(protocol 2 only: the older messages the bounded read leaves out, paged by cursor +through `/api/orchestration/threads//history?cursor=&view=conversation`, at +most 40 pages by default, the cursor percent-encoded and checked before it goes into +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 @@ -752,7 +766,11 @@ header is the full reference (`t3-api.sh --help`). `compact-cycle.sh --target [--baton FILE | --resume TEXT | --no-resume]` spawns a detached worker and returns at once; the caller ends its -turn. The worker waits for the thread to go idle (`--idle-timeout`, default 300 +turn. On a Claude T3 thread the caller is `rest-stop arm` (below), which checks the +arming order first: no uncommitted work, no failing gate on the thread's files, and +no question to the Operator asked only in prose (a question in the `asks` register +does not stop an arm, because the reply the Operator received travels with the +baton). The worker waits for the thread to go idle (`--idle-timeout`, default 300 s; a busy thread is never sent `/compact`), sends `/compact`, and waits up to `--timeout` (900 s) for T3 to report THAT request's compaction completed (on protocol 2: the run of that message completed and carries a completed compaction @@ -769,10 +787,72 @@ a top-level thread; a T3 delegated child thread (`thread:delegated-task:...`) is not in the shell's root threads, so the cycle stops with `ERR_TARGET`, and the context-watch hook never names the cycle to one. -`hooks/context-watch.sh` names the cycle in its nags only when the session is a -T3 thread on Linux and both scripts and a readable, non-empty token are present; -while a fresh (under 30 min) baton for the thread exists it stays silent, since -the agent ended its turn on purpose. A compact is proven only by T3's completion +The armed cycle. When `rest-stop arm` started the worker, an `arm-.json` in +the run dir names this target and its `baton_sha256` matches the `--baton` file; any +other record is logged as ignored and the worker behaves exactly as above. After the +idle confirmation, the worker reads the thread to check for an owner message or +another run requested or started after `validation_started_at` (`armed_at` for +older records). It checks again on the API's final thread read, after preparing +the trailer. If either check finds a change, the worker returns the baton to the +draft path, preserving any newer draft, and exits 0 with result `superseded`. +A matching record that cannot be used ends as `arm-invalid` (exit 5). + +The trailer at `trailer-.txt` carries the last 1,500 characters of the +arming turn's final reply and one line per open ask. An unreadable reply gets an +unavailable line. The worker drops secret-shaped lines before cutting the reply +to length. +The resume message is the baton followed by the trailer, at most 6,000 characters, +the trailer cut first with a marker. After a successful dispatch the record and the +trailer are removed. When the worker knows T3 did not receive `/compact`, it puts +the baton back at the draft path and removes the record. If the dispatch outcome is +uncertain, it keeps the baton and the dispatch marker so another cycle cannot send +`/compact` again for that arm. + +The lock records who holds it (LOCK LIVENESS in the script header). A worker +killed with no traps (SIGKILL, the out-of-memory killer) runs no release rule and +used to leave its lock, so every later `compact-cycle.sh` and `rest-stop arm` for the +thread refused until someone removed it by hand. The worker now writes the owner (its +pid and the start time from field 22 of `/proc//stat`) in a staging directory +and publishes it together with the lock in one no-replace rename; EXIT is the only +trap that removes the lock. The lock is live while that pid still runs with that +start time and is not a zombie. A lock with no owner file (a worker from before this +change) is live until it is older than the longest run the defaults allow, 1,500 s. +A stale lock is reclaimed, not obeyed: the next worker takes a `flock` on +`.lock.reclaim`, checks again, renames the stale directory aside and removes +it, and logs one line naming the dead owner; of two workers reclaiming at once, one +runs and the other exits 4. Before it reclaims, an unsent armed baton the dead worker +left goes back to the draft path like a stand-down, once the 120 s start window ends +and the arm record matches; when that baton was the new worker's own `--baton`, it +ends `abandoned`, exit 5. The worker marks the arm record `dispatch_started` before +calling T3 to dispatch `/compact`. If it dies during or after that call, the baton +stays at the resume path for recovery and the replacement cycle ends +`recovery-needed`, exit 5, without dispatching again (`baton-missing`, exit 5, when +the baton is gone). `compact-cycle.sh --target --tidy` prints the lock +state and does the same put-back without taking a worker lock or calling T3; it +shares the reclaim lock so it cannot move a baton as a worker starts. Both +`rest-stop prep` and `arm` run it first. `kill ` on a worker leaves no stale +lock; `kill -9` does, and the next worker reclaims it. The two numbers (1,500 s and +120 s) live in both `compact-cycle.sh` and `context-watch.sh`; change them together. + +`hooks/context-watch.sh` is a reminder ladder, not a stop sign. At 65% (NOTICE), +78% (WARNING) and 86% (URGENT) of `CC_CONTEXT_WINDOW` it adds a note to the +agent's context right after a tool call (PostToolUse `additionalContext`, re-sent +after about +75K, +40K and +15K more tokens), which never blocks and costs no +extra turn; a stop at those levels simply stops. Only at 92% (CRITICAL) does it +block a stop, on every stop, because a later compact can lose the synthesis the +compactor needs room for. A Stop hook has no passive channel (its +`additionalContext` also forces a turn), so the notes ride PostToolUse and the +per-prompt readout. `CC_CONTEXT_WATCH_POSTTOOL=0` silences the notes and +`CC_CONTEXT_WATCH=0` the whole hook. It names a self-compact route only when the +session is a T3 thread on Linux and both scripts and a readable, non-empty token +are present. It offers `rest-stop prep` and `rest-stop arm` when the thread key +and tool are available. The cycle's own route is available with `CC_THREAD_CARD=0` +or without a key in the environment. An armed baton (`resume-.txt`) for the thread silences +it only while a compactor can act on it: the baton must be under 30 minutes old, +and either its lock is live or the worker is still inside the 120 s start window (a +dead worker's newer lock or a matching dispatch marker ends that window at once). +The hook leaves the files in place, and the no-baton path reads no lock and asks no +lookup. The draft `rest-stop prep` writes never silences it. A compact is proven only by T3's completion record for that request; a completed chat reply proves nothing. Tests: `tests/t3-api-test.sh`, `tests/t3-api-v2-safety-test.py` and `tests/compact-cycle-t3-test.sh`, all against loopback stubs and the recorded frames in `tests/fixtures/t3-v2/`; each starts @@ -789,6 +869,143 @@ a default summary drops: > Be sure to preserve: (1) any difficulties or problems that came up, and how they were handled or resolved; (2) any possibilities, options, or approaches that were raised, tried, or set aside, and why; (3) anything that was asked for, decided, agreed, ruled out, or established as a preference, constraint, or boundary, stated exactly; (4) exactly where things stand now; (5) anything still open, unresolved, promised, or expected to happen next; (6) specific details that would be hard to reconstruct: names, numbers, dates, exact wording, links or references, kept exactly. Weight the two voices differently: keep what the user said, asked for, shared, or established carefully and close to their own words; your own explanations and reasoning can be condensed much further. +## `card`: the thread card + +One small record per main T3 thread, kept current while the thread works and +printed back after every compaction. It carries what neither the compaction summary +nor the baton reliably keeps: the mission and finish line, the whole to-do list, how +things are done in this thread, and who set each hold. + +- Store: `${OPS_STATE_DIR:-~/.local/state/ops}/cards/.json`, file 0600 in a + 0700 directory, outside git. The key is the T3 thread id (`$CARD_THREAD` in tests, + else `$T3CODE_THREAD_ID`; no cwd or session fallback), in the file-name form + `compact-cycle.sh` uses. No key: every command exits 5. Every write is locked + (fcntl on a sibling `.lock`), atomic (temp file, fsync, rename), stamped from the + tool's clock, and refused when the text matches a secret shape (the patterns of + `secrets-scan.sh`, mirrored). +- Main thread only. A write exits 7 when `lane-class --self` names a lane; an + in-process helper (a hook payload with `agent_id`) shares its main thread's thread + id, so `hooks/git-guard.sh` blocks its `card` writes and every `rest-stop` there. + The reads `show`, `messages` and `check` stay open to a lane. +- The owner's words. Owner messages come from T3's own record + (`lib/thread_messages.py`, through `t3-api.sh thread-messages ` and, for older + messages, `t3-api.sh history `): role `user`, `createdBy` `user`, + `creationSource` `web` or `mobile`. `server` (a harness send) and `mcp` (another + agent) never count; any other origin is shown flagged `origin_unknown` and refused + as a quote source unless `--unverified`. Each command pages back only as far as it + needs (at most 40 pages); what paging could not reach is a `history_gap` with its + reason, never a guess. Quote comments (`[Assistant quote](t3-citation://...)` + links) are shown readably, and a quote check matches only the Operator's own words, + never the assistant text they quoted. Test seams: `CARD_T3_FIXTURE`, + `CARD_T3_HISTORY_FIXTURE`, `CARD_T3_API`, `CARD_NOW`, `CARD_ASKS`. +- Limits: mission and finish line 400 characters each (their quoted words 600); + backlog line 160; how-to 15 entries of 200; holds 12; plan 12 of 200. + +``` +card init [--json] create if absent; seed the mission from the first owner message +card show [--resume|--line|--full] [--json] no flag is --full +card mission TEXT --words QUOTE --source MESSAGE_ID|first [--unverified] +card done-when TEXT --words QUOTE --source MESSAGE_ID|first [--unverified] +card add TEXT [--state next|flight|waiting|parked] [--waiting-on WHO] [--side --opened-by WHO] +card set ID next|flight|parked card set ID waiting WHO +card close ID done [--note T] | declined --by WHO [--note T] | handed --to WHERE [--note T] +card milestone TEXT a dated line in the closed log +card how add TEXT | card how rm N +card hold add TEXT --by WHO --words QUOTE --source REF --lifts CONDITION [--unverified] +card hold lift ID --words QUOTE [--source REF] +card plan add TEXT | card plan rm N +card messages [--unreviewed] [--limit 12] [--chars 600] [--json] +card reviewed --through MESSAGE_ID [--nothing-changes] +card check [--json] ok, unreviewed, unreviewed_known, history_gap, problems, notes, counts, path +card seen-compaction called by the hook +``` + +A quote must occur in the cited owner message, or the write is refused unless +`--unverified`, which stores and prints it flagged. A hold needs who set it, their +words, a source and what lifts it; the agent's own sequencing goes under `plan`, +which the resume print labels "Your own earlier plan, not a hold". `close` and +`milestone` print the next open item, nothing else: no compaction hint, because when +to compact stays the agent's call. `reviewed` without `--nothing-changes` is refused +unless the card changed substantively after that message. `check` exits 0 either +way; its `ok` is false when something blocks an arm (no card, an unreadable card, a +failed T3 read, unreviewed messages), and `problems` and `notes` say what. +`messages --json` is `{messages, more, history_gap}`, plus `history_error` only when +there is a gap. Exit codes: 0 ok, 1 the card file is unreadable or corrupt (never +replaced: `init` refuses over it), 2 usage or a limit, 5 no key or no card, 6 secret +shape, 7 lane, 8 T3 read failed. + +`hooks/thread-card.sh` is registered first in the Stage-1 `resume|compact` +SessionStart group (30 second timeout) and acts on source `compact` only. It prints +at most 8,000 characters: the card path, a staleness line (compactions and owner +messages since the last substantive change), mission, finish line, holds (who, when, +words, what lifts each, age), the plan, the open backlog, how-to, open asks from +`asks list --thread `, and "If the only next step is a wait, take the next +unblocked item." Anything cut is counted. No card: one line naming `card init`. A +queued `resume-.txt`: one line with its path. A lane's compaction prints +nothing (a payload with `agent_id`, or `lane-class` naming a lane); OPS has no +PreCompact lane marker, so an in-process lane's compaction whose payload carries no +`agent_id` is not told apart, the same limit `post-compact-resume.sh` has. + +Off switch: `CC_THREAD_CARD=0` (one name, beside the other `CC_` compaction knobs +such as `CC_CYCLE_RUNDIR`) silences the hook and puts `rest-stop`, `session-end +pause` and the context-watch route back on the hand-written baton; card files stay +readable and editable. Tests: `tests/card-test.py` and +`../hooks/thread-card-selftest.sh`. + +## `rest-stop`: the two-step rest stop + +Replaces the hand-written baton routine, which was skipped two times in three when +measured. Main thread of a Claude T3 thread only: a lane gets exit 7. When to stop +is the agent's call; nothing here nudges it, and the context hook only reminds +(its ladder is described under `compact-cycle.sh` above). + +`rest-stop prep` creates the card if absent, runs `card check`, prints the owner's +messages since the review cursor under "Does any of these change the mission, the +finish line, the list or a hold?", writes the draft baton +`~/.claude-compact-cycle/baton-draft-.txt` (header +`# baton draft thread `; MISSION and CARD filled from the card, NOW, EXPECT +and IN FLIGHT left as ``), and prints `card show --line` for the reply to the +Operator. It never touches `resume-.txt`. + +`rest-stop arm --confirm-arming "TEXT" [--allow-long] [--allow-dirty]` refuses, exit +3, one line per reason and nothing armed, when `--confirm-arming` is missing; a +live compactor holds this thread's lock (a stale lock, left by a compactor that died +without its traps, is one note line and does not refuse: the new worker reclaims +it); the draft is missing, names another +thread, has no tool-stamped header, or the header is over 30 minutes old (editing +the file does not refresh it); NOW or EXPECT is still `` (an unfilled IN +FLIGHT is only a warning); the body is over 4,000 characters without `--allow-long` +(a warning over 2,500); `card check` reports unreviewed owner messages or `ok` false; +the current git worktree has uncommitted changes (listed); or a T3 question card is +pending for the thread (when the thread can be read). `--allow-dirty` is for a +shared checkout (such as `~/OPS`) whose uncommitted files are another session's: they +are listed as a warning and stored in the arm record (`allow_dirty`, `dirty`). An open +ask in the `asks` register does not refuse; its id goes into the arm record. +`--confirm-arming` is required: the agent's one line that no question is open outside +the register and no gate is failing on this thread's files, stored in the arm +record. On success it writes `arm-.json` (thread, `armed_at`, +`validation_started_at`, `armed_turn`, `baton_sha256`, `asks_open`, +`confirm_arming`), renames the draft to `resume-.txt`, and starts +`compact-cycle.sh --backend t3 --target --baton `. Once the worker +holds the lock and confirms the arm record, `arm` prints its status line and `END +YOUR TURN NOW`. If startup fails, `arm` puts the baton back on the draft path and +removes the record (exit 4). Exit codes: 0 ok, 2 usage, 3 arm refused, 4 the worker +did not start, 5 no thread key, 7 lane. Test seams: `REST_STOP_CARD`, +`REST_STOP_COMPACT_CYCLE`, `T3_API`, `CC_CYCLE_RUNDIR`, `OPS_STATE_DIR`, +`OPS_LANE_CLASS`, `REST_STOP_NOW`. + +Both `prep` and `arm` first run `compact-cycle.sh --tidy`. Once the start window +ends, an unsent baton with a matching arm record and no live compactor goes back to +the draft path, beside any newer draft; the command removes its arm record and prints +where it went. If dispatch may already have started, the baton stays at the resume +path for recovery. Once an armed baton is sent, the set-aside `.prev` draft is +removed. + +The baton has five fields: MISSION, NOW, EXPECT, IN FLIGHT, CARD. Holds and how-to +live on the card, not in the baton. `CC_THREAD_CARD=0` makes `rest-stop` print the +hand-written route instead and exit 0. Tests: `tests/rest-stop-test.py` (listed in +`OPS_SANDBOX_SUITES`, so it always runs network-off). + ## `wf-resume`: lanes of a workflow that never returned A usage-limit hold, a crash or a restart ends every running lane of a dynamic diff --git a/.claude-config/bin/asks b/.claude-config/bin/asks index c6645ce..b7b0b54 100755 --- a/.claude-config/bin/asks +++ b/.claude-config/bin/asks @@ -480,6 +480,11 @@ def find_ref(docs, ref, thread_flag): pool = [d for d in docs if d["thread"] == want or d["thread"].startswith(want) or short_id(d["thread"]) == want] else: raise AsksError("an ask is named N or THREAD#N, not '%s'" % ref) + # An exact id wins over ids it merely prefixes: without this a short thread id could + # never be named once a longer id shared its first eight characters. + exact = [d for d in pool if d["thread"] == want] + if exact: + pool = exact if len(pool) > 1: raise AsksError("'%s' matches %d threads; use more of the thread id" % (ref, len(pool))) if not pool: diff --git a/.claude-config/bin/card b/.claude-config/bin/card new file mode 100755 index 0000000..67f0279 --- /dev/null +++ b/.claude-config/bin/card @@ -0,0 +1,1324 @@ +#!/usr/bin/env python3 +"""card: the per-thread card a main thread keeps current while it works. + +Why: measured across hundreds of compactions, four things are lost across a compaction: +the thread's mission and finish line, its whole to-do list, its how-to +knowledge, and who set each hold. The card holds those four, in the Operator's own +words where they are theirs, and hooks/thread-card.sh prints it back after every +compaction. A card that loses an entry or prints something untrue sends the +next session the wrong way, so every write is locked and atomic, every quote of +the Operator is checked against T3's own record of what they typed, and the printed card +states how stale it is. + +Interface: .claude-config/bin/README.md, "card" (rest-stop and the context +hooks call these commands, arguments, exit codes and JSON keys; keep them stable). + + card init [--json] + card show [--resume | --line | --full] [--json] + card mission TEXT --words QUOTE --source MESSAGE_ID|first [--unverified] + card done-when TEXT --words QUOTE --source MESSAGE_ID|first [--unverified] + card add TEXT [--state next|flight|waiting|parked] [--waiting-on WHO] [--side --opened-by WHO] + card set ID next|flight|parked card set ID waiting WHO + card close ID done [--note T] | declined --by WHO [--note T] | handed --to WHERE [--note T] + card milestone TEXT + card how add TEXT | card how rm N + card hold add TEXT --by WHO --words QUOTE --source REF --lifts CONDITION [--unverified] + card hold lift ID --words QUOTE [--source REF] + card plan add TEXT | card plan rm N + card messages [--unreviewed] [--limit 12] [--chars 600] [--json] + card reviewed --through MESSAGE_ID [--nothing-changes] + card check [--json] + card seen-compaction + +Identity: the thread is $CARD_THREAD (tests) else $T3CODE_THREAD_ID, and +nothing else: no cwd, no "adhoc", no session id. The file name is the key +through compact-cycle.sh's transform (tr ':. ' '---' | tr -cd 'A-Za-z0-9-'). +A command that writes is refused (exit 7) when `bin/lane-class --self` says +t3-lane or agent-lane: the card is the main thread's. Reads are not refused +(only writes are refused); a delegated T3 lane has its own thread id, so it finds +no card of its foreman's to read. + +Store: ${OPS_STATE_DIR:-~/.local/state/ops}/cards/.json, 0600 +in a 0700 directory, outside git. Each write holds an fcntl lock on the sibling +.lock, writes a temp file in the same directory, fsyncs and renames, the +bin/asks pattern. A card that cannot be parsed is reported (exit 1) and never +replaced: init on a corrupt card refuses rather than starting over. + +Owner messages come from bin/lib/thread_messages.py. T3's first read is +bounded to the latest messages; each command asks the module for what it needs +(the first message, one message by id, or everything after a time), and the +module pages back through the older history only that far. What paging could +not reach (a failed or timed out read, or the 40 page cap) is reported as a +history gap with its reason, never guessed. Messages are shown in their readable +form (the Operator's quote comments decoded) and quotes are checked against their own +words only, never the assistant text they quoted. + +substantive_updated moves only on mission, done_when, backlog (add, set, close) +and holds (add, lift) changes; `card reviewed` without --nothing-changes needs +one after the message it reviews through. compactions_at_substantive is compactions_seen at that moment, so the printed +card can say how many compactions passed since it last changed in substance. + +Secret shapes (exit 6): mirrored from bin/secrets-scan.sh, which backs +hooks/secrets-guard.sh (its HARD patterns always, its SOFT assignment patterns +unless the line reads as a pointer). They are mirrored, not imported: the +scanner is a shell and Perl program with no importable module. Keep the two +lists in step. + +Exit codes: 0 ok; 1 the card file is unreadable or corrupt (neither a usage error nor a +missing card); 2 usage or a +limit; 5 no thread key, or no card where one is required; 6 secret shape +refused; 7 lane refused; 8 T3 read failed for a command that needs owner +messages. Test seams: CARD_NOW (ISO time), CARD_T3_FIXTURE, CARD_T3_HISTORY_FIXTURE +and CARD_T3_API (thread_messages.py), CARD_ASKS (the asks script), OPS_LANE_CLASS +(lane-class's own override). Standard library only. +""" + +import argparse +import contextlib +import datetime +import fcntl +import json +import os +import re +import subprocess +import sys +import tempfile + +BIN = os.path.dirname(os.path.realpath(__file__)) +sys.path.insert(0, os.path.join(BIN, "lib")) +import thread_messages as tm # noqa: E402 (beside this script, standard library only) + +VERSION = 1 +EXIT_CORRUPT, EXIT_USAGE, EXIT_NOKEY, EXIT_SECRET, EXIT_LANE, EXIT_T3 = 1, 2, 5, 6, 7, 8 + +# Limits. Over a limit is exit 2 with the limit named. +LIM_STATEMENT, LIM_WORDS = 400, 600 +LIM_BACKLOG = 160 +LIM_HOW_N, LIM_HOW = 15, 200 +LIM_HOLDS = 12 +LIM_PLAN_N, LIM_PLAN = 12, 200 +# Not fixed by the contract; chosen so one entry stays one readable line. +LIM_HOLD_TEXT, LIM_WHO, LIM_NOTE, LIM_REF = 200, 80, 300, 300 + +STATES = ("next", "flight", "waiting", "parked") +STATE_ORDER = {"flight": 0, "next": 1, "waiting": 2, "parked": 3} +RESUME_CAP = 8000 +STALE_DAYS = 7 +BATON_FRESH_S = 30 * 60 # context-watch.sh's freshness for an armed baton +RESUME_T3_TIMEOUT = 5 # the post-compaction print must stay quick +CLOSING = "If the only next step is a wait, take the next unblocked item." + +# --- secret shapes, mirrored from bin/secrets-scan.sh (Perl engine) ---------------- +SECRET_HARD = [(n, re.compile(p)) for n, p in ( + ("github-token", r"ghp_[A-Za-z0-9]{20,}"), + ("github-pat", r"github_pat_[A-Za-z0-9_]{20,}"), + ("openai-anthropic-key", r"(^|[^A-Za-z0-9/_-])sk-[A-Za-z0-9_-]{20,}"), + ("anthropic-key", r"sk-ant-[A-Za-z0-9_-]{20,}"), + ("slack-token", r"xox[baprs]-[A-Za-z0-9-]{10,}"), + ("aws-access-key", r"AKIA[0-9A-Z]{16}"), + ("google-api-key", r"AIza[0-9A-Za-z_-]{30,}"), + ("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,}"), + ("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,}"), + ("env-var-password", r"""(SSHPASS|PGPASSWORD|MYSQL_PWD)=["'`]?[^<$"'`\s]\S{5,}"""), +)] +SECRET_SOFT = [(n, re.compile(p, re.I)) for n, p in ( + ("password-assignment", r"""(password|passwd)["']?\s*[:=]\s*["'`]?[^\s"'`]{8,}"""), + ("secret-assignment", r"""(api[_-]?key|api[_-]?token|access[_-]?token|client[_-]?secret|auth[_-]?token)""" + r"""["']?\s*[:=]\s*["'`]?[A-Za-z0-9_/+.=-]{16,}"""), +)] +SECRET_POINTER = re.compile(r"(sops|vault|1password|\.env|redacted|<[a-z-]+>|placeholder|example|" + r"pointer|see )", re.I) + + +class CardError(Exception): + def __init__(self, message, code=EXIT_USAGE): + super().__init__(message) + self.code = code + + +def secret_hit(value): + """The name of the first secret shape in VALUE, or None (scanned line by line).""" + for line in (value or "").splitlines() or [""]: + for name, pattern in SECRET_HARD: + if pattern.search(line): + return name + if not SECRET_POINTER.search(line): + for name, pattern in SECRET_SOFT: + if pattern.search(line): + return name + return None + + +def refuse_secret(label, value): + hit = secret_hit(value) + if hit: + raise CardError("%s matches a secret shape (%s); the card is printed into every resumed context, so name " + "where the value lives instead of the value" % (label, hit), EXIT_SECRET) + + +def clean(value, limit, label, required=True): + """One line of text within LIMIT characters, refused if secret-shaped.""" + refuse_secret(label, value) + text = re.sub(r"\s+", " ", value or "").strip() + if required and not text: + raise CardError("%s is empty" % label) + if len(text) > limit: + raise CardError("%s is %d characters; the limit is %d" % (label, len(text), limit)) + return text + + +# --- time ---------------------------------------------------------------------------- + +def now(): + raw = os.environ.get("CARD_NOW") + if raw: + d = tm.parse_time(raw) + if d is None: + raise CardError("CARD_NOW is not an ISO time: %r" % raw) + return d.astimezone(datetime.timezone.utc) + return datetime.datetime.now(datetime.timezone.utc) + + +def stamp(d): + return d.astimezone(datetime.timezone.utc).isoformat(timespec="milliseconds").replace("+00:00", "Z") + + +def day(value): + d = tm.parse_time(value) + return d.astimezone(datetime.timezone.utc).strftime("%Y-%m-%d %H:%M UTC") if d else "an unknown time" + + +def age(value, moment): + d = tm.parse_time(value) + if d is None: + return "an unknown time" + secs = int((moment - d).total_seconds()) + if secs < 60: + return "under a minute" + mins = secs // 60 + if mins < 60: + return "%dm" % mins + hours, mins = divmod(mins, 60) + if hours < 24: + return "%dh %dm" % (hours, mins) + days, hours = divmod(hours, 24) + return "%dd %dh" % (days, hours) + + +# --- identity ------------------------------------------------------------------------ + +def thread_key(): + key = (os.environ.get("CARD_THREAD") or os.environ.get("T3CODE_THREAD_ID") or "").strip() + if not key or not file_key(key): + raise CardError("no thread key: T3CODE_THREAD_ID is unset, and the card belongs to one T3 thread " + "(no cwd or adhoc fallback)", EXIT_NOKEY) + refuse_secret("the thread id", key) + return key + + +def file_key(key): + return re.sub(r"[^A-Za-z0-9-]", "", key.translate(str.maketrans(":. ", "---"))) + + +def refuse_lane(): + """Exit 7 when lane-class says this session is a lane. A missing or failing + lane-class reads as foreman, the behavior before lane-class existed.""" + script = os.path.join(BIN, "lane-class") + if not os.path.isfile(script): + return + try: + out = subprocess.run(["bash", script, "--self"], capture_output=True, text=True, timeout=5, + stdin=subprocess.DEVNULL).stdout.strip() + except (OSError, subprocess.SubprocessError): + return + if out in ("t3-lane", "agent-lane"): + raise CardError("refused in a lane (%s): the card belongs to the main thread; put what you found in your " + "report to the foreman" % out, EXIT_LANE) + + +def state_dir(): + return os.environ.get("OPS_STATE_DIR") or os.path.join(os.path.expanduser("~"), ".local", "state", "ops") + + +def run_dir(): + return os.environ.get("CC_CYCLE_RUNDIR") or os.path.join(os.path.expanduser("~"), ".claude-compact-cycle") + + +# --- storage ------------------------------------------------------------------------- + +def empty_statement(): + return {"text": "", "words": "", "source": {"message_id": "", "at": ""}, "history": [], + "unverified": False, "seeded": False, "set": ""} + + +def new_card(thread, at): + return {"version": VERSION, "thread": thread, "created": at, "updated": at, "substantive_updated": at, + "mission": empty_statement(), "done_when": empty_statement(), + "backlog": [], "closed": [], "how": [], "holds": [], "plan": [], + "review_cursor": {"message_id": "", "at": "", "set": ""}, + "compactions_seen": 0, "compactions_at_substantive": 0} + + +def validate(doc, thread): + """Raise ValueError naming the first thing wrong with DOC.""" + if not isinstance(doc, dict): + raise ValueError("not a JSON object") + if doc.get("version") != VERSION: + raise ValueError("version is %r, this tool reads %d" % (doc.get("version"), VERSION)) + if doc.get("thread") != thread: + raise ValueError("it is the card of thread %r" % doc.get("thread")) + for key in ("created", "updated", "substantive_updated"): + if not isinstance(doc.get(key), str): + raise ValueError("%s is missing" % key) + for key in ("mission", "done_when"): + st = doc.get(key) + if not isinstance(st, dict) or not isinstance(st.get("text"), str) or not isinstance(st.get("words"), str) \ + or not isinstance(st.get("source"), dict) or not isinstance(st.get("history"), list): + raise ValueError("%s is malformed" % key) + for key, idkey in (("backlog", "id"), ("closed", "id"), ("how", "n"), ("holds", "id"), ("plan", "n")): + items = doc.get(key) + if not isinstance(items, list): + raise ValueError("%s is not a list" % key) + for item in items: + if not isinstance(item, dict) or not isinstance(item.get(idkey), int) \ + or not isinstance(item.get("text"), str): + raise ValueError("%s holds an entry without a number and text" % key) + for item in doc["backlog"]: + if item.get("state") not in STATES: + raise ValueError("backlog #%d has state %r" % (item["id"], item.get("state"))) + if not isinstance(doc.get("review_cursor"), dict): + raise ValueError("review_cursor is malformed") + if not isinstance(doc.get("compactions_seen"), int): + raise ValueError("compactions_seen is not a number") + doc.setdefault("compactions_at_substantive", 0) + if not isinstance(doc["compactions_at_substantive"], int): + raise ValueError("compactions_at_substantive is not a number") + + +class Card: + def __init__(self, thread): + self.thread = thread + self.dir = os.path.join(state_dir(), "cards") + self.key = file_key(thread) + self.path = os.path.join(self.dir, self.key + ".json") + self.lock_path = os.path.join(self.dir, self.key + ".lock") + + def _ensure_dir(self): + try: + os.makedirs(self.dir, mode=0o700, exist_ok=True) + if os.stat(self.dir).st_mode & 0o077: + os.chmod(self.dir, 0o700) + except OSError as exc: + raise CardError("cannot create %s: %s" % (self.dir, exc.strerror or exc), EXIT_CORRUPT) + + @contextlib.contextmanager + def locked(self): + self._ensure_dir() + fd = os.open(self.lock_path, os.O_CREAT | os.O_RDWR, 0o600) + try: + fcntl.flock(fd, fcntl.LOCK_EX) + yield self + finally: + try: + fcntl.flock(fd, fcntl.LOCK_UN) + finally: + os.close(fd) + + def exists(self): + return os.path.lexists(self.path) + + def read(self): + """The card, or None when there is none. Raises CardError(1) when the file + exists but cannot be read or is not a valid version-1 card.""" + try: + with open(self.path, encoding="utf-8") as fh: + doc = json.load(fh) + except FileNotFoundError: + return None + except OSError as exc: + raise CardError("cannot read the card %s: %s" % (self.path, exc.strerror or exc), EXIT_CORRUPT) + except (ValueError, UnicodeDecodeError) as exc: + raise CardError("the card %s is not valid JSON (%s); it is left as it is" % (self.path, exc), + EXIT_CORRUPT) + try: + validate(doc, self.thread) + except ValueError as exc: + raise CardError("the card %s is not a usable card: %s; it is left as it is" % (self.path, exc), + EXIT_CORRUPT) + return doc + + def require(self): + doc = self.read() + if doc is None: + raise CardError("no card for this thread at %s: run card init" % self.path, EXIT_NOKEY) + return doc + + def write(self, doc): + self._ensure_dir() + text = json.dumps(doc, indent=1, ensure_ascii=False) + "\n" + fd, tmp = tempfile.mkstemp(prefix=".%s." % self.key, suffix=".tmp", dir=self.dir) + try: + with os.fdopen(fd, "w", encoding="utf-8", newline="\n") as fh: + fh.write(text) + fh.flush() + os.fsync(fh.fileno()) + os.chmod(tmp, 0o600) + os.replace(tmp, self.path) + except BaseException: + try: + os.unlink(tmp) + except OSError: + pass + raise + try: + dfd = os.open(self.dir, os.O_RDONLY) + try: + os.fsync(dfd) + finally: + os.close(dfd) + except OSError: + pass # the rename stands; a directory fsync is not available everywhere + + +def write_command(change, substantive): + """Lock, load the card, apply CHANGE(doc, moment) -> (changed, message), stamp + and write when it changed. Returns the message. The caller has already run + refuse_lane(), first, so a lane gets exit 7 before any input is judged.""" + card = Card(thread_key()) + moment = now() + with card.locked(): + doc = card.require() + changed, message = change(doc, moment) + if changed: + doc["updated"] = stamp(moment) + if substantive: + doc["substantive_updated"] = stamp(moment) + doc["compactions_at_substantive"] = doc["compactions_seen"] + card.write(doc) + return message + + +# --- owner messages ------------------------------------------------------------------ + +def read_window(thread, **need): + """(window, None) or (None, reason). NEED is thread_messages.load's since, need_first, + need_id or budget: how far back the read must reach for this caller.""" + try: + return tm.load(thread, **need), None + except tm.ReadError as exc: + return None, str(exc) + + +def need_for(source): + """The load() need that makes SOURCE ("first" or a message id) answerable.""" + return {"need_first": True} if source == "first" else {"need_id": source} + + +def resolve_source(window, source): + """(message, None) for an owner message named by id or "first", else (None, why).""" + if source == "first": + return window.first() + m = window.find(source) + if m is not None: + return m, None + if window.has_more: + return None, ("message %s is not among the owner messages read, and %s" + % (source, window.gap_reason())) + return None, "message %s is not a message from the Operator in this thread" % source + + +def verify_in(window, source, words): + """(message, None, 0) when WORDS occur in the owner message SOURCE of WINDOW; + otherwise (None, why, 2).""" + m, why = resolve_source(window, source) + if m is None: + return None, why, EXIT_USAGE + if m.get("origin_unknown"): + return None, ("message %s has an unknown origin (creationSource %r), so it is not taken as the Operator's" + % (m["id"], m.get("source"))), EXIT_USAGE + if not tm.quote_in(words, m["text"]): + return None, ("the quoted words do not occur in the Operator's own words in message %s (compared with whitespace " + "normalized; assistant text they quoted does not count)" % m["id"]), EXIT_USAGE + return m, None, 0 + + +def verify_quote(thread, source, words): + """verify_in over a fresh read; (None, why, 8) when T3 could not be read.""" + window, err = read_window(thread, **need_for(source)) + if window is None: + return None, "cannot read this thread's messages from T3 (%s)" % err, EXIT_T3 + return verify_in(window, source, words) + + +def looks_like_message(ref): + return ref == "first" or ref.startswith("message:") or \ + bool(re.match(r"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$", ref)) + + +# --- commands: init and statements --------------------------------------------------- + +def cut_words(text, limit): + if len(text) <= limit: + return text, False + head = text[:limit] + if " " in head[limit // 2:]: + head = head[:head.rindex(" ")] + return head.rstrip(), True + + +def cmd_init(args): + thread = thread_key() + refuse_lane() + card = Card(thread) + if card.exists(): + card.read() # a corrupt card is reported (exit 1), never started over + return report(args, {"path": card.path, "created": False, "mission_seeded": False, + "why": "the card already exists"}, + "card: already exists at %s (nothing changed)" % card.path) + window, err = read_window(thread, need_first=True) + seed, why = None, None + if window is None: + why = "T3 could not be read (%s)" % err + else: + seed, why = window.first() + if seed is not None and (secret_hit(seed["text"]) or secret_hit(seed["readable"])): + seed, why = None, "the Operator's first message matches a secret shape, so it was not copied" + if seed is not None and not tm.normalize(tm.own_text(seed["text"])): + seed, why = None, "the Operator's first message has no text of their own" + moment = now() + with card.locked(): + if card.exists(): + card.read() + return report(args, {"path": card.path, "created": False, "mission_seeded": False, + "why": "the card already exists"}, + "card: already exists at %s (nothing changed)" % card.path) + doc = new_card(thread, stamp(moment)) + if seed is not None: + # The mission shows the readable message; the words are their own words only, so + # they hold up to the same quote check as any other statement. + text, was_cut = cut_words(tm.normalize(seed["readable"]), LIM_STATEMENT - 3) + words, _ = cut_words(tm.normalize(tm.own_text(seed["text"])), LIM_WORDS) + doc["mission"].update(text=text + ("..." if was_cut else ""), words=words, + source={"message_id": seed["id"], "at": seed["at"]}, + seeded=True, unverified=False, set=stamp(moment)) + card.write(doc) + if seed is not None: + line = ("card: created %s. Mission seeded from the Operator's first message (%s); if that message does not state " + "the mission, restate it with card mission" % (card.path, seed["id"])) + else: + line = "card: created %s. Mission left unset: %s" % (card.path, why) + return report(args, {"path": card.path, "created": True, "mission_seeded": seed is not None, + "why": None if seed is not None else why}, line) + + +def report(args, data, line): + if getattr(args, "json", False): + print(json.dumps(data, ensure_ascii=False)) + else: + print(line) + return 0 + + +def cmd_statement(args, field, label): + thread = thread_key() + refuse_lane() + text = clean(args.text, LIM_STATEMENT, label) + words = clean(args.words, LIM_WORDS, "--words") + source = clean(args.source, LIM_REF, "--source") + Card(thread).require() + m, why, code = verify_quote(thread, source, words) + if m is None and not args.unverified: + raise CardError("%s not set: %s. Pass --unverified to store it flagged as unverified" % (label, why), code) + + def change(doc, moment): + cur = doc[field] + new = {"text": text, "words": words, + "source": {"message_id": m["id"] if m else source, "at": m["at"] if m else ""}, + "unverified": m is None, "seeded": False} + if all(cur.get(k) == v for k, v in new.items()): + return False, "card: %s unchanged" % label + if cur.get("text"): + old = {k: v for k, v in cur.items() if k != "history"} + old["replaced"] = stamp(moment) + cur["history"].append(old) + cur.update(new, set=stamp(moment)) + if m is None: + return True, "card: %s set UNVERIFIED (%s); it is printed flagged everywhere" % (label, why) + return True, "card: %s set; the Operator's words verified in message %s (%s)" % (label, m["id"], day(m["at"])) + + print(write_command(change, substantive=True)) + return 0 + + +# --- commands: backlog --------------------------------------------------------------- + +def next_id(doc): + return max([i["id"] for i in doc["backlog"]] + [i["id"] for i in doc["closed"]] + [0]) + 1 + + +def open_sorted(doc): + return sorted(doc["backlog"], key=lambda i: (STATE_ORDER[i["state"]], i["id"])) + + +def state_label(item): + if item["state"] == "waiting": + return "waiting on %s since %s" % (item.get("waiting_on") or "?", (item.get("since") or "")[:10]) + return item["state"] + + +def next_line(doc): + items = open_sorted(doc) + if not items: + return "Backlog is empty" + first = items[0] + tail = "" if first["state"] in ("flight", "next") else " (%s)" % state_label(first) + return "Next: #%d %s%s" % (first["id"], first["text"], tail) + + +def find_open(doc, ident): + for item in doc["backlog"]: + if item["id"] == ident: + return item + if any(c["id"] == ident for c in doc["closed"]): + raise CardError("#%d is already closed" % ident) + raise CardError("there is no open item #%d" % ident) + + +def cmd_add(args): + thread_key() + refuse_lane() + text = clean(args.text, LIM_BACKLOG, "the item") + waiting_on = clean(args.waiting_on, LIM_WHO, "--waiting-on", required=False) + opened_by = clean(args.opened_by, LIM_WHO, "--opened-by", required=False) + state = args.state or ("waiting" if waiting_on else "next") + if state == "waiting" and not waiting_on: + raise CardError("a waiting item needs --waiting-on WHO") + if state != "waiting" and waiting_on: + raise CardError("--waiting-on goes with --state waiting") + if args.side and not opened_by: + raise CardError("a side quest needs --opened-by WHO") + if opened_by and not args.side: + raise CardError("--opened-by goes with --side") + + def change(doc, moment): + for item in doc["backlog"]: + if item["text"] == text: + return False, "card: already open as #%d (nothing changed)" % item["id"] + ident = next_id(doc) + doc["backlog"].append({"id": ident, "text": text, "state": state, "waiting_on": waiting_on, + "since": stamp(moment), "side": bool(args.side), "opened_by": opened_by, + "added": stamp(moment)}) + return True, "card: added #%d [%s]" % (ident, state) + + print(write_command(change, substantive=True)) + return 0 + + +def cmd_set(args): + thread_key() + refuse_lane() + if args.state not in STATES: + raise CardError("state must be one of %s" % ", ".join(STATES)) + who = clean(args.who, LIM_WHO, "WHO", required=False) + if args.state == "waiting" and not who: + raise CardError("card set ID waiting WHO: name who it waits on") + if args.state != "waiting" and who: + raise CardError("only the waiting state takes a WHO") + + def change(doc, moment): + item = find_open(doc, args.id) + if item["state"] == args.state and (item.get("waiting_on") or "") == who: + return False, "card: #%d is already %s" % (args.id, state_label(item)) + item["state"] = args.state + item["waiting_on"] = who + item["since"] = stamp(moment) + return True, "card: #%d is now %s" % (args.id, state_label(item)) + + print(write_command(change, substantive=True)) + return 0 + + +def cmd_close(args): + thread_key() + refuse_lane() + by = clean(args.by, LIM_WHO, "--by", required=False) + to = clean(args.to, LIM_WHO, "--to", required=False) + note = clean(args.note, LIM_NOTE, "--note", required=False) + if args.how == "declined" and not by: + raise CardError("declined needs --by WHO (who declined it)") + if args.how == "handed" and not to: + raise CardError("handed needs --to WHERE (where it went)") + if by and args.how != "declined": + raise CardError("--by goes with declined") + if to and args.how != "handed": + raise CardError("--to goes with handed") + + def change(doc, moment): + item = find_open(doc, args.id) + doc["backlog"].remove(item) + doc["closed"].append({"id": item["id"], "text": item["text"], "how": args.how, "by": by, "to": to, + "note": note, "at": stamp(moment)}) + return True, next_line(doc) + + print(write_command(change, substantive=True)) + return 0 + + +def cmd_milestone(args): + thread_key() + refuse_lane() + text = clean(args.text, LIM_BACKLOG, "the milestone") + + def change(doc, moment): + doc["closed"].append({"id": next_id(doc), "text": text, "how": "milestone", "by": "", "to": "", + "note": "", "at": stamp(moment)}) + return True, next_line(doc) + + print(write_command(change, substantive=False)) + return 0 + + +# --- commands: how and plan ---------------------------------------------------------- + +def numbered_add(field, limit_n, limit_len, label): + def run(args): + thread_key() + refuse_lane() + text = clean(args.text, limit_len, label) + + def change(doc, moment): + items = doc[field] + for item in items: + if item["text"] == text: + return False, "card: already in %s as %d (nothing changed)" % (field, item["n"]) + if len(items) >= limit_n: + raise CardError("%s already holds %d entries, the limit; remove one first (card %s rm N)" + % (field, limit_n, field)) + n = max([i["n"] for i in items] + [0]) + 1 + items.append({"n": n, "text": text, "added": stamp(moment)}) + return True, "card: %s %d added" % (field, n) + + print(write_command(change, substantive=False)) + return 0 + return run + + +def numbered_rm(field): + def run(args): + thread_key() + refuse_lane() + + def change(doc, moment): + for item in doc[field]: + if item["n"] == args.n: + doc[field].remove(item) + return True, "card: %s %d removed" % (field, args.n) + raise CardError("%s has no entry %d" % (field, args.n)) + + print(write_command(change, substantive=False)) + return 0 + return run + + +# --- commands: holds ----------------------------------------------------------------- + +def check_hold_source(thread, source, words, allow_unverified, verb): + """(verified, at). A source that is an owner message in what T3 returned (or + "first") has its words checked, and a mismatch is refused unless --unverified. + A message-shaped source that T3's whole history does not hold is refused the + same way. Anything else (a standing-order reference, a ticket, a message older + than the readable window, or any source when T3 cannot be read) is stored as + given and printed "not checked".""" + if not source: + return False, "" + window, _err = read_window(thread, **(need_for(source) if looks_like_message(source) else {})) + if window is None: + return False, "" + if source == "first" or window.find(source) is not None: + m, why, code = verify_in(window, source, words) + if m is not None: + return True, m["at"] + elif looks_like_message(source) and not window.has_more: + why, code = "message %s is not a message from the Operator in this thread" % source, EXIT_USAGE + else: + return False, "" + if allow_unverified: + return False, "" + raise CardError("hold not %s: %s%s" % (verb, why, ". Pass --unverified to store it flagged" if verb == "added" + else ""), code) + + +def cmd_hold_add(args): + thread = thread_key() + refuse_lane() + text = clean(args.text, LIM_HOLD_TEXT, "the hold") + by = clean(args.by, LIM_WHO, "--by") + words = clean(args.words, LIM_WORDS, "--words") + source = clean(args.source, LIM_REF, "--source") + lifts = clean(args.lifts, LIM_HOLD_TEXT, "--lifts") + Card(thread).require() + verified, at = check_hold_source(thread, source, words, args.unverified, "added") + + def change(doc, moment): + active = [h for h in doc["holds"] if not h.get("lifted")] + if len(active) >= LIM_HOLDS: + raise CardError("holds already has %d active entries, the limit of %d; lift one first" + % (len(active), LIM_HOLDS)) + ident = max([h["id"] for h in doc["holds"]] + [0]) + 1 + doc["holds"].append({"id": ident, "text": text, "by": by, "words": words, "source": source, + "source_at": at, "verified": verified, "lifts": lifts, "set": stamp(moment), + "lifted": None}) + tail = "words verified in %s" % source if verified else "source stored as given, not checked" + return True, "card: hold #%d added (%s)" % (ident, tail) + + print(write_command(change, substantive=True)) + return 0 + + +def cmd_hold_lift(args): + thread = thread_key() + refuse_lane() + words = clean(args.words, LIM_WORDS, "--words") + source = clean(args.source, LIM_REF, "--source", required=False) + Card(thread).require() + verified, _ = check_hold_source(thread, source, words, False, "lifted") + + def change(doc, moment): + for hold in doc["holds"]: + if hold["id"] == args.id: + if hold.get("lifted"): + raise CardError("hold #%d was already lifted %s" % (args.id, hold["lifted"].get("at"))) + hold["lifted"] = {"at": stamp(moment), "words": words, "source": source, "verified": verified} + return True, "card: hold #%d lifted" % args.id + raise CardError("there is no hold #%d" % args.id) + + print(write_command(change, substantive=True)) + return 0 + + +# --- commands: messages, reviewed, check --------------------------------------------- + +def unreviewed_from(window, cursor_at): + """(messages after the cursor, history_gap). The gap is true when T3 has older + history and the cursor is not inside what was read, so messages may be missing.""" + return window.after(cursor_at), window.has_more and not (cursor_at and window.covers(cursor_at)) + + +def cursor_of(doc): + return (doc or {}).get("review_cursor") or {} + + +def cmd_messages(args): + thread = thread_key() + if args.limit < 1 or args.chars < 1: + raise CardError("--limit and --chars must be at least 1") + doc = Card(thread).read() + cursor_at = cursor_of(doc).get("at") or "" + window, err = read_window(thread, **({"since": cursor_at} if args.unreviewed else {})) + if window is None: + raise CardError("cannot read this thread's messages from T3 (%s)" % err, EXIT_T3) + if args.unreviewed: + msgs, gap = unreviewed_from(window, cursor_at) + else: + msgs, gap = list(window.owner), window.has_more + shown = msgs[:args.limit] + more = len(msgs) - len(shown) + out = [] + for m in shown: + text = tm.normalize(m["readable"]) + item = {"id": m["id"], "at": m["at"], "text": text[:args.chars], "cut": len(text) > args.chars} + if m.get("origin_unknown"): + item["origin_unknown"] = True + item["creationSource"] = m.get("source") + out.append(item) + if args.json: + doc_out = {"messages": out, "more": more, "history_gap": gap} + if gap: + # Optional, present only with a gap: why older history is missing (a failed page, + # the page cap), so rest-stop prep can say it instead of guessing. + doc_out["history_error"] = window.gap_reason() + print(json.dumps(doc_out, ensure_ascii=False)) + return 0 + scope = "after the review cursor" if args.unreviewed else "readable" + print("card: %d message(s) from the Operator %s%s" % (len(msgs), scope, ", oldest first" if msgs else "")) + for item in out: + flag = " [ORIGIN UNKNOWN: creationSource %r, not assumed to be the Operator]" % item["creationSource"] \ + if item.get("origin_unknown") else "" + print("- %s %s%s" % (item["id"], day(item["at"]), flag)) + print(" " + item["text"] + (" [cut]" if item["cut"] else "")) + if more: + print("+%d more after these: review these first, then card messages --unreviewed again" % more) + if gap: + print("History gap: %s, so earlier messages from the Operator may be missing here; read the thread in T3 for " + "them." % window.gap_reason()) + return 0 + + +def cmd_reviewed(args): + thread = thread_key() + refuse_lane() + through = clean(args.through, LIM_REF, "--through") + card = Card(thread) + card.require() + window, err = read_window(thread, need_id=through) + if window is None: + raise CardError("cannot read this thread's messages from T3 (%s)" % err, EXIT_T3) + m = window.find(through) + if m is None: + raise CardError("message %s is not among the messages from the Operator read from T3%s" + % (through, (" (%s)" % window.gap_reason()) if window.has_more else "")) + + def change(doc, moment): + cur = cursor_of(doc) + if cur.get("message_id") == m["id"]: + return False, "card: already reviewed through %s" % m["id"] + cur_at = tm.parse_time(cur.get("at")) + if cur_at is not None and tm.parse_time(m["at"]) <= cur_at: + return False, "card: already reviewed through a later message (%s); nothing changed" % cur.get("message_id") + if not args.nothing_changes: + sub = tm.parse_time(doc["substantive_updated"]) + if sub is None or sub <= tm.parse_time(m["at"]): + raise CardError("refused: the card's mission, finish line, backlog and holds have not changed since " + "message %s (%s). Edit the card for what it changes, or pass --nothing-changes if " + "none of the messages changes anything" % (m["id"], day(m["at"]))) + doc["review_cursor"] = {"message_id": m["id"], "at": m["at"], "set": stamp(moment)} + return True, "card: reviewed through %s (%s)" % (m["id"], day(m["at"])) + + print(write_command(change, substantive=False)) + return 0 + + +def check_report(thread, moment): + card = Card(thread) + problems, notes = [], [] + counts = {} + unreviewed, known, gap = 0, False, False + try: + doc = card.read() + except CardError as exc: + doc = None + problems.append(str(exc)) + else: + if doc is None: + problems.append("no card for this thread: run card init") + if doc is not None: + cursor_at = cursor_of(doc).get("at") or "" + window, err = read_window(thread, since=cursor_at) + if window is None: + problems.append("cannot read the Operator's messages from T3 (%s), so the unreviewed count is unknown" % err) + else: + msgs, gap = unreviewed_from(window, cursor_at) + unreviewed, known = len(msgs), not gap + if msgs: + problems.append("%d message(s) from the Operator not reviewed: card messages --unreviewed, edit the card, " + "then card reviewed --through %s" % (len(msgs), msgs[-1]["id"])) + if gap: + # A failed required read blocks arming. The deliberate page cap + # still reports the gap as a note. + report_to = problems if window.history_failed else notes + report_to.append("the review cursor is older than what was read (%s); earlier messages from the Operator were " + "not checked" % window.gap_reason()) + for field, label in (("mission", "mission"), ("done_when", "finish line (done when)")): + st = doc[field] + if not st["text"]: + notes.append("%s is unset" % label) + elif st.get("unverified"): + notes.append("%s is stored UNVERIFIED" % label) + for field in ("how", "plan"): + for item in doc[field]: + added = tm.parse_time(item.get("added")) + if added is None or (moment - added).days >= STALE_DAYS: + notes.append("%s %d is older than %d days: still true? (%s)" + % (field, item["n"], STALE_DAYS, item["text"][:60])) + active = [h for h in doc["holds"] if not h.get("lifted")] + for hold in active: + if not (hold.get("source") or "").strip(): + notes.append("hold #%d has no source: lift it, or keep it as plan" % hold["id"]) + counts = {"open": len(doc["backlog"]), + "waiting": sum(1 for i in doc["backlog"] if i["state"] == "waiting"), + "closed": len(doc["closed"]), "holds": len(active), "how": len(doc["how"]), + "plan": len(doc["plan"]), "compactions_seen": doc["compactions_seen"]} + return {"ok": not problems, "unreviewed": unreviewed, "unreviewed_known": known, "history_gap": gap, + "problems": problems, "notes": notes, "counts": counts, "path": card.path} + + +def cmd_check(args): + thread = thread_key() + rep = check_report(thread, now()) + if args.json: + print(json.dumps(rep, ensure_ascii=False)) + return 0 + print("card check: %s (%s)" % ("ok, nothing blocks a rest stop" if rep["ok"] else "NOT ready", rep["path"])) + for p in rep["problems"]: + print(" problem: " + p) + for n in rep["notes"]: + print(" note: " + n) + if rep["counts"]: + print(" counts: " + ", ".join("%s %d" % kv for kv in rep["counts"].items())) + return 0 + + +def cmd_seen_compaction(args): + thread_key() + refuse_lane() + + def change(doc, moment): + doc["compactions_seen"] += 1 + return True, "card: compactions_seen %d" % doc["compactions_seen"] + + print(write_command(change, substantive=False)) + return 0 + + +# --- show ---------------------------------------------------------------------------- + +def is_owner_word(who): + return bool(re.search(r"\b(operator|you|owner)\b", who or "", re.I)) + + +def summary_line(doc): + def part(st): + if not st["text"]: + return "(unset)" + return st["text"] + (" [unverified]" if st.get("unverified") else "") + waiting_you = sum(1 for i in doc["backlog"] if i["state"] == "waiting" and is_owner_word(i.get("waiting_on"))) + return "Mission: %s | Done when: %s | Open: %d (%d waiting on you)" % ( + part(doc["mission"]), part(doc["done_when"]), len(doc["backlog"]), waiting_you) + + +def statement_lines(label, st, moment): + if not st["text"]: + return ["%s: unset. Set it only from the Operator's own words: card %s TEXT --words QUOTE --source MESSAGE_ID" + % (label, "mission" if label == "MISSION" else "done-when")] + lines = ["%s: %s" % (label, st["text"])] + src = st.get("source") or {} + if st.get("unverified"): + lines.append(" [UNVERIFIED: these words were not found in a readable message from the Operator] words: \"%s\" " + "(source given: %s)" % (st["words"], src.get("message_id") or "none")) + else: + lines.append(" the Operator's words (%s, message %s): \"%s\"" % (day(src.get("at")), src.get("message_id"), + st["words"])) + if st.get("seeded"): + lines.append(" (seeded from the Operator's first message; restate it if that message does not state it)") + if st.get("history"): + lines.append(" (%d earlier version(s): card show --full)" % len(st["history"])) + return lines + + +def hold_line(h, moment): + src = h.get("source") or "NONE (treat as plan, not a hold)" + checked = "" if h.get("verified") or not h.get("source") else " (not checked)" + return (" #%d %s\n set by %s, %s (%s ago); words: \"%s\"; source: %s%s; lifts when: %s" + % (h["id"], h["text"], h.get("by") or "?", day(h.get("set")), age(h.get("set"), moment), + h.get("words") or "", src, checked, h.get("lifts") or "?")) + + +def backlog_line(item): + side = " (side quest, opened by %s)" % item.get("opened_by") if item.get("side") else "" + return " #%d [%s] %s%s" % (item["id"], state_label(item), item["text"], side) + + +def read_asks(thread): + """(titles, warning). Titles are '#n text' of the open asks for THREAD.""" + script = os.environ.get("CARD_ASKS") or os.path.join(BIN, "asks") + try: + proc = subprocess.run([sys.executable, script, "list", "--thread", thread, "--json"], capture_output=True, + text=True, timeout=RESUME_T3_TIMEOUT, stdin=subprocess.DEVNULL) + except (OSError, subprocess.SubprocessError) as exc: + return [], "the asks register could not be read (%s): run asks list" % exc + try: + items = json.loads(proc.stdout) + if not isinstance(items, list): + raise ValueError("not a list") + except ValueError: + return [], "the asks register could not be read (asks exit %d): run asks list" % proc.returncode + titles = ["#%s %s" % (i.get("n"), i.get("text")) for i in items if isinstance(i, dict) and not i.get("resolved")] + warn = None + if proc.returncode != 0: + warn = "part of the asks register could not be read (asks exit %d): run asks list" % proc.returncode + return titles, warn + + +def fresh_baton(thread, moment): + path = os.path.join(run_dir(), "resume-%s.txt" % file_key(thread)) + try: + mtime = os.path.getmtime(path) + except OSError: + return None + return path if moment.timestamp() - mtime < BATON_FRESH_S else None + + +def baton_line(path): + return "A resume baton is at %s. Read it if its contents have yet to arrive." % path + + +def render_resume(thread, moment): + """The post-compaction print as (text, exit code), at most RESUME_CAP characters.""" + card = Card(thread) + baton = fresh_baton(thread, moment) + try: + doc = card.read() + except CardError as exc: + lines = ["THREAD CARD: %s; nothing from it is printed. card show --full shows the error; do not recreate " + "the card by hand." % exc] + if baton: + lines.append(baton_line(baton)) + return "\n".join(lines), EXIT_CORRUPT + if doc is None: + lines = ["THREAD CARD: none for this thread yet: run %s init" % os.path.join(BIN, "card")] + if baton: + lines.append(baton_line(baton)) + return "\n".join(lines), EXIT_NOKEY + + # One budget for the bounded read and any paging: the SessionStart hook has 15 s for the + # whole print, and a count it could not finish is printed as unknown, never guessed. + window, err = read_window(thread, budget=RESUME_T3_TIMEOUT, since=doc["substantive_updated"]) + comps = max(0, doc["compactions_seen"] - doc.get("compactions_at_substantive", 0)) + if window is None: + msgs = "an unknown number of messages from the Operator (T3 read failed: %s)" % err[:120] + else: + since, gap = unreviewed_from(window, doc["substantive_updated"]) + known = [m for m in since if not m.get("origin_unknown")] + if gap: + msgs = "an unknown number of messages from the Operator (at least %d; %s)" % (len(known), + window.gap_reason()[:160]) + else: + msgs = "%d message(s) from the Operator" % len(known) + if len(known) < len(since): + msgs += " (and %d of unknown origin)" % (len(since) - len(known)) + fixed = ["THREAD CARD: %s (change it only with %s; card show --full prints all of it)" + % (card.path, os.path.join(BIN, "card")), + "Last substantive change: %s ago; %d compaction(s) and %s since. Treat as a hypothesis where stale." + % (age(doc["substantive_updated"], moment), comps, msgs)] + if baton: + fixed.append(baton_line(baton)) + fixed += statement_lines("MISSION", doc["mission"], moment) + fixed += statement_lines("DONE WHEN", doc["done_when"], moment) + + active = [h for h in doc["holds"] if not h.get("lifted")] + titles, asks_warn = read_asks(thread) + sections = [ + ("HOLDS (%d; each binds only as its source says):" % len(active) if active else "HOLDS: none", + [hold_line(h, moment) for h in active]), + ("Your own earlier plan, not a hold:" if doc["plan"] else None, + [" %d. %s (added %s)" % (p["n"], p["text"], (p.get("added") or "")[:10]) for p in doc["plan"]]), + ("BACKLOG (%d open):" % len(doc["backlog"]) if doc["backlog"] else "BACKLOG: empty", + [backlog_line(i) for i in open_sorted(doc)]), + ("HOW (this thread's commands, paths and ids):" if doc["how"] else None, + [" %d. %s" % (h["n"], h["text"]) for h in doc["how"]]), + ("OPEN ASKS waiting on the Operator (asks register, titles only):" if titles or asks_warn else None, + ([" " + t for t in titles]) + ([" (%s)" % asks_warn] if asks_warn else [])), + ] + + out = list(fixed) + used = sum(len(x) + 1 for x in out) + reserve = len(CLOSING) + 1 + 6 * 48 # the closing line and one cut marker per section + for header, items in sections: + if header is None: + continue + if used + len(header) + 1 + reserve > RESUME_CAP: + if items: + out.append("+%d more: card show --full" % len(items)) + used += len(out[-1]) + 1 + continue + out.append(header) + used += len(header) + 1 + cut = 0 + for item in items: + if cut or used + len(item) + 1 + reserve > RESUME_CAP: + cut += 1 + continue + out.append(item) + used += len(item) + 1 + if cut: + out.append(" +%d more: card show --full" % cut) + used += len(out[-1]) + 1 + out.append(CLOSING) + text = "\n".join(out) + if len(text) > RESUME_CAP: # the fixed part alone can only overflow if limits change + marker = "\n+%d characters cut: card show --full\n" + CLOSING + keep = RESUME_CAP - len(marker % (len(text))) - 2 + text = text[:keep] + marker % (len(text) - keep) + return text, 0 + + +def render_full(doc, moment): + lines = [summary_line(doc), "card: %s" % Card(doc["thread"]).path, + "created %s; updated %s; last substantive change %s; compactions seen %d" + % (day(doc["created"]), day(doc["updated"]), day(doc["substantive_updated"]), doc["compactions_seen"])] + lines += statement_lines("MISSION", doc["mission"], moment) + for h in doc["mission"]["history"]: + lines.append(" earlier (%s): %s" % (day(h.get("set")), h.get("text"))) + lines += statement_lines("DONE WHEN", doc["done_when"], moment) + for h in doc["done_when"]["history"]: + lines.append(" earlier (%s): %s" % (day(h.get("set")), h.get("text"))) + lines.append("HOLDS:") + for h in doc["holds"]: + lines.append(hold_line(h, moment)) + if h.get("lifted"): + lines.append(" LIFTED %s: \"%s\" (%s)" % (day(h["lifted"].get("at")), h["lifted"].get("words"), + h["lifted"].get("source") or "no source")) + lines.append("PLAN (your own, not a hold):") + lines += [" %d. %s (added %s)" % (p["n"], p["text"], (p.get("added") or "")[:10]) for p in doc["plan"]] + lines.append("BACKLOG:") + lines += [backlog_line(i) for i in open_sorted(doc)] + lines.append("HOW:") + lines += [" %d. %s (added %s)" % (h["n"], h["text"], (h.get("added") or "")[:10]) for h in doc["how"]] + lines.append("CLOSED:") + for c in doc["closed"]: + extra = "".join(" %s %s" % (k, c[k]) for k in ("by", "to") if c.get(k)) + note = " (%s)" % c["note"] if c.get("note") else "" + lines.append(" #%d %s %s%s%s: %s" % (c["id"], (c.get("at") or "")[:10], c.get("how"), extra, note, c["text"])) + cur = cursor_of(doc) + lines.append("REVIEW CURSOR: %s" % ("through %s (%s), set %s" % (cur.get("message_id"), day(cur.get("at")), + day(cur.get("set"))) + if cur.get("message_id") else "unset")) + return "\n".join(lines) + + +def cmd_show(args): + thread = thread_key() + moment = now() + if args.resume: + text, code = render_resume(thread, moment) + if args.json: + print(json.dumps({"text": text}, ensure_ascii=False)) + else: + print(text) + return code + doc = Card(thread).require() + if args.line: + line = summary_line(doc) + print(json.dumps({"line": line}, ensure_ascii=False) if args.json else line) + return 0 + if args.json: + print(json.dumps(doc, indent=1, ensure_ascii=False)) + return 0 + print(render_full(doc, moment)) + return 0 + + +# --- CLI ----------------------------------------------------------------------------- + +def build_parser(): + ap = argparse.ArgumentParser(prog="card", description="The per-thread card: mission, finish line, backlog, " + "how-to, holds and plan, kept current while working.") + sub = ap.add_subparsers(dest="cmd", required=True) + + p = sub.add_parser("init", help="create the card if absent") + p.add_argument("--json", action="store_true") + + p = sub.add_parser("show", help="print the card") + g = p.add_mutually_exclusive_group() + g.add_argument("--resume", action="store_true", help="the post-compaction print") + g.add_argument("--line", action="store_true", help="one line for the Operator") + g.add_argument("--full", action="store_true", help="everything (the default)") + p.add_argument("--json", action="store_true") + + for name in ("mission", "done-when"): + p = sub.add_parser(name, help="set the %s from the Operator's own words" % name) + p.add_argument("text") + p.add_argument("--words", required=True, help="the Operator's exact words") + p.add_argument("--source", required=True, help="their message id, or 'first'") + p.add_argument("--unverified", action="store_true", help="store it flagged when the quote cannot be checked") + + p = sub.add_parser("add", help="add a backlog item") + p.add_argument("text") + p.add_argument("--state", choices=STATES) + p.add_argument("--waiting-on") + p.add_argument("--side", action="store_true") + p.add_argument("--opened-by") + + p = sub.add_parser("set", help="change an item's state") + p.add_argument("id", type=int) + p.add_argument("state") + p.add_argument("who", nargs="?") + + p = sub.add_parser("close", help="close an item") + p.add_argument("id", type=int) + p.add_argument("how", choices=("done", "declined", "handed")) + p.add_argument("--by") + p.add_argument("--to") + p.add_argument("--note") + + p = sub.add_parser("milestone", help="a dated line in the closed log") + p.add_argument("text") + + for name in ("how", "plan"): + p = sub.add_parser(name, help="%s entries" % name) + s = p.add_subparsers(dest="op", required=True) + a = s.add_parser("add") + a.add_argument("text") + r = s.add_parser("rm") + r.add_argument("n", type=int) + + p = sub.add_parser("hold", help="holds and who set them") + s = p.add_subparsers(dest="op", required=True) + a = s.add_parser("add") + a.add_argument("text") + a.add_argument("--by", required=True) + a.add_argument("--words", required=True) + a.add_argument("--source", required=True) + a.add_argument("--lifts", required=True) + a.add_argument("--unverified", action="store_true", + help="store it when --source names a message whose text does not hold --words") + li = s.add_parser("lift") + li.add_argument("id", type=int) + li.add_argument("--words", required=True) + li.add_argument("--source") + + p = sub.add_parser("messages", help="the Operator's messages, oldest first") + p.add_argument("--unreviewed", action="store_true") + p.add_argument("--limit", type=int, default=12) + p.add_argument("--chars", type=int, default=600) + p.add_argument("--json", action="store_true") + + p = sub.add_parser("reviewed", help="advance the review cursor") + p.add_argument("--through", required=True) + p.add_argument("--nothing-changes", action="store_true") + + p = sub.add_parser("check", help="what blocks a rest stop") + p.add_argument("--json", action="store_true") + + sub.add_parser("seen-compaction", help="count a compaction (the hook calls this)") + return ap + + +def dispatch(args): + if args.cmd == "how": + return (numbered_add("how", LIM_HOW_N, LIM_HOW, "the how entry") if args.op == "add" + else numbered_rm("how"))(args) + if args.cmd == "plan": + return (numbered_add("plan", LIM_PLAN_N, LIM_PLAN, "the plan entry") if args.op == "add" + else numbered_rm("plan"))(args) + if args.cmd == "hold": + return cmd_hold_add(args) if args.op == "add" else cmd_hold_lift(args) + return { + "init": cmd_init, "show": cmd_show, + "mission": lambda a: cmd_statement(a, "mission", "mission"), + "done-when": lambda a: cmd_statement(a, "done_when", "finish line"), + "add": cmd_add, "set": cmd_set, "close": cmd_close, "milestone": cmd_milestone, + "messages": cmd_messages, "reviewed": cmd_reviewed, "check": cmd_check, + "seen-compaction": cmd_seen_compaction, + }[args.cmd](args) + + +def main(argv): + args = build_parser().parse_args(argv) + try: + return dispatch(args) + except CardError as exc: + print("card: %s" % exc, file=sys.stderr) + return exc.code + except OSError as exc: + print("card: %s" % (exc.strerror or exc), file=sys.stderr) + return EXIT_CORRUPT + + +if __name__ == "__main__": + sys.exit(main(sys.argv[1:])) diff --git a/.claude-config/bin/compact-cycle.sh b/.claude-config/bin/compact-cycle.sh index 22caccd..c59dc4d 100755 --- a/.claude-config/bin/compact-cycle.sh +++ b/.claude-config/bin/compact-cycle.sh @@ -48,6 +48,7 @@ # over the API, so it is never fired into a busy thread). # --timeout max wait for the compaction to complete (the compact-status # answer, not an idle thread). Default 900. +# --tidy report the lock and put an abandoned armed baton back; see LOCK LIVENESS. # # Runtime dir: ~/.claude-compact-cycle/ (locks, logs, status files, batons); CC_CYCLE_RUNDIR # overrides. Nothing here names a checkout: the sibling t3-api.sh is found from this script's @@ -114,15 +115,97 @@ # None of them retries or waits out the timeout, except that a transport blip (code 4) on a # read is retried three times first. No failure ever sends the resume. # +# ARMED BY REST-STOP (bin/README.md, "rest-stop"). `rest-stop arm` writes +# $RUNDIR/arm-.json just before it starts this script. With no such file nothing below +# runs and the cycle is exactly the one described above. A record is used only when it names +# this target and its baton_sha256 is the sha256 of the --baton file, and only for a baton +# resume (not --resume or --no-resume); any other record is logged as ignored and the plain +# cycle runs, so a record left by a failed arming cannot change a later legacy cycle. A used +# record adds two steps after the idle confirmation and before /compact, one thread read +# (t3-api.sh thread) for both: +# 1. Stand down when the owner typed after validation began (armed_at for an older record). +# A user message whose creationSource is not server or mcp counts; a message with no creationSource, as on +# protocol 1, counts as the owner's: the safe side) or a run other than armed_turn was +# requested or started after validation began. Nothing is sent, the baton goes back to +# baton-draft-.txt (a newer draft there is never overwritten), the record is removed, +# the status says superseded, exit 0. WHY: the baton was written before that message or +# run, so compacting now would wake the thread on a stale picture of what the Operator said. +# 2. Write $RUNDIR/trailer-.txt: "LAST REPLY TO THE OWNER (delivered