From 6d37b451ae8bbfa5decc2696ec5c4ca02a22720b Mon Sep 17 00:00:00 2001 From: Alex Ivantsov Date: Tue, 17 Nov 2026 20:22:22 -0500 Subject: [PATCH] feat(bin): add session-end, asks and active-minutes session-end runs the mechanical half of every thread ending: a read-only git snapshot, branch-gc --apply for the current repo and each --repo (one detached, deadline-bounded worker, only the repos the pre-compact hook manages), the memory index rebuild, verify-ops when the thread named harness files, and on close a list of what the thread created. It never commits, pushes, compacts, settles or removes scratch. session-end finish advances last-closeout only after a completed receipt, and after a close moves the thread's billing stamp files into a fresh reaped/ directory by rename, beside a reaped.meta. Claude sessions, Linux, main thread only: git-guard.sh blocks a run other than --dry-run from a helper agent. asks is the per-thread register of open asks for the box's owner. active-minutes measures working minutes from a session transcript, with --time-tool and --zone. memory-index gains --pool-for. Tests: session-end-test.py (recording stubs, sandbox guard, listed in OPS_SANDBOX_SUITES), asks-test.py, active-minutes-test.py (standard library), memory-index-test.sh, guard-selftest.sh probes. Docs: bin/README.md, DEPLOYMENT.md, CHANGELOG.md. --- .claude-config/bin/README.md | 190 +- .claude-config/bin/active-minutes | 499 ++++ .claude-config/bin/asks | 571 +++++ .claude-config/bin/memory-index | 43 +- .claude-config/bin/session-end | 2059 +++++++++++++++++ .../bin/tests/active-minutes-test.py | 843 +++++++ .claude-config/bin/tests/asks-test.py | 357 +++ .claude-config/bin/tests/memory-index-test.sh | 38 + .claude-config/bin/tests/session-end-test.py | 1531 ++++++++++++ .claude-config/bin/verify-ops.sh | 8 +- .claude-config/hooks/git-guard.sh | 81 +- .claude-config/hooks/guard-selftest.sh | 73 + CHANGELOG.md | 68 + DEPLOYMENT.md | 2 +- 14 files changed, 6356 insertions(+), 7 deletions(-) create mode 100755 .claude-config/bin/active-minutes create mode 100755 .claude-config/bin/asks create mode 100755 .claude-config/bin/session-end create mode 100644 .claude-config/bin/tests/active-minutes-test.py create mode 100644 .claude-config/bin/tests/asks-test.py create mode 100644 .claude-config/bin/tests/session-end-test.py diff --git a/.claude-config/bin/README.md b/.claude-config/bin/README.md index 43bef80..3bdd65c 100644 --- a/.claude-config/bin/README.md +++ b/.claude-config/bin/README.md @@ -196,7 +196,7 @@ under `~/.local/state/ops/` (`branch-gc.log`, `branch-gc-trash/`). Who runs it: `../backup/daily-sync.sh` nightly (`--apply`, after the project pull), the PreCompact hook for the repo holding the cwd (detached, with a soft deadline and the purge off), and closeout on each repo a session -touched. Tests (all inside `sandbox-run`): `tests/branch-gc-test.sh`, +touched (`session-end`, with the hook's numbers and managed set). Tests (all inside `sandbox-run`): `tests/branch-gc-test.sh`, `tests/branch-gc-safety-test.py`, `tests/branch-gc-t3v2-test.py`, `tests/branch-gc-deadline-test.py`, `tests/branch-gc-late-writer-test.py`; the hook's half: `tests/pre-compact-test.sh`. @@ -233,6 +233,189 @@ prints one row per session or lane: calls, input, cache writes and reads, output, idle gaps and the cache re-writes after them. Metadata only, never message text. Test: `tests/transcript-usage-test.py`. +## `asks`: the register of what is waiting on the box's owner + +An Operator running several threads at once should not poll each one for status. +`asks` is the register each thread writes to, one line per open ask, so everything +waiting on the Operator can be read in one place. Python standard library only. + +``` +asks add "" [--thread ID] [--why TEXT] [--rec TEXT] [--default TEXT] + [--kind decision|console|action] [--title TEXT] [--owner TEXT] + [--deadline YYYY-MM-DD] [--client NAME] + [--tool NAME] [--step TEXT]... [--paste TEXT|@FILE|-] [--expect TEXT] [--link URL] +asks list [--all | --thread ID] [--json] [--resolved] +asks resolve [--thread ID] [--note TEXT] +asks prune [--days N] +``` + +- **Storage.** One JSON file per thread under `${OPS_STATE_DIR:-~/.local/state/ops}/asks/`, + mode 0600 in a 0700 directory (an ask can name a client). The thread is `--thread`, + else `$ASKS_THREAD`, else `$T3CODE_THREAD_ID` (a lane inherits its foreman's id, so its asks + land on the thread the Operator reads); with none, asks file under `adhoc` and say so. + A write takes one lock for the whole directory, so concurrent threads do not lose asks. +- **Kinds.** `decision` (the default: a question with a recommendation), `action` (something + only the Operator can click or send) and `console` (a step only a person can take in a + vendor's web console, carrying its steps and the full paste text; `--tool`, `--step` or + `--paste` makes an ask a console ask by itself). +- **Idempotent.** An ask with the same text, kind and thread as an open one updates it + (fields the re-add leaves empty keep their value), so a closing step re-run after a + compaction adds no duplicate. Numbers are per thread and never reused. Resolved asks are kept + 14 days, then pruned. The empty thread record keeps its next number so an old reference + cannot resolve a new ask. An unreadable register file stops pruning and new adds before + they change any asks. +- **Limits.** The ask 400 characters, a field 1200, a step 600, a paste 64 KB, 200 open asks + per thread. Over a limit is a refusal, never a silent cut. +- **Secrets.** A secret-shaped value (private key block, GitHub, Anthropic or OpenAI, AWS or + Slack token, JSON web token) is refused in the ask, every add field, `--title`, `--thread` + and `resolve --note`; the refusal names the shape and never echoes the value. +- **Who reads it.** `asks list` (`--json` for a script) and `session-end`, which lists the + thread's open asks at every ending. Nothing else in OPS reads the register. +- **Exit codes.** 0 ok; 1 a register file could not be read or written (a corrupt file is + named, never read as an empty register), or the platform has no `fcntl`; 2 a usage error or + a refused input. +- **Platform.** POSIX only (it locks with `fcntl`). On native Windows it prints one line and + exits 1; use WSL. + +Test: `tests/asks-test.py` (unittest, runs in the sandbox against a throwaway +`OPS_STATE_DIR`). + +## `active-minutes`: working minutes from a session transcript + +`active-minutes ` measures a thread's working time from its Claude Code +transcript, before that time is billed to a ticket. Python standard library only. + +- **The rule.** A silent stretch of 30 minutes or less between events is working time. A longer + gap is classified from its evidence and printed with its cause, COUNTED or EXCLUDED: an + attended pause (the Operator typed next) counts up to `--attended-max` hours (default 4); + unattended agent time (a background task that ran through the gap) counts to the same + limit; a usage-limit or provider-error hold, a stated break, a wait ended by a harness message + (scheduled check, context handoff, resume message, `/compact`), a gap with no prompt + evidence and a gap past the limit are excluded. `--keep ISO` and `--drop ISO` settle one + gap on evidence the transcript cannot show; `--also FILE...` adds lane transcripts as work + trace; `--strict` excludes every gap over `--gap` seconds (default 1800). The figure to bill + is the `ACTIVE (bill this)` line, decimal hours to two places, never rounded. +- **Options.** `--gap SECONDS`, `--attended-max HOURS`, `--since ISO`, `--until ISO` (no offset + means UTC), `--zone NAME`, `--tz-offset H`, `--also FILE...`, `--keep ISO`, `--drop ISO`, + `--strict`, `--time-tool NAME`, and the hook mode `--since-last-entry [--ticket T] [--now ISO] + --brief`, which prints one `key=value` line (unlogged minutes since the transcript's last + time-entry create, and the age of the last create for the ticket). +- **Display zone.** The work blocks print in one zone, converted per timestamp so a block across + a daylight-saving change is right at each end: `--zone NAME` (an IANA name), else `$TZ` if + it names a valid zone, else the machine's own zone, else UTC. `--tz-offset H` prints a fixed + offset with no zone tag and cannot be combined with `--zone`. A named zone that cannot load + (no zone database and no `tzdata` package) prints one line and exits 2. The total and the gap + rule never depend on the display zone. +- **`--time-tool NAME`.** Which tool call is the ticketing system's time-entry tool: any tool + whose name ends with `NAME` (default `time_manage`) and whose input carries `mode` `create` + and a `ticket`. Only the hook mode reads it. A ticketing system whose tool has another + input shape is not read as a time entry. A call without a ticket, or with an explicit + error result, does not reset the unlogged window. +- **Exit codes.** 0 ok; 1 too few timestamped events to measure; 2 a usage error or a zone that + cannot be loaded. + +Test: `tests/active-minutes-test.py` (unittest; builds synthetic transcripts, never reads a +real one). + +## `session-end`: the mechanical half of ending a thread + +``` +session-end [--repo PATH]... [--transcript FILE] [--wait SECONDS] [--dry-run] [--json] +session-end finish [--logged N | --declined REASON] [--json] +``` + +Every ending (pause, move, close) starts with it, so the steps a close used to assemble by +hand from three skills run the same way every time. Python standard library only. + +- **What the first call does.** It snapshots git read-only, starts `branch-gc --apply` on the + thread's repos, rebuilds this directory's memory index (the pool comes from `memory-index + --pool-for --cwd --ops `, the digest's own lookup, with the checkout the + 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 + (`.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 + (listed, never removed), and the settle route. OPS ships no vault renderer, so that step + prints an explicit skip. +- **What it never does.** It never commits, pushes, edits a ticket, logs time, writes a baton, + compacts, settles or deletes scratch. Its writes are branch-gc's own mechanic on the selected + repos, the memory index, its receipt and GC run files, and (`finish` only) the closeout stamp + and the archive of this thread's billing stamps. +- **Which repos GC reaches.** The current repo plus each `--repo` when the thread's Claude + transcript is verified, else only explicit `--repo` values; other repos the transcript names + are printed as candidates with read-only snapshots. Of those, only the repos the PreCompact + hook would hand to branch-gc (`~/OPS`, `~/OPS/PROJECTS//` and `~/linuxploitacious`, + by realpath under the current `$HOME`; a clone of OPS under another name is not one) with + exactly one github.com origin. One detached worker per call runs them serially, each under + the hooks' timeout program with the hook's numbers: 900 s, a soft deadline + (`BRANCH_GC_DEADLINE`) at two thirds, 30 s from TERM to KILL, and `BRANCH_GC_TRASH_DAYS=0`. + GC works on the whole repo, including other threads' eligible idle work; branch-gc's own + process and T3 checks hold live worktrees. `--wait` (default 90) is the total time to wait + for the result; past it the call exits 3 with the result path, and a repeat call for the + same thread and repos reuses the pending worker. The output prints `branch-gc --restore` for + each quarantined worktree and the recorded tip of each deleted branch. +- **Lint.** `verify-ops.sh --quiet` with `OPS_DIR` set to this checkout (the gate has no + lint-only mode). Its FAIL lines are findings, not a failed run: on a shared box the gate + almost always carries FAILs owned by other sessions, and whose a FAIL is stays the agent's + call. A lint that exits 1 with the gate's summary line (`verify-ops: N ok · N warn · N fail + (...)`) and FAIL lines gets the status `findings` (`fail_lines` in `--json`): every FAIL line + is printed, the receipt records them and stays passing, `finish` names their count and still + stamps, and the remainder asks the agent to fix the ones on its own files and name the rest. + Exit 0 also requires the gate's summary line with zero failures and no FAIL lines. A lint + that could not run or finish (no gate beside the command, a start error, a timeout, + another exit status, or no usable summary line) is `failed` and fails the receipt. +- **Settle (close).** The remainder names T3's own settle tool first (`t3_thread_organize` + with action `settle`, as the last tool call of the turn) and `t3-api.sh settle-when-idle + ` only as the fallback when that tool is not available, never both. Outside T3 there + is no settle step. +- **`finish`.** Runs after the agent has saved lessons, fixed documents and written the resume + note. It reads the receipt `/session-end/.json`, refuses a receipt of another + thread, a failed run, or a GC run still going or failed, and then advances + `/last-closeout` (the stamp `session-briefing.sh` reads) in `date -Is` format and + moves the receipt to `/session-end/done/`. The first call never moves the stamp: it is + the lower bound of transcript knowledge mining. `` is `$OPS_STATE_DIR`, else + `~/.local/state/ops`; GC runs keep `plan.json`, `run.log`, `result.json` and the worker lock + under `/session-end/gc//`. +- **The billing archive (close).** `finish` then needs exactly one of `--logged N` (time + entries created and read back; 0 is valid) or `--declined REASON`, and moves this thread's + `~/.claude-compact-cycle/session-start-` and `work-log-` (the stamps + `hooks/session-work-init.sh` and the PreCompact hook write; key from `hooklib.sh`'s + `work_session_key`) into one fresh `~/.claude-compact-cycle/reaped/--/` + (exclusive `mkdir`, mode 0700, never reused), each by a single rename, the work-log first and + the session-start flag last. A rename keeps the file, so bytes a writer appends through a + descriptor it already holds land in the archive, and a writer that opens the name afterwards + creates a new live stamp that stays live; nothing is copied or deleted. `reaped.meta` beside + them holds `reaped_at`, `reaped_reason`, `reaped_key` and, per file, its original path, size + and sha256. The report prints the `mv -n ` that restores a file while its + live name is free. It archives only a key from the T3 session-id branch (`t3-`, + with `ops_backend` saying t3code): a shared-cwd key or a tmux key is refused, and the stamps + are then handled by hand per `SKILLS/session-close/mechanics.md`. If a new work-log appears + during archival, or a step fails after a move, the session-start flag stays live. +- **Scope.** Claude sessions only: under Codex or OpenCode the transcript, time and billing + steps print "unsupported provider" and `finish` archives nothing. Main thread only: a + T3-delegated lane (thread id `thread:delegated-task:` or `thread:provider:`, or `lane-class + --self` saying `t3-lane` or `agent-lane`) is refused every writing mode, and + `hooks/git-guard.sh` blocks a run other than `--dry-run` from a payload with an `agent_id` + (an in-process helper shares its main thread's environment), under either `GIT_GUARD=off` + hatch too. The guard reads command text, so a wrapper script that calls the command is not + seen. Linux only (`fcntl` locks, `setsid` through `start_new_session`). +- **`--dry-run`** writes nothing: branch-gc runs in report mode with its log and lock in a + scratch directory, and the writing helpers are only named. The human output is cut for an + agent under context pressure (one worktree list per main checkout; branch-gc's report-only + rows only for branches and worktrees the thread named, with a count of the rest); `--json` + keeps every child's full output. +- **Exit codes.** 0 the requested steps completed; 1 a step failed or the call was refused; 2 + invalid arguments; 3 GC still pending after the wait budget. All writing modes hold one + per-key lock through receipt creation or retirement (`SESSION_END_LOCK_WAIT`, default 10 + seconds). + +Test: `tests/session-end-test.py` (unittest, runs only in the sandbox; every tool it calls is +a recording stub beside a copy of the command in a fixture tree, git runs through a wrapper +that fails the case on any writing subcommand, and a sentinel tree outside the fixture must +be byte-identical after every case). The guard rule's probes are in `hooks/guard-selftest.sh`. + ## `memory-index`, `memory-init`, `memory-init.ps1`: auto-memory `memory-init` (bash; `memory-init.ps1` on Windows) walks Claude Code's encoded @@ -298,7 +481,10 @@ frontmatter for three more jobs, all read-only: settings decide. A failure prints one notice line naming the indexes, never a partial block. It never writes anything and creates no pool. `--digest-fit ...` prints one row per pool (entries, described, by name - only, not shown) for a gate or an inventory script. + only, not shown) for a gate or an inventory script. `--pool-for [--cwd DIR] + [--ops DIR]` prints the existing pool the digest would show for a directory + (the same lookup, so `session-end` rebuilds the index the digest reads), exits + 4 with nothing on stdout when there is none, and creates nothing. - `--hint` reads a UserPromptSubmit payload on stdin and prints at most three `Relevant memory: : ` lines when the prompt strongly matches the names and descriptions of this directory's pool and the root diff --git a/.claude-config/bin/active-minutes b/.claude-config/bin/active-minutes new file mode 100755 index 0000000..de4b9f6 --- /dev/null +++ b/.claude-config/bin/active-minutes @@ -0,0 +1,499 @@ +#!/usr/bin/env python3 +"""Billable working minutes from a Claude session transcript. + +Two rules set the measure, and the code follows both. + + A silent stretch of 30 minutes or less between transcript events is working + time (the operator reads, takes a portal step, works the same task outside + the chat). A longer one is a candidate break, so it is classified, never + silently dropped. + + An interactive session counts its whole span, pauses included. A real break + needs evidence: the operator says so, or a long gap shows no work trace + anywhere. Unattended agent time counts like attended time. An unattended hold + (a usage limit, an overnight stop) is not work and needs evidence too: + counting a limit hold as work would bill hours in which nothing happened. + +So every gap over --gap seconds (default 1800) is classified by its evidence and +printed with its cause, COUNTED or EXCLUDED: + + COUNTED attended pause: the gap ends with a prompt the operator typed, and + lasted no longer than --attended-max hours (default 4). + COUNTED background task: the gap ends with a task notification whose task was + launched before the gap began, so agent work ran through it, and the + gap lasted no longer than --attended-max hours (default 4). + EXCLUDED usage-limit hold or other provider error: an API error record sits + just before the gap. + EXCLUDED operator-stated break: the last prompt before the gap, or the one + that ends it, says the operator was away ("brb", "going to lunch", + "I'm back"). + EXCLUDED idle until a harness message: a scheduled check, fleet notice, + context handoff, resume message, compact command or cross-thread + message ended the gap, so nobody is shown present. + EXCLUDED long attended pause: over --attended-max hours with no other + evidence (overnight, away). The 4 hours sit between the pauses + seen in practice (an hour or two while the operator works a console + or a report) and the stops that mean overnight or a weekend. The + line only decides counted versus listed; --keep overrides it with + evidence. + EXCLUDED long background-task gap: the same task notification, but the gap + is over --attended-max hours and nothing shows work inside it. A + launch record is not work: a watcher or an idle poll that exits the + next morning would otherwise bill the night (the measure bills work + that ran, not elapsed time). Work trace inside the gap (--also lane + transcripts, which fill the gap) or --keep with evidence counts it. + EXCLUDED no prompt evidence: nothing in the transcript says who ended it, or + the agent resumed with no prompt after the gap. A foreground tool + call that ran long, a permission wait and an unrecorded hold look the + same in a transcript and only the first is work, so the gap is + listed (with that said in its cause) until --also lane transcripts + or --keep give evidence. + +--also FILE... adds other transcripts (a thread's subagent and workflow lane +files) as work trace: an event in any of them inside a gap means work was +running, so the gap is not one. --keep ISO / --drop ISO force one gap (matched +by its UTC start, any prefix such as 2026-11-06T22:10) to COUNTED or EXCLUDED +when the operator gives evidence the transcript cannot see. --strict drops every +gap over --gap with no classification, for a session with no operator in it. + +Bill to the minute as decimal hours, two places; never round. + +The contiguous work blocks print in one display zone, each timestamp converted +on its own, so a block that spans a daylight-saving change prints each end with +that day's offset and a zone tag (EDT and EST, for example). The zone is +--zone NAME (an IANA name such as America/Chicago); without it, the TZ +environment variable if it names a valid zone, else the machine's own zone +(/etc/localtime), else UTC. A fixed offset read every block an hour late once the +zone changed its offset, and the windows go onto a time entry's Time line, so +they must be right. --tz-offset H is the explicit fixed-offset override; it +prints plain times with no zone tag and cannot be combined with --zone. If a +named zone cannot be loaded (a machine with no time zone database and no tzdata +package) the run prints one line and exits 2: pass --tz-offset H instead. The +ACTIVE total and the gap rule never depend on the display zone. + +--time-tool NAME says which tool call is the ticketing system's time-entry tool: +any tool whose name ends with NAME (default time_manage, so a namespaced name +such as mcp__server__group__time_manage matches) and whose input carries +mode "create" and the ticket it was filed against. --since-last-entry +--brief reads those calls. + +--since-last-entry --brief is the hook mode: one key=value line with the +unlogged minutes since this transcript's last time-entry create, the age of the +last create for --ticket (ticket_entry_age_min), and the age of the last create +naming a ticket in the other form, ticket number versus numeric id +(other_form_entry_age_min): it may be the same ticket, so a hook stays silent. + +Usage: + active-minutes [--gap SECONDS] [--attended-max HOURS] + [--since ISO] [--until ISO] [--zone NAME | --tz-offset H] [--also FILE ...] + [--keep ISO ...] [--drop ISO ...] [--strict] [--time-tool NAME] + [--since-last-entry [--ticket T] [--now ISO] --brief] + +Exit 0 ok; 1 too few timestamped events to measure; 2 a usage error or a zone +that cannot be loaded. +""" +import argparse, json, os, re, sys, datetime +from zoneinfo import ZoneInfo, ZoneInfoNotFoundError + +p = argparse.ArgumentParser() +p.add_argument("transcript") +p.add_argument("--gap", type=float, default=1800.0, help="seconds of silence above which a gap is classified instead of counted (default 1800 = 30 min)") +p.add_argument("--attended-max", type=float, default=4.0, help="hours an attended pause may last and still count without other evidence (default 4)") +p.add_argument("--since", default=None, help="ignore events before this ISO time (no offset = UTC)") +p.add_argument("--until", default=None, help="ignore events after this ISO time (no offset = UTC)") +zone_group = p.add_mutually_exclusive_group() +zone_group.add_argument("--zone", default=None, metavar="NAME", help="IANA time zone for the block display, converted per timestamp so it follows daylight saving (default: $TZ if it names a valid zone, else the machine's zone, else UTC)") +zone_group.add_argument("--tz-offset", type=float, default=None, help="fixed hours from UTC for the block display (e.g. -5), no zone tag; overrides the zone default") +p.add_argument("--also", nargs="*", default=[], metavar="FILE", help="other transcripts (subagent and workflow lanes) whose events count as work trace; put after the transcript") +p.add_argument("--keep", action="append", default=[], metavar="ISO", help="count the gap whose UTC start begins with this text (evidence the transcript cannot see)") +p.add_argument("--drop", action="append", default=[], metavar="ISO", help="exclude the gap whose UTC start begins with this text (the operator said it was a break)") +p.add_argument("--strict", action="store_true", help="exclude every gap over --gap with no classification (no operator in the session)") +p.add_argument("--time-tool", default="time_manage", metavar="NAME", help="the ticketing system's time-entry tool: any tool name ending with NAME (default time_manage)") +p.add_argument("--since-last-entry", action="store_true", help="measure from this transcript's last time-entry create (hook mode)") +p.add_argument("--ticket", default=None, help="with --since-last-entry: report the age of the last time create for this ticket") +p.add_argument("--now", default=None, help="with --since-last-entry: the clock to age entries against (ISO, default the real clock)") +p.add_argument("--brief", action="store_true", help="with --since-last-entry: print one key=value line only") +# Transcript pool directories are named after the working directory path, like +# -home-user-project, so a path relative to ~/.claude/projects starts with "-" +# and argparse reads it as an option (usage error). Pin any argument that is an +# existing file to ./ first. +a = p.parse_args(["./" + x if x.startswith("-") and os.path.isfile(x) else x + for x in sys.argv[1:]]) +if a.brief and not a.since_last_entry: + p.error("--brief needs --since-last-entry") +# An empty name ends every tool name, so every call would read as a time entry. +if not a.time_tool.strip(): + p.error("--time-tool: need a tool name, got an empty one") +TIME_TOOL = a.time_tool.strip() + +def parse(t): + # Transcript stamps are UTC. A naive time is read as UTC too, because + # comparing naive with aware datetimes raises TypeError. + try: dt = datetime.datetime.fromisoformat(str(t).replace("Z", "+00:00")) + except Exception: return None + return dt if dt.tzinfo else dt.replace(tzinfo=datetime.timezone.utc) + +def bound(name, value): + # An unparseable bound must stop the run: silently dropping it would + # measure the whole transcript and bill the wrong window. + if not value: return None + dt = parse(value) + if dt is None: p.error(f"--{name}: not an ISO time: {value!r}") + return dt + +since = bound("since", a.since) +until = bound("until", a.until) +now = bound("now", a.now) or datetime.datetime.now(datetime.timezone.utc) + +# Display zone. Default: --zone, else the TZ variable when it names a loadable +# zone, else the machine's own zone, else UTC, converted per timestamp. An +# explicit --tz-offset is a fixed zone with no tag. Every failure stops the run +# with one line: printing blocks in some other zone would put wrong windows on a +# time entry. Checked before the transcript is read, so a bad option exits 2 +# whatever the transcript holds. +def stop(message): + print("active-minutes: " + message, file=sys.stderr) + sys.exit(2) + +def tz_database_missing(): + """True when the machine has no IANA zone data at all (no system database and + no tzdata package), so no named zone can load. UTC is in every database.""" + try: ZoneInfo("UTC") + except (ZoneInfoNotFoundError, ValueError, OSError): return True + return False + +def named_zone(name, source): + try: return ZoneInfo(name) + except (ZoneInfoNotFoundError, ValueError, OSError) as e: + if tz_database_missing(): + stop("no time zone database on this machine, so %s %r cannot load (%s); install the tzdata package, or pass --tz-offset H for a fixed offset" % (source, name, e)) + return None + +def machine_zone(): + """(zone, label) of the machine's own zone from /etc/localtime, or None.""" + try: + with open("/etc/localtime", "rb") as fh: zone = ZoneInfo.from_file(fh) + except (OSError, ValueError): return None + label = "system local time" + try: + target = os.readlink("/etc/localtime") + if "zoneinfo/" in target: label = target.split("zoneinfo/", 1)[1] + except OSError: pass + return zone, label + +if a.tz_offset is not None: + try: zone = datetime.timezone(datetime.timedelta(hours=a.tz_offset)) + except (ValueError, OverflowError): p.error("--tz-offset: need hours strictly between -24 and 24, got %r" % a.tz_offset) + zone_label, stamp = "tz-offset %+g" % a.tz_offset, "%m-%d %H:%M" +else: + zone = zone_label = None + if a.zone is not None: + zone = named_zone(a.zone, "--zone") + if zone is None: stop("--zone: no such time zone %r" % a.zone) + zone_label = a.zone + else: + env_tz = os.environ.get("TZ", "").strip().lstrip(":") + if env_tz: + zone = named_zone(env_tz, "TZ") + if zone is not None: zone_label = env_tz + if zone is None: + found = machine_zone() + if found is not None: zone, zone_label = found + if zone is None: zone, zone_label = datetime.timezone.utc, "UTC" + stamp = "%m-%d %H:%M %Z" +# The %Z tag also tells apart the two 01:xx hours of a fall-back night, which +# print the same wall-clock time an hour apart. +def loc(t): return t.astimezone(zone).strftime(stamp) + +# --- classifying one record ------------------------------------------------- + +# Prompts the harness sends into a thread as if the operator typed them. The +# list is deliberately short: an unknown prompt is read as the operator's, and +# every gap line quotes the prompt that ended it, so a miss shows on the Time +# line instead of hiding. Each shape is one OPS or T3 itself produces or its +# prompt filter (memory-index) already names. +HARNESS = [ + (re.compile(r"^\s*\s*(toolu_[A-Za-z0-9_]+)\s*") + +def content_text(d): + c = (d.get("message") or {}).get("content") + if isinstance(c, str): return c + if isinstance(c, list): + return " ".join(x.get("text", "") for x in c if isinstance(x, dict) and x.get("type") == "text") + return "" + +def prompt_text(d): + """Text of a prompt-like record (None for anything else). A prompt arrives as + a queue-operation enqueue (T3), a user message, or both.""" + t = d.get("type") + if t == "queue-operation": + if d.get("operation") == "enqueue" and str(d.get("content") or "").strip(): return str(d["content"]) + return None + if t != "user" or d.get("isSidechain") or d.get("isMeta") or "toolUseResult" in d: return None + c = (d.get("message") or {}).get("content") + if isinstance(c, list): + if any(isinstance(x, dict) and x.get("type") == "tool_result" for x in c): return None + txt = content_text(d).strip() + if txt: return txt + return "[attachment]" if any(isinstance(x, dict) and x.get("type") in ("image", "document") for x in c) else None + txt = content_text(d).strip() + return txt or None + +def harness_kind(text, d): + # A compaction summary is written by the harness into the user role. + if d.get("isCompactSummary") or d.get("isVisibleInTranscriptOnly"): return "compaction summary" + for rx, label in HARNESS: + if rx.search(text): return label + if d.get("promptSource") == "system": return "system message" + return None + +def one_line(s, n=70): + s = " ".join(str(s).split()) + return (s[:n - 1] + "...") if len(s) > n else s + +class Ev: + __slots__ = ("ts", "kind", "text", "label", "err", "tool_ids", "launches") + def __init__(self, ts, kind="event", text="", label="", err="", tool_ids=(), launches=()): + self.ts, self.kind, self.text, self.label, self.err = ts, kind, text, label, err + self.tool_ids, self.launches = tool_ids, launches + +def read_events(path, main): + """Every timestamped record. In the main transcript each is classified (human + prompt, harness prompt, API error, assistant, plain); an --also file only + adds trace.""" + out = [] + failed_creates = set() + with open(path) as fh: + for line in fh: + line = line.strip() + if not line: continue + try: d = json.loads(line) + except Exception: continue + if not isinstance(d, dict): continue + t = d.get("timestamp") or d.get("ts") + if not t: continue + dt = parse(t) + if dt is None: continue + if since and dt < since: continue + if until and dt > until: continue + if not main: + out.append(Ev(dt, "trace")); continue + pt = prompt_text(d) + if pt is not None: + hk = harness_kind(pt, d) + out.append(Ev(dt, "harness" if hk else "human", pt, hk or "")) + elif d.get("isApiErrorMessage"): + out.append(Ev(dt, "api_error", content_text(d), err=str(d.get("error") or ""))) + else: + tids, launches = [], [] + c = (d.get("message") or {}).get("content") + if d.get("type") == "user" and isinstance(c, list): + failed_creates.update(x.get("tool_use_id") for x in c + if isinstance(x, dict) and x.get("type") == "tool_result" and x.get("is_error")) + if d.get("type") == "assistant" and isinstance(c, list): + for x in c: + if isinstance(x, dict) and x.get("type") == "tool_use": + tids.append(x.get("id")) + if str(x.get("name", "")).endswith(TIME_TOOL) and isinstance(x.get("input"), dict) and x["input"].get("mode") == "create": + ticket = str(x["input"].get("ticket") or "").strip() + if ticket: + launches.append((x.get("id"), ticket)) + out.append(Ev(dt, "assistant" if d.get("type") == "assistant" else "event", tool_ids=tuple(tids), launches=tuple(launches))) + # An explicitly failed create is not logged time. Keep that work in the + # unlogged window instead of suppressing the reminder that it still needs billing. + for e in out: + e.launches = tuple(ticket for tool_id, ticket in e.launches if tool_id not in failed_creates) + return out + +ev = read_events(a.transcript, True) +for extra in a.also: + try: ev += read_events(extra, False) + except OSError as e: p.error("--also %s: %s" % (extra, e)) + +def ticket_form(t): + """How a ticket is named: the ticket number (the letter T, eight digits, a dot, then digits) or the numeric + id (12345). A ticketing tool may accept either, so one ticket can appear in + both forms in one thread and a string compare cannot tell they are the same.""" + t = str(t).strip() + if re.fullmatch(r"T\d{8}\.\d+", t, re.I): return "number" + return "id" if t.isdigit() else "other" + +def same_ticket(x, y): return str(x).strip().upper() == str(y).strip().upper() + +# Hook mode: measure from the last time create in this transcript. +# ticket_entry: the latest create naming this ticket in the same form. +# other_form_entry: the latest create naming a ticket in the OTHER form. It might +# be the same ticket, which this script cannot tell (it makes no ticketing +# lookup), so a hook reads it as "may already be logged" and stays silent +# instead of claiming no entry exists. +last_entry = ticket_entry = other_form_entry = None +if a.since_last_entry: + for e in ev: + if e.launches: + last_entry = e.ts if last_entry is None or e.ts > last_entry else last_entry + if a.ticket is not None and str(a.ticket).strip(): + if any(same_ticket(a.ticket, l) for l in e.launches): + ticket_entry = e.ts if ticket_entry is None or e.ts > ticket_entry else ticket_entry + elif any(l.strip() and ticket_form(l) != ticket_form(a.ticket) for l in e.launches): + other_form_entry = e.ts if other_form_entry is None or e.ts > other_form_entry else other_form_entry + if last_entry is not None: + ev = [e for e in ev if e.ts >= last_entry] + +def age_min(t): return "%.1f" % ((now - t).total_seconds() / 60) if t else "none" + +if len(ev) < 2: + if a.brief: + print("unlogged_min=0.0 window_start=none last_entry=%s ticket_entry_age_min=%s other_form_entry_age_min=%s" % ( + last_entry.isoformat() if last_entry else "none", age_min(ticket_entry), age_min(other_form_entry))) + sys.exit(0) + print("not enough timestamped events to measure", file=sys.stderr) + sys.exit(1) + +ev.sort(key=lambda e: e.ts) +ts = [e.ts for e in ev] +span = (ts[-1] - ts[0]).total_seconds() + +# Fast lookups the gap rules need. +launch_ts = {} # tool_use id -> when this transcript recorded the call +last_human = [] # per event index: the latest human prompt at or before it +cur = None +for i, e in enumerate(ev): + for tid in e.tool_ids: launch_ts.setdefault(tid, e.ts) + if e.kind == "human": cur = e + last_human.append(cur) + +def ending_prompt(i): + """The first prompt, or an unprompted assistant record, within two minutes + after the gap ends (hook and queue records can sit between the two).""" + start = ev[i + 1].ts + for j in range(i + 1, len(ev)): + if (ev[j].ts - start).total_seconds() > 120: break + if ev[j].kind in ("human", "harness", "assistant"): return ev[j] + return None + +def api_error_before(i): + """The API error that ended the turn before the gap, if the last substantive + record at or before ev[i] is one. An error followed by any prompt or agent + output is a retry, not a hold, so older errors never excuse a later gap.""" + for j in range(i, -1, -1): + if ev[j].kind == "api_error": return ev[j] + if ev[j].kind in ("human", "harness", "assistant"): return None + return None + +def classify(i): + """(counted, cause) for the gap between ev[i] and ev[i+1].""" + x, y = ev[i], ev[i + 1] + d = (y.ts - x.ts).total_seconds() + iso = x.ts.astimezone(datetime.timezone.utc).isoformat() + for k in a.keep: + if iso.startswith(k): return True, "kept: the operator gave evidence of work (--keep %s)" % k + for k in a.drop: + if iso.startswith(k): return False, "dropped: the operator gave evidence of a break (--drop %s)" % k + err = api_error_before(i) + if err is not None: + if err.err == "rate_limit" or LIMIT.search(err.text): + return False, 'usage-limit hold: "%s" ended the turn before the gap' % one_line(err.text) + return False, "provider error hold (%s) ended the turn before the gap" % (err.err or "api error") + end = ending_prompt(i) + h = last_human[i] + if h is not None and (x.ts - h.ts).total_seconds() <= BREAK_BEFORE_WINDOW: + m = BREAK_BEFORE.search(h.text.replace("’", "'")) + if m: return False, 'operator-stated break before the gap: "%s"' % one_line(h.text) + if end is not None and end.kind == "human": + if BREAK_AFTER.search(end.text.replace("’", "'")): + return False, 'operator-stated break, said when the operator returned: "%s"' % one_line(end.text) + if end is None: + return False, "no prompt evidence: nothing in the transcript says who ended the gap" + if end.kind == "assistant": + # A foreground tool call that ran past 30 minutes, a permission wait and + # an unrecorded hold all leave this same shape (a call, then its result, + # nothing between), and only the first is work. Counting it would bill + # holds, which the measure forbids, so it stays listed; the cause names + # what it could be so the Time line is not misleading, and --also or + # --keep settles it. + return False, "no prompt evidence: the agent resumed with no prompt after the gap (a long tool call, a permission wait or an unrecorded hold look the same here): pass the lane transcripts with --also, or --keep with evidence" + if end.kind == "harness": + if end.label == "task notification": + m = TOOL_USE_ID.search(end.text) + launched = launch_ts.get(m.group(1)) if m else None + if launched is not None and launched <= x.ts: + # A launch record proves a task started, not that it worked all + # night. Past the attended ceiling the gap needs work trace inside + # it (--also lane files fill the gap, so it never gets here) or + # the operator's --keep; the measure bills work that ran, not + # elapsed time. + if d > a.attended_max * 3600: + return False, "background task launched %s, but the gap is over %g h and nothing in the transcript shows work inside it (a launch record is not work): pass the lane transcripts with --also, or --keep with evidence" % (loc(launched), a.attended_max) + return True, "background task: launched %s, still running through the gap, finished at its end (unattended agent work counts)" % loc(launched) + return False, "task notification ended the gap but its launch is not in this transcript: pass the lane transcripts with --also, or --keep with evidence" + return False, "idle until %s (nobody shown present): \"%s\"" % (end.label, one_line(end.text, 50)) + if d > a.attended_max * 3600: + return False, 'attended pause over %g h with no other evidence (overnight or away): next prompt "%s"' % (a.attended_max, one_line(end.text, 50)) + return True, 'attended pause: the operator typed next ("%s"), assumed working' % one_line(end.text, 50) + +active = 0.0 +gaps = [] # (start, end, seconds, counted, cause) +for i, (x, y) in enumerate(zip(ev, ev[1:])): + d = (y.ts - x.ts).total_seconds() + if d <= a.gap: + active += d + continue + if a.strict: + counted, cause = False, "--strict: every gap over %d min is excluded" % (a.gap // 60) + else: + counted, cause = classify(i) + if counted: active += d + gaps.append((x.ts, y.ts, d, counted, cause)) +excluded = [g for g in gaps if not g[3]] +counted = [g for g in gaps if g[3]] + +if a.brief: + print("unlogged_min=%.1f window_start=%s last_entry=%s ticket_entry_age_min=%s other_form_entry_age_min=%s" % ( + active / 60, ts[0].isoformat(), last_entry.isoformat() if last_entry else "none", + age_min(ticket_entry), age_min(other_form_entry))) + sys.exit(0) + +print("events : %d" % len(ts)) +print("first (UTC) : %s" % ts[0].isoformat()) +print("last (UTC) : %s" % ts[-1].isoformat()) +print("raw span : %.1f min (%.2f h)" % (span/60, span/3600)) +# Truncate the billing display: %.2f alone rounds 40 minutes up to 0.67 hours. +# Keep the measured minutes and higher-precision hours beside it as evidence. +billable_hundredths = int(active // 36) +print("ACTIVE (bill this): %.1f min = %.4f h -> %.2f h" % (active/60, active/3600, billable_hundredths/100)) +print("counted gaps : %d, total %.1f min" % (len(counted), sum(g[2] for g in counted)/60)) +print("excluded gaps : %d, total %.1f min" % (len(excluded), sum(g[2] for g in excluded)/60)) + +if gaps: + print("\ngaps over %d min, each with its cause (UTC start for --keep and --drop):" % (a.gap // 60)) + for s, e, d, c, cause in gaps: + print(" %-8s %7.1f min %s -> %s [%s] %s" % ("COUNTED" if c else "EXCLUDED", d/60, loc(s), loc(e), s.astimezone(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M"), cause)) + +print("\ncontiguous work blocks (%s):" % zone_label) +segstart = ts[0] +for s, e, d, c, cause in excluded: + print(" %s -> %s (%.1f min)" % (loc(segstart), loc(s), (s-segstart).total_seconds()/60)) + segstart = e +print(" %s -> %s (%.1f min)" % (loc(segstart), loc(ts[-1]), (ts[-1]-segstart).total_seconds()/60)) diff --git a/.claude-config/bin/asks b/.claude-config/bin/asks new file mode 100755 index 0000000..c6645ce --- /dev/null +++ b/.claude-config/bin/asks @@ -0,0 +1,571 @@ +#!/usr/bin/env python3 +"""asks: the per-thread register of what is waiting on the box's owner. + +An Operator who runs several threads at once should not have to poll each one +for status and decisions. Each thread writes what it needs from the Operator +here, one line per ask, and anything that reads the register shows every +thread's open asks in one place. + + asks add "" [--thread ID] [--why TEXT] [--rec TEXT] + [--default TEXT] [--kind decision|console|action] [--title TEXT] + [--owner TEXT] [--deadline YYYY-MM-DD] [--client NAME] + console asks (steps only a person can do in a vendor's web console): + [--tool NAME] [--step TEXT]... [--paste TEXT|@FILE|-] + [--expect TEXT] [--link URL] + asks list [--all | --thread ID] [--json] [--resolved] + asks resolve [--thread ID] [--note TEXT] + asks prune [--days N] + +Who reads it: `asks list` (with --json for a script) and `session-end`, which +lists the thread's open asks at every ending. Nothing else in OPS reads these files. + +Where it lives: one JSON file per thread under +${OPS_STATE_DIR:-~/.local/state/ops}/asks/. The thread defaults to +$ASKS_THREAD, else $T3CODE_THREAD_ID (a lane inherits its foreman's id, so a +lane's asks land on the thread the Operator actually reads). Files are mode +0600 in a 0700 directory: an ask can name a client. + +Kinds. `decision` (default) is a question with a recommendation; `action` is +something only the Operator can click or send; `console` is a step that only a +person can take in a vendor's own web console because the vendor offers no +write API for it. Console asks carry their steps and the full paste text, so +the Operator can do every console step in one sitting instead of one script per +chat message. + +Why a file and not a hook: a thread may stop without ever running a closing +step, so a register written only at the end of a session would be empty for +the threads the Operator most needs to see. Each thread writes as it goes. + +An ask with the same text, kind and thread as an open one updates it instead +of adding a duplicate, so a thread that re-runs its closing step after a +compaction stays idempotent. Resolved asks are kept 14 days, then pruned. + +Platform: the register is locked with fcntl, which only POSIX Python has. On a +platform without it (native Windows) the command prints one line and exits 1 +rather than crash; run it under WSL or on a Linux or macOS box. + +Exit 0 ok; 1 a register file could not be read or written, or the platform has +no fcntl; 2 usage error or a refused input (a secret-shaped value is never +stored: the ask, every add field, --title, --thread and resolve --note are all +checked). +""" + +import argparse +import datetime +import hashlib +import json +import os +import re +import sys +import tempfile + +try: + import fcntl +except ImportError: + print("asks: this platform's Python has no fcntl, which the register lock needs; " + "run asks on Linux, macOS or WSL", file=sys.stderr) + sys.exit(1) + +VERSION = 1 +KINDS = ("decision", "action", "console") +KEEP_RESOLVED_DAYS = 14 +MAX_ASK = 400 +MAX_FIELD = 1200 +MAX_STEP = 600 +MAX_PASTE = 64 * 1024 +MAX_ASKS_PER_THREAD = 200 + +UUID = re.compile(r"^(?:mcp:)?([0-9a-f]{8})-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$") +REF = re.compile(r"^(.+)#(\d+)$") + +# High-precision credential shapes only. A paste kit legitimately names +# parameters such as "password", so a keyword match would refuse real scripts; +# these match the value shapes that should never reach a register (the register +# is shown in chats and may be synced). +SECRET_SHAPES = ( + ("private key block", re.compile(r"-----BEGIN [A-Z ]*PRIVATE KEY-----")), + ("GitHub token", re.compile(r"\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{30,}|\bgithub_pat_[A-Za-z0-9_]{30,}")), + ("Anthropic or OpenAI key", re.compile(r"\bsk-(?:ant-)?[A-Za-z0-9_-]{24,}")), + ("AWS access key id", re.compile(r"\bAKIA[0-9A-Z]{16}\b")), + ("Slack token", re.compile(r"\bxox[abprs]-[A-Za-z0-9-]{10,}")), + ("JSON web token", re.compile(r"\beyJ[A-Za-z0-9_-]{8,}\.eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}")), +) + + +class AsksError(Exception): + """A refused input or an unreadable register; main turns it into an exit code.""" + + def __init__(self, message, code=2): + super().__init__(message) + self.code = code + + +# --- paths and time ----------------------------------------------------------- + +def asks_dir(): + base = os.environ.get("OPS_STATE_DIR") or os.path.join(os.path.expanduser("~"), ".local", "state", "ops") + return os.path.join(base, "asks") + + +def now(): + # ASKS_NOW is a test seam: the suite pins the clock to prove the retention rule. + raw = os.environ.get("ASKS_NOW") + if raw: + return datetime.datetime.fromisoformat(raw) + return datetime.datetime.now().astimezone() + + +def current_thread(): + return (os.environ.get("ASKS_THREAD") or os.environ.get("T3CODE_THREAD_ID") or "").strip() + + +def file_name(thread): + """A filename for any thread id. Subagent ids carry ':' and '%' and can be + longer than a filesystem allows, so anything that is not a plain safe id + gets a hash suffix; the full id is stored inside the file.""" + safe = re.sub(r"[^A-Za-z0-9._-]", "_", thread) + if safe != thread or len(safe) > 80 or safe.startswith("."): + digest = hashlib.sha1(thread.encode("utf-8")).hexdigest()[:12] + safe = "%s-%s" % (safe.lstrip(".")[:40] or "thread", digest) + return safe + ".json" + + +def short_id(thread): + m = UUID.match(thread) + if m: + return ("mcp:" if thread.startswith("mcp:") else "") + m.group(1) + if thread.startswith("thread:"): + return "lane:" + hashlib.sha1(thread.encode("utf-8")).hexdigest()[:8] + return thread[:12] + + +# --- text hygiene ------------------------------------------------------------- + +def one_line(value, limit, label): + text = re.sub(r"\s+", " ", value or "").strip() + if len(text) > limit: + raise AsksError("%s is %d characters; the limit is %d (keep an ask to one line, put detail in --why)" + % (label, len(text), limit)) + return text + + +def refuse_secrets(label, value): + for name, pattern in SECRET_SHAPES: + if pattern.search(value or ""): + raise AsksError("%s looks like it holds a %s; the register is shown in chats and may be synced, " + "so put the value in your secrets store or the console and name it instead" % (label, name)) + + +def read_paste(spec): + if spec is None: + return None + if spec == "-": + data = sys.stdin.read() + elif spec.startswith("@"): + try: + with open(spec[1:], encoding="utf-8") as fh: + data = fh.read() + except (OSError, UnicodeDecodeError) as exc: + raise AsksError("cannot read paste file %s: %s" % (spec[1:], getattr(exc, "strerror", None) or exc)) + else: + data = spec + data = data.replace("\r\n", "\n").strip("\n") + if len(data.encode("utf-8")) > MAX_PASTE: + raise AsksError("the paste text is over %d KB; split it into one console ask per script" % (MAX_PASTE // 1024)) + return data or None + + +# --- storage ------------------------------------------------------------------ + +class Store: + """The asks directory with one lock for every read-modify-write.""" + + def __init__(self, path=None): + self.path = path or asks_dir() + + def _ensure(self): + try: + os.makedirs(self.path, mode=0o700, exist_ok=True) + except OSError as exc: + raise AsksError("cannot create %s: %s" % (self.path, exc.strerror or exc), 1) + + def locked(self): + store = self + + class _Lock: + def __enter__(self): + store._ensure() + self.fd = os.open(os.path.join(store.path, ".lock"), os.O_CREAT | os.O_RDWR, 0o600) + fcntl.flock(self.fd, fcntl.LOCK_EX) + return store + + def __exit__(self, *exc): + try: + fcntl.flock(self.fd, fcntl.LOCK_UN) + finally: + os.close(self.fd) + + return _Lock() + + def read_all(self): + """(docs, errors). A missing directory is an empty register; a file that + cannot be read or parsed is an error that names it, never an empty list.""" + docs, errors = [], [] + try: + names = sorted(os.listdir(self.path)) + except FileNotFoundError: + return docs, errors + except OSError as exc: + return docs, ["cannot list %s: %s" % (self.path, exc.strerror or exc)] + for name in names: + if name.startswith(".") or not name.endswith(".json"): + continue + doc, err = self._read_one(os.path.join(self.path, name), name) + if err: + errors.append(err) + else: + docs.append(doc) + return docs, errors + + @staticmethod + def _read_one(path, name): + try: + with open(path, encoding="utf-8") as fh: + doc = json.load(fh) + except OSError as exc: + return None, "cannot read asks/%s: %s" % (name, exc.strerror or exc) + except (ValueError, UnicodeDecodeError) as exc: + return None, "asks/%s is not valid JSON: %s" % (name, exc) + if (not isinstance(doc, dict) or not isinstance(doc.get("thread"), str) or not doc["thread"] + or not isinstance(doc.get("asks"), list)): + return None, "asks/%s has no thread id or asks list" % name + for ask in doc["asks"]: + if not isinstance(ask, dict) or not isinstance(ask.get("n"), int) or not isinstance(ask.get("text"), str): + return None, "asks/%s holds an ask without a number and text" % name + doc["_file"] = name + return doc, None + + def load(self, thread): + """The document for THREAD (a fresh one when none exists yet).""" + path = os.path.join(self.path, file_name(thread)) + if not os.path.lexists(path): + return {"version": VERSION, "thread": thread, "title": "", "next": 1, "asks": [], "_file": file_name(thread)} + doc, err = self._read_one(path, file_name(thread)) + if err: + raise AsksError(err, 1) + return doc + + def save(self, doc): + self._ensure() + out = {k: v for k, v in doc.items() if not k.startswith("_")} + out["version"] = VERSION + text = json.dumps(out, indent=1, ensure_ascii=False) + "\n" + path = os.path.join(self.path, file_name(doc["thread"])) + fd, tmp = tempfile.mkstemp(prefix=".ask.", suffix=".tmp", dir=self.path) + 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, path) + except BaseException: + try: + os.unlink(tmp) + except OSError: + pass + raise + + def prune(self, moment, days=KEEP_RESOLVED_DAYS): + """Drop resolved asks older than DAYS, retaining each thread's next number. + Returns the number of asks dropped. Caller holds the lock.""" + dropped = 0 + docs, errors = self.read_all() + if errors: + # A failed read cannot stand in for an empty register, including + # during the automatic prune an add performs. + raise AsksError("; ".join(errors), 1) + for doc in docs: + keep = [] + for ask in doc["asks"]: + when = parse_stamp(ask.get("resolved")) + if when is not None and (moment - when).days >= days: + dropped += 1 + else: + keep.append(ask) + if len(keep) == len(doc["asks"]): + continue + # Keep the counter even after the last ask expires: reusing #1 + # would let an old reference resolve a different, new question. + doc["asks"] = keep + self.save(doc) + return dropped + + +def parse_stamp(value): + if not value: + return None + try: + d = datetime.datetime.fromisoformat(str(value).replace("Z", "+00:00")) + except ValueError: + return None + return d if d.tzinfo is not None else d.astimezone() + + +def open_asks(docs): + """Every unresolved ask of every document, each with its thread attached.""" + out = [] + for doc in docs: + for ask in doc["asks"]: + if ask.get("resolved"): + continue + item = dict(ask) + item["thread"] = doc["thread"] + item["thread_title"] = doc.get("title") or "" + item["ref"] = "%s#%d" % (short_id(doc["thread"]), ask["n"]) + out.append(item) + return out + + +# --- commands ----------------------------------------------------------------- + +def cmd_add(args): + thread = (args.thread or current_thread()).strip() + fallback = False + if not thread: + thread, fallback = "adhoc", True + text = one_line(args.text, MAX_ASK, "the ask") + if not text: + raise AsksError("the ask is empty") + fields = { + "why": one_line(args.why, MAX_FIELD, "--why"), + "rec": one_line(args.rec, MAX_FIELD, "--rec"), + "default": one_line(args.default, MAX_FIELD, "--default"), + "owner": one_line(args.owner, MAX_FIELD, "--owner"), + "client": one_line(args.client, 200, "--client"), + "tool": one_line(args.tool, 200, "--tool"), + "expect": one_line(args.expect, MAX_FIELD, "--expect"), + "link": one_line(args.link, 1000, "--link"), + } + if fields["link"] and not re.match(r"^https?://", fields["link"]): + raise AsksError("--link must be an http or https URL") + steps = [one_line(s, MAX_STEP, "--step") for s in (args.step or [])] + steps = [s for s in steps if s] + paste = read_paste(args.paste) + deadline = None + if args.deadline: + try: + deadline = datetime.date.fromisoformat(args.deadline).isoformat() + except ValueError: + raise AsksError("--deadline must be YYYY-MM-DD") + kind = args.kind or ("console" if (fields["tool"] or steps or paste) else "decision") + if kind == "console" and not (fields["tool"] or steps or paste): + raise AsksError("a console ask needs --tool, at least one --step or a --paste text") + title = one_line(args.title, 200, "--title") + # Every text input is checked before the lock or any write. The thread id is + # included because it becomes the file name, and the title because a page that + # lists the register shows it when the thread has no other title. + for label, value in [("the ask", text), ("--thread", thread), ("--title", title)] + \ + [("--" + k, v) for k, v in fields.items()] + \ + [("--step", s) for s in steps] + [("--paste", paste or "")]: + refuse_secrets(label, value) + + moment = now() + stamp = moment.isoformat(timespec="seconds") + with Store().locked() as store: + store.prune(moment) + doc = store.load(thread) + if title: + doc["title"] = title + existing = next((a for a in doc["asks"] + if not a.get("resolved") and a["text"] == text and a.get("kind", "decision") == kind), None) + values = dict(fields, kind=kind, text=text, steps=steps, paste=paste, deadline=deadline) + if existing is not None: + # A re-add refreshes the detail, but a field the re-add leaves empty keeps its value. + for key, value in values.items(): + if value not in (None, "", []): + existing[key] = value + existing["updated"] = stamp + n, verb = existing["n"], "updated" + else: + open_count = sum(1 for a in doc["asks"] if not a.get("resolved")) + if open_count >= MAX_ASKS_PER_THREAD: + raise AsksError("this thread already has %d open asks; resolve some first" % open_count) + n = doc.get("next", 1) + if any(a["n"] >= n for a in doc["asks"]): + n = max(a["n"] for a in doc["asks"]) + 1 + ask = dict(values, n=n, created=stamp, updated=stamp, resolved=None, note=None) + doc["asks"].append(ask) + doc["next"] = n + 1 + verb = "added" + doc["updated"] = stamp + store.save(doc) + where = "thread %s" % short_id(thread) + if fallback: + print("asks: no thread id (T3CODE_THREAD_ID is unset); filed under 'adhoc'", file=sys.stderr) + print("asks: %s #%d (%s) for %s" % (verb, n, kind, where)) + return 0 + + +def select_docs(docs, args): + if args.thread: + want = args.thread.strip() + picked = [d for d in docs if d["thread"] == want or d["thread"].startswith(want) or short_id(d["thread"]) == want] + return picked + if args.all: + return docs + thread = current_thread() + if not thread: + return docs + return [d for d in docs if d["thread"] == thread] + + +def cmd_list(args): + store = Store() + docs, errors = store.read_all() + for err in errors: + print("asks: " + err, file=sys.stderr) + chosen = select_docs(docs, args) + items = [] + for doc in chosen: + for ask in doc["asks"]: + if bool(ask.get("resolved")) != bool(args.resolved): + continue + item = dict(ask) + item["thread"] = doc["thread"] + item["thread_title"] = doc.get("title") or "" + item["ref"] = "%s#%d" % (short_id(doc["thread"]), ask["n"]) + items.append(item) + items.sort(key=lambda i: (i.get("created") or "", i["thread"], i["n"])) + if args.json: + sys.stdout.write(json.dumps(items, indent=1, ensure_ascii=False) + "\n") + return 1 if errors else 0 + if not items: + scope = "this thread" if not (args.all or args.thread) and current_thread() else "the register" + print("asks: nothing %s in %s" % ("resolved" if args.resolved else "open", scope)) + return 1 if errors else 0 + last = None + for item in items: + if item["thread"] != last: + last = item["thread"] + title = " (%s)" % item["thread_title"] if item["thread_title"] else "" + print("thread %s%s" % (short_id(last), title)) + stamp = (item.get("created") or "")[:10] + print(" %s %-8s %s %s" % (item["ref"], item.get("kind", "decision"), stamp, item["text"])) + for label, key in (("why", "why"), ("recommend", "rec"), ("if no answer", "default"), + ("owner", "owner"), ("client", "client"), ("deadline", "deadline"), + ("tool", "tool"), ("expect", "expect"), ("link", "link")): + if item.get(key): + print(" %s: %s" % (label, item[key])) + for i, step in enumerate(item.get("steps") or [], 1): + print(" step %d: %s" % (i, step)) + if item.get("paste"): + print(" paste: %d lines (use --json to read the text)" % (item["paste"].count("\n") + 1)) + if item.get("resolved"): + print(" resolved: %s%s" % (item["resolved"], " (%s)" % item["note"] if item.get("note") else "")) + return 1 if errors else 0 + + +def find_ref(docs, ref, thread_flag): + """(doc, ask) for a ref: 'N' on the current or --thread thread, or 'THREAD#N'.""" + m = REF.match(ref) + if m: + want, n = m.group(1), int(m.group(2)) + pool = [d for d in docs if d["thread"] == want or d["thread"].startswith(want) or short_id(d["thread"]) == want] + elif ref.isdigit(): + n = int(ref) + want = (thread_flag or current_thread()).strip() + if not want: + raise AsksError("no thread: pass THREAD#N, --thread, or run it where T3CODE_THREAD_ID is set") + 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) + if len(pool) > 1: + raise AsksError("'%s' matches %d threads; use more of the thread id" % (ref, len(pool))) + if not pool: + raise AsksError("no thread matches '%s'" % ref, 1) + for ask in pool[0]["asks"]: + if ask["n"] == n: + return pool[0], ask + raise AsksError("thread %s has no ask #%d" % (short_id(pool[0]["thread"]), n), 1) + + +def cmd_resolve(args): + moment = now() + note = one_line(args.note, MAX_FIELD, "--note") or None + refuse_secrets("--note", note) # shown by `asks list --resolved`, so it gets the same refusal as an ask + with Store().locked() as store: + docs, errors = store.read_all() + if errors: + raise AsksError("; ".join(errors), 1) + doc, ask = find_ref(docs, args.ref, args.thread) + if ask.get("resolved"): + print("asks: %s#%d was already resolved %s" % (short_id(doc["thread"]), ask["n"], ask["resolved"])) + return 0 + ask["resolved"] = moment.isoformat(timespec="seconds") + ask["note"] = note + doc["updated"] = ask["resolved"] + store.save(doc) + store.prune(moment) + print("asks: resolved %s#%d" % (short_id(doc["thread"]), ask["n"])) + return 0 + + +def cmd_prune(args): + with Store().locked() as store: + dropped = store.prune(now(), args.days) + print("asks: pruned %d resolved ask%s older than %d days" % (dropped, "" if dropped == 1 else "s", args.days)) + return 0 + + +def build_parser(): + ap = argparse.ArgumentParser(prog="asks", description="The per-thread register of what is waiting on the box's owner.") + sub = ap.add_subparsers(dest="cmd", required=True) + add = sub.add_parser("add", help="record one ask") + add.add_argument("text", help="the ask, one line") + add.add_argument("--thread") + add.add_argument("--title", help="the thread's title, shown when nothing else names the thread") + add.add_argument("--why", help="why it matters, one line") + add.add_argument("--rec", help="your recommendation") + add.add_argument("--default", help="what happens if the Operator says nothing") + add.add_argument("--kind", choices=KINDS) + add.add_argument("--owner", help="the owning lane and scope") + add.add_argument("--deadline", metavar="YYYY-MM-DD") + add.add_argument("--client") + add.add_argument("--tool", help="console asks: the vendor console or the page in it, for example 'Example vendor script library'") + add.add_argument("--step", action="append", help="console asks: one action per --step, in order") + add.add_argument("--paste", help="console asks: the text to paste (TEXT, @FILE or - for stdin)") + add.add_argument("--expect", help="console asks: what the Operator should see when it worked") + add.add_argument("--link", help="console asks: a direct link to the console page") + ls = sub.add_parser("list", help="show asks") + scope = ls.add_mutually_exclusive_group() + scope.add_argument("--all", action="store_true") + scope.add_argument("--thread") + ls.add_argument("--json", action="store_true") + ls.add_argument("--resolved", action="store_true", help="show resolved asks instead of open ones") + res = sub.add_parser("resolve", help="mark one ask done") + res.add_argument("ref", metavar="n|THREAD#n") + res.add_argument("--thread") + res.add_argument("--note") + pr = sub.add_parser("prune", help="drop resolved asks past their retention") + pr.add_argument("--days", type=int, default=KEEP_RESOLVED_DAYS) + return ap + + +def main(argv): + args = build_parser().parse_args(argv) + try: + # --thread names a file on add and is matched on list and resolve; none of them + # should ever carry a credential, so the flag is refused on every subcommand. + refuse_secrets("--thread", getattr(args, "thread", None)) + return {"add": cmd_add, "list": cmd_list, "resolve": cmd_resolve, "prune": cmd_prune}[args.cmd](args) + except AsksError as exc: + print("asks: %s" % exc, file=sys.stderr) + return exc.code + except OSError as exc: + print("asks: %s" % (exc.strerror or exc), file=sys.stderr) + return 1 + + +if __name__ == "__main__": + sys.exit(main(sys.argv[1:])) diff --git a/.claude-config/bin/memory-index b/.claude-config/bin/memory-index index 932d8b1..df42e3b 100755 --- a/.claude-config/bin/memory-index +++ b/.claude-config/bin/memory-index @@ -59,6 +59,9 @@ # # the same scorer by hand: top matches with scores # memory-index --digest-fit ... # # per pool: entries, described, by name only, not shown +# 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 -h | --help # # Exit codes: @@ -70,6 +73,8 @@ # caller detect "backfill needed" without losing good lines. # --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. +# --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 @@ -106,7 +111,8 @@ 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] ") + "--hint [--cwd DIR] [--ops DIR] | --find [--cwd DIR] [--ops DIR] [--limit N] | " + "--pool-for [--cwd DIR] [--ops DIR]") # The index line separator (see the header): an em dash between spaces. INDEX_SEP = " \u2014 " @@ -972,6 +978,30 @@ def digest_main(cwd, ops): return 0 +def pool_for_main(cwd, ops): + """--pool-for: print this directory's existing pool, the one --digest shows, + and exit 0; exit 4 with nothing on stdout when there is none. It resolves + the way digest_main does (the same cwd and OPS defaults and the same + 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.""" + ops = resolve_ops(ops) + cwd = cwd or os.environ.get("CLAUDE_PROJECT_DIR") or os.getcwd() + try: + pool = resolve_pools(cwd, ops, os.environ.get("MEMORY_INDEX_DIR"))[0] + except DigestError as e: + sys.stderr.write(f"memory-index: {e}\n") + return 1 + if pool is None: + sys.stderr.write(f"memory-index: no memory pool for {cwd}\n") + return 4 + print(pool) + return 0 + + def digest_fit_main(pools): """One line per pool, digested as a directory's own pool with no root section: "\t\t\t\t", @@ -1196,6 +1226,16 @@ def main(argv): directory = None if len(argv) > 2 and argv[1] == "--digest-fit": return digest_fit_main(argv[2:]) + if len(argv) > 1 and argv[1] == "--pool-for": + 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 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 ("--digest", "--hint", "--find"): mode = argv[1] opts = {"--cwd": None, "--ops": None, "--limit": "5"} @@ -1225,6 +1265,7 @@ def main(argv): 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") return 0 elif arg == "--check": check = True diff --git a/.claude-config/bin/session-end b/.claude-config/bin/session-end new file mode 100755 index 0000000..10a8483 --- /dev/null +++ b/.claude-config/bin/session-end @@ -0,0 +1,2059 @@ +#!/usr/bin/env python3 +"""session-end: the mechanical half of ending a thread (pause, move or close). + + session-end [--repo PATH]... [--transcript FILE] + [--wait SECONDS] [--dry-run] [--json] + session-end finish [--logged N | --declined REASON] [--json] + +Every ending starts with `session-end `. It snapshots git, starts the +repo cleanup (branch-gc), rebuilds this directory's memory index, lints when the +thread touched harness files, and prints what is left for the agent to decide. +It makes no judgment calls: it never commits, pushes, edits a ticket, logs +time, writes a baton, compacts, settles or deletes scratch. Its writes are the +selected repos' existing branch-gc mechanic, the resolved memory index, its own +receipt and GC run files, and (finish only) the closeout stamp and the archive +of this thread's billing stamps. + +`finish` runs after the agent has saved lessons, fixed documents and written +the resume note. It reads this thread's receipt, re-reads a pending GC result, +and only when that run was real and nothing failed does it advance +/last-closeout. After a close it requires exactly one of --logged N (N +time entries created and read back, 0 allowed) or --declined REASON, and +archives this thread's two billing stamp files. + +Why one command: the +mechanical steps of the three endings lived as prose in three skills, and a +close assembled by hand skipped steps. Why `finish` is separate: clearing the +billing stamps inside the first call would erase the unbilled-window flag +before the time is logged, so a close that stopped halfway would lose the +evidence; and last-closeout is the lower bound of transcript knowledge mining, +so it must not move before knowledge capture is done. + +Scope, stated in the output too: + - Claude sessions only (CLAUDE_CODE_SESSION_ID). Under Codex or OpenCode the + steps that need no transcript run for explicit --repo values; the + transcript, time and billing steps print "unsupported provider", and + finish archives nothing. The billing stamp's key helper has no Codex branch. + - The main thread only. A T3-delegated lane (T3CODE_THREAD_ID starting + thread:delegated-task: or thread:provider:, or `lane-class --self` saying + t3-lane or agent-lane) is refused every writing mode; --dry-run stays open. + An in-process helper shares its main thread's environment, so the Bash + guard (hooks/git-guard.sh) blocks it from the payload's agent_id instead. + - Linux (fcntl locks, setsid via start_new_session). + +Repos. With a verified transcript, GC runs on the current repo plus every +--repo; without one, only on explicit --repo values. Git roots of other paths +the thread's tool calls named are printed as candidates ("pass --repo for any +of these you changed") and get read-only snapshots only: transcript text is +data and never selects a repo to change. GC runs once per main checkout, only +for a repo the pre-compact hook would hand to branch-gc (hooks/pre-compact.sh, +"Branch and worktree GC": ~/OPS, ~/OPS/PROJECTS// and +~/linuxploitacious, compared by realpath under the current $HOME; a clone of +OPS under another name is not one) with exactly one github.com origin. GC works +on the whole selected repo, including other threads' eligible idle work; +branch-gc's own process and T3 checks hold live worktrees. + +GC worker. One detached worker per run serializes the repos (branch-gc holds a +global nonblocking lock). Each branch-gc --apply runs under the hooks' GNU +timeout resolver (hook_timeout) with the pre-compact hook's numbers: a 900 s +hard timeout, a soft deadline (BRANCH_GC_DEADLINE) at two thirds of it from the +same start, 30 s from TERM to KILL, and BRANCH_GC_TRASH_DAYS=0 so this call +purges nothing. The worker records pre-GC branch tips and worktree paths in its +run log and writes an atomic result.json; --wait (default 90, a total budget +for GC) bounds how long this call waits for it. Pending is exit 3 with the +result path, never success; a second call for the same thread and repos +reuses the pending worker instead of starting a conflicting copy. + +Paths: /session-end/.json is the receipt (key from hooklib.sh's +work_session_key); /session-end/gc// holds plan.json, run.log, +result.json and the worker lock; /session-end/done/ keeps finished +receipts. is $OPS_STATE_DIR, else ~/.local/state/ops when verify-ops.sh +sits beside this file (the directory hooks/session-briefing.sh reads +last-closeout from). Billing stamps are +~/.claude-compact-cycle/session-start- and work-log-, the names +hooks/session-work-init.sh writes; finish moves them, each by one rename, into a +fresh ~/.claude-compact-cycle/reaped/--/ beside a reaped.meta that +holds the outcome (archive_billing says why). + +Where OPS keeps the rest: the key's backend is hooklib.sh's ops_backend; the +memory pool is `memory-index --pool-for --cwd --ops `, with the +checkout the memory-digest hook passes ($OPS_DIR, else this one); the baton is +key.sh's name under ${OPS_DIR:-~/OPS}/.claude-handoffs/pending, where +hooks/handoff-check.sh looks; the lint is `verify-ops.sh --quiet` with OPS_DIR +set to this checkout (the gate has no lint-only mode, and its summary line is +the result). OPS ships no vault renderer, so that step is an explicit skip. + +Exit codes: 0 the requested mechanical steps completed; 1 an executed step or a +required prerequisite failed, or the call was refused; 2 invalid arguments; 3 +GC still pending after the wait budget (failure wins over pending). A lint that +ran to the gate's summary line and reported FAIL lines is the step status +`findings`: it is printed, recorded in the receipt and named again by finish, +but it does not fail the receipt or change the exit code, because whose FAIL it +is stays the agent's judgment (lint_verdict says why). A lint that could not run +or finish is `failed`. + +Test seam: SESSION_END_TEST_HOOK names an executable run as ` +` at three points of the billing archive: archive-target (the archive +directory about to be created), before-move (a stamp's destination, just before +its rename) and archived (the stamp's live path, just after its rename), so the +suite can collide a name, fail a rename or write a stamp at an exact moment. A failing +hook fails the archive. SESSION_END_LOCK_WAIT (seconds, default 10) bounds the +wait for a competing ending's lock, held through receipt retirement. +""" + +import argparse +import datetime +import fcntl +import glob +import hashlib +import json +import math +import os +import re +import shlex +import stat +import subprocess +import sys +import tempfile +import time + +SCRIPT = os.path.realpath(__file__) +BIN = os.path.dirname(SCRIPT) +ROOT = os.path.dirname(os.path.dirname(BIN)) +HOOKLIB = os.path.join(ROOT, ".claude-config", "hooks", "hooklib.sh") +KEY_SH = os.path.join(ROOT, ".claude-handoffs", "key.sh") + +MODES = ("pause", "move", "close") +# The pre-compact hook's numbers ("Branch and worktree GC" in hooks/pre-compact.sh): +# a kill inside a quarantine strands a worktree, so the soft deadline sits at two +# thirds of the hard timeout and the KILL waits 30 s after the TERM. The slowest +# --apply on record took 787 s. +GC_TIMEOUT = 900 +GC_KILL_AFTER = 30 +GIT_TIMEOUT = 20 +LANE_THREAD_PREFIXES = ("thread:delegated-task:", "thread:provider:") +MAIN_ONLY = "session-end belongs to the main thread; return your result instead" +CAP = 64 * 1024 +SCRATCH_ROOTS_FIXED = ("/tmp", "/var/tmp") +RESUME_FIELDS = ("NEXT ACTION (one step)", "VERIFY FIRST", "DO NOT (with who said so)", + "DEAD ENDS", "ASK THE OWNER") +UNSUPPORTED = "unsupported provider: this version supports Claude sessions only" + + +class Usage(Exception): + """Invalid arguments: exit 2.""" + + +# --- small helpers -------------------------------------------------------------- + +def now_local(): + return datetime.datetime.now().astimezone() + + +def stamp_text(dt=None): + """The `date -Is` format last-closeout has always used.""" + return (dt or now_local()).isoformat(timespec="seconds") + + +def cap(text): + if text is None: + return "" + if len(text) <= CAP: + return text + return text[:CAP] + "\n(output cut at %d characters; %d more not shown)" % (CAP, len(text) - CAP) + + +def as_text(v): + if v is None: + return "" + if isinstance(v, bytes): + return v.decode("utf-8", "replace") + return v + + +def run(cmd, timeout, cwd=None, env=None, merge=True): + """(rc, stdout, stderr). rc is None on timeout and -1 when the program could + not be started; the reason is then in stderr. With merge, stderr is folded + into stdout so a child's output is shown in order.""" + try: + p = subprocess.run(cmd, cwd=cwd, env=env, stdin=subprocess.DEVNULL, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT if merge else subprocess.PIPE, + timeout=timeout, text=True, errors="replace", check=False) + return p.returncode, p.stdout or "", p.stderr or "" + except subprocess.TimeoutExpired as e: + out = as_text(e.stdout) + err = as_text(e.stderr) + "timed out after %ss" % timeout + return (None, out + "\n" + err, "") if merge else (None, out, err) + except OSError as e: + err = "cannot run %s: %s" % (cmd[0], e.strerror or e) + return (-1, err, "") if merge else (-1, "", err) + + +def git_env(): + env = dict(os.environ, GIT_OPTIONAL_LOCKS="0", GIT_TERMINAL_PROMPT="0") + for k in ("GIT_DIR", "GIT_WORK_TREE", "GIT_COMMON_DIR", "GIT_INDEX_FILE"): + env.pop(k, None) + return env + + +def git(d, *args, timeout=GIT_TIMEOUT): + """Read-only git at d: (rc, stdout, stderr), never merged.""" + return run(["git", "-C", d] + list(args), timeout, env=git_env(), merge=False) + + +def atomic_write(path, data, mode=0o600): + d = os.path.dirname(path) + fd, tmp = tempfile.mkstemp(prefix=".%s." % os.path.basename(path), dir=d) + try: + with os.fdopen(fd, "wb") as f: + f.write(data if isinstance(data, bytes) else data.encode("utf-8")) + f.flush() + os.fsync(f.fileno()) + os.chmod(tmp, mode) + os.replace(tmp, path) + except BaseException: + try: + os.unlink(tmp) + except FileNotFoundError: + pass + raise + fsync_dir(d) + + +def fsync_dir(d): + fd = os.open(d, os.O_RDONLY | os.O_DIRECTORY) + try: + os.fsync(fd) + finally: + os.close(fd) + + +def read_json_strict(path): + """A regular file's JSON (no symlink); raises OSError or ValueError.""" + fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW) + with os.fdopen(fd, "rb") as f: + if not stat.S_ISREG(os.fstat(f.fileno()).st_mode): + raise ValueError("%s is not a regular file" % path) + return json.loads(f.read().decode("utf-8")) + + +def mkdirs(path): + os.makedirs(path, mode=0o700, exist_ok=True) + + +# --- where things are ----------------------------------------------------------- + +def gate_script(): + """(path, default state dir) of the gate beside this file, or Nones. + verify-ops.sh beside the command is what marks an OPS checkout; without it + there is no default state directory and no lint, and both say so.""" + p = os.path.join(BIN, "verify-ops.sh") + if os.path.isfile(p): + return p, os.path.expanduser("~/.local/state/ops") + return None, None + + +def state_dir(): + # OPS_STATE_DIR first, as every OPS tool that reads this state resolves it. + v = os.environ.get("OPS_STATE_DIR") + if v: + return v + return gate_script()[1] + + +def sibling(name): + p = os.path.join(BIN, name) + return p if os.path.isfile(p) and os.access(p, os.X_OK) else None + + +def stamp_dir(): + # The writer (hooks/session-work-init.sh) uses $HOME/.claude-compact-cycle, no override. + return os.path.join(os.path.expanduser("~"), ".claude-compact-cycle") + + +# --- the step record ------------------------------------------------------------ + +class Report: + def __init__(self, mode, dry_run): + self.mode, self.dry_run = mode, dry_run + self.steps = [] + self.remainder = [] + self.identity = {} + self.receipt = None + + def step(self, name, status, summary, output="", **extra): + rec = {"step": name, "status": status, "summary": summary, "output": output or ""} + rec.update(extra) + self.steps.append(rec) + return rec + + def status(self): + if any(s["status"] == "failed" for s in self.steps): + return "failed", 1 + if any(s["status"] == "pending" for s in self.steps): + return "pending", 3 + return "completed", 0 + + +def print_report(rep, as_json, extra=None): + status, code = rep.status() + if as_json: + obj = {"command": "session-end", "mode": rep.mode, "dry_run": rep.dry_run, + "status": status, "exit": code, "identity": rep.identity, + "receipt": rep.receipt, "remainder": rep.remainder, + # --json keeps every child's full output; the trimmed human copy stays out. + "steps": [{k: v for k, v in s.items() if k != "human"} for s in rep.steps]} + if extra: + obj.update(extra) + sys.stdout.write(json.dumps(obj, indent=1, sort_keys=False) + "\n") + return code + idn = rep.identity + head = "session-end %s%s" % (rep.mode, " --dry-run (nothing written)" if rep.dry_run else "") + print(head) + print(" provider session: %s (%s)" % (idn.get("session_id") or "none", idn.get("provider") or "unknown")) + print(" T3 thread: %s" % (idn.get("t3_thread_id") or "none")) + for s in rep.steps: + print("[%s] %s: %s" % (s["status"], s["step"], s["summary"])) + out = cap(s.get("human", s.get("output")) or "").rstrip("\n") + if out: + for line in out.split("\n"): + print(" " + line) + if rep.remainder: + print("") + for line in rep.remainder: + print(line) + print("") + print("status: %s (exit %d)%s" % (status, code, ("; receipt " + rep.receipt) if rep.receipt else "")) + return code + + +# --- identity ------------------------------------------------------------------- + +def hook_identity(cwd): + """(key, backend, timeout program, error) from hooklib.sh, run from the + original cwd, so the key is the one the stamp writer computes.""" + if not os.path.isfile(HOOKLIB): + return None, None, None, "hooklib.sh not found at %s" % HOOKLIB + # ops_backend is OPS's backend verdict (tmux, t3code or bare); a hooklib.sh + # without it or without work_session_key cannot give a key this file trusts. + script = ('. "$1" || exit 97\n' + 'declare -F work_session_key ops_backend >/dev/null || exit 96\n' + 'printf "%s\\n" "$(work_session_key)" "$(ops_backend)" "$(hook_timeout 2>/dev/null || true)"') + rc, out, err = run(["bash", "-c", script, "session-end-identity", HOOKLIB], 15, cwd=cwd, merge=False) + if rc == 96: + return None, None, None, "hooklib.sh at %s defines no work_session_key or ops_backend" % HOOKLIB + if rc != 0: + return None, None, None, "hooklib.sh failed (exit %s): %s" % (rc, (err or out).strip()[:300]) + parts = out.split("\n") + key, backend, to = (parts + ["", "", ""])[:3] + if not re.fullmatch(r"[A-Za-z0-9-]{1,200}", key or ""): + return None, backend or None, to or None, "work_session_key gave an unusable key %r" % key + return key, backend or None, to or None, None + + +def sanitized_sid(sid): + return re.sub(r"[^A-Za-z0-9-]", "", sid or "") + + +def identity(cwd): + sid = os.environ.get("CLAUDE_CODE_SESSION_ID", "").strip() + codex = os.environ.get("CODEX_THREAD_ID", "").strip() + provider = "claude" if sid else ("codex" if codex else "unknown") + key, backend, to, err = hook_identity(cwd) + return {"provider": provider, "session_id": sid or codex or None, + "t3_thread_id": os.environ.get("T3CODE_THREAD_ID", "").strip() or None, + "key": key, "key_error": err, "backend": backend, "timeout_program": to, + "cwd": cwd} + + +def billing_key_ok(idn): + """None when this thread's key is the per-thread key of the T3 session-id + branch of work_session_key, else why not. Positive check, fail closed: a + shared-cwd fallback key would clear another thread's unbilled-work flag.""" + if idn["provider"] != "claude": + return UNSUPPORTED + "; billing stamps are not archived (archive them by hand per session-close mechanics.md)" + if not idn["key"]: + return "no stamp key: %s" % (idn["key_error"] or "unknown") + want = "t3-" + sanitized_sid(idn["session_id"]) + if idn["backend"] == "t3code" and want != "t3-" and idn["key"] == want: + return None + if idn["backend"] == "tmux": # ops_backend's one session-name backend + return ("the %s backend keys stamps by session name, which this version does not verify; " + "archive the stamps by hand per session-close mechanics.md" % idn["backend"]) + return ("key %s is not this thread's own (the T3 session-id branch did not apply, so " + "work_session_key fell back to the shared cwd key); refusing to archive" % idn["key"]) + + +def lane_refusal(): + """None for a main thread, else the reason this call is refused.""" + tid = os.environ.get("T3CODE_THREAD_ID", "") + if tid.startswith(LANE_THREAD_PREFIXES): + return "%s (T3 thread %s is a delegated lane)" % (MAIN_ONLY, tid) + lc = sibling("lane-class") + if not lc: + return None + rc, out, err = run([lc, "--self"], 10, merge=False) + word = out.strip() + if rc == 0 and word == "foreman": + return None + if rc == 0 and word in ("t3-lane", "agent-lane"): + return "%s (lane-class --self: %s)" % (MAIN_ONLY, word) + return "lane-class --self gave no usable answer (exit %s, %r); refusing to write" % (rc, (out + err).strip()[:200]) + + +def lane_check_note(): + if os.environ.get("T3CODE_THREAD_ID", "").startswith(LANE_THREAD_PREFIXES): + return "refused" + return "lane-class --self" if sibling("lane-class") else "lane-class not installed; T3 thread-id check only" + + +# --- the transcript ------------------------------------------------------------- + +def find_transcript(sid): + if not re.fullmatch(r"[A-Za-z0-9-]{1,128}", sid or ""): + return None, "the session id has unexpected characters; no transcript searched" + cfg = os.environ.get("CLAUDE_CONFIG_DIR") or os.path.join(os.path.expanduser("~"), ".claude") + hits = sorted(glob.glob(os.path.join(glob.escape(cfg), "projects", "*", sid + ".jsonl"))) + if not hits: + return None, "no transcript %s.jsonl under %s/projects" % (sid, cfg) + if len(hits) > 1: + return None, "ambiguous: %d transcripts named %s.jsonl (%s)" % (len(hits), sid, ", ".join(hits)) + return hits[0], None + + +def parse_ts(v): + if not isinstance(v, str) or not v: + return None + try: + d = datetime.datetime.fromisoformat(v.replace("Z", "+00:00")) + except ValueError: + return None + return d if d.tzinfo else d.replace(tzinfo=datetime.timezone.utc) + + +def load_transcript(path, sid): + """(data, None) for a verified Claude transcript of this session, else + (None, why). Verified: a regular file (no symlink), every line JSON except + possibly a torn last one, at least one user or assistant record carrying + this session id, and no record carrying another.""" + try: + st = os.lstat(path) + except OSError as e: + return None, "cannot read %s: %s" % (path, e.strerror) + if not stat.S_ISREG(st.st_mode): + return None, "%s is not a regular file" % path + try: + fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW) + with os.fdopen(fd, "rb") as f: + raw = f.read() + except OSError as e: + return None, "cannot read %s: %s" % (path, e.strerror) + lines = raw.split(b"\n") + while lines and not lines[-1].strip(): + lines.pop() + data = {"path": path, "uses": [], "results": {}, "first": None, "last": None, "lanes": 0} + own = 0 + for i, line in enumerate(lines): + try: + d = json.loads(line) + except ValueError: + if i == len(lines) - 1: + continue + return None, "unsupported format: line %d of %s is not JSON" % (i + 1, path) + if not isinstance(d, dict): + return None, "unsupported format: line %d of %s is not a JSON object" % (i + 1, path) + s = d.get("sessionId") + if s is not None and s != sid: + return None, "%s holds records of another session (%s); not this thread's evidence" % (path, s) + typ = d.get("type") + if s == sid and typ in ("user", "assistant"): + own += 1 + ts = parse_ts(d.get("timestamp")) + if ts: + data["first"] = ts if data["first"] is None or ts < data["first"] else data["first"] + data["last"] = ts if data["last"] is None or ts > data["last"] else data["last"] + content = (d.get("message") or {}).get("content") if isinstance(d.get("message"), dict) else None + if not isinstance(content, list): + continue + for c in content: + if not isinstance(c, dict): + continue + if typ == "assistant" and c.get("type") == "tool_use": + inp = c.get("input") if isinstance(c.get("input"), dict) else {} + data["uses"].append({"id": c.get("id"), "name": c.get("name"), "input": inp, + "cwd": d.get("cwd")}) + if c.get("name") in ("Agent", "Task"): + data["lanes"] += 1 + elif typ == "user" and c.get("type") == "tool_result": + t = c.get("content") + if isinstance(t, list): + t = " ".join(x.get("text", "") for x in t if isinstance(x, dict)) + data["results"][c.get("tool_use_id")] = {"error": bool(c.get("is_error")), + "text": t if isinstance(t, str) else ""} + if not own: + return None, "unsupported format: no user or assistant record of session %s in %s" % (sid, path) + return data, None + + +def named_paths(tx, cwd=None): + """Paths under $HOME named by this thread's tool calls (the candidate logic of + session-close mechanics.md). Transcript text is data: nothing is executed.""" + home = os.path.expanduser("~") + pat = re.compile(re.escape(home) + r"/[\w.@+-]+(?:/[\w.@+-]+)*") + out = set() + for u in tx["uses"]: + inp = u["input"] + base = u.get("cwd") or cwd + for k in ("file_path", "path", "notebook_path"): + v = inp.get(k) + if isinstance(v, str): + p = expand(v, base) + if p: + out.add(p) + cmd = inp.get("command") + if isinstance(cmd, str): + for words in simple_commands(cmd): + for w in words: + if literal(w) and w.startswith(("./", "../", ".claude-config/", "SKILLS/")): + p = expand(w, base) + if p: + out.add(p) + for v in (inp.get("file_path"), inp.get("path"), inp.get("notebook_path"), inp.get("command")): + if isinstance(v, str): + v = re.sub(r"(^|[\s\"'=:(])~/", lambda m: m.group(1) + home + "/", v) + v = v.replace("$HOME/", home + "/").replace("${HOME}/", home + "/") + out.update(pat.findall(v)) + return out + + +# --- repos ---------------------------------------------------------------------- + +def toplevel(path): + """(toplevel realpath, None) or (None, why).""" + d = path if os.path.isdir(path) else os.path.dirname(path) + rc, out, err = git(d, "rev-parse", "--show-toplevel") + if rc != 0 or not out.strip(): + return None, (err or "not in a git work tree").strip()[:200] if rc is not None else "git timed out" + return os.path.realpath(out.strip()), None + + +def main_checkout(top): + """(main worktree realpath, None) or (None, why): the first entry of + `git worktree list --porcelain -z`, as the pre-compact hook reads it.""" + rc, out, err = git(top, "worktree", "list", "--porcelain", "-z") + if rc != 0: + return None, "cannot list worktrees: %s" % (err.strip()[:200] if rc is not None else "git timed out") + first = out.split("\0", 1)[0] + if not first.startswith("worktree "): + return None, "cannot resolve the main worktree" + return os.path.realpath(first[len("worktree "):]), None + + +def worktrees(top): + rc, out, err = git(top, "worktree", "list", "--porcelain", "-z") + if rc != 0: + return None + res, cur = [], {} + for field in out.split("\0"): + if not field: + if cur: + res.append(cur) + cur = {} + continue + k, _, v = field.partition(" ") + cur[k] = v if v else True + if cur: + res.append(cur) + return res + + +def harness_main(): + top, _ = toplevel(ROOT) + if not top: + return os.path.realpath(ROOT) + m, _ = main_checkout(top) + return m or top + + +def harness_home(): + """Where the box's batons live: $OPS_DIR, else ~/OPS, the directory the + SessionStart notifier (hooks/handoff-check.sh) reads, so a run from a + linked worktree or another clone names the baton that notifier finds.""" + return os.environ.get("OPS_DIR") or os.path.join(os.path.expanduser("~"), "OPS") + + +def managed(main): + """branch-gc's managed set, exactly as hooks/pre-compact.sh checks it before + it starts branch-gc --apply: ~/OPS, ~/linuxploitacious and + ~/OPS/PROJECTS//, the main checkout by realpath under the + realpath of the CURRENT $HOME. So a fixture HOME never reaches a real repo, + and the set is no wider than that hook's: a clone of OPS under another name, + or the checkout this file runs from when it is not ~/OPS, is not in it.""" + home = os.path.realpath(os.path.expanduser("~")) + ops = os.path.join(home, "OPS") + if main in (ops, os.path.join(home, "linuxploitacious")): + return True + proj = os.path.join(ops, "PROJECTS") + os.sep + if main.startswith(proj): + parts = main[len(proj):].split(os.sep) + return len(parts) == 2 and all(parts) + return False + + +def github_origin(main): + """None when main has exactly one github.com origin, else why not.""" + rc, out, err = git(main, "config", "--get-all", "remote.origin.url") + urls = [u for u in out.split("\n") if u.strip()] if rc == 0 else [] + if len(urls) != 1: + return "no github.com origin (or multiple origins)" + url = urls[0].strip() + path = "" + for pre in ("git@github.com:", "ssh://git@github.com/", "https://github.com/"): + if url.startswith(pre): + path = url[len(pre):] + break + if path.endswith(".git"): + path = path[:-4] + if not re.fullmatch(r"[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+", path): + return "no github.com origin (or multiple origins)" + return None + + +def snapshot(top, main, printed_mains, invoking=None, named=()): + """Read-only lines for one checkout, and whether a git call failed outright. + printed_mains collects the main checkouts whose worktree list is already out.""" + lines, broken = [], False + + def g(*a): + nonlocal broken + rc, out, err = git(top, *a) + if rc is None: + broken = True + return rc, out + rc, out = g("symbolic-ref", "--quiet", "--short", "HEAD") + if rc == 0: + branch = out.strip() + else: + rc2, out2 = g("rev-parse", "--short", "HEAD") + branch = ("detached at " + out2.strip()) if rc2 == 0 else "unknown" + rc, up = g("rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{upstream}") + if rc == 0 and up.strip(): + rc2, ab = g("rev-list", "--left-right", "--count", "HEAD...@{upstream}") + m = re.fullmatch(r"\s*(\d+)\s+(\d+)\s*", ab) if rc2 == 0 else None + track = ("upstream %s, ahead %s, behind %s" % (up.strip(), m.group(1), m.group(2))) if m \ + else "upstream %s, ahead/behind unknown" % up.strip() + else: + track = "no upstream (ahead/behind unknown)" + rc, st = g("status", "--short") + if rc == 0: + dirty = [l for l in st.split("\n") if l.strip()] + state = "clean" if not dirty else "%d changed or untracked" % len(dirty) + else: + dirty, state = [], "status unknown" + label = top if top == main else "%s (linked worktree of %s)" % (top, main) + lines.append("%s: branch %s; %s; %s" % (label, branch, track, state)) + lines.extend(" " + l for l in dirty[:30]) + if len(dirty) > 30: + lines.append(" ... %d more" % (len(dirty) - 30)) + if top != main: + rc, mb = g("-C", main, "symbolic-ref", "--quiet", "--short", "HEAD") + lines.append("main checkout %s: branch %s" % (main, mb.strip() if rc == 0 else "unknown")) + rc, dref = g("symbolic-ref", "--quiet", "--short", "refs/remotes/origin/HEAD") + if rc == 0 and dref.strip().startswith("origin/"): + default = dref.strip()[len("origin/"):] + rc, mb = g("-C", main, "symbolic-ref", "--quiet", "--short", "HEAD") + off = "unknown" if rc != 0 else ("no" if mb.strip() == default else "yes, on %s" % mb.strip()) + lines.append("main checkout off its default branch (%s): %s" % (default, off)) + else: + lines.append("default branch unknown (no origin/HEAD); main checkout off default: unknown") + if top != main or main in printed_mains: + lines.append("worktrees: see main checkout %s" % main) + else: + printed_mains.add(main) + lines.extend(worktree_block(main, invoking, named)) + return lines, broken + + +def worktree_block(main, invoking, named): + """A main checkout's worktree list, printed once per main checkout and capped + to the invoking worktree and the ones this thread's tool calls named: one + main can hold dozens, and every checkout sharing it used to repeat them (a + real dry run printed 33 lines three times, 2026-11-17).""" + lines = [] + wts = worktrees(main) + if wts is None: + return ["worktrees of main checkout %s: unknown" % main] + shown = 0 + lines.append("worktrees of main checkout %s: %d" % (main, len(wts))) + for w in wts: + path = os.path.normpath(str(w.get("worktree", ""))) + wanted = path == invoking or (path != main and any(under(n, path) for n in named)) + if not wanted: + continue + shown += 1 + b = w.get("branch", "") + b = b[len("refs/heads/"):] if isinstance(b, str) and b.startswith("refs/heads/") else ("detached" if w.get("detached") else str(b)) + lines.append(" worktree %s [%s]%s%s" % (path, b, " locked" if w.get("locked") else "", + " (this call's cwd)" if path == invoking else "")) + if len(wts) > shown: + lines.append(" ... and %d more (git -C %s worktree list)" % (len(wts) - shown, main)) + return lines + + +# --- creation evidence for close ------------------------------------------------ + +def scratch_roots(): + roots = set(SCRATCH_ROOTS_FIXED) + t = os.environ.get("TMPDIR") + if t: + roots.add(os.path.normpath(t)) + return roots + + +def under(path, root): + return path == root or path.startswith(root.rstrip("/") + "/") + + +def simple_commands(cmd): + """Literal simple commands of one Bash call, or [] for text shlex cannot read.""" + out = [] + for line in cmd.split("\n"): + try: + lex = shlex.shlex(line, posix=True, punctuation_chars=True) + lex.whitespace_split = True + toks = list(lex) + except ValueError: + continue + cur = [] + for t in toks: + if t and set(t) <= set(";&|()<>"): + if cur: + out.append(cur) + cur = [] + else: + cur.append(t) + if cur: + out.append(cur) + return out + + +def all_commands_succeeded(cmd): + """A zero Bash exit proves each command succeeded only for a single command + or a literal && chain. A semicolon, pipeline, fallback or another line can + hide a failed mkdir/docker call on somebody else's existing object.""" + if len([line for line in cmd.splitlines() if line.strip()]) != 1: + return False + try: + lex = shlex.shlex(cmd, posix=True, punctuation_chars=True) + lex.whitespace_split = True + return all(t == "&&" or not (t and set(t) <= set(";&|()<>")) for t in lex) + except ValueError: + return False + + +def literal(tok): + return not any(ch in tok for ch in "$`*?[{") + + +def expand(tok, base=None): + home = os.path.expanduser("~") + if tok.startswith("~/"): + tok = home + tok[1:] + if not tok.startswith("/"): + if base and base.startswith("/"): + return os.path.normpath(os.path.join(base, tok)) + return None + return os.path.normpath(tok) + + +def creations(tx): + """Objects this thread's successful calls created: (kind, name, owned, how).""" + found = [] + for u in tx["uses"]: + res = tx["results"].get(u["id"]) + if res is None or res["error"]: + continue + inp = u["input"] + if u["name"] == "Write" and isinstance(inp.get("file_path"), str): + p = expand(inp["file_path"]) + if p: + owned = res["text"].startswith("File created successfully") + found.append(("file", p, owned, "Write" if owned else "Write over an existing file")) + continue + if u["name"] != "Bash" or not isinstance(inp.get("command"), str): + continue + first = len(found) + for words in simple_commands(inp["command"]): + while words and re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*=.*", words[0]): + words = words[1:] + while words and words[0] in ("command", "sudo", "exec", "nohup"): + words = words[1:] + if not words: + continue + prog = os.path.basename(words[0]) + if prog == "mkdir": + opts = [w for w in words[1:] if w.startswith("-")] + parents = any(o == "--parents" or (not o.startswith("--") and "p" in o) for o in opts) + for w in words[1:]: + if w.startswith("-") or not literal(w): + continue + p = expand(w) + if p: + found.append(("dir", p, not parents, + "mkdir -p (succeeds on an existing directory)" if parents else "mkdir")) + elif prog == "git": + base, rest = None, words[1:] + while rest and rest[0] in ("-C", "-c"): + if rest[0] == "-C" and len(rest) > 1: + base = expand(rest[1]) + rest = rest[2:] + if rest[:2] != ["worktree", "add"]: + continue + args, skip = [], False + for w in rest[2:]: + if skip: + skip = False + continue + if w in ("-b", "-B", "--reason"): + skip = True + continue + if w.startswith("-"): + continue + args.append(w) + if args and literal(args[0]): + p = expand(args[0], base) + if p: + found.append(("worktree", p, True, "git worktree add")) + elif prog == "docker": + rest = words[1:] + if rest[:1] in (["container"], ["image"], ["buildx"]): + rest = rest[1:] + sub = rest[0] if rest else "" + if sub in ("run", "create"): + for i, w in enumerate(rest): + name = rest[i + 1] if w == "--name" and i + 1 < len(rest) else (w[7:] if w.startswith("--name=") else None) + if name and literal(name): + found.append(("container", name, True, "docker %s --name" % sub)) + elif sub == "build": + for i, w in enumerate(rest): + tag = rest[i + 1] if w in ("-t", "--tag") and i + 1 < len(rest) else (w[6:] if w.startswith("--tag=") else None) + if tag and literal(tag): + found.append(("image", tag, False, "docker build -t (may reuse an existing tag or cached image)")) + elif sub in ("network", "volume") and len(rest) > 2 and rest[1] == "create": + names = [w for w in rest[2:] if not w.startswith("-")] + if names and literal(names[-1]): + # docker volume create succeeds on an existing volume. + found.append((sub, names[-1], sub == "network", "docker %s create" % sub)) + if not all_commands_succeeded(inp["command"]): + for i in range(first, len(found)): + kind, name, _own, how = found[i] + found[i] = (kind, name, False, how + "; this command's success is unknown in the compound shell call") + seen, uniq = set(), [] + for f in found: + if (f[0], f[1]) not in seen: + seen.add((f[0], f[1])) + uniq.append(f) + return uniq + + +def docker_present(kind, name): + rc, out, err = run(["docker", "inspect", "--type", kind, name], 15) + if rc == 0: + return "present" + if rc not in (None, -1) and re.search(r"no such", out, re.I): + return "absent" + return "unknown (%s)" % ("docker not available" if rc == -1 else "docker did not answer: exit %s" % rc) + + +# --- memory --------------------------------------------------------------------- + +def entry_modified(path): + """metadata.modified of a pool entry's frontmatter, as text, or None.""" + try: + with open(path, encoding="utf-8", errors="replace") as f: + head = f.read(16384) + except OSError: + return None + if not head.startswith("---"): + return None + block = head.split("\n---", 1)[0] + in_meta = False + for line in block.split("\n")[1:]: + if re.match(r"^metadata:\s*$", line): + in_meta = True + continue + if in_meta and re.match(r"^\S", line): + in_meta = False + m = re.match(r"^\s+modified:\s*(.+?)\s*$", line) if in_meta else None + if m: + return m.group(1).strip("'\"") + return None + + +def entries_in_window(pool, start): + rows = [] + try: + names = sorted(os.listdir(pool)) + except OSError as e: + return None, "cannot list %s: %s" % (pool, e.strerror) + for n in names: + if not n.endswith(".md") or n == "MEMORY.md": + continue + p = os.path.join(pool, n) + try: + st = os.lstat(p) + except OSError: + continue + if not stat.S_ISREG(st.st_mode): + continue + why = [] + mod = entry_modified(p) + md = parse_ts(mod) if mod and "T" in mod else None + if md and md >= start: + why.append("metadata.modified %s" % mod) + elif mod and re.fullmatch(r"\d{4}-\d{2}-\d{2}", mod) and mod >= start.astimezone().date().isoformat() \ + and mod <= now_local().date().isoformat(): + why.append("metadata.modified %s" % mod) + if st.st_mtime >= start.timestamp(): + why.append("file time %s" % datetime.datetime.fromtimestamp(st.st_mtime).astimezone().isoformat(timespec="seconds")) + if why: + rows.append(" - %s (%s)" % (n, "; ".join(why))) + return rows, None + + +# --- the GC worker -------------------------------------------------------------- + +def gc_root(state): + return os.path.join(state, "session-end", "gc") + + +def lock_held(path): + """True while a worker holds the run's lock.""" + try: + fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW) + except FileNotFoundError: + return False + try: + fcntl.flock(fd, fcntl.LOCK_SH | fcntl.LOCK_NB) + except BlockingIOError: + return True + finally: + os.close(fd) + return False + + +def read_result(run_dir): + p = os.path.join(run_dir, "result.json") + if not os.path.lexists(p): + return None + return read_json_strict(p) + + +def pre_gc_record(repo): + rc, heads, _ = git(repo, "for-each-ref", "--format=%(refname:short) %(objectname)", "refs/heads", timeout=60) + branches = {} + if rc == 0: + for line in heads.split("\n"): + if " " in line: + b, oid = line.rsplit(" ", 1) + branches[b] = oid + wts = worktrees(repo) or [] + return {"branches": branches if rc == 0 else None, + "worktrees": [w.get("worktree") for w in wts]} + + +def parse_rows(out): + rows, on = [], False + for line in out.split("\n"): + if line.startswith("REPO\tBRANCH\tWORKTREE\tPR\tACTION\tREASON"): + on = True + continue + if on: + if not line.strip(): + break + f = line.split("\t") + if len(f) == 6: + rows.append(f) + return rows + + +def gc_worker(run_dir, lock_fd): + """The detached worker: branch-gc --apply on each planned repo in turn.""" + del lock_fd # held open until exit: the lock lives as long as this process + plan = read_json_strict(os.path.join(run_dir, "plan.json")) + log_path = os.path.join(run_dir, "run.log") + results = [] + with open(log_path, "a", encoding="utf-8") as log: + log.write("worker started %s pid %d\n" % (stamp_text(), os.getpid())) + log.flush() + for repo in plan["repos"]: + pre = pre_gc_record(repo) + log.write("pre-GC %s: branches %s; worktrees %s\n" % (repo, json.dumps(pre["branches"]), json.dumps(pre["worktrees"]))) + deadline = int(time.time()) + plan["timeout"] * 2 // 3 + cmd = [plan["timeout_program"], "-k", str(plan["kill_after"]), str(plan["timeout"]), + plan["branch_gc"], "--apply", "--tsv", repo] + env = dict(os.environ, BRANCH_GC_TRASH_DAYS="0", BRANCH_GC_DEADLINE=str(deadline)) + log.write("run %s (BRANCH_GC_TRASH_DAYS=0 BRANCH_GC_DEADLINE=%d)\n" % (" ".join(cmd), deadline)) + log.flush() + # GNU timeout bounds the call; this backstop only catches a timeout program that hangs. + rc, out, _ = run(cmd, plan["timeout"] + plan["kill_after"] + 60, env=env) + log.write(out + ("" if out.endswith("\n") else "\n")) + if rc is None or rc in (124, 137): + status = "timeout" + elif rc == 0: + status = "completed" + else: + status = "failed" + m = re.search(r"^Summary.*\n\s*(\S.*)$", out, re.M) + results.append({"repo": repo, "rc": rc, "status": status, + "summary": m.group(1).strip() if m else "no summary", + "rows": parse_rows(out), "pre": pre, + "tail": "\n".join(out.rstrip("\n").split("\n")[-40:]), "output": out}) + log.write("exit %s (%s)\n" % (rc, status)) + log.flush() + overall = "completed" if all(r["status"] == "completed" for r in results) else "failed" + atomic_write(os.path.join(run_dir, "result.json"), + json.dumps({"run": os.path.basename(run_dir), "finished_at": stamp_text(), + "status": overall, "repos": results}, indent=1)) + log.write("worker finished %s: %s\n" % (stamp_text(), overall)) + return 0 + + +GC_TABLE_HEAD = "REPO\tBRANCH\tWORKTREE\tPR\tACTION\tREASON" + + +def trim_gc(out, named_row, full_ref): + """branch-gc --tsv output cut for a reader under context pressure (a real dry + run printed 76 report rows, 2026-11-17): the lines before the table (its + header line), every row whose ACTION is not `report`, report rows for a + branch or worktree this thread named, and everything after the table (the + Summary block and any error lines), then a count of the rows left out. + Output that is not the documented six-column TSV is returned whole, never + guessed at.""" + lines = out.rstrip("\n").split("\n") + try: + h = lines.index(GC_TABLE_HEAD) + except ValueError: + return out + end = h + 1 + while end < len(lines) and lines[end].strip(): + end += 1 + rows = [l.split("\t") for l in lines[h + 1:end]] + if any(len(r) != 6 for r in rows): + return out + kept, hidden = [], 0 + for r in rows: + if r[4] != "report" or named_row(r[1], r[2]): + kept.append("\t".join(r)) + else: + hidden += 1 + res = lines[:h] + ([GC_TABLE_HEAD] + kept if kept else []) + lines[end:] + if hidden: + res.append("%d report-only rows not shown; %s" % (hidden, full_ref)) + return "\n".join(res) + + +def row_namer(tx, named_norm): + """named_row(branch, worktree): True when this thread's tool calls named the + worktree's path or the branch (as a whole word in a tool input).""" + texts = [] + for u in (tx or {}).get("uses", []): + texts.extend(v for v in u["input"].values() if isinstance(v, str)) + blob = "\n".join(texts) + + def named_row(branch, wt): + if wt and wt != "-": + p = os.path.normpath(os.path.expanduser(wt)) + if any(under(n, p) for n in named_norm): + return True + if branch and branch != "-" and blob: + return re.search(r"(?)". +GATE_SUMMARY = re.compile(r"^verify-ops: (\d+) ok · (\d+) warn · (\d+) fail \(") + + +def lint_verdict(cmd, rc, out): + """The lint step's record. A lint that ran to its summary and reported FAIL + lines is `findings`, not `failed`: on a shared box the gate almost always + carries FAILs owned by other sessions, and whose a FAIL is stays the agent's + judgment (settled after the first real run made every receipt fail on other + work's FAILs; a closing agent already lists other sessions' FAILs in one + line). A lint that could not run or did + not finish (a start error, a timeout, an exit other than 0 or 1, or exit 1 + without the summary line, where an empty or broken read must not pass for a + result) stays `failed` and fails the receipt.""" + lines = out.split("\n") + fails = [l for l in lines if l.startswith("FAIL")] + summary = [m for m in (GATE_SUMMARY.match(l) for l in lines) if m] + head = "%s exited %s" % (cmd, rc) + if rc == 0 and summary and int(summary[-1].group(3)) == 0 and not fails: + return dict(name="lint", status="completed", summary="%s; %d FAIL line(s)" % (head, len(fails)), + output="\n".join(fails) if fails else out[-4000:]) + if rc == 1 and summary and int(summary[-1].group(3)) > 0 and fails: + return dict(name="lint", status="findings", + summary="%s with %s FAIL(s) in its summary; FAIL ownership is yours to judge, not a failed run" + % (head, summary[-1].group(3)), + output="\n".join(fails), fail_lines=fails) + if rc is None: + why = "it did not finish" + elif rc == -1: + why = "it could not start" + elif rc == 0: + # Exit zero alone cannot prove the gate reached its final summary: + # an empty/truncated helper must not turn a failed check into a receipt. + why = "exit 0 without a clean gate summary or with contradictory FAIL lines, so no clean result could be read" + elif rc != 1: + why = "exit %s is neither a clean run nor findings" % rc + else: + why = "exit 1 without the gate's summary line and FAIL lines, so no result could be read" + return dict(name="lint", status="failed", summary="%s; %s" % (head, why), output=out[-4000:]) + + +def cmd_end(args, idn): + mode, dry = args.mode, args.dry_run + rep = Report(mode, dry) + cwd = idn["cwd"] + rep.identity = {k: idn[k] for k in ("provider", "session_id", "t3_thread_id", "key", "backend", "cwd")} + + rep.step("lane check", "completed", lane_check_note() if not dry else "dry run: open to lanes, writes nothing") + + # Explicit repos first: a typo is an invalid argument, refused before anything runs. + explicit = [] + for r in args.repo: + p = os.path.abspath(os.path.expanduser(r)) + if not os.path.isdir(p): + raise Usage("--repo %s: not a directory" % r) + top, why = toplevel(p) + if not top: + raise Usage("--repo %s: not in a git work tree (%s)" % (r, why)) + explicit.append(top) + + # 1. Identity and the transcript. + tx, tx_why = None, None + if idn["provider"] != "claude": + tx_why = UNSUPPORTED + "; no transcript, time or stamp step (explicit --repo values still run)" + else: + path = args.transcript + if path: + path = os.path.abspath(os.path.expanduser(path)) + else: + path, tx_why = find_transcript(idn["session_id"]) + if path: + tx, tx_why = load_transcript(path, idn["session_id"]) + if tx: + rep.step("transcript", "completed", "verified: %s (window from %s)" % (tx["path"], tx["first"].isoformat() if tx["first"] else "unknown")) + else: + rep.step("transcript", "skipped", "not verified: %s. No inferred repos, no time figure, no memory window." % tx_why) + if idn["key_error"]: + rep.step("stamp key", "failed" if not dry else "skipped", idn["key_error"]) + + # 2. Repo selection. + hmain = harness_main() + current = None + if tx: + current, _ = toplevel(cwd) + selected = [] + for top in ([current] if current else []) + explicit: + if top not in selected: + selected.append(top) + candidates = [] + harness_named = [] + named = set() + if tx: + named = named_paths(tx, cwd) + roots_seen = {} + main_roots = {} + home = os.path.expanduser("~") + for p in sorted(named): + d = p if os.path.isdir(p) else os.path.dirname(p) + while d and d != home and not os.path.isdir(d): + d = os.path.dirname(d) + if not d or d == home: + continue + if d not in roots_seen: + roots_seen[d], _ = toplevel(d) + top = roots_seen[d] + if top: + if top not in main_roots: + main_roots[top], _ = main_checkout(top) + # The executable can live in the main checkout while the thread + # edits any linked worktree of it. Compare repo identity first. + if main_roots[top] == hmain: + rel = os.path.relpath(p, top) + if any(under(rel, root) for root in (".claude-config", "SKILLS")): + harness_named.append(p) + for top in sorted({t for t in roots_seen.values() if t}): + if top not in selected: + candidates.append(top) + mains, sel_lines = {}, [] + for top in selected: + m, why = main_checkout(top) + if not m: + sel_lines.append("%s: %s" % (top, why)) + continue + mains.setdefault(m, []).append(top) + for m, tops in mains.items(): + extra = [t for t in tops if t != m] + sel_lines.append("%s%s" % (m, (" (from worktree %s)" % ", ".join(extra)) if extra else "")) + if candidates: + sel_lines.append("candidates this thread's tool calls named (read-only; pass --repo for any of these you changed):") + sel_lines.extend(" " + c for c in candidates) + rep.step("repos", "completed", + "%d selected for GC (%s)" % (len(mains), "current repo plus --repo" if tx else "explicit --repo only"), + "\n".join(sel_lines)) + + # 3. Git snapshots, read-only. + snap_lines, snap_broken, printed_mains = [], False, set() + invoking, _ = toplevel(cwd) + named_norm = {os.path.normpath(p) for p in named} + named_row = row_namer(tx, named_norm) + seen_mains = [] + for top in selected + candidates: + m, why = main_checkout(top) + lines, broken = snapshot(top, m or top, printed_mains, invoking, named_norm) + snap_lines.extend(lines) + snap_broken = snap_broken or broken + if (m or top) not in seen_mains: + seen_mains.append(m or top) + for m in seen_mains: + if m not in printed_mains: # reached only through its linked worktrees + printed_mains.add(m) + snap_lines.extend(worktree_block(m, invoking, named_norm)) + rep.step("git snapshot", "failed" if snap_broken else "completed", + "%d checkout(s), read-only%s" % (len(selected) + len(candidates), "; a git call timed out" if snap_broken else ""), + "\n".join(snap_lines)) + + # 8 (before). Disk. + free_before = statvfs_free() + + # 4. GC. + state = state_dir() + gc_rec, gc_run, gc_deadline, gc_eligible = None, None, None, [] + bgc = sibling("branch-gc") + boundary = ("GC works on the whole selected repo, including other threads' eligible idle work; " + "branch-gc's process and T3 checks hold live worktrees; its worker can outlive this call.") + if not mains: + gc_rec = rep.step("branch-gc", "skipped", "no repo selected for GC" + ("" if tx else " (no verified transcript and no --repo)")) + elif not bgc: + gc_rec = rep.step("branch-gc", "failed", "branch-gc not found beside session-end (%s); repo cleanup not run" % BIN) + else: + notes = [] + for m in mains: + if not managed(m): + notes.append("not run: %s is not a repo branch-gc manages" % m) + continue + why = github_origin(m) + if why: + notes.append("not run: %s has %s" % (m, why)) + continue + gc_eligible.append(m) + # Sorted: the selection is a set, so the same repos in another --repo order + # reuse a pending worker instead of meeting it as a conflicting copy. + gc_eligible.sort() + if not gc_eligible: + gc_rec = rep.step("branch-gc", "skipped", "no selected repo qualifies", "\n".join(notes)) + elif dry: + out_lines, hum_lines = list(notes), list(notes) + budget_end = time.monotonic() + args.wait + with tempfile.TemporaryDirectory(prefix="session-end-dry-") as scratch: + env = dict(os.environ, BRANCH_GC_LOG=os.path.join(scratch, "branch-gc.log"), BRANCH_GC_TRASH_DAYS="0") + failed = False + for m in gc_eligible: + left = budget_end - time.monotonic() + if left <= 0: + out_lines.append("not evaluated: %s (the --wait budget is spent)" % m) + hum_lines.append(out_lines[-1]) + continue + # TERM first through the hooks' timeout program, so branch-gc's + # trap removes its own temp files; the Python bound is a backstop. + cmd = [bgc, "--dry-run", "--tsv", m] + if idn["timeout_program"]: + cmd = [idn["timeout_program"], "-k", "5", str(max(1, int(left))), *cmd] + rc, out, _ = run(cmd, left + 10, env=env) + if rc is None or rc in (124, 137): + out_lines.append("--dry-run %s: not finished within the --wait budget; stopped (it writes nothing)" % m) + else: + out_lines.append("--dry-run %s: exit %s" % (m, rc)) + failed = failed or rc != 0 + hum_lines.append(out_lines[-1]) + out_lines.extend(" " + l for l in out.rstrip("\n").split("\n") if l) + trimmed = trim_gc(out, named_row, "they are in --json") + hum_lines.extend(" " + l for l in trimmed.rstrip("\n").split("\n") if l) + gc_rec = rep.step("branch-gc", "failed" if failed else "completed", + "report only (--dry-run; no --apply, logs and lock in a scratch dir removed after)", + "\n".join(out_lines), human=cap("\n".join(hum_lines))) + elif not idn["timeout_program"]: + gc_rec = rep.step("branch-gc", "failed", "no timeout program (hook_timeout found neither gnutimeout nor timeout); GC not started", + "\n".join(notes)) + elif not state or not idn["key"]: + gc_rec = rep.step("branch-gc", "failed", "no state directory or stamp key; GC not started", "\n".join(notes)) + else: + try: + gc_run, reused, err = launch_worker(state, idn, gc_eligible, idn["timeout_program"], bgc) + except OSError as e: + gc_run, reused, err = None, False, "could not start the GC worker: %s" % (e.strerror or e) + if err: + gc_rec = rep.step("branch-gc", "failed", err, "\n".join(notes)) + else: + gc_deadline = time.monotonic() + args.wait + gc_rec = rep.step("branch-gc", "pending", ("reusing the pending worker" if reused else "worker started") + " for %d repo(s)" % len(gc_eligible), + "\n".join(notes + [boundary]), result=os.path.join(gc_run, "result.json"), log=os.path.join(gc_run, "run.log")) + + # 5. Memory index. + pool = None + mi = sibling("memory-index") + pool_cwd = os.environ.get("CLAUDE_PROJECT_DIR") or cwd + # The checkout hooks/memory-digest.sh passes as --ops ($OPS_DIR, else its own), + # so the pool rebuilt here is the one the digest shows. + ops_root = os.environ.get("OPS_DIR") or ROOT + if not mi: + rep.step("memory index", "failed", "memory-index not found beside session-end (%s)" % BIN) + else: + rc, out, err = run([mi, "--pool-for", "--cwd", pool_cwd, "--ops", ops_root], 30, merge=False) + if rc == 0 and out.strip() and os.path.isdir(out.strip()): + pool = out.strip() + if dry: + rep.step("memory index", "completed", "would rebuild %s/MEMORY.md (memory-index %s)" % (pool, pool)) + else: + rc2, out2, _ = run([mi, pool], 120) + if rc2 == 0: + rep.step("memory index", "completed", "rebuilt %s/MEMORY.md" % pool, out2) + elif rc2 == 2: + rep.step("memory index", "completed", "rebuilt %s/MEMORY.md; WARNING: entries need backfill (exit 2), not a failed rebuild" % pool, out2) + else: + rep.step("memory index", "failed", "memory-index %s exited %s" % (pool, rc2), out2) + elif rc == 4: + rep.step("memory index", "skipped", "no memory pool for %s; none created" % pool_cwd, out + err) + else: + rep.step("memory index", "failed", "memory-index --pool-for exited %s" % rc, out + err) + + # 6. Lint. + gate, _ = gate_script() + if not tx: + rep.step("lint", "skipped", "no verified transcript, so no evidence of harness files; if this thread changed .claude-config/ or SKILLS/, run the gate's lint by hand") + elif not harness_named: + rep.step("lint", "skipped", "this thread named no file under .claude-config/ or SKILLS/") + elif not gate: + rep.step("lint", "failed", "this thread touched harness files but no gate script sits beside session-end") + else: + # verify-ops.sh has no lint-only mode: --quiet prints its WARN and FAIL lines + # and the summary line, and OPS_DIR points it at this checkout, not ~/OPS. + cmd = [gate, "--quiet"] + env = dict(os.environ, OPS_DIR=ROOT) + if dry: + rep.step("lint", "completed", "would run OPS_DIR=%s %s" % (ROOT, " ".join(cmd))) + else: + rc, out, _ = run(cmd, 600, env=env) + rep.step(**lint_verdict(" ".join(cmd), rc, out)) + + # 4 (wait). The GC result, within the --wait budget measured from launch. + gc_res = None + if gc_run: + res_path = os.path.join(gc_run, "result.json") + lock_path = os.path.join(gc_run, "worker.lock") + while True: + try: + gc_res = read_result(gc_run) + except (OSError, ValueError) as e: + gc_rec.update(status="failed", summary="unreadable GC result %s: %s" % (res_path, e)) + break + if gc_res is not None: + break + if not lock_held(lock_path): + try: + gc_res = read_result(gc_run) + except (OSError, ValueError): + gc_res = None + if gc_res is None: + gc_rec.update(status="failed", summary="the GC worker ended without a result; see %s/run.log" % gc_run) + break + left = gc_deadline - time.monotonic() + if left <= 0: + gc_rec.update(summary="%s; still running after the --wait budget; read %s before reporting cleanup as done (session-end finish does)" + % (gc_rec["summary"], res_path)) + break + time.sleep(min(0.1, left)) + if gc_res is not None: + ok = gc_res.get("status") == "completed" + gc_rec.update(status="completed" if ok else "failed", + summary="finished: %s" % gc_res.get("status"), + output=(gc_rec.get("output") or "") + "\n" + "\n".join(describe_result(gc_res, gc_run)), + human=cap((gc_rec.get("output") or "") + "\n" + "\n".join(describe_result(gc_res, gc_run, named_row)))) + + # 8 (after). Disk. + free_after = statvfs_free() + if free_before is None or free_after is None: + rep.step("disk", "skipped", "statvfs / failed") + else: + delta = free_after - free_before + rep.step("disk", "completed", + "free on /: %s before, %s after (%+.1f MiB); a box-wide observation, not bytes this thread reclaimed%s" + % (fmt_bytes(free_before), fmt_bytes(free_after), delta / 1024 ** 2, + "; GC is still running, so this sample is incomplete" if gc_rec and gc_rec["status"] == "pending" else ""), + "Quarantine on the same filesystem keeps a worktree's bytes.") + + # 9. Close: list what this thread created; remove nothing. + if mode == "close": + if not tx: + rep.step("cleanup list", "skipped", "no verified transcript: no creation evidence to list") + else: + rows_by_wt = {} + if gc_res: + for r in gc_res["repos"]: + for row in r.get("rows", []): + wt = row[2] + if wt and wt != "-": + rows_by_wt[os.path.normpath(os.path.expanduser(wt))] = "%s: %s" % (row[4], row[5]) + roots = scratch_roots() + owned, unknown = [], [] + for kind, name, own, how in creations(tx): + if kind in ("file", "dir", "worktree"): + if kind != "worktree" and not any(under(name, r) for r in roots): + continue + if any(under(r, name) for r in roots): + continue # a scratch root or its parent is never this thread's own + if not os.path.lexists(name): + continue + line = "%s %s (%s)" % (kind, name, how) + if kind == "worktree": + line += "; GC: %s" % rows_by_wt.get(name, "GC pending/not evaluated" if not gc_res else "no row for it") + else: + pres = docker_present(kind, name) + if pres == "absent": + continue + line = "docker %s %s (%s; %s)" % (kind, name, how, pres) + if pres != "present": + unknown.append(line) + continue + (owned if own else unknown).append(line) + out = ["created by this thread and still present (remove by exact path or id if disposable; never over a live-worktree hold):"] + out += [" " + l for l in owned] or [" (none found)"] + if unknown: + out.append("ownership unknown (not suggested for removal):") + out += [" " + l for l in unknown] + out.append("check for anything else you created, by exact path or id; establish ownership before removing it") + rep.step("cleanup list", "completed", "%d created object(s) listed; nothing removed" % len(owned), "\n".join(out)) + + # 10. Box extras. + # OPS ships no vault renderer, so the step is an explicit skip, never a guess. + rep.step("vault view", "skipped", "this checkout ships no vault renderer; nothing checked or written") + asks = sibling("asks") + thread_for_asks = os.environ.get("ASKS_THREAD") or idn["t3_thread_id"] + if not asks: + rep.step("open asks", "skipped", "asks not installed on this box") + elif not thread_for_asks: + rep.step("open asks", "skipped", "no T3 thread id (and no ASKS_THREAD), so no register to read") + else: + rc, out, _ = run([asks, "list"], 30) + rep.step("open asks", "completed" if rc == 0 else "failed", "asks list exited %s" % rc, out) + + # 11. The remainder. + remainder(rep, mode, idn, tx, pool) + + # 7. The receipt (not on a dry run; last-closeout moves only at finish). + status, code = rep.status() + if not dry: + if not state or not idn["key"]: + rep.step("receipt", "failed", "no state directory or stamp key; no receipt written, so finish cannot run") + else: + try: + d = os.path.join(state, "session-end") + mkdirs(d) + path = os.path.join(d, "%s.json" % idn["key"]) + status, code = rep.status() + atomic_write(path, json.dumps({ + "version": 1, "mode": mode, "dry_run": False, "written_at": stamp_text(), + "status": status, "exit": code, "identity": rep.identity, + "gc": {"run_dir": gc_run, "status": gc_rec["status"] if gc_rec else "skipped"}, + "lint_findings": [l for s in rep.steps if s["step"] == "lint" and s["status"] == "findings" + for l in s["fail_lines"]], + "steps": rep.steps}, indent=1)) + rep.receipt = path + except OSError as e: + rep.step("receipt", "failed", "cannot write the receipt: %s" % (e.strerror or e)) + return print_report(rep, args.json) + + +def remainder(rep, mode, idn, tx, pool): + out = rep.remainder + out.append("What only you can do now:") + out.append(" - Save the lessons worth keeping: one fact per file in the memory pool%s. A thread with none saves none." + % (" (%s)" % pool if pool else "")) + out.append(" - Put knowledge where the next person will look, and fix any document this thread made untrue.") + out.append(" - Write the resume note at the top of the anchor or baton: %s." % ", ".join(RESUME_FIELDS)) + lint = [s for s in rep.steps if s["step"] == "lint" and s["status"] == "findings"] + if lint: + out.append(" - Lint reported %d FAIL line(s) above: fix the ones on files this thread changed, " + "and name the rest as other work's in your report." % len(lint[-1]["fail_lines"])) + # Memory stewardship: the closing agent owns it, because only it knows what this thread learned. + if not pool: + out.append("Memory stewardship: no pool for this directory.") + elif not tx or not tx["first"]: + out.append("Memory stewardship: no verified transcript window, so entries are not listed; check %s by hand." % pool) + else: + rows, err = entries_in_window(pool, tx["first"]) + # The pool is shared by concurrent threads, so the window list cannot say who wrote what. + out.append("Memory stewardship (pool %s, window from %s): entries written or changed in this pool during " + "this thread's window, by this thread or another one sharing the pool:" % (pool, tx["first"].isoformat())) + if err: + out.append(" " + err) + rep.step("memory window", "failed", err) + else: + out.extend(rows or [" (no entry modified or touched in this window)"]) + out.append(" Correct an entry this thread proved wrong, merge duplicates it touched, move a lesson that belongs in a repo's docs. session-end changed no entry.") + tid = idn["t3_thread_id"] + if mode == "pause": + cc = sibling("compact-cycle.sh") + if tid and cc: + out.append("Pause: compact with %s --target %s" % (cc, tid)) + else: + out.append("Pause: no compact line (%s)" % ("no T3 thread id" if not tid else "compact-cycle.sh not installed")) + out.append(" Never compact over an unanswered question.") + elif mode == "move": + if not os.path.isfile(KEY_SH): + out.append("Move: key.sh not found at %s; baton path unknown" % KEY_SH) + rep.step("baton key", "failed", "key.sh not found at %s" % KEY_SH) + else: + rc, key, err = run(["bash", KEY_SH], 15, cwd=idn["cwd"], merge=False) + if rc != 0 or not key.strip(): + out.append("Move: key.sh failed (exit %s); baton path unknown" % rc) + rep.step("baton key", "failed", "key.sh exited %s: %s" % (rc, err.strip()[:200])) + else: + # The SessionStart notifier (hooks/handoff-check.sh) reads + # ${OPS_DIR:-$HOME/OPS}/.claude-handoffs; harness_home() is that directory. + hdir = os.path.join(harness_home(), ".claude-handoffs") + baton = os.path.join(hdir, "pending", key.strip() + ".md") + out.append("Move: the baton is %s (%s)." % (baton, "exists: read it, never overwrite an unread one" if os.path.exists(baton) else "not written yet")) + out.append(" One pending baton per project. Commit and push it, or the other machine never sees it.") + elif mode == "close": + time_block(rep, tx, idn) + out.append("Bill only if this thread worked a ticket; read what is already on the ticket first.") + out.append("Remove what this thread made (the cleanup list above), never another thread's.") + finish = "session-end finish --logged N | --declined REASON" if mode == "close" else "session-end finish" + out.append("When the above is done: %s%s" % (finish, " (N = time entries created and read back; 0 is valid)" if mode == "close" else "")) + if mode == "close": + out.append("Then print the receipt first, because nothing after the settle reaches the owner.") + if tid: + out.append("Settle: t3_thread_organize with action \"settle\" and threadId omitted, as the last tool call; it applies at turn end" + " (a failed turn or a queued message leaves the thread active). Only if that tool is not available: " + "%s settle-when-idle %s. Never both." % (sibling("t3-api.sh") or "t3-api.sh", tid)) + else: + out.append("Settle: not a T3 thread; no settle step (see session-close teardown for tmux or a plain terminal).") + + +def time_block(rep, tx, idn): + if idn["provider"] != "claude": + rep.step("time", "skipped", UNSUPPORTED + "; no time figure") + return + if not tx: + rep.step("time", "skipped", "no verified transcript; no time figure. Ask the owner for the window; never bill a guessed span.") + return + am = sibling("active-minutes") + if not am: + rep.step("time", "skipped", "active-minutes not installed on this box; no time figure") + return + base = tx["path"][:-len(".jsonl")] + also = sorted(glob.glob(os.path.join(glob.escape(base), "subagents", "*.jsonl")) + + glob.glob(os.path.join(glob.escape(base), "subagents", "workflows", "*", "*.jsonl"))) + also = [a for a in also if os.path.isfile(a) and not os.path.islink(a)] + cmd = [am, tx["path"]] + (["--also"] + also if also else []) + rc, out, _ = run(cmd, 120) + m = re.search(r"^ACTIVE \(bill this\): ([\d.]+) min", out, re.M) + if rc != 0 or not m: + rep.step("time", "failed", "active-minutes exited %s%s; no time figure" % (rc, "" if m else " without an ACTIVE line"), out) + return + caveat = "" + if tx["lanes"] and not also: + caveat = ("; NOT CONFIDENT: this thread started %d lane(s) but no lane transcript exists under %s/subagents, " + "so gaps a lane worked through may be excluded" % (tx["lanes"], base)) + rep.step("time", "completed", + "measured %s active minutes as evidence, not an amount to enter%s" % (m.group(1), caveat), + out, confident=not caveat, lane_transcripts=len(also)) + + +# --- finish --------------------------------------------------------------------- + +def lock_wait(): + raw = os.environ.get("SESSION_END_LOCK_WAIT", "10") + try: + v = float(raw) + except ValueError: + v = 10.0 + return v if math.isfinite(v) and v >= 0 else 10.0 + + +def test_hook(phase, path): + hook = os.environ.get("SESSION_END_TEST_HOOK") + if not hook: + return + rc, out, err = run([hook, phase, path], 10) + if rc != 0: + raise OSError("test hook %s %s exited %s: %s" % (phase, path, rc, out.strip()[:200])) + + +def sha256_file(path): + h = hashlib.sha256() + size = 0 + with open(path, "rb") as f: + for chunk in iter(lambda: f.read(65536), b""): + h.update(chunk) + size += len(chunk) + return size, h.hexdigest() + + +def archive_billing(key, outcome): + """(ok, lines). Moves this thread's live stamps into one fresh archive + directory, /reaped/--/, each by a single rename. + + Why a rename and never a copy (a code review finding): the + copy, compare and unlink sequence raced the stamp writers, which take no lock + of ours; a writer that appended after the compare lost its unbilled bytes to + the unlink while finish reported success. A rename keeps the inode, so bytes + a writer appends through a descriptor it already holds land in the archive, + and a writer that opens the name afterwards creates a new live file that + stays live as fresh unbilled evidence. Nothing is deleted, so no byte can be + lost. branch-gc's quarantine moves worktrees the same way. + + Order: the work-log first and the session-start stamp last, because the + session-start stamp is the unbilled-window flag. A work-log that appears + before or right after the session-start move keeps (or puts back) that flag: + the new segment has to be reconciled first. The outcome goes into a separate + reaped.meta written with O_EXCL after the moves, so the archived bytes stay + exactly the stamps' own.""" + run = stamp_dir() + reaped = os.path.join(run, "reaped") + names = ["work-log-%s" % key, "session-start-%s" % key] + live = [n for n in names if os.path.lexists(os.path.join(run, n))] + if not live: + return True, ["no live billing stamps for key %s; nothing archived (a repeated finish is a no-op)" % key] + # Every source is checked before anything moves, so a refusal moves nothing. + for n in live: + src = os.path.join(run, n) + try: + mode = os.lstat(src).st_mode + except FileNotFoundError: + continue # gone since the listing; the move loop reports it absent + if not stat.S_ISREG(mode): + return False, ["%s is not a regular file (a symlink or special file); nothing moved, originals left in place" % src] + try: + if os.path.lexists(reaped): + if not stat.S_ISDIR(os.lstat(reaped).st_mode): + return False, ["%s is not a directory (a symlink?); nothing moved, originals left in place" % reaped] + else: + os.mkdir(reaped, 0o700) + adir = None + ts = time.strftime("%Y%m%dT%H%M%S") + for _ in range(100): + cand = os.path.join(reaped, "%s-%s-%s" % (key, ts, os.urandom(4).hex())) + test_hook("archive-target", cand) + try: + os.mkdir(cand, 0o700) # exclusive: an existing directory is never reused + adir = cand + break + except FileExistsError: + continue + if adir is None: + return False, ["no free archive directory name under %s; nothing moved" % reaped] + fsync_dir(reaped) + except OSError as e: + return False, ["cannot prepare an archive directory under %s: %s; nothing moved, originals left in place" % (reaped, e)] + + moved, lines, failure = [], [], None + wl_live = os.path.join(run, "work-log-%s" % key) + for name in names: + src, dest = os.path.join(run, name), os.path.join(adir, name) + try: + try: + st = os.lstat(src) + except FileNotFoundError: + lines.append("%s: absent" % src) + continue + if not stat.S_ISREG(st.st_mode): + raise OSError("%s is no longer a regular file; left in place" % src) + if name.startswith("session-start-") and os.path.lexists(wl_live): + raise OSError("a new work-log appeared at %s during archival; session-start left live, " + "reconcile the new segment first" % wl_live) + test_hook("before-move", dest) + os.rename(src, dest) # same filesystem by construction; never a copy + # Record a successful move before fsync or hashing can fail: losing + # its recovery path would strand an archived unbilled-window flag. + moved.append((name, src, dest, None, None)) + lines.append("%s -> %s" % (src, dest)) + fsync_dir(run) + fsync_dir(adir) + size, digest = sha256_file(dest) + moved[-1] = (name, src, dest, size, digest) + test_hook("archived", src) + if name.startswith("session-start-") and os.path.lexists(wl_live): + # A segment arrived right after the flag moved: put the flag back + # by link (fails rather than replace a newer live stamp). + try: + os.link(dest, src) + os.unlink(dest) + moved.pop() + lines.pop() + fsync_dir(run) + fsync_dir(adir) + raise OSError("a new work-log appeared at %s during archival; session-start put back live, " + "reconcile the new segment first" % wl_live) + except FileExistsError: + raise OSError("a new work-log appeared at %s and a newer session-start already exists; " + "the moved flag stays at %s, compare the two by hand" % (wl_live, dest)) + except OSError as e: + failure = e + break + + meta_ready = False + if moved: + meta = ["reaped_at=%s" % stamp_text(), "reaped_reason=session-end finish: %s" % outcome, + "reaped_key=%s" % key, "status=%s" % ("partial" if failure else "complete")] + for name, src, dest, size, digest in moved: + meta.append("file=%s\toriginal=%s\tsize=%s\tsha256=%s" % + (name, src, size if size is not None else "unknown", digest or "unavailable")) + try: + mfd = os.open(os.path.join(adir, "reaped.meta"), os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600) + with os.fdopen(mfd, "wb") as m: + m.write(("\n".join(meta) + "\n").encode("utf-8")) + m.flush() + os.fsync(m.fileno()) + fsync_dir(adir) + meta_ready = True + except OSError as e: + failure = failure or OSError("the stamps moved but %s/reaped.meta could not be written: %s" % (adir, e)) + else: + try: + os.rmdir(adir) # this call's own empty directory + except OSError: + pass + + if failure: + # A failed finish leaves its receipt active. Keep the billing window + # discoverable too, even if the flag's rename succeeded before the + # failure. An exclusive hard link preserves the archive and cannot + # overwrite a newer live flag created by a writer we do not lock. + for name, src, dest, _s, _d in moved: + if not name.startswith("session-start-"): + continue + try: + os.link(dest, src) + fsync_dir(run) + lines.append("billing window kept live at %s (archive preserved at %s)" % (src, dest)) + except FileExistsError: + lines.append("live billing flag at %s was not replaced" % src) + except OSError as e: + lines.append("FAILED to restore the live billing flag from %s to %s: %s" % (dest, src, e)) + lines.append("FAILED: %s" % failure) + still = [os.path.join(run, n) for n in names if os.path.lexists(os.path.join(run, n))] + lines.append("still live: %s" % (", ".join(still) or "none")) + if moved: + note = ("reaped.meta holds the outcome and available sizes and sha256" if meta_ready else + "reaped.meta could not be completed; inspect the moved files") + lines.append("archive directory: %s (%s)" % (adir, note)) + for name, src, dest, _s, _d in moved: + lines.append("restore %s, only while that name is free (never over a newer live stamp): mv -n %s %s" % (name, dest, src)) + return failure is None, lines + + +def cmd_finish(args, idn): + rep = Report("finish", False) + rep.identity = {k: idn[k] for k in ("provider", "session_id", "t3_thread_id", "key", "backend", "cwd")} + state = state_dir() + if not state or not idn["key"]: + rep.step("receipt", "failed", "no state directory or stamp key (%s); nothing done" % (idn["key_error"] or "no gate script beside session-end")) + return print_report(rep, args.json) + rpath = os.path.join(state, "session-end", "%s.json" % idn["key"]) + try: + rec = read_json_strict(rpath) + except FileNotFoundError: + rep.step("receipt", "failed", "no receipt at %s: run session-end first" % rpath) + return print_report(rep, args.json) + except (OSError, ValueError) as e: + rep.step("receipt", "failed", "unreadable receipt %s: %s" % (rpath, e)) + return print_report(rep, args.json) + got = rec.get("identity") or {} + for k in ("key", "provider", "session_id", "t3_thread_id"): + if got.get(k) != rep.identity.get(k): + rep.step("receipt", "failed", "the receipt at %s belongs to another thread (%s %r, this thread %r); nothing done" + % (rpath, k, got.get(k), rep.identity.get(k))) + return print_report(rep, args.json) + mode = rec.get("mode") + if mode not in MODES or rec.get("dry_run"): + rep.step("receipt", "failed", "the receipt at %s is not a real pause, move or close run; nothing done" % rpath) + return print_report(rep, args.json) + if mode == "close": + if (args.logged is None) == (args.declined is None): + raise Usage("after a close, finish needs exactly one of --logged N or --declined REASON") + elif args.logged is not None or args.declined is not None: + raise Usage("--logged and --declined apply only after a close; this receipt is a %s" % mode) + rep.mode = "finish (%s)" % mode + if rec.get("status") == "failed": + rep.step("receipt", "failed", "the %s run failed (%s); fix it and run session-end %s again; no stamp" % (mode, rpath, mode)) + return print_report(rep, args.json) + rep.step("receipt", "completed", "%s run of %s" % (mode, rec.get("written_at"))) + findings = rec.get("lint_findings") or [] + if findings: + # Reported, never a refusal: whose FAIL each is was the agent's call at the start. + rep.step("lint findings", "completed", "lint findings were reported at the start: %d" % len(findings), + "\n".join(findings)) + gc = rec.get("gc") or {} + if gc.get("status") == "pending": + rd = gc.get("run_dir") or "" + if os.path.dirname(rd) != gc_root(state): + rep.step("branch-gc", "failed", "the receipt names an unexpected GC run directory %r" % rd) + return print_report(rep, args.json) + try: + res = read_result(rd) + except (OSError, ValueError) as e: + rep.step("branch-gc", "failed", "unreadable GC result in %s: %s" % (rd, e)) + return print_report(rep, args.json) + if res is None: + if lock_held(os.path.join(rd, "worker.lock")): + rep.step("branch-gc", "failed", "GC is still running (%s); run finish again once %s/result.json exists; no stamp" % (rd, rd)) + else: + rep.step("branch-gc", "failed", "the GC worker ended without a result; see %s/run.log; no stamp" % rd) + return print_report(rep, args.json) + if res.get("status") != "completed": + rep.step("branch-gc", "failed", "GC finished with a failure; no stamp", "\n".join(describe_result(res, rd)), + human="\n".join(describe_result(res, rd, row_namer(None, set())))) + return print_report(rep, args.json) + rep.step("branch-gc", "completed", "the pending GC run finished cleanly", "\n".join(describe_result(res, rd)), + human="\n".join(describe_result(res, rd, row_namer(None, set())))) + if mode == "close": + if args.logged is not None: + outcome = "logged=%s time entries created and read back" % args.logged + else: + outcome = "declined: %s" % args.declined + why = billing_key_ok(idn) + if why and idn["provider"] != "claude": + rep.step("billing stamps", "skipped", why) + elif why: + rep.step("billing stamps", "failed", why + "; originals left in place; no stamp") + return print_report(rep, args.json) + else: + ok, lines = archive_billing(idn["key"], outcome) + rep.step("billing stamps", "completed" if ok else "failed", + "%s: %s" % ("recorded outcome" if ok else "archive failed for outcome", outcome), "\n".join(lines)) + if not ok: + return print_report(rep, args.json) + try: + atomic_write(os.path.join(state, "last-closeout"), stamp_text() + "\n", mode=0o644) + done = os.path.join(state, "session-end", "done") + mkdirs(done) + os.replace(rpath, os.path.join(done, "%s-%s.json" % (idn["key"], time.strftime("%Y%m%dT%H%M%S")))) + except OSError as e: + rep.step("closeout stamp", "failed", "cannot write %s/last-closeout or retire the receipt: %s" % (state, e.strerror or e)) + return print_report(rep, args.json) + rep.step("closeout stamp", "completed", "advanced %s/last-closeout; receipt moved to %s" % (state, done)) + return print_report(rep, args.json) + + +def run_ending(args): + """Serialize the entire read/act/retire cycle per receipt key. Locking just + archive_billing let an overlapping start replace the receipt a finish then + retired, and let two starts both launch a worker before either set the run + pointer. The lock must cover the receipt read through its retirement.""" + idn = identity(os.getcwd()) + if args.cmd == "end" and args.dry_run: + return cmd_end(args, idn) + rep = Report("finish" if args.cmd == "finish" else args.mode, False) + rep.identity = {k: idn[k] for k in ("provider", "session_id", "t3_thread_id", "key", "backend", "cwd")} + why = lane_refusal() + if why: + rep.step("lane check", "failed", why) + return print_report(rep, args.json) + state = state_dir() + if not state or not idn["key"]: + rep.step("receipt", "failed", "no state directory or stamp key (%s); nothing done" % + (idn["key_error"] or "no gate script beside session-end")) + return print_report(rep, args.json) + try: + lock_dir = os.path.join(state, "session-end", "locks") + mkdirs(lock_dir) + lfd = os.open(os.path.join(lock_dir, "billing-%s.lock" % idn["key"]), + os.O_RDWR | os.O_CREAT | os.O_NOFOLLOW, 0o600) + except OSError as e: + rep.step("receipt lock", "failed", "cannot acquire the receipt/billing lock: %s; nothing done" % e) + return print_report(rep, args.json) + try: + end = time.monotonic() + lock_wait() + while True: + try: + fcntl.flock(lfd, fcntl.LOCK_EX | fcntl.LOCK_NB) + break + except BlockingIOError: + if time.monotonic() >= end: + rep.step("receipt lock", "failed", "another ending for this key holds the billing lock; nothing done") + return print_report(rep, args.json) + time.sleep(min(0.1, max(0, end - time.monotonic()))) + return cmd_finish(args, idn) if args.cmd == "finish" else cmd_end(args, idn) + finally: + os.close(lfd) + + +# --- arguments ------------------------------------------------------------------ + +class Parser(argparse.ArgumentParser): + def error(self, message): + raise Usage(message) + + +def wait_seconds(v): + try: + f = float(v) + except ValueError: + raise argparse.ArgumentTypeError("--wait takes seconds, got %r" % v) + if not math.isfinite(f) or f < 0: + raise argparse.ArgumentTypeError("--wait takes a finite nonnegative number of seconds, got %r" % v) + return f + + +def logged_count(v): + if not re.fullmatch(r"[0-9]+", v or ""): + raise argparse.ArgumentTypeError("--logged takes a nonnegative whole number of time entries, got %r" % v) + return int(v) + + +def reason_text(v): + v = (v or "").strip() + if not v or any(ord(ch) < 32 for ch in v): + raise argparse.ArgumentTypeError("--declined needs a nonempty one-line reason") + return v + + +def parse(argv): + if argv[:1] == ["finish"]: + p = Parser(prog="session-end finish", description="Finish an ending after knowledge capture (see the header).") + g = p.add_mutually_exclusive_group() + g.add_argument("--logged", type=logged_count, metavar="N") + g.add_argument("--declined", type=reason_text, metavar="REASON") + p.add_argument("--json", action="store_true") + a = p.parse_args(argv[1:]) + a.cmd = "finish" + return a + p = Parser(prog="session-end", description="The mechanical half of ending a thread (see the header). " + "Also: session-end finish [--logged N | --declined REASON] [--json].") + p.add_argument("mode", choices=MODES) + p.add_argument("--repo", action="append", default=[], metavar="PATH") + p.add_argument("--transcript", metavar="FILE") + p.add_argument("--wait", type=wait_seconds, default=90.0, metavar="SECONDS") + p.add_argument("--dry-run", action="store_true") + p.add_argument("--json", action="store_true") + a = p.parse_args(argv) + a.cmd = "end" + return a + + +def main(argv): + if argv[:1] == ["_gc-worker"] and len(argv) == 3: + return gc_worker(argv[1], int(argv[2])) + if argv[:1] in (["-h"], ["--help"]): + print(__doc__) + return 0 + try: + args = parse(argv) + return run_ending(args) + except Usage as e: + sys.stderr.write("session-end: %s\n(session-end [--repo PATH]... [--transcript FILE] " + "[--wait SECONDS] [--dry-run] [--json] | session-end finish [--logged N | --declined REASON] [--json])\n" % e) + return 2 + + +if __name__ == "__main__": + sys.exit(main(sys.argv[1:])) diff --git a/.claude-config/bin/tests/active-minutes-test.py b/.claude-config/bin/tests/active-minutes-test.py new file mode 100644 index 0000000..d7028d0 --- /dev/null +++ b/.claude-config/bin/tests/active-minutes-test.py @@ -0,0 +1,843 @@ +#!/usr/bin/env python3 +"""Behavior tests for bin/active-minutes: billable working minutes from a session transcript. + +Standard library only (unittest): no pytest is installed in CI, and a pytest +module run as `python3 ` prints nothing and exits 0, a vacuous green. This +file runs its tests under `python3 ` and exits non-zero on a failure; one +case below proves that by running the file itself. + +Offline. The script runs as a subprocess on a synthetic transcript in a +temporary directory, so nothing here reads a real session transcript. Every run +gets TZ=UTC unless a case says otherwise, so no result depends on the box's own +zone. + +Three groups. The display zone of the contiguous work blocks: the blocks print on +a time entry's Time line, so a wrong offset puts a wrong window on a billed +entry. The defect these tests pin: a fixed UTC-4 display read every block an hour +late once US Eastern went back to UTC-5 (an 18:05 ET start printed as 19:05). +The ACTIVE total never depended on the display zone, and one case holds that so +a later change cannot make it start to. The gap rule: every silent stretch over +the threshold is classified and printed with its cause, because a billed +figure that silently drops or silently adds an hour is a wrong bill. And the +hook mode (--since-last-entry --brief) with its --time-tool option. + +The two Eastern changes the zone cases straddle (UTC instants): + fall back 2026-11-01 06:00Z 02:00 EDT -> 01:00 EST + spring fwd 2027-03-14 07:00Z 02:00 EST -> 03:00 EDT +""" +import json +import os +import re +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path + +SCRIPT = Path(__file__).resolve().parent.parent / "active-minutes" +BLOCK = re.compile(r"^ (\d\d-\d\d \d\d:\d\d(?: [A-Za-z+\-0-9]{2,6})?) -> (\d\d-\d\d \d\d:\d\d(?: [A-Za-z+\-0-9]{2,6})?) \(([\d.]+) min\)$") +NY = ("--zone", "America/New_York") +TIME_TOOL_NAME = "mcp__example-psa__psa__time_manage" +# Ticket forms: a ticket number (T plus eight digits, a dot, a sequence) and a numeric id. +# Built from parts: a literal in this shape reads as a real ticket number to a scanner. +TICKET_NO = "T" + "20260101" + ".0001" +TICKET_NO_OTHER = "T" + "20260101" + ".0099" +TICKET_ID = "10001" +TICKET_ID_OTHER = "10002" + + +def base_env(**extra): + """The test process's environment with TZ pinned to UTC, then EXTRA on top.""" + env = {k: v for k, v in os.environ.items() if k != "TZ"} + env.update(TZ="UTC", PYTHONDONTWRITEBYTECODE="1") + env.update(extra) + return env + + +def run(tmp_path, stamps, *args, env=None): + """Run the script on a transcript of the given UTC stamps; return the + CompletedProcess (text).""" + transcript = tmp_path / "t.jsonl" + transcript.write_text("".join(json.dumps({"timestamp": s}) + "\n" for s in stamps)) + return subprocess.run( + [sys.executable, str(SCRIPT), str(transcript), *args], + capture_output=True, text=True, env=env or base_env(), timeout=60, + ) + + +def every(start_hhmm_utc, count, step_min, day="2026-11-01"): + """UTC stamps from a start time, one every step_min minutes (always under + the 30 minute gap, so they form one block).""" + h, m = map(int, start_hhmm_utc.split(":")) + base = h * 60 + m + return [f"{day}T{(base + i * step_min) // 60:02d}:{(base + i * step_min) % 60:02d}:00Z" for i in range(count)] + + +def active_line(proc): + return next(l for l in proc.stdout.splitlines() if l.startswith("ACTIVE")) + + +# --- the gap rule: classify every gap, print its cause ----------------------- +# +# An interactive session counts its whole span, pauses included. A gap that ends +# with a prompt the operator typed counts; a usage-limit hold, an overnight stop +# and an idle wait for a scheduled check do not, because a hold is not work and a +# break needs evidence. Records below carry the shapes real transcripts carry: a +# T3 queue-operation enqueue, a user message, an assistant message, an API error. + +GAP_LINE = re.compile(r"^ (COUNTED|EXCLUDED) +([\d.]+) min (.+?) -> (.+?) \[([\dT:-]+)\] (.*)$") + + +def iso(day_hhmm): + """'11-06 14:10' -> a UTC stamp on 2026-11-06 (the cases stay in one month).""" + day, hhmm = day_hhmm.split() + return f"2026-{day}T{hhmm}:00Z" + + +def assistant(at, text="ok", **extra): + return {"timestamp": iso(at), "type": "assistant", "message": {"content": [{"type": "text", "text": text}]}, **extra} + + +def human(at, text): + return {"timestamp": iso(at), "type": "user", "promptSource": "sdk", "message": {"role": "user", "content": text}} + + +def tool_result(at): + return {"timestamp": iso(at), "type": "user", "toolUseResult": {}, "message": {"content": [{"type": "tool_result", "tool_use_id": "x", "content": "ok"}]}} + + +def queued(at, text): + return {"timestamp": iso(at), "type": "queue-operation", "operation": "enqueue", "content": text} + + +def api_error(at, error="rate_limit", text="You've hit your limit · resets 3am"): + return {"timestamp": iso(at), "type": "assistant", "isApiErrorMessage": True, "error": error, + "message": {"content": [{"type": "text", "text": text}]}} + + +def launch(at, tool_id): + return {"timestamp": iso(at), "type": "assistant", "message": {"content": [{"type": "tool_use", "id": tool_id, "name": "Workflow", "input": {}}]}} + + +def notice(tool_id): + return f"\nw1\n{tool_id}\ncompleted\n" + + +def time_create(at, ticket, tool=TIME_TOOL_NAME): + return {"timestamp": iso(at), "type": "assistant", "message": {"content": [{"type": "tool_use", "id": "toolu_T" + at.replace(" ", "").replace(":", ""), + "name": tool, "input": {"mode": "create", "ticket": ticket}}]}} + + +def overnight_task_records(): + # A background watcher launched at 20:05 whose notice arrives at 10:00 the + # next morning: the transcript holds a launch record and nothing else. + return [human("11-05 20:00", "watch the build"), launch("11-05 20:05", "toolu_NIGHT"), assistant("11-05 20:06", "Watching in the background."), + queued("11-06 10:00", notice("toolu_NIGHT")), assistant("11-06 10:01", "It exited.")] + + +class ActiveMinutesTest(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory(prefix="active-minutes-test.") + self.addCleanup(self.tmp.cleanup) + self.tmp_path = Path(self.tmp.name) + + # --- helpers bound to this test's directory ----------------------------- + + def run_stamps(self, stamps, *args, env=None): + return run(self.tmp_path, stamps, *args, env=env) + + def parsed(self, proc): + """(header, blocks) from stdout, blocks as (start, end, minutes) strings; + asserts the run succeeded so a crash never reads as 'no blocks'.""" + self.assertEqual(proc.returncode, 0, proc.stderr) + lines = proc.stdout.splitlines() + header = next(l for l in lines if l.startswith("contiguous work blocks")) + blocks = [BLOCK.match(l).groups() for l in lines[lines.index(header) + 1:] if l.strip()] + return header, blocks + + def run_records(self, records, *args, name="t.jsonl", env=None): + path = self.tmp_path / name + path.write_text("".join(json.dumps(r) + "\n" for r in records)) + return subprocess.run([sys.executable, str(SCRIPT), str(path), *args], capture_output=True, text=True, + env=env or base_env(), timeout=60) + + def gaps_of(self, proc): + self.assertEqual(proc.returncode, 0, proc.stderr) + return [GAP_LINE.match(l).groups() for l in proc.stdout.splitlines() if GAP_LINE.match(l)] + + def active_minutes(self, proc): + return float(re.search(r"ACTIVE.*?: ([\d.]+) min", proc.stdout).group(1)) + + # --- the display zone: converted per timestamp --------------------------- + + def test_block_before_the_fall_change_prints_in_edt(self): + # 22:05Z to 22:35Z on 10-31 is 18:05 to 18:35 EDT (UTC-4). + header, blocks = self.parsed(self.run_stamps(["2026-10-31T22:05:00Z", "2026-10-31T22:20:00Z", "2026-10-31T22:35:00Z"], *NY)) + self.assertEqual(header, "contiguous work blocks (America/New_York):") + self.assertEqual(blocks, [("10-31 18:05 EDT", "10-31 18:35 EDT", "30.0")]) + + def test_block_after_the_fall_change_prints_in_est(self): + # The reported defect: 23:05Z on 11-02 is 18:05 EST (UTC-5), and used to + # print as 19:05. + _, blocks = self.parsed(self.run_stamps(["2026-11-02T23:05:00Z", "2026-11-02T23:20:00Z", "2026-11-02T23:35:00Z"], *NY)) + self.assertEqual(blocks, [("11-02 18:05 EST", "11-02 18:35 EST", "30.0")]) + + def test_block_spanning_the_fall_change_prints_each_end_in_its_own_offset(self): + # 04:30Z is 00:30 EDT; 07:00Z is 02:00 EST. The elapsed time is 150 min, + # not the 90 min the two wall-clock readings alone suggest. + _, blocks = self.parsed(self.run_stamps(every("04:30", 8, 20) + ["2026-11-01T07:00:00Z"], *NY)) + self.assertEqual(blocks, [("11-01 00:30 EDT", "11-01 02:00 EST", "150.0")]) + + def test_block_spanning_the_spring_change_prints_each_end_in_its_own_offset(self): + # 06:30Z is 01:30 EST; 07:30Z is 03:30 EDT (the 02:00 hour does not exist). + stamps = ["2027-03-14T06:30:00Z", "2027-03-14T07:00:00Z", "2027-03-14T07:30:00Z"] + _, blocks = self.parsed(self.run_stamps(stamps, *NY)) + self.assertEqual(blocks, [("03-14 01:30 EST", "03-14 03:30 EDT", "60.0")]) + + def test_fall_back_hour_prints_distinct_times_for_distinct_instants(self): + # 05:30Z and 06:30Z are one hour apart yet both read 01:30 on the wall; the + # zone tag is what keeps the two ends of the block apart. + _, blocks = self.parsed(self.run_stamps(["2026-11-01T05:30:00Z", "2026-11-01T06:00:00Z", "2026-11-01T06:30:00Z"], *NY)) + self.assertEqual(blocks, [("11-01 01:30 EDT", "11-01 01:30 EST", "60.0")]) + + def test_two_blocks_either_side_of_the_change_each_use_their_own_offset(self): + # A gap over 30 minutes splits the blocks; the 10-31 block is EDT, the + # 11-02 block is EST. + stamps = ["2026-10-31T22:05:00Z", "2026-10-31T22:30:00Z", "2026-11-02T23:05:00Z", "2026-11-02T23:30:00Z"] + _, blocks = self.parsed(self.run_stamps(stamps, *NY)) + self.assertEqual(blocks, [ + ("10-31 18:05 EDT", "10-31 18:30 EDT", "25.0"), + ("11-02 18:05 EST", "11-02 18:30 EST", "25.0"), + ]) + + def test_host_time_zone_does_not_change_the_display(self): + # A named --zone is the display zone, never the box's own TZ. (The default + # without --zone does follow TZ: the cases below.) + env = base_env(TZ="Asia/Tokyo") + _, blocks = self.parsed(self.run_stamps(["2026-11-02T23:05:00Z", "2026-11-02T23:35:00Z"], *NY, env=env)) + self.assertEqual(blocks, [("11-02 18:05 EST", "11-02 18:35 EST", "30.0")]) + + # --- the zone default: --zone, then TZ, then the machine, then UTC -------- + + def test_default_zone_follows_a_valid_tz(self): + stamps = ["2026-11-02T23:05:00Z", "2026-11-02T23:35:00Z"] + header, blocks = self.parsed(self.run_stamps(stamps, env=base_env(TZ="America/New_York"))) + self.assertEqual(header, "contiguous work blocks (America/New_York):") + self.assertEqual(blocks, [("11-02 18:05 EST", "11-02 18:35 EST", "30.0")]) + header, blocks = self.parsed(self.run_stamps(stamps, env=base_env(TZ="Asia/Tokyo"))) + self.assertEqual(header, "contiguous work blocks (Asia/Tokyo):") + self.assertEqual(blocks, [("11-03 08:05 JST", "11-03 08:35 JST", "30.0")]) + + def test_zone_option_beats_tz_and_names_the_header(self): + stamps = ["2026-11-02T23:05:00Z", "2026-11-02T23:35:00Z"] + header, blocks = self.parsed(self.run_stamps(stamps, "--zone", "Europe/London", env=base_env(TZ="Asia/Tokyo"))) + self.assertEqual(header, "contiguous work blocks (Europe/London):") + self.assertEqual(blocks, [("11-02 23:05 GMT", "11-02 23:35 GMT", "30.0")]) + + def machine_expectation(self): + """The first block's start as this box's own zone prints it, asked of a + fresh interpreter with TZ unset, so the case holds on any host zone.""" + code = ("import datetime; print(datetime.datetime(2026, 11, 2, 23, 5, tzinfo=datetime.timezone.utc)" + ".astimezone().strftime('%m-%d %H:%M %Z'))") + env = {k: v for k, v in base_env().items() if k != "TZ"} + out = subprocess.run([sys.executable, "-c", code], capture_output=True, text=True, env=env, timeout=30) + self.assertEqual(out.returncode, 0, out.stderr) + return out.stdout.strip() + + def test_unset_or_invalid_tz_falls_back_to_the_machine_zone(self): + stamps = ["2026-11-02T23:05:00Z", "2026-11-02T23:35:00Z"] + want = self.machine_expectation() + unset = {k: v for k, v in base_env().items() if k != "TZ"} + _, blocks = self.parsed(self.run_stamps(stamps, env=unset)) + self.assertEqual(blocks[0][0], want) + # A TZ that names no zone is ignored, not an error: the machine zone is used. + _, blocks = self.parsed(self.run_stamps(stamps, env=base_env(TZ="Not/AZone"))) + self.assertEqual(blocks[0][0], want) + + def test_no_machine_zone_falls_back_to_utc(self): + # Hide /etc/localtime from the script (a container or a platform without it): + # with no zone anywhere the display is UTC, never a guessed city. + transcript = self.tmp_path / "t.jsonl" + transcript.write_text("".join(json.dumps({"timestamp": s}) + "\n" for s in ["2026-11-02T23:05:00Z", "2026-11-02T23:35:00Z"])) + snippet = ( + "import builtins, os, runpy, sys\n" + "real_open = builtins.open\n" + "def fake_open(path, *a, **k):\n" + " if str(path) == '/etc/localtime': raise FileNotFoundError(path)\n" + " return real_open(path, *a, **k)\n" + "builtins.open = fake_open\n" + "def no_link(path, *a, **k): raise OSError('no link')\n" + "os.readlink = no_link\n" + "sys.argv = [%r, %r]\n" + "runpy.run_path(%r, run_name='__main__')\n" % (str(SCRIPT), str(transcript), str(SCRIPT))) + for tz in (None, "Not/AZone"): + with self.subTest(tz=tz): + env = {k: v for k, v in base_env().items() if k != "TZ"} + if tz: + env["TZ"] = tz + proc = subprocess.run([sys.executable, "-c", snippet], capture_output=True, text=True, env=env, timeout=60) + header, blocks = self.parsed(proc) + self.assertEqual(header, "contiguous work blocks (UTC):") + self.assertEqual(blocks, [("11-02 23:05 UTC", "11-02 23:35 UTC", "30.0")]) + + def test_zone_and_tz_offset_cannot_be_combined_and_an_unknown_zone_stops_the_run(self): + stamps = ["2026-11-02T23:05:00Z", "2026-11-02T23:35:00Z"] + both = self.run_stamps(stamps, "--zone", "America/New_York", "--tz-offset", "-5") + self.assertEqual(both.returncode, 2) + self.assertIn("not allowed with", both.stderr) + unknown = self.run_stamps(stamps, "--zone", "Not/AZone") + self.assertEqual(unknown.returncode, 2) + self.assertEqual(len(unknown.stderr.strip().splitlines()), 1, unknown.stderr) + self.assertIn("Not/AZone", unknown.stderr) + self.assertNotIn("contiguous work blocks", unknown.stdout) + + # --- --tz-offset: the explicit fixed-offset override ---------------------- + + def test_tz_offset_override_is_fixed_and_labeled(self): + # -4 kept on purpose for post-change data: an operator who asks for it + # gets it, with no zone tag, and the header says what was used. + header, blocks = self.parsed(self.run_stamps(["2026-11-02T23:05:00Z", "2026-11-02T23:35:00Z"], "--tz-offset", "-4")) + self.assertEqual(header, "contiguous work blocks (tz-offset -4):") + self.assertEqual(blocks, [("11-02 19:05", "11-02 19:35", "30.0")]) + + def test_tz_offset_override_applies_one_offset_across_the_change(self): + # Fixed means fixed: both ends of the spanning block use -5. + stamps = every("04:30", 8, 20) + ["2026-11-01T07:00:00Z"] + header, blocks = self.parsed(self.run_stamps(stamps, "--tz-offset", "-5")) + self.assertEqual(header, "contiguous work blocks (tz-offset -5):") + self.assertEqual(blocks, [("10-31 23:30", "11-01 02:00", "150.0")]) + + def test_tz_offset_zero_and_fractional_are_honored(self): + stamps = ["2026-11-02T23:05:00Z", "2026-11-02T23:35:00Z"] + header, blocks = self.parsed(self.run_stamps(stamps, "--tz-offset", "0")) + self.assertEqual(header, "contiguous work blocks (tz-offset +0):") + self.assertEqual(blocks, [("11-02 23:05", "11-02 23:35", "30.0")]) + header, blocks = self.parsed(self.run_stamps(stamps, "--tz-offset", "5.5")) + self.assertEqual(header, "contiguous work blocks (tz-offset +5.5):") + self.assertEqual(blocks, [("11-03 04:35", "11-03 05:05", "30.0")]) + + def test_tz_offset_out_of_range_stops_the_run(self): + # An unusable override must stop the run, never fall back to another zone + # and print blocks the operator did not ask for. + for bad in ["24", "-24", "30", "nan", "inf"]: + with self.subTest(bad=bad): + proc = self.run_stamps(["2026-11-02T23:05:00Z", "2026-11-02T23:35:00Z"], f"--tz-offset={bad}") + self.assertEqual(proc.returncode, 2) + self.assertIn("--tz-offset: need hours strictly between -24 and 24", proc.stderr) + self.assertNotIn("contiguous work blocks", proc.stdout) + + # --- the display zone never touches the measurement ------------------------ + + def test_active_total_and_gap_rule_are_identical_in_every_display_zone(self): + # Two blocks (25 min each) around a 30 min+ gap: the total counts the + # blocks and drops the gap, whatever zone prints them. + stamps = ["2026-10-31T22:05:00Z", "2026-10-31T22:30:00Z", "2026-11-02T23:05:00Z", "2026-11-02T23:30:00Z"] + default = self.run_stamps(stamps, *NY) + self.assertIn("50.0 min = 0.8333 h -> 0.83 h", active_line(default)) + self.assertIn("excluded gaps : 1", default.stdout) + for offset in ("-4", "-5", "0", "5.5", "-12", "13"): + fixed = self.run_stamps(stamps, "--tz-offset", offset) + self.assertEqual(active_line(fixed), active_line(default), offset) + self.assertIn("excluded gaps : 1", fixed.stdout, offset) + for zone in ("Asia/Tokyo", "Europe/London", "UTC"): + named = self.run_stamps(stamps, "--zone", zone) + self.assertEqual(active_line(named), active_line(default), zone) + + def test_a_bad_option_exits_2_even_when_the_transcript_is_too_short(self): + # The zone and offset are checked before the transcript is read, so a bad + # --tz-offset is a usage error (2), not the short-transcript exit (1). + proc = self.run_stamps(["2026-11-02T23:05:00Z"], "--tz-offset", "99") + self.assertEqual(proc.returncode, 2) + self.assertIn("--tz-offset: need hours strictly between -24 and 24", proc.stderr) + + def test_billable_hours_never_round_up(self): + proc = self.run_stamps(["2026-11-06T10:00:00Z", "2026-11-06T10:20:00Z", "2026-11-06T10:40:00Z"]) + self.assertEqual(proc.returncode, 0, proc.stderr) + self.assertIn("40.0 min = 0.6667 h -> 0.66 h", active_line(proc)) + boundary = self.run_stamps(["2026-11-06T10:00:00Z", "2026-11-06T10:06:00Z"]) + self.assertIn("6.0 min = 0.1000 h -> 0.10 h", active_line(boundary)) + + # --- failure and help ----------------------------------------------------- + + def test_missing_zone_database_stops_the_run_and_names_the_override(self): + # With no system tz database and no tzdata package, a named zone cannot + # load. That must be one named line pointing at --tz-offset, not blocks + # printed in a guessed zone. PYTHONTZPATH empties the system search path, + # and a stub tzdata package that fails to import shadows any installed one + # (zoneinfo reads an ImportError from tzdata as "no zone"), so this case + # runs on every machine instead of skipping where tzdata is installed. + empty = self.tmp_path / "no-zoneinfo" + empty.mkdir() + stub = self.tmp_path / "stub" / "tzdata" + stub.mkdir(parents=True) + (stub / "__init__.py").write_text('raise ImportError("tzdata hidden by the test")\n') + pythonpath = os.pathsep.join(filter(None, [str(stub.parent), os.environ.get("PYTHONPATH")])) + stamps = ["2026-11-02T23:05:00Z", "2026-11-02T23:35:00Z"] + # Both ways to name a zone hit it: the option, and the TZ variable. + for label, args, tz in (("--zone", NY, "UTC"), ("TZ", (), "America/New_York")): + with self.subTest(named_by=label): + env = base_env(TZ=tz, PYTHONTZPATH=str(empty), PYTHONPATH=pythonpath) + proc = self.run_stamps(stamps, *args, env=env) + self.assertEqual(proc.returncode, 2) + self.assertEqual(len(proc.stderr.strip().splitlines()), 1, proc.stderr) + self.assertIn("time zone database", proc.stderr) + self.assertTrue("America/New_York" in proc.stderr or "UTC" in proc.stderr) + self.assertIn("--tz-offset", proc.stderr) + self.assertNotIn("contiguous work blocks", proc.stdout) + # The documented escape works on the same machine. + env = base_env(TZ="America/New_York", PYTHONTZPATH=str(empty), PYTHONPATH=pythonpath) + _, blocks = self.parsed(self.run_stamps(stamps, "--tz-offset", "-5", env=env)) + self.assertEqual(blocks, [("11-02 18:05", "11-02 18:35", "30.0")]) + + def test_help_and_docstring_describe_the_zone_default(self): + out = subprocess.run([sys.executable, str(SCRIPT), "--help"], capture_output=True, text=True, env=base_env(), timeout=60) + self.assertEqual(out.returncode, 0) + flat = " ".join(out.stdout.split()) + self.assertIn("--zone NAME", flat) + self.assertIn("$TZ", flat) + self.assertIn("daylight saving", flat) + self.assertIn("--time-tool NAME", flat) + self.assertNotIn("default -4", flat) # the old fixed default + self.assertNotIn("US Eastern DST", flat) + doc = " ".join(SCRIPT.read_text().split('"""')[1].split()) + for needle in ("--zone NAME", "--tz-offset H", "--time-tool NAME", "else UTC"): + self.assertIn(needle, doc, needle) + + # --- the gap rule ----------------------------------------------------------- + + def test_a_45_minute_interactive_pause_counts_as_work(self): + # The operator reads a report and works a console for 45 minutes, then types + # the next message. The whole span is billed, pauses included. 10 min of + # chat before, the 45 min pause, 10 min of chat after. + records = [human("11-06 14:00", "run the audit"), assistant("11-06 14:10", "Audit done; check the portal and tell me what it shows."), + human("11-06 14:55", "The portal shows two failures."), assistant("11-06 15:05", "Fixed.")] + proc = self.run_records(records) + self.assertEqual(self.active_minutes(proc), 65.0) # 10 + 45 + 10 + self.assertIn("counted gaps : 1, total 45.0 min", proc.stdout) + self.assertIn("excluded gaps : 0", proc.stdout) + [(verdict, mins, _, _, _, cause)] = self.gaps_of(proc) + self.assertEqual((verdict, mins), ("COUNTED", "45.0")) + self.assertTrue(cause.startswith("attended pause")) + self.assertIn("The portal shows two failures", cause) + _, blocks = self.parsed(proc) + self.assertEqual(len(blocks), 1) # the counted gap does not split the block + + def test_the_same_45_minutes_are_excluded_under_the_strict_old_rule(self): + records = [human("11-06 14:00", "run the audit"), assistant("11-06 14:10"), human("11-06 14:55", "ok"), assistant("11-06 15:05")] + proc = self.run_records(records, "--strict") + self.assertEqual(self.active_minutes(proc), 20.0) + self.assertEqual([g[0] for g in self.gaps_of(proc)], ["EXCLUDED"]) + + def test_a_usage_limit_hold_is_excluded_with_its_cause_even_when_a_typed_prompt_ends_it(self): + # The agent hits a limit at 23:17 and the operator types "continue" at 09:30. + # Nobody worked in between and a hold needs evidence of work to count, so + # the 10 h 13 min are listed and left out. + records = [human("11-05 22:50", "keep going"), assistant("11-05 23:10", "Working."), api_error("11-05 23:17"), + human("11-06 09:30", "continue"), assistant("11-06 09:40", "Resumed.")] + proc = self.run_records(records) + [(verdict, mins, _, _, _, cause)] = self.gaps_of(proc) + self.assertTrue(verdict == "EXCLUDED" and mins == "613.0") + self.assertTrue(cause.startswith("usage-limit hold")) + self.assertIn("hit your limit", cause) + self.assertEqual(self.active_minutes(proc), 27.0 + 10.0) # 22:50 to 23:17, then 09:30 to 09:40 + _, blocks = self.parsed(proc) + self.assertEqual(len(blocks), 2) + + def test_another_provider_error_hold_is_excluded_by_its_error_name(self): + records = [assistant("11-06 10:00"), api_error("11-06 10:05", error="authentication_failed", text="OAuth session expired"), + human("11-06 11:30", "I re-logged in"), assistant("11-06 11:35")] + [(verdict, _, _, _, _, cause)] = self.gaps_of(self.run_records(records)) + self.assertEqual(verdict, "EXCLUDED") + self.assertIn("provider error hold (authentication_failed)", cause) + + def test_a_limit_hold_ended_by_a_fleet_notice_is_still_a_hold(self): + records = [assistant("11-06 08:00"), api_error("11-06 08:05"), queued("11-06 12:00", "Automated fleet notice: capacity cleared, continue."), assistant("11-06 12:01")] + [(verdict, _, _, _, _, cause)] = self.gaps_of(self.run_records(records)) + self.assertEqual(verdict, "EXCLUDED") + self.assertTrue(cause.startswith("usage-limit hold")) + + def test_an_overnight_gap_over_the_attended_ceiling_is_listed_and_excluded(self): + records = [human("11-05 21:00", "go"), assistant("11-05 21:20", "Done."), human("11-06 08:10", "Morning, next one."), assistant("11-06 08:20")] + proc = self.run_records(records) + [(verdict, mins, _, _, key, cause)] = self.gaps_of(proc) + self.assertEqual(verdict, "EXCLUDED") + self.assertIn("over 4 h", cause) + self.assertIn("Morning, next one", cause) + self.assertEqual(self.active_minutes(proc), 30.0) + # --keep, given by the operator's evidence, counts exactly that gap. + kept = self.run_records(records, "--keep", key) + self.assertEqual([g[0] for g in self.gaps_of(kept)], ["COUNTED"]) + self.assertEqual(self.active_minutes(kept), 30.0 + float(mins)) + self.assertIn("kept", self.gaps_of(kept)[0][5]) + # So does a higher ceiling. + self.assertEqual([g[0] for g in self.gaps_of(self.run_records(records, "--attended-max", "12"))], ["COUNTED"]) + + def test_the_ceiling_is_inclusive_at_exactly_four_hours(self): + records = [assistant("11-06 10:00"), human("11-06 14:00", "back at it"), assistant("11-06 14:05")] + self.assertEqual([g[0] for g in self.gaps_of(self.run_records(records))], ["COUNTED"]) + records = [assistant("11-06 10:00"), human("11-06 14:01", "back at it"), assistant("11-06 14:05")] + self.assertEqual([g[0] for g in self.gaps_of(self.run_records(records))], ["EXCLUDED"]) + + def test_a_stated_break_before_the_gap_is_excluded_and_quoted(self): + records = [human("11-06 12:00", "Going to lunch, back in an hour"), assistant("11-06 12:05", "Understood."), + human("11-06 13:20", "ok what did you find"), assistant("11-06 13:25")] + [(verdict, _, _, _, _, cause)] = self.gaps_of(self.run_records(records)) + self.assertEqual(verdict, "EXCLUDED") + self.assertIn("operator-stated break", cause) + self.assertIn("Going to lunch", cause) + + def test_a_break_remark_older_than_an_hour_does_not_excuse_the_gap(self): + # "lunch" was said at 09:00; the gap starts at 11:00 after real work. + records = [human("11-06 09:00", "Going to lunch soon, just do the audit"), assistant("11-06 09:20"), assistant("11-06 09:50"), + assistant("11-06 10:20"), assistant("11-06 10:50"), assistant("11-06 11:00", "Audit done."), + human("11-06 11:50", "thanks, now the next one"), assistant("11-06 11:55")] + [(verdict, _, _, _, _, cause)] = self.gaps_of(self.run_records(records)) + self.assertTrue(verdict == "COUNTED" and cause.startswith("attended pause")) + + def test_a_stated_break_when_the_operator_returns_is_excluded(self): + records = [assistant("11-06 12:00", "Report posted."), human("11-06 13:10", "I'm back, what do you need from me?"), assistant("11-06 13:15")] + [(verdict, _, _, _, _, cause)] = self.gaps_of(self.run_records(records)) + self.assertEqual(verdict, "EXCLUDED") + self.assertIn("when the operator returned", cause) + + def test_a_curly_apostrophe_in_the_return_remark_still_matches(self): + records = [assistant("11-06 12:00"), human("11-06 13:10", "I’m back"), assistant("11-06 13:15")] + self.assertEqual([g[0] for g in self.gaps_of(self.run_records(records))], ["EXCLUDED"]) + + def test_a_gap_ended_by_a_harness_message_is_idle_time(self): + # Each shape is text OPS or T3 itself sends into a thread as if typed. + cases = [ + ("Automated fleet notice: pool capacity cleared", "fleet notice"), + ("Context handoff (manual_context): Provider context handoff. Thread: abc", "context handoff"), + ("/compact", "compact command"), + ("Delegated task node:delegated-task:x reached a terminal state.", "delegated-task notice"), + ("FYI from the example foreman thread: the port is live", "cross-thread message"), + ("Scheduled one-time check from the example thread abc", "scheduled check"), + ("This session is being continued from a previous conversation.", "session continuation"), + ("Continue the standing work. Read the freshest durable anchor, then execute NEXT ACTION.", "resume baton"), + ("## RESUME PROTOCOL (updated 2026-11-06 12:00Z)", "resume baton"), + ] + for prompt, label in cases: + with self.subTest(label=label, prompt=prompt): + records = [assistant("11-06 10:00", "Waiting for the window."), queued("11-06 12:00", prompt), human("11-06 12:00", prompt), assistant("11-06 12:05")] + [(verdict, mins, _, _, _, cause)] = self.gaps_of(self.run_records(records)) + self.assertTrue(verdict == "EXCLUDED" and mins == "120.0") + self.assertTrue(cause.startswith(f"idle until {label}"), cause) + + def test_a_compaction_summary_is_not_a_typed_prompt(self): + summary = {"timestamp": iso("11-06 12:00"), "type": "user", "isCompactSummary": True, "isVisibleInTranscriptOnly": True, + "message": {"role": "user", "content": "The summarized conversation included..."}} + records = [assistant("11-06 10:00"), summary, assistant("11-06 12:01")] + [(verdict, _, _, _, _, cause)] = self.gaps_of(self.run_records(records)) + self.assertEqual(verdict, "EXCLUDED") + self.assertIn("compaction summary", cause) + + def test_a_long_tool_call_with_no_prompt_is_listed_with_a_cause_that_says_what_it_could_be(self): + # A call, its result 45 minutes later and nothing between looks the same + # whether a foreground call ran, a permission prompt waited or a hold went + # unrecorded, and counting it would bill holds. It stays EXCLUDED, but the + # cause must not read as if the agent simply resumed: it names the three + # shapes and the way to settle it. + records = [human("11-06 14:00", "run the long check"), launch("11-06 14:01", "toolu_FG"), tool_result("11-06 14:46"), assistant("11-06 14:47", "Done.")] + proc = self.run_records(records) + [(verdict, mins, _, _, _, cause)] = self.gaps_of(proc) + self.assertTrue(verdict == "EXCLUDED" and mins == "45.0" and cause.startswith("no prompt evidence")) + for needle in ("long tool call", "permission wait", "--also", "--keep"): + self.assertIn(needle, cause) + self.assertEqual(self.active_minutes(proc), 2.0) + + def test_a_tool_result_is_not_a_prompt(self): + # Nobody typed anything: the gap ends with a tool result, then the agent. + records = [assistant("11-06 10:00"), tool_result("11-06 11:00"), assistant("11-06 11:01")] + [(verdict, _, _, _, _, cause)] = self.gaps_of(self.run_records(records)) + self.assertTrue(verdict == "EXCLUDED" and cause.startswith("no prompt evidence")) + + def test_a_background_task_that_ran_through_the_gap_counts_as_unattended_agent_work(self): + # The foreman launched a workflow at 10:00 and waited; its notice arrived at + # 11:10. Unattended agent time counts like attended time. + records = [human("11-06 09:50", "run the sweep"), launch("11-06 10:00", "toolu_AAA"), assistant("11-06 10:01", "Running in the background."), + queued("11-06 11:10", notice("toolu_AAA")), assistant("11-06 11:11", "Finished.")] + proc = self.run_records(records) + [(verdict, mins, _, _, _, cause)] = self.gaps_of(proc) + self.assertTrue(verdict == "COUNTED" and mins == "69.0" and cause.startswith("background task")) + + def test_a_task_notice_with_no_launch_in_the_transcript_needs_evidence(self): + records = [assistant("11-06 10:00"), queued("11-06 11:10", notice("toolu_ZZZ")), assistant("11-06 11:11")] + [(verdict, _, _, _, _, cause)] = self.gaps_of(self.run_records(records)) + self.assertEqual(verdict, "EXCLUDED") + self.assertIn("launch is not in this transcript", cause) + self.assertIn("--also", cause) + + def test_an_overnight_background_task_with_only_a_launch_record_is_listed_not_counted(self): + # The launch-only branch once billed 14 hours. The measure bills work that + # ran, not elapsed time, so past the 4 h ceiling a launch record is not + # enough. + proc = self.run_records(overnight_task_records()) + [(verdict, mins, _, _, _, cause)] = self.gaps_of(proc) + self.assertTrue(verdict == "EXCLUDED" and mins == "834.0") + for needle in ("launch record is not work", "--also", "--keep"): + self.assertIn(needle, cause) + self.assertEqual(self.active_minutes(proc), 7.0) # 20:00 to 20:06, then 10:00 to 10:01 + + def test_an_overnight_background_task_counts_with_keep_evidence(self): + records = overnight_task_records() + [(_, _, _, _, key, _)] = self.gaps_of(self.run_records(records)) + kept = self.run_records(records, "--keep", key) + self.assertEqual([g[0] for g in self.gaps_of(kept)], ["COUNTED"]) + self.assertEqual(self.active_minutes(kept), 841.0) + + def test_an_overnight_background_task_counts_when_lane_trace_shows_work_inside_the_gap(self): + # The lane transcripts (--also) show the task working through the night: an + # event every 20 minutes, so there is no gap left to classify and the whole + # span is work, counted once. + records = overnight_task_records() + lane = self.tmp_path / "lane.jsonl" + stamps = ["2026-11-05T20:25:00Z"] + while stamps[-1] < "2026-11-06T09:45:00Z": + h, m = int(stamps[-1][11:13]), int(stamps[-1][14:16]) + 20 + day = stamps[-1][:10] + if m >= 60: h, m = h + 1, m - 60 + if h >= 24: h, day = h - 24, "2026-11-06" + stamps.append(f"{day}T{h:02d}:{m:02d}:00Z") + lane.write_text("".join(json.dumps({"timestamp": t}) + "\n" for t in stamps)) + with_lane = self.run_records(records, "--also", str(lane)) + self.assertEqual(self.gaps_of(with_lane), []) + self.assertEqual(self.active_minutes(with_lane), 841.0) + + def test_a_background_task_gap_is_counted_up_to_the_ceiling_and_listed_past_it(self): + # Inclusive at exactly 4 h, as for a typed prompt; one minute more is listed. + def records(hhmm): + # The gap runs from the 06:06 assistant record to the notice at hhmm. + h, m = map(int, hhmm.split(":")) + return [human("11-06 06:00", "run it"), launch("11-06 06:05", "toolu_C"), assistant("11-06 06:06", "Running."), + queued(f"11-06 {hhmm}", notice("toolu_C")), assistant(f"11-06 {h:02d}:{m + 1:02d}")] + self.assertEqual([g[0] for g in self.gaps_of(self.run_records(records("10:06")))], ["COUNTED"]) + self.assertEqual([g[0] for g in self.gaps_of(self.run_records(records("10:07")))], ["EXCLUDED"]) + # The ceiling is the same option as the attended pause's. + self.assertEqual([g[0] for g in self.gaps_of(self.run_records(records("10:07"), "--attended-max", "5"))], ["COUNTED"]) + + def test_lane_transcripts_passed_with_also_fill_the_gap_with_real_trace(self): + # The foreman is silent from 10:00 to 11:10 but a workflow lane worked the + # whole time: no gap, the hour counts, and nothing is double-counted. + main = [human("11-06 09:50", "run the sweep"), assistant("11-06 10:00"), assistant("11-06 11:10")] + lane = self.tmp_path / "lane.jsonl" + lane.write_text("".join(json.dumps({"timestamp": iso(f"11-06 {h:02d}:{m:02d}")}) + "\n" for h, m in [(10, 5), (10, 25), (10, 45), (11, 5)])) + plain = self.run_records(main) + with_lane = self.run_records(main, "--also", str(lane)) + self.assertEqual([g[0] for g in self.gaps_of(plain)], ["EXCLUDED"]) # alone, the silence is a gap + self.assertEqual(self.gaps_of(with_lane), []) + self.assertEqual(self.active_minutes(with_lane), 80.0) # 09:50 to 11:10, once + + def test_an_unreadable_also_file_stops_the_run(self): + proc = self.run_records([assistant("11-06 10:00"), assistant("11-06 10:05")], "--also", str(self.tmp_path / "missing.jsonl")) + self.assertTrue(proc.returncode == 2 and "--also" in proc.stderr) + + def test_drop_forces_an_attended_gap_out(self): + records = [assistant("11-06 10:00"), human("11-06 10:50", "ok"), assistant("11-06 10:55")] + [(_, _, _, _, key, _)] = self.gaps_of(self.run_records(records)) + dropped = self.run_records(records, "--drop", key) + self.assertEqual([g[0] for g in self.gaps_of(dropped)], ["EXCLUDED"]) + self.assertIn("--drop", self.gaps_of(dropped)[0][5]) + self.assertEqual(self.active_minutes(dropped), 5.0) + + def test_every_excluded_gap_is_listed_with_its_cause_and_none_hides(self): + records = [assistant("11-06 08:00"), api_error("11-06 08:05"), human("11-06 10:00", "continue"), assistant("11-06 10:05"), + queued("11-06 12:00", "Scheduled one-time check from the example thread x"), assistant("11-06 12:01"), human("11-06 13:00", "next"), assistant("11-06 13:05")] + proc = self.run_records(records) + excl = [g for g in self.gaps_of(proc) if g[0] == "EXCLUDED"] + n = int(re.search(r"excluded gaps : (\d+)", proc.stdout).group(1)) + self.assertTrue(n == len(excl) == 2 and all(g[5] for g in excl)) + + def test_gaps_at_or_under_the_threshold_are_never_classified(self): + records = [assistant("11-06 10:00"), assistant("11-06 10:30"), assistant("11-06 11:00")] + proc = self.run_records(records) + self.assertEqual(self.gaps_of(proc), []) + self.assertEqual(self.active_minutes(proc), 60.0) + self.assertNotIn("gaps over", proc.stdout) + + def test_the_gap_threshold_option_still_moves_the_classification_line(self): + records = [assistant("11-06 10:00"), human("11-06 10:20", "ok"), assistant("11-06 10:21")] + self.assertEqual(self.gaps_of(self.run_records(records)), []) + self.assertEqual([g[0] for g in self.gaps_of(self.run_records(records, "--gap", "600"))], ["COUNTED"]) + + def test_an_old_api_error_does_not_excuse_a_later_gap(self): + # The error at 08:05 was retried and the session went on; the later pause is + # an ordinary attended one. + records = [assistant("11-06 08:00"), api_error("11-06 08:05"), human("11-06 08:10", "retry"), assistant("11-06 08:15", "Done."), + human("11-06 09:10", "next"), assistant("11-06 09:15")] + [(verdict, _, _, _, _, cause)] = self.gaps_of(self.run_records(records)) + self.assertTrue(verdict == "COUNTED" and cause.startswith("attended pause")) + + # --- hook mode: --since-last-entry --brief --------------------------------- + + def test_brief_reports_unlogged_minutes_since_the_last_time_create(self): + records = [human("11-06 09:00", "start"), assistant("11-06 09:20"), time_create("11-06 09:25", TICKET_NO), + assistant("11-06 09:30"), assistant("11-06 09:45"), assistant("11-06 10:00")] + proc = self.run_records(records, "--since-last-entry", "--brief", "--ticket", TICKET_NO, "--now", iso("11-06 10:01")) + self.assertEqual(proc.returncode, 0, proc.stderr) + line = proc.stdout.strip() + self.assertEqual(line.count("\n"), 0) + self.assertIn("unlogged_min=35.0", line) # 09:25 to 10:00 + self.assertIn("last_entry=2026-11-06T09:25:00+00:00", line) + self.assertIn("ticket_entry_age_min=36.0", line) # 09:25 to 10:01 + + def test_brief_with_no_prior_entry_measures_from_the_first_event(self): + records = [human("11-06 09:00", "start"), assistant("11-06 09:20"), assistant("11-06 09:40")] + proc = self.run_records(records, "--since-last-entry", "--brief", "--now", iso("11-06 09:41")) + for needle in ("unlogged_min=40.0", "last_entry=none", "ticket_entry_age_min=none"): + self.assertIn(needle, proc.stdout) + + def test_a_failed_time_create_does_not_reset_the_unlogged_window(self): + create = time_create("11-06 09:25", TICKET_NO) + failure = tool_result("11-06 09:26") + result = failure["message"]["content"][0] + result.update(tool_use_id=create["message"]["content"][0]["id"], is_error=True, content="create failed") + records = [human("11-06 09:00", "start"), assistant("11-06 09:20"), create, + failure, assistant("11-06 09:40")] + proc = self.run_records(records, "--since-last-entry", "--brief", "--ticket", TICKET_NO) + self.assertEqual(proc.returncode, 0, proc.stderr) + for needle in ("unlogged_min=40.0", "last_entry=none", "ticket_entry_age_min=none"): + self.assertIn(needle, proc.stdout) + + def test_a_create_without_a_ticket_does_not_reset_the_unlogged_window(self): + records = [human("11-06 09:00", "start"), assistant("11-06 09:20"), + time_create("11-06 09:25", None), assistant("11-06 09:40")] + proc = self.run_records(records, "--since-last-entry", "--brief") + self.assertEqual(proc.returncode, 0, proc.stderr) + self.assertIn("unlogged_min=40.0", proc.stdout) + self.assertIn("last_entry=none", proc.stdout) + + def test_brief_only_matches_the_ticket_asked_about(self): + records = [assistant("11-06 09:00"), time_create("11-06 09:05", TICKET_NO_OTHER), assistant("11-06 09:10")] + proc = self.run_records(records, "--since-last-entry", "--brief", "--ticket", TICKET_NO, "--now", iso("11-06 09:11")) + self.assertIn("last_entry=2026-11-06T09:05:00+00:00", proc.stdout) + self.assertIn("ticket_entry_age_min=none", proc.stdout) + + def test_brief_does_not_treat_a_time_list_or_overview_as_a_create(self): + listing = {"timestamp": iso("11-06 09:05"), "type": "assistant", "message": {"content": [{"type": "tool_use", "id": "toolu_L", + "name": TIME_TOOL_NAME, "input": {"mode": "overview"}}]}} + records = [assistant("11-06 09:00"), listing, assistant("11-06 09:10")] + proc = self.run_records(records, "--since-last-entry", "--brief", "--now", iso("11-06 09:11")) + self.assertIn("last_entry=none", proc.stdout) + + def brief_for(self, logged, closing): + records = [human("11-06 09:00", "start"), assistant("11-06 09:20"), time_create("11-06 09:25", logged), + assistant("11-06 09:40"), assistant("11-06 10:00")] + proc = self.run_records(records, "--since-last-entry", "--brief", "--ticket", closing, "--now", iso("11-06 10:01")) + self.assertEqual(proc.returncode, 0, proc.stderr) + return proc.stdout.strip() + + def test_brief_reports_an_entry_logged_under_the_other_ticket_form(self): + # A ticketing tool can take a ticket number or a numeric id, so a thread can + # log under one and close under the other. The script cannot map them (it + # makes no ticketing lookup), so it reports the other-form entry's age and + # a hook stays silent rather than claim nothing was logged. + line = self.brief_for(TICKET_NO, TICKET_ID) + self.assertIn("ticket_entry_age_min=none", line) + self.assertIn("other_form_entry_age_min=36.0", line) + line = self.brief_for(TICKET_ID, TICKET_NO) + self.assertIn("ticket_entry_age_min=none", line) + self.assertIn("other_form_entry_age_min=36.0", line) + + def test_brief_same_form_entries_are_matched_by_name_not_reported_as_other_form(self): + line = self.brief_for(TICKET_NO, TICKET_NO) + self.assertIn("ticket_entry_age_min=36.0", line) + self.assertIn("other_form_entry_age_min=none", line) + line = self.brief_for(TICKET_NO, TICKET_NO.lower()) # case does not make a different ticket + self.assertIn("ticket_entry_age_min=36.0", line) + self.assertIn("other_form_entry_age_min=none", line) + line = self.brief_for(TICKET_ID, TICKET_ID) + self.assertIn("ticket_entry_age_min=36.0", line) + self.assertIn("other_form_entry_age_min=none", line) + + def test_brief_a_different_ticket_in_the_same_form_is_neither(self): + # Two numeric ids that differ are two tickets: nothing is logged for this + # one, so the hook may speak. + line = self.brief_for(TICKET_ID, TICKET_ID_OTHER) + self.assertIn("ticket_entry_age_min=none", line) + self.assertIn("other_form_entry_age_min=none", line) + + def test_brief_keeps_the_other_form_key_when_the_transcript_is_too_short(self): + proc = self.run_records([assistant("11-06 09:00")], "--since-last-entry", "--brief", "--ticket", TICKET_ID, "--now", iso("11-06 09:01")) + self.assertTrue(proc.returncode == 0 and "other_form_entry_age_min=none" in proc.stdout) + + def test_brief_without_since_last_entry_is_a_usage_error(self): + proc = self.run_records([assistant("11-06 09:00"), assistant("11-06 09:05")], "--brief") + self.assertTrue(proc.returncode == 2 and "--since-last-entry" in proc.stderr) + + def test_a_single_event_transcript_is_still_exit_1_without_brief_and_zero_with_it(self): + one = [assistant("11-06 09:00")] + self.assertEqual(self.run_records(one).returncode, 1) + brief = self.run_records(one, "--since-last-entry", "--brief", "--now", iso("11-06 09:01")) + self.assertTrue(brief.returncode == 0 and "unlogged_min=0.0" in brief.stdout) + + # --- --time-tool: which tool call is the time-entry tool --------------------- + + def test_time_tool_option_names_the_time_entry_tool(self): + # A ticketing system whose time tool is not called time_manage: the default + # does not see its creates, and --time-tool NAME does. A time_manage call is + # in turn not a create once another name is asked for. + other = "mcp__example-tickets__tickets__log_hours" + records = [human("11-06 09:00", "start"), assistant("11-06 09:20"), time_create("11-06 09:25", TICKET_NO, tool=other), + assistant("11-06 09:40"), assistant("11-06 10:00")] + brief = ("--since-last-entry", "--brief", "--ticket", TICKET_NO, "--now", iso("11-06 10:01")) + default = self.run_records(records, *brief) + self.assertIn("last_entry=none", default.stdout) + self.assertIn("unlogged_min=60.0", default.stdout) + named = self.run_records(records, *brief, "--time-tool", "log_hours") + self.assertIn("last_entry=2026-11-06T09:25:00+00:00", named.stdout) + self.assertIn("unlogged_min=35.0", named.stdout) + self.assertIn("ticket_entry_age_min=36.0", named.stdout) + # The full tool name works too, and the default name stops matching. + full = self.run_records(records, *brief, "--time-tool", other) + self.assertIn("last_entry=2026-11-06T09:25:00+00:00", full.stdout) + psa = [human("11-06 09:00", "start"), assistant("11-06 09:20"), time_create("11-06 09:25", TICKET_NO), + assistant("11-06 09:40"), assistant("11-06 10:00")] + self.assertIn("last_entry=2026-11-06T09:25:00+00:00", self.run_records(psa, *brief).stdout) + self.assertIn("last_entry=none", self.run_records(psa, *brief, "--time-tool", "log_hours").stdout) + + def test_an_empty_time_tool_name_is_refused(self): + # An empty name ends every tool name, so every call would read as a time entry. + proc = self.run_records([assistant("11-06 09:00"), assistant("11-06 09:05")], "--time-tool", "") + self.assertEqual(proc.returncode, 2) + self.assertIn("--time-tool", proc.stderr) + + # --- the docstring and the file itself --------------------------------------- + + def test_docstring_names_the_rules_and_the_hold_rule(self): + text = SCRIPT.read_text() + doc = " ".join(text.split('"""')[1].split()) + for needle in ("30 minutes or less", "Unattended agent time counts like attended time", "usage-limit hold", + "--keep", "--also", "--strict"): + self.assertIn(needle, doc, needle) + self.assertNotIn(chr(0x2014), text) # no em or en dashes + self.assertNotIn(chr(0x2013), text) + + def test_running_the_file_directly_runs_the_tests_and_cannot_pass_vacuously(self): + here = Path(__file__) + env = base_env() + one = subprocess.run([sys.executable, str(here), "ActiveMinutesTest.test_a_45_minute_interactive_pause_counts_as_work"], + capture_output=True, text=True, env=env, timeout=120) + self.assertTrue(one.returncode == 0 and "Ran 1 test" in one.stderr and "OK" in one.stderr, one.stdout + one.stderr) + # A selection that matches nothing must fail, not pass. + nothing = subprocess.run([sys.executable, str(here), "ActiveMinutesTest.no_test_has_this_name"], + capture_output=True, text=True, env=env, timeout=120) + self.assertNotEqual(nothing.returncode, 0) + if sys.version_info >= (3, 12): + # unittest's -k filter exits 5 when it ran no test at all. + none_ran = subprocess.run([sys.executable, str(here), "-k", "no_test_has_this_name"], + capture_output=True, text=True, env=env, timeout=120) + self.assertNotEqual(none_ran.returncode, 0) + # A failing test must fail the run: append one to a copy and run only it. + copy = self.tmp_path / "test_copy.py" + text = here.read_text() + marker = 'if __name__ == "__main__":\n' + at = text.rindex(marker) # the real block is the last one; this test names the marker too + copy.write_text(text[:at] + "class ForcedFailure(unittest.TestCase):\n def test_forced_failure(self):\n self.fail('forced')\n\n\n" + text[at:]) + failed = subprocess.run([sys.executable, str(copy), "ForcedFailure.test_forced_failure"], + capture_output=True, text=True, env=env, timeout=120) + self.assertTrue(failed.returncode == 1 and "FAILED" in failed.stderr, failed.stdout + failed.stderr) + + +if __name__ == "__main__": + unittest.main() diff --git a/.claude-config/bin/tests/asks-test.py b/.claude-config/bin/tests/asks-test.py new file mode 100644 index 0000000..1f689a9 --- /dev/null +++ b/.claude-config/bin/tests/asks-test.py @@ -0,0 +1,357 @@ +#!/usr/bin/env python3 +"""Behavior tests for bin/asks, the per-thread register of what is waiting on the box's owner. + +The register replaces polling several threads for status, so the failures that +matter are the quiet ones: an ask that vanishes, a duplicate that doubles the +page, a corrupt file read as an empty register, a secret stored where a chat +page will show it, and two threads writing at once. Every case runs the real +script against a throwaway OPS_STATE_DIR; the live ~/.local/state/ops is never +read. +""" +import os, runpy; runpy.run_path(os.path.join(os.path.dirname(os.path.realpath(__file__)), "..", "sandbox_guard.py"))["require"]() + +import json +import stat +import subprocess +import sys +import tempfile +import threading +import unittest +from pathlib import Path + +ASKS = Path(__file__).resolve().parent.parent / "asks" +T1 = "aaaaaaaa-1111-4111-8111-111111111111" +T2 = "bbbbbbbb-2222-4222-8222-222222222222" +NOW = "2026-11-07T12:00:00-05:00" + + +class AsksTest(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory(prefix="asks-test.") + self.addCleanup(self.tmp.cleanup) + self.root = Path(self.tmp.name) + self.state = self.root / "state" + self.asks_dir = self.state / "asks" + self.env = {k: v for k, v in os.environ.items() if k not in ("ASKS_THREAD", "T3CODE_THREAD_ID", "OPS_STATE_DIR")} + self.env.update(OPS_STATE_DIR=str(self.state), HOME=str(self.root / "home"), ASKS_NOW=NOW, + PYTHONDONTWRITEBYTECODE="1") + + def run_asks(self, *args, thread=T1, stdin=None, env=None): + e = dict(env or self.env) + if thread: + e["ASKS_THREAD"] = thread + return subprocess.run([sys.executable, str(ASKS), *args], capture_output=True, text=True, env=e, + input=stdin, timeout=30) + + def ok(self, *args, **kw): + p = self.run_asks(*args, **kw) + self.assertEqual(p.returncode, 0, p.stderr + p.stdout) + return p + + def listed(self, *args, **kw): + return json.loads(self.ok("list", "--json", *args, **kw).stdout) + + # --- add and list ------------------------------------------------------ + + def test_add_records_every_field_and_lists_it(self): + self.ok("add", "Ship the lint?", "--why", "It checks every final message", "--rec", "Yes", + "--default", "It stays off", "--owner", "lane register", "--client", "Example Client", + "--deadline", "2026-11-10", "--title", "Prompt hooks") + (item,) = self.listed() + self.assertEqual((item["n"], item["kind"], item["text"]), (1, "decision", "Ship the lint?")) + self.assertEqual((item["why"], item["rec"], item["default"]), ("It checks every final message", "Yes", "It stays off")) + self.assertEqual((item["owner"], item["client"], item["deadline"]), ("lane register", "Example Client", "2026-11-10")) + self.assertEqual((item["thread"], item["thread_title"], item["ref"]), (T1, "Prompt hooks", "aaaaaaaa#1")) + self.assertEqual(item["created"], NOW) + self.assertIsNone(item["resolved"]) + + def test_numbers_are_per_thread_and_never_reused(self): + self.ok("add", "one") + self.ok("add", "two") + self.ok("add", "other thread", thread=T2) + self.ok("resolve", "2") + self.ok("add", "three") + by = {(i["thread"][:8], i["n"]): i["text"] for i in self.listed("--all")} + self.assertEqual(by, {("aaaaaaaa", 1): "one", ("aaaaaaaa", 3): "three", ("bbbbbbbb", 1): "other thread"}) + + def test_same_open_ask_updates_instead_of_duplicating(self): + self.ok("add", "Pick one", "--rec", "A") + p = self.ok("add", "Pick one", "--default", "stays as is") + self.assertIn("updated #1", p.stdout) + (item,) = self.listed() + # The re-add refreshes what it passes and keeps what it left empty. + self.assertEqual((item["rec"], item["default"]), ("A", "stays as is")) + + def test_resolved_ask_can_be_asked_again_as_a_new_ask(self): + self.ok("add", "Pick one") + self.ok("resolve", "1") + self.ok("add", "Pick one") + self.assertEqual([i["n"] for i in self.listed()], [2]) + + def test_default_thread_comes_from_t3codethread_id_and_scopes_the_list(self): + env = dict(self.env, T3CODE_THREAD_ID=T1) + self.run_asks("add", "mine", thread=None, env=env) + self.ok("add", "theirs", thread=T2) + mine = json.loads(self.run_asks("list", "--json", thread=None, env=env).stdout) + self.assertEqual([i["text"] for i in mine], ["mine"]) + everything = json.loads(self.run_asks("list", "--json", "--all", thread=None, env=env).stdout) + self.assertEqual(sorted(i["text"] for i in everything), ["mine", "theirs"]) + by_prefix = json.loads(self.run_asks("list", "--json", "--thread", "bbbbbbbb", thread=None, env=env).stdout) + self.assertEqual([i["text"] for i in by_prefix], ["theirs"]) + + def test_no_thread_id_files_under_adhoc_and_says_so(self): + p = self.run_asks("add", "orphan", thread=None) + self.assertEqual(p.returncode, 0, p.stderr) + self.assertIn("adhoc", p.stderr) + self.assertEqual([i["thread"] for i in self.listed("--all", thread=None)], ["adhoc"]) + + def test_long_and_colon_thread_ids_get_a_safe_file_name(self): + lane = "thread:provider:claudeAgent:native-thread:" + "x" * 300 + self.ok("add", "from a lane", thread=lane) + (path,) = [p for p in self.asks_dir.iterdir() if p.suffix == ".json"] + self.assertLess(len(path.name), 100) + self.assertEqual(json.loads(path.read_text())["thread"], lane) + (item,) = self.listed("--all") + self.assertTrue(item["ref"].startswith("lane:"), item["ref"]) + + # --- console asks ------------------------------------------------------ + + def test_console_ask_keeps_steps_and_paste_and_defaults_its_kind(self): + paste = 'Write-Host "hi"\r\nexit 0\r\n' + self.ok("add", "Update the census script", "--tool", "Example script library", "--step", "Open the library", + "--step", "Replace the body and save", "--paste", paste, "--expect", "Version 4", "--link", "https://x.example/n") + (item,) = self.listed() + self.assertEqual(item["kind"], "console") + self.assertEqual(item["steps"], ["Open the library", "Replace the body and save"]) + self.assertEqual(item["paste"], 'Write-Host "hi"\nexit 0') + self.assertEqual((item["tool"], item["expect"], item["link"]), ("Example script library", "Version 4", "https://x.example/n")) + + def test_paste_from_file_and_stdin(self): + f = self.root / "p.ps1" + f.write_text("from file\n") + self.ok("add", "a", "--tool", "T", "--paste", "@" + str(f)) + self.ok("add", "b", "--tool", "T", "--paste", "-", stdin="from stdin\n") + self.assertEqual([i["paste"] for i in self.listed()], ["from file", "from stdin"]) + + def test_console_ask_without_tool_steps_or_paste_is_refused(self): + p = self.run_asks("add", "empty", "--kind", "console") + self.assertEqual(p.returncode, 2) + self.assertIn("console ask needs", p.stderr) + + def test_oversize_paste_and_bad_link_and_bad_deadline_are_refused(self): + self.assertEqual(self.run_asks("add", "big", "--tool", "T", "--paste", "x" * (65 * 1024)).returncode, 2) + self.assertEqual(self.run_asks("add", "x", "--tool", "T", "--link", "ftp://nope").returncode, 2) + self.assertEqual(self.run_asks("add", "x", "--deadline", "11/10/2026").returncode, 2) + self.assertEqual(self.run_asks("add", "x" * 401).returncode, 2) + self.assertFalse(self.asks_dir.exists() and any(p.suffix == ".json" for p in self.asks_dir.iterdir())) + + # --- secrets ----------------------------------------------------------- + + def test_secret_shaped_values_are_refused_in_every_field_and_never_stored(self): + token = "ghp_" + "a1B2c3D4e5" * 4 + # Built from parts so this file never holds a literal key header line: a secret + # scanner would flag it, and two such lines side by side read as one key. + key_header = "-" * 5 + "BEGIN RSA PRIVATE" + " KEY" + "-" * 5 + cases = [("add", "key " + token), ("add", "x", "--why", token), ("add", "x", "--tool", "T", "--paste", token), + ("add", "x", "--tool", "T", "--step", token), + ("add", "x", "--tool", "T", "--paste", key_header + "\nabc")] + for args in cases: + with self.subTest(args=args): + p = self.run_asks(*args) + self.assertEqual(p.returncode, 2, p.stdout) + self.assertNotIn(token, p.stderr) # the refusal names the shape, never echoes the value + self.assertFalse(any(p.suffix == ".json" for p in self.asks_dir.iterdir()) if self.asks_dir.exists() else False) + + def test_title_note_and_thread_id_get_the_same_refusal(self): + # --title, resolve --note and --thread must be checked like the ask itself: the + # title shows on any page that lists the register, the note in `list --resolved`, + # and the thread id becomes the file name. + token = "ghp_" + "a1B2c3D4e5" * 4 + self.ok("add", "plain ask") + before = sorted(p.name for p in self.asks_dir.iterdir()) + cases = { + "add --title": ("add", "another ask", "--title", token), + "resolve --note": ("resolve", "1", "--note", "closed with " + token), + "add --thread": ("add", "x", "--thread", token), + "list --thread": ("list", "--thread", token), + "resolve --thread": ("resolve", "1", "--thread", token), + } + for name, args in cases.items(): + with self.subTest(case=name): + p = self.run_asks(*args) + self.assertEqual(p.returncode, 2, p.stdout + p.stderr) + self.assertIn("GitHub token", p.stderr) + self.assertNotIn(token, p.stderr + p.stdout) # the refusal never echoes the value + # An id that arrives through the environment becomes a file name just as a flag would. + p = self.run_asks("add", "x", thread=token) + self.assertEqual(p.returncode, 2, p.stdout + p.stderr) + self.assertNotIn(token, p.stderr + p.stdout) + # Nothing was stored: no new file, no title, no note, the ask is still open. + self.assertEqual(sorted(p.name for p in self.asks_dir.iterdir()), before) + (item,) = self.listed() + self.assertEqual((item["thread_title"], item["note"], item["resolved"]), ("", None, None)) + + def test_a_plain_title_and_note_are_still_stored(self): + self.ok("add", "ask", "--title", "Prompt hooks") + self.ok("resolve", "1", "--note", "answered in chat") + (item,) = self.listed("--resolved") + self.assertEqual((item["thread_title"], item["note"]), ("Prompt hooks", "answered in chat")) + + def test_a_script_that_names_a_password_parameter_is_not_refused(self): + self.ok("add", "script", "--tool", "T", "--paste", "param([string]$Password)\nWrite-Host 'password prompt'") + + # --- resolve and prune ------------------------------------------------- + + def test_resolve_by_number_by_ref_and_not_found(self): + self.ok("add", "one") + self.ok("add", "two", thread=T2) + self.ok("resolve", "1", "--note", "answered in chat") + self.ok("resolve", "bbbbbbbb#1") + self.assertEqual(self.listed("--all"), []) + done = {i["text"]: i["note"] for i in self.listed("--all", "--resolved")} + self.assertEqual(done, {"one": "answered in chat", "two": None}) + self.assertEqual(self.run_asks("resolve", "9").returncode, 1) + self.assertEqual(self.run_asks("resolve", "zzzzzzzz#1").returncode, 1) + self.assertEqual(self.run_asks("resolve", "not-a-ref").returncode, 2) + self.assertIn("already resolved", self.ok("resolve", "1").stdout) + + def test_resolved_asks_are_pruned_after_fourteen_days(self): + self.ok("add", "old") + self.ok("add", "kept") + self.ok("resolve", "1") + later = dict(self.env, ASKS_NOW="2026-11-30T12:00:00-05:00") + self.ok("add", "new", env=later) + self.assertEqual(sorted(i["text"] for i in self.listed("--all", env=later)), ["kept", "new"]) + self.assertEqual(self.listed("--all", "--resolved", env=later), []) + + def test_pruning_all_resolved_asks_keeps_numbers_unambiguous(self): + self.ok("add", "only", thread=T2) + self.ok("resolve", "1", thread=T2) + later = dict(self.env, ASKS_NOW="2026-12-30T12:00:00-05:00") + self.assertIn("pruned 1", self.ok("prune", env=later).stdout) + self.assertEqual(self.listed("--all", "--resolved", env=later), []) + self.ok("add", "new question", thread=T2, env=later) + self.assertEqual([i["n"] for i in self.listed("--all", env=later)], [2]) + # A stale reference must never resolve the new question. + self.assertEqual(self.run_asks("resolve", "bbbbbbbb#1", env=later).returncode, 1) + self.assertEqual([i["text"] for i in self.listed("--all", env=later)], ["new question"]) + + def test_prune_refuses_an_unreadable_register_before_changing_any_asks(self): + self.ok("add", "only", thread=T2) + self.ok("resolve", "1", thread=T2) + path = self.asks_dir / (T2 + ".json") + before = path.read_bytes() + (self.asks_dir / "broken.json").write_text("{not json") + later = dict(self.env, ASKS_NOW="2026-12-30T12:00:00-05:00") + p = self.run_asks("prune", env=later) + self.assertEqual(p.returncode, 1, p.stdout + p.stderr) + self.assertIn("broken.json", p.stderr) + self.assertEqual(path.read_bytes(), before) + + def test_add_reports_an_unreadable_register_before_writing(self): + self.asks_dir.mkdir(parents=True) + (self.asks_dir / "broken.json").write_text("{not json") + p = self.run_asks("add", "new question") + self.assertEqual(p.returncode, 1, p.stdout + p.stderr) + self.assertIn("broken.json", p.stderr) + self.assertFalse((self.asks_dir / (T1 + ".json")).exists()) + + # --- files and failure modes ------------------------------------------- + + def test_files_are_private(self): + self.ok("add", "x") + self.assertEqual(stat.S_IMODE(self.asks_dir.stat().st_mode), 0o700) + (path,) = [p for p in self.asks_dir.iterdir() if p.suffix == ".json"] + self.assertEqual(stat.S_IMODE(path.stat().st_mode), 0o600) + + def test_corrupt_file_is_an_error_not_an_empty_register(self): + self.ok("add", "fine", thread=T2) + (self.asks_dir / "broken.json").write_text("{not json") + p = self.run_asks("list", "--all") + self.assertEqual(p.returncode, 1) + self.assertIn("broken.json", p.stderr) + self.assertIn("fine", p.stdout) # the readable thread still shows + p = self.run_asks("resolve", "1", thread=T2) + self.assertEqual(p.returncode, 1) + self.assertIn("broken.json", p.stderr) + + def test_a_file_with_the_wrong_shape_is_named(self): + self.asks_dir.mkdir(parents=True) + (self.asks_dir / "odd.json").write_text(json.dumps({"thread": T1, "asks": [{"n": "x"}]})) + p = self.run_asks("list", "--all") + self.assertEqual(p.returncode, 1) + self.assertIn("odd.json", p.stderr) + + def test_concurrent_adds_to_one_thread_all_land(self): + errors = [] + + def add(i): + p = self.run_asks("add", "ask %d" % i) + if p.returncode: + errors.append(p.stderr) + + threads = [threading.Thread(target=add, args=(i,)) for i in range(8)] + for t in threads: + t.start() + for t in threads: + t.join() + self.assertEqual(errors, []) + items = self.listed() + self.assertEqual(sorted(i["n"] for i in items), list(range(1, 9))) + self.assertEqual(len({i["text"] for i in items}), 8) + + def test_a_write_waits_for_the_register_lock(self): + """Eight racing writers rarely hit the read-modify-write window, so prove the lock directly: + hold it here and a writer must block until it is released, then land its ask.""" + import fcntl + self.asks_dir.mkdir(parents=True) + fd = os.open(str(self.asks_dir / ".lock"), os.O_CREAT | os.O_RDWR, 0o600) + fcntl.flock(fd, fcntl.LOCK_EX) + try: + e = dict(self.env, ASKS_THREAD=T1) + proc = subprocess.Popen([sys.executable, str(ASKS), "add", "waits"], env=e, + stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) + with self.assertRaises(subprocess.TimeoutExpired): + proc.communicate(timeout=1.5) + finally: + fcntl.flock(fd, fcntl.LOCK_UN) + os.close(fd) + out, err = proc.communicate(timeout=15) + self.assertEqual(proc.returncode, 0, err) + self.assertEqual([i["text"] for i in self.listed()], ["waits"]) + + def test_list_text_output_names_the_thread_and_the_recommendation(self): + self.ok("add", "Pick one", "--rec", "A", "--title", "Prompt hooks") + out = self.ok("list").stdout + self.assertIn("thread aaaaaaaa (Prompt hooks)", out) + self.assertIn("aaaaaaaa#1", out) + self.assertIn("recommend: A", out) + self.assertIn("nothing open", self.ok("list", thread=T2).stdout) + + # --- the OPS state directory and the platform --------------------------- + + def test_state_defaults_to_the_ops_state_directory_under_home(self): + # With no OPS_STATE_DIR the register lives in ~/.local/state/ops/asks, the same root + # the other OPS tools use; HOME here is a fixture, never the real one. + env = {k: v for k, v in self.env.items() if k != "OPS_STATE_DIR"} + self.ok("add", "default home", env=env) + default = self.root / "home" / ".local" / "state" / "ops" / "asks" + self.assertEqual([p.name for p in default.iterdir() if p.suffix == ".json"], [T1 + ".json"]) + self.assertFalse(self.state.exists()) + + def test_a_platform_without_fcntl_gets_one_line_and_exit_1_not_a_traceback(self): + # sys.modules["fcntl"] = None makes `import fcntl` raise ImportError, the way a + # native Windows Python does. The command must say so once and exit 1. + snippet = ("import runpy, sys; sys.modules['fcntl'] = None; sys.argv = ['asks', 'list']; " + "runpy.run_path(%r, run_name='__main__')" % str(ASKS)) + p = subprocess.run([sys.executable, "-c", snippet], capture_output=True, text=True, env=self.env, timeout=30) + self.assertEqual(p.returncode, 1, p.stdout + p.stderr) + self.assertEqual(p.stdout, "") + self.assertEqual(len(p.stderr.strip().splitlines()), 1, p.stderr) + self.assertIn("fcntl", p.stderr) + self.assertNotIn("Traceback", p.stderr) + self.assertFalse(self.state.exists()) # it refused before touching the register + + +if __name__ == "__main__": + unittest.main() diff --git a/.claude-config/bin/tests/memory-index-test.sh b/.claude-config/bin/tests/memory-index-test.sh index d93f361..d2d69ef 100755 --- a/.claude-config/bin/tests/memory-index-test.sh +++ b/.claude-config/bin/tests/memory-index-test.sh @@ -17,6 +17,7 @@ # still written and the exit status is unchanged (a pool is its owner's) # - 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) # # Run: bash ~/OPS/.claude-config/bin/tests/memory-index-test.sh # Exit: 0 = all pass; non-zero on first failure. @@ -282,5 +283,42 @@ 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 +# 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" +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" +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=$? +[ "$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" \ + || 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" = "$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" \ + || 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=$? +[ "$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=$? +[ "$rc" = 1 ] || fail "--pool-for with an unknown argument must exit 1, got $rc" +rm -rf "$P" +pass "--pool-for: the digest's pool for a worktree, host-key file and profile dir; exit 4 and nothing created without one" + echo echo "ALL TESTS PASSED" diff --git a/.claude-config/bin/tests/session-end-test.py b/.claude-config/bin/tests/session-end-test.py new file mode 100644 index 0000000..4c72d91 --- /dev/null +++ b/.claude-config/bin/tests/session-end-test.py @@ -0,0 +1,1531 @@ +#!/usr/bin/env python3 +"""session-end safety and contract tests. Every repo, stamp, pool and tool is a fixture. + +Oracle: the OPS files the command must agree with, not its code: +hooks/pre-compact.sh ("Branch and worktree GC": the managed set, github.com +origin, 900 s, two-thirds deadline, 30 s kill, BRANCH_GC_TRASH_DAYS=0), +hooks/session-work-init.sh and hooks/hooklib.sh (the stamp names, the key and +ops_backend), hooks/handoff-check.sh (the baton directory), +hooks/memory-digest.sh (the --ops checkout), verify-ops.sh (its summary line +and --quiet) and SKILLS/session-close/mechanics.md (the stamps a close owns). + +Every tool session-end calls (branch-gc, memory-index, verify-ops.sh, asks, +active-minutes, lane-class, compact-cycle.sh, t3-api.sh, docker, the timeout +program) is a recording stub beside a COPY of the script in a fixture tree; git +runs through a recording wrapper that fails the case on any writing subcommand. +The real hooklib.sh and key.sh are copied in, so the stamp key and the baton key +come from the real helpers. The guard below refuses to run outside sandbox-run, +and a sentinel tree in the sandbox home must be byte-identical after every case, +so the suite's safety does not rest on the command under test. +""" +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 pathlib import Path +from unittest import mock + +BIN = Path(__file__).resolve().parents[1] +CHECKOUT = BIN.parents[1] +SRC = BIN / "session-end" +REAL_GIT = shutil.which("git") +SID = "1f0e2d3c-4b5a-6978-8a9b-0c1d2e3f4a5b" +TID = "6a7b8c9d-0e1f-4a2b-8c3d-4e5f6a7b8c9d" +GIT_ENV = {"GIT_CONFIG_GLOBAL": "/dev/null", "GIT_CONFIG_NOSYSTEM": "1", + "GIT_AUTHOR_NAME": "T", "GIT_AUTHOR_EMAIL": "t@example.invalid", + "GIT_COMMITTER_NAME": "T", "GIT_COMMITTER_EMAIL": "t@example.invalid"} + +STUB = r'''#!/usr/bin/env python3 +import json, os, sys, time +name = os.path.basename(sys.argv[0]) +rec = os.environ["SE_REC"] +try: + beh = json.load(open(os.path.join(rec, "behavior.json"))).get(name, {}) +except FileNotFoundError: + beh = {} +def log(event, **kw): + with open(os.path.join(rec, "calls.jsonl"), "a") as f: + f.write(json.dumps(dict(tool=name, event=event, argv=sys.argv[1:], cwd=os.getcwd(), t=time.time(), + env={k: os.environ.get(k) for k in ("BRANCH_GC_TRASH_DAYS", "BRANCH_GC_DEADLINE", "BRANCH_GC_LOG", "OPS_DIR")}, **kw)) + "\n") +log("start") +args = sys.argv[1:] +if name == "branch-gc": + repo = args[-1] + if "raw" in beh: + print(beh["raw"]); log("end"); sys.exit(0) + rel = beh.get("block_until") + if rel and "--apply" in args: + end = time.time() + 60 + while not os.path.exists(rel): + if time.time() > end: + print("stub: never released"); sys.exit(70) + time.sleep(0.02) + if "--dry-run" in args: + bl = os.environ.get("BRANCH_GC_LOG") + open(bl, "a").write("dry run log line\n") + print("branch-gc %s 2026-11-17 10:00:00 UTC T3=ok" % ("apply" if "--apply" in args else "dry-run")) + print("REPO\tBRANCH\tWORKTREE\tPR\tACTION\tREASON") + for row in beh.get("rows", []): + if row[0] == repo: + print("\t".join(row)) + print("") + print("Summary (remove / report / quarantine / failed):") + print(" %s 0 0 0 0" % repo) + if beh.get("out"): + print(beh["out"]) + log("end") + sys.exit(beh.get("rc_by_repo", {}).get(repo, beh.get("rc", 0))) +if name == "memory-index": + if args[:1] == ["--pool-for"]: + if beh.get("pool"): + print(beh["pool"]); sys.exit(0) + print("memory-index: no memory pool", file=sys.stderr); sys.exit(4) + print(beh.get("out", "[memory-index] wrote 1 line(s)")); sys.exit(beh.get("rebuild_rc", 0)) +if name == "lane-class": + print(beh.get("word", "foreman")); sys.exit(0) +if name == "active-minutes": + print(beh.get("out", "events : 9\nACTIVE (bill this): 42.0 min = 0.7000 h -> 0.70 h\nexcluded gaps : 1, total 50.0 min")) + sys.exit(beh.get("rc", 0)) +if name == "docker": + if args[:1] == ["inspect"]: + if args[-1] in beh.get("present", []): + print("[{}]"); sys.exit(0) + print("Error: No such object: %s" % args[-1]); sys.exit(1) + sys.exit(64) +print(beh.get("out", "%s ok" % name)) +sys.exit(beh.get("rc", 0)) +''' + +TIMEOUT_STUB = r'''#!/usr/bin/env python3 +import json, os, sys, time +with open(os.path.join(os.environ["SE_REC"], "calls.jsonl"), "a") as f: + f.write(json.dumps(dict(tool="gnutimeout", event="start", argv=sys.argv[1:], t=time.time())) + "\n") +a = sys.argv[1:] +assert a[0] == "-k", a +os.execv(a[3], a[3:]) +''' + +GIT_WRAPPER = r'''#!/usr/bin/env python3 +import json, os, sys +args = sys.argv[1:] +i = 0 +while i < len(args) and args[i] in ("-C", "-c"): + i += 2 +sub = args[i] if i < len(args) else "" +rest = args[i + 1:] +WRITE = {"commit", "push", "checkout", "switch", "stash", "reset", "merge", "rebase", "pull", "fetch", + "tag", "cherry-pick", "revert", "rm", "mv", "add", "clean", "gc", "prune", "update-ref", + "restore", "am", "apply", "init", "clone", "remote", "notes", "replace", "reflog"} +bad = sub in WRITE +if sub == "branch": + bad = True +if sub == "worktree" and rest[:1] != ["list"]: + bad = True +if sub == "config" and not any(a.startswith("--get") or a in ("--list", "-l") for a in rest): + bad = True +if sub == "symbolic-ref" and len([a for a in rest if not a.startswith("-")]) >= 2: + bad = True +rec = os.environ["SE_REC"] +with open(os.path.join(rec, "git.jsonl"), "a") as f: + f.write(json.dumps(args) + "\n") +if bad: + with open(os.path.join(rec, "git-violations"), "a") as f: + f.write(json.dumps(args) + "\n") + sys.exit(99) +os.execv(os.environ["REAL_GIT"], [os.environ["REAL_GIT"]] + args) +''' + +SIBLING_STUBS = ("branch-gc", "memory-index", "verify-ops.sh", "asks", "active-minutes", + "lane-class", "compact-cycle.sh", "t3-api.sh") +# The tools a run may start without writing anything: the read-only steps. +READ_ONLY_TOOLS = {"branch-gc", "gnutimeout", "memory-index", "asks", "active-minutes", "lane-class"} + + +def tree_state(root, with_mtime=True): + """Every path under root: type, bytes digest or link target, mode and mtime.""" + out = {} + root = str(root) + for d, dirs, files in os.walk(root): + for n in dirs + files: + p = os.path.join(d, n) + st = os.lstat(p) + rel = os.path.relpath(p, root) + if stat.S_ISLNK(st.st_mode): + out[rel] = ("link", os.readlink(p)) + elif stat.S_ISDIR(st.st_mode): + out[rel] = ("dir", stat.S_IMODE(st.st_mode)) + else: + with open(p, "rb") as f: + h = hashlib.sha256(f.read()).hexdigest() + out[rel] = ("file", h, stat.S_IMODE(st.st_mode), st.st_mtime_ns if with_mtime else 0) + return out + + +def g(cwd, *args): + return subprocess.run([REAL_GIT, "-C", str(cwd)] + list(args), env=dict(os.environ, **GIT_ENV), + check=True, capture_output=True, text=True).stdout.strip() + + +def make_repo(path, origin=None, extra_origin=None): + path.mkdir(parents=True, exist_ok=True) + g(path, "init", "-q", "-b", "main") + (path / "README.md").write_text("fixture\n") + g(path, "add", "README.md") + g(path, "commit", "-q", "-m", "base") + if origin: + g(path, "config", "remote.origin.url", origin) + if extra_origin: + g(path, "config", "--add", "remote.origin.url", extra_origin) + g(path, "update-ref", "refs/remotes/origin/main", "HEAD") + g(path, "symbolic-ref", "refs/remotes/origin/HEAD", "refs/remotes/origin/main") + return path + + +SENTINEL = {} + + +def setUpModule(): + home = Path(os.environ["HOME"]) + s = home / "session-end-sentinel" + s.mkdir() + (s / "notes.txt").write_text("must survive every case\n") + repo = make_repo(s / "repo", origin="https://github.com/acme/sentinel.git") + g(repo, "branch", "feature") + g(repo, "worktree", "add", "-q", str(s / "repo-wt"), "feature") + SENTINEL["root"] = s + SENTINEL["state"] = tree_state(s) + + +class SessionEnd(unittest.TestCase): + maxDiff = None + + def setUp(self): + self.tmp = Path(tempfile.mkdtemp(prefix="se-test-")).resolve() + self.addCleanup(shutil.rmtree, self.tmp, True) + self.home = self.tmp / "home" + self.rec = self.tmp / "rec" + self.scratch = self.tmp / "scratch" + self.stubbin = self.tmp / "stubbin" + for d in (self.home, self.rec, self.scratch, self.stubbin): + d.mkdir() + self.cw = self.home / "OPS" + make_repo(self.cw, origin="git@github.com:acme/harness.git") + bin_ = self.cw / ".claude-config" / "bin" + bin_.mkdir(parents=True) + (self.cw / ".claude-config" / "hooks").mkdir() + (self.cw / ".claude-handoffs" / "pending").mkdir(parents=True) + shutil.copy2(SRC, bin_ / "session-end") + shutil.copy2(CHECKOUT / ".claude-config" / "hooks" / "hooklib.sh", self.cw / ".claude-config" / "hooks" / "hooklib.sh") + shutil.copy2(CHECKOUT / ".claude-handoffs" / "key.sh", self.cw / ".claude-handoffs" / "key.sh") + for n in SIBLING_STUBS: + self.write_exec(bin_ / n, STUB) + (self.cw / ".gitignore").write_text("PROJECTS/\n.claude-memory/\n") + g(self.cw, "add", "-A") + g(self.cw, "commit", "-q", "-m", "fixture harness") + self.script = bin_ / "session-end" + self.bin = bin_ + self.write_exec(self.stubbin / "git", GIT_WRAPPER) + self.write_exec(self.stubbin / "gnutimeout", TIMEOUT_STUB) + self.write_exec(self.stubbin / "docker", STUB) + self.proj = make_repo(self.cw / "PROJECTS" / "acme" / "widget", origin="https://github.com/acme/widget.git") + self.other = make_repo(self.cw / "PROJECTS" / "acme" / "other", origin="ssh://git@github.com/acme/other.git") + self.pool = self.cw / ".claude-memory" / "fixture-pool" + self.pool.mkdir(parents=True) + self.state = self.home / ".local" / "state" / "ops" + self.state.mkdir(parents=True) + self.closeout = self.state / "last-closeout" + self.closeout.write_text("2026-11-01T09:00:00-04:00\n") + self.run_dir = self.home / ".claude-compact-cycle" + self.run_dir.mkdir() + self.key = "t3-" + SID + self.stamps = {"session-start-" + self.key: b"t0=2026-11-17T10:00:00-05:00\nrepos=OPS\n", + "work-log-" + self.key: b"## segment\nelapsed=1h\n", + "session-start-t3-sibling": b"t0=2026-11-16T08:00:00-05:00\n", + "work-log-t3-sibling": b"sibling log\n"} + for n, b in self.stamps.items(): + (self.run_dir / n).write_bytes(b) + self.behavior = {"memory-index": {"pool": str(self.pool)}} + self.save_behavior() + self.tx_dir = self.home / ".claude" / "projects" / "-fixture" + self.tx_dir.mkdir(parents=True) + self.addCleanup(self.drain_workers) + + def tearDown(self): + self.assertFalse((self.rec / "git-violations").exists(), + "a writing git subcommand ran: %s" % self.read_text(self.rec / "git-violations")) + self.assertEqual(SENTINEL["state"], tree_state(SENTINEL["root"]), "the sentinel outside the fixture changed") + + # --- helpers -------------------------------------------------------------- + + @staticmethod + def read_text(p): + return p.read_text() if p.exists() else "" + + @staticmethod + def write_exec(path, body): + path.write_text(body) + path.chmod(0o755) + + def save_behavior(self): + (self.rec / "behavior.json").write_text(json.dumps(self.behavior)) + + def drain_workers(self): + """Release every blocked stub and wait until each GC worker has written its result.""" + rel = self.behavior.get("branch-gc", {}).get("block_until") + if rel: + Path(rel).touch() + gcroot = self.state / "session-end" / "gc" + if not gcroot.is_dir(): + return + for rd in gcroot.iterdir(): + if rd.is_dir(): + self.wait_for(lambda rd=rd: (rd / "result.json").exists() or not self.locked(rd / "worker.lock")) + + @staticmethod + def locked(path): + try: + fd = os.open(str(path), os.O_RDONLY) + except FileNotFoundError: + return False + try: + fcntl.flock(fd, fcntl.LOCK_SH | fcntl.LOCK_NB) + return False + except BlockingIOError: + return True + finally: + os.close(fd) + + def wait_for(self, pred, timeout=30): + end = time.monotonic() + timeout + while time.monotonic() < end: + if pred(): + return + time.sleep(0.02) + self.fail("condition not met within %ss" % timeout) + + def env(self, **over): + path = ":".join(p for p in os.environ.get("PATH", "/usr/bin:/bin").split(":") if ".claude-config" not in p) + e = {"PATH": "%s:%s" % (self.stubbin, path), "HOME": str(self.home), "LANG": "C.UTF-8", + "TMPDIR": str(self.scratch), "SE_REC": str(self.rec), "REAL_GIT": REAL_GIT, + "CLAUDE_CODE_SESSION_ID": SID, "T3CODE_THREAD_ID": TID} + e.update(GIT_ENV) + for k, v in over.items(): + if v is None: + e.pop(k, None) + else: + e[k] = v + return e + + def se(self, *args, cwd=None, env=None, timeout=90, script=None): + return subprocess.run([sys.executable, str(script or self.script)] + list(args), cwd=str(cwd or self.cw), + env=env or self.env(), capture_output=True, text=True, timeout=timeout) + + def sej(self, *args, **kw): + p = self.se(*args, "--json", **kw) + try: + obj = json.loads(p.stdout) + except ValueError: + self.fail("stdout is not one JSON object (exit %s):\n%s\nstderr:\n%s" % (p.returncode, p.stdout, p.stderr)) + self.assertEqual(obj["exit"], p.returncode) + return p, obj + + @staticmethod + def step(obj, name): + hits = [s for s in obj["steps"] if s["step"] == name] + return hits[-1] if hits else None + + def calls(self, tool=None, event="start"): + p = self.rec / "calls.jsonl" + rows = [json.loads(l) for l in p.read_text().splitlines()] if p.exists() else [] + return [r for r in rows if (tool is None or r["tool"] == tool) and (event is None or r["event"] == event)] + + def gc_applies(self): + rows = [c for c in self.calls("branch-gc") if "--apply" in c["argv"]] + for c in self.calls("branch-gc"): + for bad in ("--force", "-f", "--remote", "-D"): + self.assertNotIn(bad, c["argv"], "branch-gc got %s" % bad) + return rows + + def transcript(self, uses=(), sid=SID, lines_extra=(), first_offset=3600): + """A Claude transcript for sid: uses are (tool, input, result text, is_error).""" + t0 = time.time() - first_offset + iso = lambda t: time.strftime("%Y-%m-%dT%H:%M:%S.000Z", time.gmtime(t)) + lines = [{"type": "user", "sessionId": sid, "timestamp": iso(t0), "message": {"role": "user", "content": "go"}}] + for i, (name, inp, res, err) in enumerate(uses): + uid = "toolu_%02d" % i + lines.append({"type": "assistant", "sessionId": sid, "timestamp": iso(t0 + i + 1), + "message": {"role": "assistant", "content": [{"type": "tool_use", "id": uid, "name": name, "input": inp}]}}) + r = {"type": "tool_result", "tool_use_id": uid, "content": res} + if err: + r["is_error"] = True + lines.append({"type": "user", "sessionId": sid, "timestamp": iso(t0 + i + 1.5), + "message": {"role": "user", "content": [r]}}) + lines.extend(lines_extra) + p = self.tx_dir / ("%s.jsonl" % sid) + p.write_text("".join(json.dumps(l) + "\n" for l in lines)) + return p + + def stamps_now(self): + return {n: (self.run_dir / n).read_bytes() for n in self.stamps if (self.run_dir / n).exists()} + + # --- step 2 and 4: which repos reach branch-gc ------------------------------ + + def test_gc_gets_current_plus_explicit_never_a_transcript_only_candidate(self): + self.transcript([("Read", {"file_path": str(self.proj / "README.md")}, "fixture", False), + ("Bash", {"command": "ls ~/OPS/PROJECTS/acme/widget"}, "README.md", False)]) + p, obj = self.sej("pause", "--repo", str(self.other), "--wait", "30") + self.assertEqual(p.returncode, 0, p.stdout) + applied = sorted(c["argv"][-1] for c in self.gc_applies()) + self.assertEqual(applied, sorted([str(self.cw), str(self.other)])) + self.assertNotIn(str(self.proj), applied, "a transcript-only candidate reached --apply") + repos = self.step(obj, "repos") + self.assertIn("pass --repo for any of these you changed", repos["output"]) + self.assertIn(str(self.proj), repos["output"]) + + def test_gc_without_a_verified_transcript_gets_only_explicit_repos(self): + p, obj = self.sej("pause", "--repo", str(self.proj), "--wait", "30") + self.assertEqual(p.returncode, 0, p.stdout) + self.assertEqual([c["argv"][-1] for c in self.gc_applies()], [str(self.proj)]) + self.assertEqual(self.step(obj, "transcript")["status"], "skipped") + + def test_canonical_duplicates_make_one_invocation_and_keep_the_worktree_snapshot(self): + sub = self.proj / "src" + sub.mkdir() + wt = self.tmp / "widget-lane" + g(self.proj, "worktree", "add", "-q", "-b", "lane", str(wt)) + (wt / "dirty.txt").write_text("unlanded\n") + p, obj = self.sej("pause", "--repo", str(self.proj), "--repo", str(sub), "--repo", str(wt), "--wait", "30", cwd=wt) + self.assertEqual(p.returncode, 0, p.stdout) + self.assertEqual([c["argv"][-1] for c in self.gc_applies()], [str(self.proj)]) + snap = self.step(obj, "git snapshot")["output"] + self.assertRegex(snap, r"%s \(linked worktree of %s\): branch lane; .*1 changed or untracked" % (re.escape(str(wt)), re.escape(str(self.proj)))) + self.assertIn("?? dirty.txt", snap) + self.assertRegex(snap, r"%s: branch main; .*; clean" % re.escape(str(self.proj))) + + def test_unmanaged_and_non_github_or_multiple_origins_never_reach_apply(self): + unmanaged = make_repo(self.home / "elsewhere" / "tool", origin="https://github.com/acme/tool.git") + gitlab = make_repo(self.cw / "PROJECTS" / "acme" / "gitlab", origin="https://gitlab.com/acme/gitlab.git") + multi = make_repo(self.cw / "PROJECTS" / "acme" / "multi", origin="https://github.com/acme/multi.git", + extra_origin="https://github.com/acme/fork.git") + deep = make_repo(self.cw / "PROJECTS" / "acme" / "nest" / "deep", origin="https://github.com/acme/deep.git") + p, obj = self.sej("pause", "--repo", str(unmanaged), "--repo", str(gitlab), "--repo", str(multi), + "--repo", str(deep), "--wait", "30") + self.assertEqual(p.returncode, 0, p.stdout) + self.assertEqual(self.calls("branch-gc"), []) + out = self.step(obj, "branch-gc")["output"] + self.assertIn("not run: %s is not a repo branch-gc manages" % unmanaged, out) + self.assertIn("not run: %s is not a repo branch-gc manages" % deep, out) + self.assertIn("not run: %s has no github.com origin (or multiple origins)" % gitlab, out) + self.assertIn("not run: %s has no github.com origin (or multiple origins)" % multi, out) + + def test_gc_runs_under_the_hook_timeout_numbers_and_prints_recovery(self): + tip = g(self.proj, "rev-parse", "HEAD") + g(self.proj, "update-ref", "refs/heads/feat", tip) + entry = "~/.local/state/ops/branch-gc-trash/20261117T100000Z__widget__lane" + self.behavior["branch-gc"] = {"rows": [ + [str(self.proj), "feat", "-", "#7 MERGED", "removed", "tip == merged PR #7 head"], + [str(self.proj), "lane", str(self.tmp / "gone"), "#8 MERGED", "quarantined", "merged; worktree moved to " + entry]]} + self.save_behavior() + t0 = time.time() + p, obj = self.sej("pause", "--repo", str(self.proj), "--wait", "30") + self.assertEqual(p.returncode, 0, p.stdout) + to = self.calls("gnutimeout") + self.assertEqual(len(to), 1) + self.assertEqual(to[0]["argv"], ["-k", "30", "900", str(self.bin / "branch-gc"), "--apply", "--tsv", str(self.proj)]) + call = self.gc_applies()[0] + self.assertEqual(call["env"]["BRANCH_GC_TRASH_DAYS"], "0") + self.assertLessEqual(abs(int(call["env"]["BRANCH_GC_DEADLINE"]) - (t0 + 600)), 30) + out = self.step(obj, "branch-gc")["output"] + self.assertIn("branch-gc --restore %s" % (str(self.home) + entry[1:]), out) + self.assertIn("git -C %s branch feat %s" % (self.proj, tip), out) + self.assertIn("including other threads' eligible idle work", out) + + def test_a_failing_branch_gc_exits_1_with_its_output_and_later_steps_run(self): + self.behavior["branch-gc"] = {"rc": 1, "out": "branch-gc: gh said HTTP 401"} + self.save_behavior() + p, obj = self.sej("close", "--repo", str(self.proj), "--wait", "30") + self.assertEqual(p.returncode, 1) + gc = self.step(obj, "branch-gc") + self.assertEqual(gc["status"], "failed") + self.assertIn("HTTP 401", gc["output"]) + for later in ("memory index", "disk", "vault view", "open asks"): + self.assertIsNotNone(self.step(obj, later), later) + self.assertEqual(len(self.calls("asks")), 1, "a later step's tool did not run") + + # --- step 4: the worker, the wait budget, pending ------------------------- + + def block_gc(self): + rel = self.tmp / "release" + self.behavior["branch-gc"] = dict(self.behavior.get("branch-gc", {}), block_until=str(rel)) + self.save_behavior() + return rel + + def result_of(self, obj): + return Path(self.step(obj, "branch-gc")["result"]) + + def test_two_repos_one_serial_worker_pending_survives_and_is_reused(self): + rel = self.block_gc() + p, obj = self.sej("pause", "--repo", str(self.proj), "--repo", str(self.other), "--wait", "0") + self.assertEqual(p.returncode, 3, p.stdout) + gc = self.step(obj, "branch-gc") + self.assertEqual(gc["status"], "pending") + result = self.result_of(obj) + self.assertFalse(result.exists()) + p2, obj2 = self.sej("pause", "--repo", str(self.other), "--repo", str(self.proj), "--wait", "0") + self.assertEqual(p2.returncode, 3) + self.assertIn("reusing the pending worker", self.step(obj2, "branch-gc")["summary"]) + self.assertEqual(len(list((self.state / "session-end" / "gc").glob("*/plan.json"))), 1) + rel.touch() + self.wait_for(result.exists) + starts = [(c["argv"][-1], c["t"]) for c in self.calls("branch-gc") if "--apply" in c["argv"]] + ends = [(c["argv"][-1], c["t"]) for c in self.calls("branch-gc", event="end")] + self.assertEqual([s[0] for s in starts], sorted([str(self.proj), str(self.other)])) + self.assertLessEqual(ends[0][1], starts[1][1], "the second repo started before the first finished") + self.assertEqual(json.loads(result.read_text())["status"], "completed") + before = self.closeout.read_text() + f = self.se("finish") + self.assertEqual(f.returncode, 0, f.stdout + f.stderr) + self.assertNotEqual(self.closeout.read_text(), before) + + def test_a_pending_run_for_another_selection_is_not_started_twice(self): + self.block_gc() + p, _ = self.sej("pause", "--repo", str(self.proj), "--wait", "0") + self.assertEqual(p.returncode, 3) + p2, obj2 = self.sej("pause", "--repo", str(self.other), "--wait", "0") + self.assertEqual(p2.returncode, 1) + self.assertIn("not starting a conflicting copy", self.step(obj2, "branch-gc")["summary"]) + self.assertEqual(len(list((self.state / "session-end" / "gc").glob("*/plan.json"))), 1) + + def test_finish_refuses_while_gc_runs_and_after_a_later_failure(self): + rel = self.block_gc() + self.behavior["branch-gc"]["rc"] = 1 + self.save_behavior() + p, obj = self.sej("pause", "--repo", str(self.proj), "--wait", "0") + self.assertEqual(p.returncode, 3) + before = self.closeout.read_bytes() + f = self.se("finish") + self.assertEqual(f.returncode, 1) + self.assertIn("GC is still running", f.stdout) + rel.touch() + self.wait_for(self.result_of(obj).exists) + self.assertEqual(json.loads(self.result_of(obj).read_text())["status"], "failed") + f = self.se("finish") + self.assertEqual(f.returncode, 1) + self.assertIn("GC finished with a failure", f.stdout) + self.assertEqual(self.closeout.read_bytes(), before, "a failed or pending GC advanced last-closeout") + + def test_missing_prerequisites_fail_visibly_without_a_worker(self): + (self.bin / "branch-gc").unlink() + p, obj = self.sej("pause", "--repo", str(self.proj), "--wait", "0") + self.assertEqual(p.returncode, 1) + self.assertIn("branch-gc not found", self.step(obj, "branch-gc")["summary"]) + self.write_exec(self.bin / "branch-gc", STUB) + (self.bin / "memory-index").unlink() + p, obj = self.sej("pause", "--repo", str(self.proj), "--wait", "30") + self.assertEqual(p.returncode, 1) + self.assertIn("memory-index not found", self.step(obj, "memory index")["summary"]) + self.assertEqual(self.step(obj, "branch-gc")["status"], "completed") + + def test_no_timeout_program_starts_no_worker(self): + nobin = self.tmp / "nobin" + nobin.mkdir() + for d in os.environ.get("PATH", "").split(":"): + if not d or ".claude-config" in d or not os.path.isdir(d): + continue + for n in os.listdir(d): + if n in ("timeout", "gnutimeout", "git") or os.path.lexists(nobin / n): + continue + os.symlink(os.path.join(d, n), nobin / n) + os.symlink(self.stubbin / "git", nobin / "git") + p, obj = self.sej("pause", "--repo", str(self.proj), "--wait", "0", env=self.env(PATH=str(nobin))) + self.assertEqual(p.returncode, 1, p.stdout) + self.assertIn("no timeout program", self.step(obj, "branch-gc")["summary"]) + self.assertFalse((self.state / "session-end" / "gc").exists()) + self.assertEqual(self.calls("branch-gc"), []) + + def test_worker_launch_failure_is_a_failure(self): + (self.state / "session-end").mkdir() + (self.state / "session-end" / "gc").write_text("not a directory\n") + p, obj = self.sej("pause", "--repo", str(self.proj), "--wait", "0") + self.assertEqual(p.returncode, 1) + self.assertIn("could not start the GC worker", self.step(obj, "branch-gc")["summary"]) + self.assertEqual(self.calls("branch-gc"), []) + + # --- dry run ---------------------------------------------------------------- + + def test_dry_run_passes_no_apply_detaches_nothing_and_writes_nothing(self): + self.transcript([("Edit", {"file_path": str(self.cw / ".claude-config" / "bin" / "x")}, "ok", False)]) + (self.pool / "entry.md").write_text("---\nname: entry\nmetadata:\n modified: 2020-01-01\n---\nbody\n") + (self.state / "branch-gc.log").write_text("older run\n") + (self.state / "session-end").mkdir() + (self.state / "session-end" / ("%s.json" % self.key)).write_text('{"old": true}\n') + before_home, before_scratch = tree_state(self.home), tree_state(self.scratch) + p, obj = self.sej("close", "--dry-run", "--repo", str(self.proj), "--wait", "30") + self.assertEqual(p.returncode, 0, p.stdout) + self.assertEqual(tree_state(self.home), before_home, "a dry run changed the fixture home") + self.assertEqual(tree_state(self.scratch), before_scratch, "a dry run left files in TMPDIR") + gcs = self.calls("branch-gc") + self.assertTrue(gcs) + for c in gcs: + self.assertNotIn("--apply", c["argv"]) + self.assertIn("--dry-run", c["argv"]) + self.assertTrue(c["env"]["BRANCH_GC_LOG"].startswith(str(self.scratch) + "/")) + self.assertEqual([c["argv"][0] for c in self.calls("memory-index")], ["--pool-for"]) + self.assertEqual(self.calls("verify-ops.sh"), []) + # Only read-only helpers ran: no gate, no writer, no T3 tool. + self.assertLessEqual({c["tool"] for c in self.calls()}, READ_ONLY_TOOLS) + self.assertIsNone(obj["receipt"]) + + # --- close: what the thread made -------------------------------------------- + + def test_close_lists_only_this_threads_creations_and_removes_nothing(self): + s = self.scratch + other = s / "other-thread" + other.mkdir() + (other / "work.txt").write_text("theirs\n") + (s / "mine").mkdir() + (s / "mine" / "a.txt").write_text("mine\n") + (s / "mydir").mkdir() + (s / "maybe").mkdir() + (s / "edited.txt").write_text("existed before\n") + wt = s / "wt-new" + g(self.proj, "worktree", "add", "-q", "-b", "x", str(wt)) + self.behavior["docker"] = {"present": ["mybox", "shared"]} + self.behavior["branch-gc"] = {"rows": [[str(self.proj), "x", str(wt), "-", "kept", "dirty: untracked files"]]} + self.save_behavior() + self.transcript([ + ("Write", {"file_path": str(s / "mine" / "a.txt")}, "File created successfully at: %s" % (s / "mine" / "a.txt"), False), + ("Write", {"file_path": str(s / "edited.txt")}, "The file %s has been updated successfully." % (s / "edited.txt"), False), + ("Bash", {"command": "mkdir %s && mkdir -p %s" % (s / "mydir", s / "maybe")}, "", False), + ("Bash", {"command": "mkdir %s" % s}, "", False), + ("Bash", {"command": "mkdir %s" % (s / "failed")}, "mkdir: cannot create", True), + ("Bash", {"command": "ls %s; cat %s/work.txt" % (other, other)}, "work.txt", False), + ("Bash", {"command": "git -C %s worktree add %s -b x" % (self.proj, wt)}, "Preparing worktree", False), + ("Bash", {"command": "docker run --rm alpine:3 true; docker run -d --name mybox img; docker run --name gone img"}, "", False), + ("Bash", {"command": "docker volume create shared"}, "shared", False), + ]) + before_other = tree_state(other) + p, obj = self.sej("close", "--repo", str(self.proj), "--wait", "30") + lst = self.step(obj, "cleanup list")["output"] + owned, _, unknown = lst.partition("ownership unknown") + for want in (str(s / "mine" / "a.txt"), str(s / "mydir"), str(wt)): + self.assertIn(want, owned) + self.assertIn("GC: kept: dirty: untracked files", owned) + for want in (str(s / "maybe"), str(s / "edited.txt"), "volume shared", "container mybox"): + self.assertIn(want, unknown) + self.assertNotIn(want, owned) + for never in (str(other), "alpine", "gone", "dir %s (" % s, str(s / "failed")): + self.assertNotIn(never, lst) + self.assertIn("check for anything else you created, by exact path or id", lst) + for path in (s / "mine" / "a.txt", s / "mydir", s / "maybe", wt, s / "edited.txt"): + self.assertTrue(path.exists(), path) + self.assertEqual(tree_state(other), before_other) + + def test_a_compound_shell_success_does_not_prove_each_object_was_created(self): + shared = self.scratch / "another-threads-dir" + shared.mkdir() + self.behavior["docker"] = {"present": ["shared-box", "shared-image", "shared-net", "shared-cached"]} + self.save_behavior() + self.transcript([ + ("Bash", {"command": "mkdir %s; true" % shared}, "mkdir: File exists", False), + ("Bash", {"command": "docker create --name shared-box img || true"}, "name already in use", False), + ("Bash", {"command": "docker build -t shared-image .; true"}, "build failed", False), + ("Bash", {"command": "docker network create shared-net | cat"}, "network already exists", False), + ("Bash", {"command": "docker build -t shared-cached ."}, "Using cache\nSuccessfully tagged shared-cached", False), + ]) + p, obj = self.sej("close", "--dry-run", "--wait", "30") + self.assertEqual(p.returncode, 0, p.stdout) + owned, _, unknown = self.step(obj, "cleanup list")["output"].partition("ownership unknown") + for name in (str(shared), "shared-box", "shared-image", "shared-net", "shared-cached"): + self.assertNotIn(name, owned, "a successful final command proves nothing about an earlier failure") + self.assertIn(name, unknown) + + # --- finish and the billing stamps ------------------------------------------ + + def close_then(self, *finish_args, env=None): + self.transcript() + p, _ = self.sej("close", "--wait", "30", env=env) + self.assertEqual(p.returncode, 0, p.stdout) + return self.se("finish", *finish_args, env=env) + + def archive_dirs(self): + reaped = self.run_dir / "reaped" + return sorted(d for d in reaped.iterdir() if d.is_dir()) if reaped.is_dir() else [] + + def test_finish_moves_exact_bytes_of_only_this_threads_stamps_beside_a_meta(self): + f = self.close_then("--logged", "2") + self.assertEqual(f.returncode, 0, f.stdout + f.stderr) + dirs = self.archive_dirs() + self.assertEqual(len(dirs), 1, dirs) + adir = dirs[0] + self.assertRegex(adir.name, r"^%s-\d{8}T\d{6}-[0-9a-f]{8}$" % re.escape(self.key)) + self.assertEqual(stat.S_IMODE(adir.stat().st_mode), 0o700) + names = ["work-log-" + self.key, "session-start-" + self.key] + self.assertEqual(sorted(p.name for p in adir.iterdir()), sorted(names + ["reaped.meta"])) + meta = (adir / "reaped.meta").read_text() + for want in ("reaped_reason=session-end finish: logged=2 time entries created and read back", + "reaped_key=%s" % self.key, "status=complete"): + self.assertIn(want, meta) + for live in names: + b = self.stamps[live] + self.assertFalse((self.run_dir / live).exists()) + self.assertEqual((adir / live).read_bytes(), b, "the archived stamp must hold exactly the original bytes") + self.assertIn("file=%s\toriginal=%s\tsize=%d\tsha256=%s" % (live, self.run_dir / live, len(b), + hashlib.sha256(b).hexdigest()), meta) + self.assertIn("mv -n %s %s" % (adir / live, self.run_dir / live), f.stdout) + for sib in ("session-start-t3-sibling", "work-log-t3-sibling"): + self.assertEqual((self.run_dir / sib).read_bytes(), self.stamps[sib]) + self.assertRegex(self.closeout.read_text(), r"^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d[+-]\d\d:\d\d\n$") + self.assertNotEqual(self.closeout.read_text(), "2026-11-01T09:00:00-04:00\n") + self.assertFalse((self.state / "session-end" / ("%s.json" % self.key)).exists()) + again = self.close_then("--logged", "0") + self.assertEqual(again.returncode, 0, again.stdout) + self.assertIn("nothing archived", again.stdout) + self.assertEqual(len(self.archive_dirs()), 1, "a no-op finish made an archive directory") + + def test_finish_flags_are_exclusive_required_after_close_and_refused_otherwise(self): + self.transcript() + self.assertEqual(self.sej("close", "--wait", "30")[0].returncode, 0) + for bad in ([], ["--logged", "1", "--declined", "x"], ["--logged", "-1"], ["--logged", "1.5"], + ["--logged", "+1"], ["--declined", ""], ["--declined", " "]): + r = self.se("finish", *bad) + self.assertEqual(r.returncode, 2, (bad, r.stdout, r.stderr)) + self.assertEqual(self.stamps_now(), self.stamps) + self.assertEqual(self.closeout.read_text(), "2026-11-01T09:00:00-04:00\n") + self.assertEqual(self.sej("pause", "--wait", "30")[0].returncode, 0) + self.assertEqual(self.se("finish", "--logged", "1").returncode, 2) + self.assertEqual(self.se("finish", "--declined", "x").returncode, 2) + r = self.se("finish") + self.assertEqual(r.returncode, 0, r.stdout) + self.assertEqual(self.stamps_now(), self.stamps, "finish after a pause touched billing stamps") + + def test_lanes_are_refused_every_writing_mode_without_changes(self): + before = tree_state(self.home) + for env in (self.env(T3CODE_THREAD_ID="thread:delegated-task:abc"), + self.env(T3CODE_THREAD_ID="thread:provider:xyz")): + for args in (["close", "--repo", str(self.proj)], ["finish", "--declined", "x"]): + p, obj = self.sej(*args, env=env) + self.assertEqual(p.returncode, 1, "a delegated lane was not refused (%s): %s" % (env["T3CODE_THREAD_ID"], args)) + self.assertIn("session-end belongs to the main thread", p.stdout) + self.behavior["lane-class"] = {"word": "t3-lane"} + self.save_behavior() + p, _ = self.sej("pause", "--repo", str(self.proj)) + self.assertEqual(p.returncode, 1) + self.assertIn("lane-class --self: t3-lane", p.stdout) + self.behavior["lane-class"] = {"word": "weird"} + self.save_behavior() + self.assertEqual(self.sej("pause", "--repo", str(self.proj))[0].returncode, 1) + self.assertEqual(self.calls("branch-gc"), []) + self.assertEqual(self.calls("memory-index"), []) + self.assertEqual(tree_state(self.home), before) + p, _ = self.sej("pause", "--dry-run", env=self.env(T3CODE_THREAD_ID="thread:delegated-task:abc")) + self.assertEqual(p.returncode, 0, p.stdout) + + def test_cwd_fallback_key_is_refused_and_leaves_stamps(self): + # ops_backend says t3code only with T3CODE_HOME or T3CODE_THREAD_ID set. + env = self.env(T3CODE_THREAD_ID=None) + cwdkey = re.sub(r"[^A-Za-z0-9-]", "", str(self.cw).replace("/", "-")) + (self.run_dir / ("session-start-" + cwdkey)).write_bytes(b"shared cwd stamp\n") + (self.run_dir / ("work-log-" + cwdkey)).write_bytes(b"shared cwd log\n") + f = self.close_then("--logged", "1", env=env) + self.assertEqual(f.returncode, 1, f.stdout) + self.assertIn("refusing to archive", f.stdout) + self.assertEqual((self.run_dir / ("session-start-" + cwdkey)).read_bytes(), b"shared cwd stamp\n") + self.assertEqual((self.run_dir / ("work-log-" + cwdkey)).read_bytes(), b"shared cwd log\n") + self.assertFalse((self.run_dir / "reaped").exists()) + self.assertEqual(self.closeout.read_text(), "2026-11-01T09:00:00-04:00\n") + + def test_a_receipt_of_another_thread_is_refused(self): + self.transcript() + self.assertEqual(self.sej("close", "--wait", "30")[0].returncode, 0) + f = self.se("finish", "--logged", "1", env=self.env(T3CODE_THREAD_ID="0d0d0d0d-0000-4000-8000-000000000000")) + self.assertEqual(f.returncode, 1, "finish acted on another thread's receipt: " + f.stdout) + self.assertIn("belongs to another thread", f.stdout) + self.assertEqual(self.stamps_now(), self.stamps) + + def test_codex_only_runs_explicit_repos_and_finish_archives_nothing(self): + env = self.env(CLAUDE_CODE_SESSION_ID=None, CODEX_THREAD_ID="019a-codex-thread") + self.transcript() + p, obj = self.sej("close", "--repo", str(self.proj), "--wait", "30", env=env) + self.assertEqual(p.returncode, 0, p.stdout) + self.assertEqual([c["argv"][-1] for c in self.gc_applies()], [str(self.proj)]) + self.assertIn("unsupported provider", self.step(obj, "transcript")["summary"]) + self.assertIn("unsupported provider", self.step(obj, "time")["summary"]) + self.assertEqual(self.calls("active-minutes"), []) + f = self.se("finish", "--declined", "no ticket work", env=env) + self.assertEqual(f.returncode, 0, f.stdout) + self.assertIn("unsupported provider", f.stdout) + self.assertEqual(self.stamps_now(), self.stamps) + self.assertFalse((self.run_dir / "reaped").exists()) + + def test_archive_failure_keeps_every_original_and_retry_completes(self): + reaped = self.run_dir / "reaped" + reaped.mkdir() + reaped.chmod(0o500) + self.addCleanup(reaped.chmod, 0o700) + f = self.close_then("--declined", "personal work") + self.assertEqual(f.returncode, 1, f.stdout) + self.assertEqual(self.stamps_now(), self.stamps) + self.assertEqual(self.closeout.read_text(), "2026-11-01T09:00:00-04:00\n") + reaped.chmod(0o700) + f = self.se("finish", "--declined", "personal work") + self.assertEqual(f.returncode, 0, f.stdout) + self.assertFalse((self.run_dir / ("session-start-" + self.key)).exists()) + + def test_a_symlinked_or_special_source_moves_nothing(self): + live = self.run_dir / ("session-start-" + self.key) + wl = self.run_dir / ("work-log-" + self.key) + live.unlink() + target = self.tmp / "elsewhere-stamp" + target.write_bytes(self.stamps[live.name]) + live.symlink_to(target) + f = self.close_then("--logged", "1") + self.assertEqual(f.returncode, 1, f.stdout) + self.assertIn("not a regular file", f.stdout) + self.assertTrue(live.is_symlink()) + self.assertEqual(target.read_bytes(), self.stamps[live.name]) + self.assertEqual(wl.read_bytes(), self.stamps[wl.name], "a refusal must move nothing, the work-log included") + self.assertEqual(self.archive_dirs(), []) + live.unlink() + live.write_bytes(self.stamps[live.name]) + wl.unlink() + os.mkfifo(str(wl)) + f = self.se("finish", "--logged", "1") + self.assertEqual(f.returncode, 1, f.stdout) + self.assertEqual(live.read_bytes(), self.stamps[live.name]) + self.assertEqual(self.archive_dirs(), []) + wl.unlink() + wl.write_bytes(self.stamps[wl.name]) + f = self.se("finish", "--logged", "1") + self.assertEqual(f.returncode, 0, f.stdout) + self.assertFalse(live.exists() or wl.exists()) + self.assertEqual(len(self.archive_dirs()), 1) + + def test_a_symlinked_reaped_directory_is_refused(self): + real = self.tmp / "reaped-target" + real.mkdir() + (self.run_dir / "reaped").symlink_to(real) + f = self.close_then("--logged", "1") + self.assertEqual(f.returncode, 1) + self.assertEqual(self.stamps_now(), self.stamps) + self.assertEqual(list(real.iterdir()), []) + + def test_an_existing_archive_directory_is_never_reused(self): + hook = self.tmp / "hook" + self.write_exec(hook, '#!/bin/sh\nif [ "$1" = archive-target ] && [ ! -e "$SE_MARK" ]; then\n' + ' mkdir "$2" && printf "earlier archive\\n" > "$2/theirs" && : > "$SE_MARK"\nfi\nexit 0\n') + f = self.close_then("--logged", "1", env=self.env(SESSION_END_TEST_HOOK=str(hook), SE_MARK=str(self.tmp / "mark"))) + self.assertEqual(f.returncode, 0, f.stdout) + dirs = self.archive_dirs() + self.assertEqual(len(dirs), 2, dirs) + theirs = [d for d in dirs if (d / "theirs").exists()] + ours = [d for d in dirs if (d / "reaped.meta").exists()] + self.assertEqual(len(theirs), 1) + self.assertEqual(sorted(p.name for p in theirs[0].iterdir()), ["theirs"]) + self.assertEqual((theirs[0] / "theirs").read_bytes(), b"earlier archive\n") + self.assertEqual(len(ours), 1) + self.assertNotEqual(ours[0], theirs[0]) + self.assertEqual((ours[0] / ("work-log-" + self.key)).read_bytes(), self.stamps["work-log-" + self.key]) + + def test_a_writer_holding_the_work_log_open_appends_into_the_archive(self): + self.transcript() + self.assertEqual(self.sej("close", "--wait", "30")[0].returncode, 0) + wl = self.run_dir / ("work-log-" + self.key) + fd = os.open(str(wl), os.O_WRONLY | os.O_APPEND) + try: + f = self.se("finish", "--logged", "1") + os.write(fd, b"late segment\n") + finally: + os.close(fd) + self.assertEqual(f.returncode, 0, f.stdout) + self.assertIn("still live: none", f.stdout) + self.assertFalse(wl.exists()) + archived = self.archive_dirs()[0] / wl.name + self.assertEqual(archived.read_bytes(), self.stamps[wl.name] + b"late segment\n", + "bytes a writer appends through its open descriptor must land in the archive") + + def test_a_session_start_created_by_name_after_the_move_stays_live(self): + hook = self.tmp / "hook" + self.write_exec(hook, '#!/bin/sh\ncase "$1:$2" in archived:*session-start-*) printf "t0=fresh window\\n" > "$2" ;; esac\nexit 0\n') + f = self.close_then("--logged", "1", env=self.env(SESSION_END_TEST_HOOK=str(hook))) + self.assertEqual(f.returncode, 0, f.stdout) + live = self.run_dir / ("session-start-" + self.key) + self.assertEqual(live.read_bytes(), b"t0=fresh window\n", "a new stamp written by name must stay live and untouched") + self.assertEqual((self.archive_dirs()[0] / live.name).read_bytes(), self.stamps[live.name]) + + def test_a_writer_at_the_old_compare_and_unlink_point_loses_no_bytes(self): + # A review's reproduction appended unbilled bytes between the copy's last + # compare and the unlink; finish erased them and reported success. The + # writer here appends by name at both edges of the move. + hook = self.tmp / "hook" + self.write_exec(hook, '''#!/usr/bin/env python3 +import os, sys +phase, path = sys.argv[1], sys.argv[2] +live = os.path.join(os.environ["SE_RUN"], os.path.basename(path)) +if os.path.basename(path).startswith("work-log-") and phase in ("before-move", "archived"): + chunk = ("unbilled %s\\n" % phase).encode() + with open(live, "ab") as f: + f.write(chunk) + with open(os.environ["SE_WROTE"], "ab") as f: + f.write(chunk) +''') + wrote = self.tmp / "wrote" + f = self.close_then("--logged", "1", env=self.env(SESSION_END_TEST_HOOK=str(hook), SE_RUN=str(self.run_dir), + SE_WROTE=str(wrote))) + name = "work-log-" + self.key + live = self.run_dir / name + archived = self.archive_dirs()[0] / name + together = archived.read_bytes() + (live.read_bytes() if live.exists() else b"") + self.assertEqual(together, self.stamps[name] + wrote.read_bytes(), + "every byte the writer wrote must be in the archive or the live file") + self.assertEqual(live.read_bytes(), b"unbilled archived\n") + self.assertEqual(f.returncode, 1, "a new segment keeps the window open: " + f.stdout) + self.assertEqual((self.run_dir / ("session-start-" + self.key)).read_bytes(), self.stamps["session-start-" + self.key]) + self.assertEqual(self.closeout.read_text(), "2026-11-01T09:00:00-04:00\n") + + def test_a_failed_rename_leaves_the_live_stamp_and_exits_1(self): + hook = self.tmp / "hook" + self.write_exec(hook, '#!/bin/sh\ncase "$1:$2" in before-move:*work-log-*) chmod 500 "$(dirname "$2")" ;; esac\nexit 0\n') + self.addCleanup(lambda: [d.chmod(0o700) for d in self.archive_dirs()]) + f = self.close_then("--logged", "1", env=self.env(SESSION_END_TEST_HOOK=str(hook))) + self.assertEqual(f.returncode, 1, f.stdout) + self.assertIn("FAILED", f.stdout) + self.assertEqual(self.stamps_now(), self.stamps) + self.assertEqual(self.archive_dirs(), [], "an archive directory with nothing moved is removed") + self.assertEqual(self.closeout.read_text(), "2026-11-01T09:00:00-04:00\n") + + def test_a_post_rename_hash_failure_records_the_move_and_keeps_the_window_live(self): + # A rename can succeed before hashing fails. The moved file still needs + # a recovery path, and an unsuccessful finish must retain the billing flag. + live = self.run_dir / ("session-start-" + self.key) + live.chmod(0o000) + try: + f = self.close_then("--logged", "1") + finally: + if live.exists(): + live.chmod(0o600) + for adir in self.archive_dirs(): + archived = adir / live.name + if archived.exists(): + archived.chmod(0o600) + self.assertEqual(f.returncode, 1, f.stdout) + self.assertEqual(self.closeout.read_text(), "2026-11-01T09:00:00-04:00\n") + adir = self.archive_dirs()[0] + self.assertEqual((adir / live.name).read_bytes(), self.stamps[live.name]) + self.assertIn("restore %s" % live.name, f.stdout) + meta = (adir / "reaped.meta").read_text() + self.assertIn("file=%s\t" % live.name, meta) + self.assertIn("size=unknown\tsha256=unavailable", meta) + self.assertTrue(live.exists(), "a failed finish cleared the unbilled-window flag") + self.assertEqual(live.read_bytes(), self.stamps[live.name]) + + def test_a_failed_meta_write_keeps_the_window_live_and_reports_the_archive(self): + hook = self.tmp / "meta-hook" + self.write_exec(hook, '''#!/usr/bin/env python3 +import os, sys +from pathlib import Path +if sys.argv[1] == "archived" and os.path.basename(sys.argv[2]).startswith("session-start-"): + reaped = Path(os.environ["SE_RUN"]) / "reaped" + for adir in reaped.iterdir(): + adir.chmod(0o500) +''') + f = self.close_then("--logged", "1", env=self.env(SESSION_END_TEST_HOOK=str(hook), SE_RUN=str(self.run_dir))) + for adir in self.archive_dirs(): + adir.chmod(0o700) + self.assertEqual(f.returncode, 1, f.stdout) + self.assertEqual(self.closeout.read_text(), "2026-11-01T09:00:00-04:00\n") + adir = self.archive_dirs()[0] + self.assertFalse((adir / "reaped.meta").exists()) + self.assertIn(str(adir), f.stdout) + self.assertNotIn("reaped.meta holds the outcome", f.stdout) + live = self.run_dir / ("session-start-" + self.key) + self.assertTrue(live.exists(), "a metadata failure cleared the unbilled-window flag") + self.assertEqual(live.read_bytes(), self.stamps[live.name]) + retry = self.se("finish", "--logged", "1") + self.assertEqual(retry.returncode, 0, retry.stdout + retry.stderr) + self.assertFalse(live.exists()) + + def test_a_failed_meta_write_never_replaces_a_newer_live_flag(self): + hook = self.tmp / "meta-hook" + self.write_exec(hook, '''#!/usr/bin/env python3 +import os, sys +from pathlib import Path +if sys.argv[1] == "archived" and os.path.basename(sys.argv[2]).startswith("session-start-"): + Path(sys.argv[2]).write_bytes(b"newer unbilled window\\n") + for adir in (Path(os.environ["SE_RUN"]) / "reaped").iterdir(): + adir.chmod(0o500) +''') + f = self.close_then("--logged", "1", env=self.env(SESSION_END_TEST_HOOK=str(hook), SE_RUN=str(self.run_dir))) + for adir in self.archive_dirs(): + adir.chmod(0o700) + self.assertEqual(f.returncode, 1, f.stdout) + live = self.run_dir / ("session-start-" + self.key) + self.assertEqual(live.read_bytes(), b"newer unbilled window\n") + self.assertEqual((self.archive_dirs()[0] / live.name).read_bytes(), self.stamps[live.name]) + self.assertEqual(self.closeout.read_text(), "2026-11-01T09:00:00-04:00\n") + + def test_a_sync_failure_after_the_start_rename_keeps_recovery_and_window_live(self): + archive = runpy.run_path(str(self.script))["archive_billing"] + real_sync = archive.__globals__["fsync_dir"] + live = self.run_dir / ("session-start-" + self.key) + injected = False + + def fail_once(path): + nonlocal injected + if Path(path) == self.run_dir and not live.exists() and not injected: + injected = True + raise OSError("injected sync failure after the flag move") + real_sync(path) + + with mock.patch.dict(archive.__globals__, {"stamp_dir": lambda: str(self.run_dir), + "fsync_dir": fail_once, "test_hook": lambda *_: None}): + ok, lines = archive(self.key, "logged=1") + self.assertTrue(injected) + self.assertFalse(ok) + self.assertEqual(live.read_bytes(), self.stamps[live.name]) + adir = self.archive_dirs()[0] + self.assertEqual((adir / live.name).read_bytes(), self.stamps[live.name]) + self.assertIn("file=%s\t" % live.name, (adir / "reaped.meta").read_text()) + self.assertIn("restore %s" % live.name, "\n".join(lines)) + + def test_a_sync_failure_after_flag_restoration_does_not_record_a_missing_archive(self): + archive = runpy.run_path(str(self.script))["archive_billing"] + real_sync = archive.__globals__["fsync_dir"] + live = self.run_dir / ("session-start-" + self.key) + work_log = self.run_dir / ("work-log-" + self.key) + injected = False + + def write_segment(phase, path): + if phase == "archived" and Path(path) == live: + work_log.write_bytes(b"new unbilled segment\n") + + def fail_once(path): + nonlocal injected + if Path(path) == self.run_dir and live.exists() and work_log.exists() and not injected: + injected = True + raise OSError("injected sync failure after the flag was restored") + real_sync(path) + + with mock.patch.dict(archive.__globals__, {"stamp_dir": lambda: str(self.run_dir), + "fsync_dir": fail_once, "test_hook": write_segment}): + ok, lines = archive(self.key, "logged=1") + self.assertTrue(injected) + self.assertFalse(ok) + self.assertEqual(live.read_bytes(), self.stamps[live.name]) + self.assertEqual(work_log.read_bytes(), b"new unbilled segment\n") + adir = self.archive_dirs()[0] + self.assertFalse((adir / live.name).exists()) + self.assertNotIn("file=%s\t" % live.name, (adir / "reaped.meta").read_text()) + self.assertNotIn("restore %s," % live.name, "\n".join(lines)) + + def test_a_competing_finish_holds_the_lock(self): + self.transcript() + self.assertEqual(self.sej("close", "--wait", "30")[0].returncode, 0) + locks = self.state / "session-end" / "locks" + locks.mkdir(parents=True, exist_ok=True) + fd = os.open(str(locks / ("billing-%s.lock" % self.key)), os.O_RDWR | os.O_CREAT, 0o600) + self.addCleanup(os.close, fd) + fcntl.flock(fd, fcntl.LOCK_EX) + f = self.se("finish", "--logged", "1", env=self.env(SESSION_END_LOCK_WAIT="0")) + self.assertEqual(f.returncode, 1) + self.assertIn("holds the billing lock", f.stdout) + self.assertEqual(self.stamps_now(), self.stamps) + + def test_a_running_finish_cannot_retire_a_newer_ending_receipt(self): + self.transcript() + self.assertEqual(self.sej("close", "--wait", "30")[0].returncode, 0) + receipt = self.state / "session-end" / (self.key + ".json") + original = receipt.read_bytes() + ready, release = self.tmp / "finish-ready", self.tmp / "finish-release" + hook = self.tmp / "archive-hook" + self.write_exec(hook, '''#!/usr/bin/env python3 +import os, sys, time +from pathlib import Path +if sys.argv[1] == "archived" and os.path.basename(sys.argv[2]).startswith("work-log-"): + Path(os.environ["SE_FINISH_READY"]).touch() + end = time.monotonic() + 20 + while not Path(os.environ["SE_FINISH_RELEASE"]).exists(): + if time.monotonic() >= end: + sys.exit(1) + time.sleep(0.02) +''') + child = subprocess.Popen([sys.executable, str(self.script), "finish", "--logged", "1"], + cwd=self.cw, env=self.env(SESSION_END_TEST_HOOK=str(hook), SE_FINISH_READY=str(ready), + SE_FINISH_RELEASE=str(release)), + stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) + try: + self.wait_for(ready.exists) + p, obj = self.sej("pause", "--wait", "0", env=self.env(SESSION_END_LOCK_WAIT="0")) + self.assertEqual(p.returncode, 1, "an overlapping ending replaced the receipt: " + p.stdout) + self.assertIn("holds the billing lock", p.stdout) + self.assertEqual(receipt.read_bytes(), original) + finally: + release.touch() + out, err = child.communicate(timeout=30) + self.assertEqual(child.returncode, 0, out + err) + done = list((self.state / "session-end" / "done").iterdir()) + self.assertEqual(len(done), 1) + self.assertEqual(done[0].read_bytes(), original) + + def test_a_new_work_log_during_start_stamp_archival_keeps_the_window_live(self): + hook = self.tmp / "new-work-hook" + self.write_exec(hook, '''#!/usr/bin/env python3 +import os, sys +if sys.argv[1] == "archived" and os.path.basename(sys.argv[2]).startswith("session-start-"): + key = os.path.basename(sys.argv[2])[len("session-start-"):] + with open(os.path.join(os.path.dirname(sys.argv[2]), "work-log-" + key), "w") as f: + f.write("new unbilled segment\\n") +''') + f = self.close_then("--logged", "1", env=self.env(SESSION_END_TEST_HOOK=str(hook))) + self.assertEqual(f.returncode, 1, f.stdout) + self.assertEqual((self.run_dir / ("session-start-" + self.key)).read_bytes(), + self.stamps["session-start-" + self.key]) + self.assertEqual((self.run_dir / ("work-log-" + self.key)).read_bytes(), b"new unbilled segment\n") + self.assertEqual(self.closeout.read_text(), "2026-11-01T09:00:00-04:00\n") + + def test_the_first_call_never_advances_last_closeout(self): + self.transcript() + for mode in ("pause", "move", "close"): + p, _ = self.sej(mode, "--wait", "30") + self.assertEqual(p.returncode, 0, p.stdout) + self.assertEqual(self.closeout.read_text(), "2026-11-01T09:00:00-04:00\n", mode) + self.assertEqual(self.se("finish").returncode, 2, "finish after a close needs a billing flag") + self.assertEqual(self.closeout.read_text(), "2026-11-01T09:00:00-04:00\n") + + def test_finish_without_a_receipt_fails(self): + f = self.se("finish") + self.assertEqual(f.returncode, 1) + self.assertIn("no receipt", f.stdout) + self.assertEqual(self.closeout.read_text(), "2026-11-01T09:00:00-04:00\n") + + # --- lint, extras, modes ------------------------------------------------------ + + def test_lint_runs_only_when_the_transcript_names_a_harness_file(self): + self.transcript([("Read", {"file_path": str(self.proj / "README.md")}, "x", False)]) + p, obj = self.sej("pause", "--wait", "30") + self.assertEqual(p.returncode, 0, p.stdout) + self.assertEqual(self.calls("verify-ops.sh"), []) + self.transcript([("Edit", {"file_path": str(self.cw / "SKILLS" / "x" / "SKILL.md")}, "ok", False)]) + self.behavior["verify-ops.sh"] = {"rc": 1, "out": "FAIL: check 7: something broke\n" + self.LINT_SUMMARY} + self.save_behavior() + p, obj = self.sej("pause", "--wait", "30") + # Settled behavior: a completed lint's FAILs are findings, not a failed receipt. + self.assertEqual(p.returncode, 0, p.stdout) + self.assertEqual(self.step(obj, "lint")["status"], "findings") + self.assertEqual([c["argv"] for c in self.calls("verify-ops.sh")], [["--quiet"]]) + self.assertIn("FAIL: check 7: something broke", self.step(obj, "lint")["output"]) + + LINT_SUMMARY = "verify-ops: 57 ok · 1 warn · 2 fail (2026-11-17T18:00:00-05:00)" + + def lint_run(self, rc, out, *args): + self.transcript([("Edit", {"file_path": str(self.cw / ".claude-config" / "bin" / "x")}, "ok", False)]) + self.behavior["verify-ops.sh"] = {"rc": rc, "out": out} + self.save_behavior() + return self.sej("pause", "--wait", "30", *args) + + def test_lint_fail_lines_with_the_gate_summary_are_findings_and_finish_still_stamps(self): + out = ("FAIL: the launch environment overrides the auto-compact policy:\n detail line\n" + "WARN: disk-guard: last run is not healthy\n" + "FAIL: SessionStart hook stdout over 8192B budget\n" + self.LINT_SUMMARY) + self.behavior["verify-ops.sh"] = {"rc": 1, "out": out} + self.save_behavior() + self.transcript([("Edit", {"file_path": str(self.cw / ".claude-config" / "bin" / "x")}, "ok", False)]) + text = self.se("pause", "--wait", "30") + self.assertEqual(text.returncode, 0, text.stdout) + self.assertIn("[findings] lint:", text.stdout) + p, obj = self.sej("pause", "--wait", "30") + self.assertEqual(p.returncode, 0, "lint findings must not fail the receipt: " + p.stdout) + self.assertEqual(obj["status"], "completed") + lint = self.step(obj, "lint") + self.assertEqual(lint["status"], "findings") + self.assertEqual(lint["fail_lines"], ["FAIL: the launch environment overrides the auto-compact policy:", + "FAIL: SessionStart hook stdout over 8192B budget"]) + self.assertIn(" - Lint reported 2 FAIL line(s) above: fix the ones on files this thread changed, " + "and name the rest as other work's in your report.", obj["remainder"]) + receipt = json.loads((self.state / "session-end" / (self.key + ".json")).read_text()) + self.assertEqual(receipt["status"], "completed") + self.assertEqual(len(receipt["lint_findings"]), 2) + f = self.se("finish") + self.assertEqual(f.returncode, 0, f.stdout) + self.assertIn("lint findings were reported at the start: 2", f.stdout) + self.assertNotEqual(self.closeout.read_text(), "2026-11-01T09:00:00-04:00\n") + + def test_lint_without_a_readable_result_stays_failed_and_finish_refuses(self): + for rc, out, why in ((1, "FAIL: check 7: something broke", "without the gate's summary line"), + (1, "", "without the gate's summary line"), + (1, self.LINT_SUMMARY.replace("2 fail", "0 fail"), "without the gate's summary line"), + (2, "verify-ops: unknown option", "exit 2 is neither")): + p, obj = self.lint_run(rc, out) + self.assertEqual(p.returncode, 1, (rc, out, p.stdout)) + lint = self.step(obj, "lint") + self.assertEqual(lint["status"], "failed", (rc, out)) + self.assertIn(why, lint["summary"]) + self.assertFalse(any("Lint reported" in l for l in obj["remainder"])) + f = self.se("finish") + self.assertEqual(f.returncode, 1, f.stdout) + self.assertEqual(self.closeout.read_text(), "2026-11-01T09:00:00-04:00\n") + self.write_exec(self.bin / "verify-ops.sh", "#!/no-such-interpreter\n") + self.transcript([("Edit", {"file_path": str(self.cw / ".claude-config" / "bin" / "x")}, "ok", False)]) + p, obj = self.sej("pause", "--wait", "30") + self.assertEqual(p.returncode, 1) + self.assertEqual(self.step(obj, "lint")["status"], "failed") + self.assertIn("could not start", self.step(obj, "lint")["summary"]) + + def test_a_clean_lint_is_completed_with_no_remainder_line(self): + p, obj = self.lint_run(0, self.LINT_SUMMARY.replace("2 fail", "0 fail")) + self.assertEqual(p.returncode, 0, p.stdout) + self.assertEqual(self.step(obj, "lint")["status"], "completed") + self.assertNotIn("fail_lines", self.step(obj, "lint")) + self.assertFalse(any("Lint reported" in l for l in obj["remainder"])) + + def test_exit_zero_without_a_clean_gate_summary_cannot_complete_the_receipt(self): + for out in ("", "a helper stopped before the summary", self.LINT_SUMMARY, + "FAIL: inconsistent result\n" + self.LINT_SUMMARY.replace("2 fail", "0 fail")): + with self.subTest(output=out): + p, obj = self.lint_run(0, out) + self.assertEqual(p.returncode, 1, p.stdout) + self.assertEqual(self.step(obj, "lint")["status"], "failed") + f = self.se("finish") + self.assertEqual(f.returncode, 1, f.stdout) + self.assertEqual(self.closeout.read_text(), "2026-11-01T09:00:00-04:00\n") + + def test_lint_recognizes_relative_paths_and_another_harness_worktree(self): + lane = self.home / "harness-worktree" + g(self.cw, "worktree", "add", "-q", "-b", "lint-lane", str(lane)) + for inp in ({"file_path": str(lane / ".claude-config" / "bin" / "changed")}, + {"file_path": ".claude-config/bin/changed"}, + {"command": "sed -n '1p' SKILLS/example/SKILL.md"}): + self.transcript([("Bash" if "command" in inp else "Edit", inp, "ok", False)]) + p, obj = self.sej("pause", "--dry-run", "--wait", "0", cwd=lane) + self.assertEqual(p.returncode, 0, p.stdout) + self.assertEqual(self.step(obj, "lint")["status"], "completed", inp) + self.assertIn("would run", self.step(obj, "lint")["summary"]) + + def test_a_helper_that_cannot_start_reports_the_os_error(self): + self.write_exec(self.bin / "asks", "#!/no-such-interpreter\n") + p, obj = self.sej("pause", "--wait", "30") + self.assertEqual(p.returncode, 1, p.stdout) + self.assertIn("cannot run", self.step(obj, "open asks")["output"]) + + def test_vault_view_is_an_explicit_skip_that_runs_nothing(self): + # OPS ships no vault renderer: the step says so, even beside a NOTES tree, + # and starts no tool of its own in a real run or a dry run. + (self.cw / "NOTES").mkdir() + for args in (["pause", "--wait", "30"], ["pause", "--dry-run", "--wait", "30"]): + p, obj = self.sej(*args) + self.assertEqual(p.returncode, 0, p.stdout) + vv = self.step(obj, "vault view") + self.assertEqual(vv["status"], "skipped", args) + self.assertIn("ships no vault renderer", vv["summary"]) + self.assertLessEqual({c["tool"] for c in self.calls()}, READ_ONLY_TOOLS) + + @staticmethod + def section(text, step): + """The human-output block of one step: its status line and indented lines.""" + m = re.search(r"^\[\w+\] %s:.*?(?=^\[|^\Z|\n\n)" % re.escape(step), text, re.M | re.S) + return m.group(0) if m else "" + + def test_baton_is_resolved_where_the_notifier_reads_it_from_a_linked_worktree(self): + # hooks/handoff-check.sh reads ${OPS_DIR:-$HOME/OPS}/.claude-handoffs, so a + # run from a linked worktree (which holds no batons of its own) names ~/OPS's. + lane = self.home / "ops-lane" + g(self.cw, "worktree", "add", "-q", "-b", "lane", str(lane)) + script = lane / ".claude-config" / "bin" / "session-end" + key = str(lane).replace("/", "-").lstrip("-") + p = self.se("move", "--wait", "30", script=script, cwd=lane) + self.assertEqual(p.returncode, 0, p.stdout) + baton = self.cw / ".claude-handoffs" / "pending" / (key + ".md") + self.assertIn("the baton is %s (not written yet)" % baton, p.stdout) + self.assertNotIn(str(lane / ".claude-handoffs"), p.stdout) + other = self.tmp / "ops-dir" + p = self.se("move", "--wait", "30", script=script, cwd=lane, env=self.env(OPS_DIR=str(other))) + self.assertEqual(p.returncode, 0, p.stdout) + self.assertIn("the baton is %s (not written yet)" % (other / ".claude-handoffs" / "pending" / (key + ".md")), + p.stdout) + + def test_worktree_list_is_printed_once_and_capped(self): + wts = [] + for i in range(5): + w = self.home / "wt" / ("wl-%d" % i) + g(self.proj, "worktree", "add", "-q", "-b", "wl%d" % i, str(w)) + wts.append(w) + self.transcript([("Read", {"file_path": str(wts[3] / "README.md")}, "fixture", False)]) + p = self.se("pause", "--repo", str(self.proj), "--repo", str(wts[1]), "--wait", "30", cwd=wts[0]) + self.assertEqual(p.returncode, 0, p.stdout) + snap = self.section(p.stdout, "git snapshot") + self.assertEqual(snap.count("worktrees of main checkout %s: 6" % self.proj), 1, snap) + self.assertEqual(snap.count("worktrees: see main checkout %s" % self.proj), 3, snap) + self.assertIn("worktree %s [wl0] (this call's cwd)" % wts[0], snap) + self.assertIn("worktree %s [wl3]" % wts[3], snap) + for hidden in (wts[2], wts[4]): + self.assertNotIn(str(hidden), snap) + self.assertIn("... and 4 more (git -C %s worktree list)" % self.proj, snap) + + def gc_rows_fixture(self): + P = str(self.proj) + wt = self.home / "wt-named" + self.behavior["branch-gc"] = {"rows": [ + [P, "feat-done", "-", "#7 MERGED", "remove", "tip == merged PR #7 head"], + [P, "named-br", "-", "#9 OPEN", "report", "open PR"], + [P, "lane", str(wt), "-", "report", "dirty worktree"], + [P, "unnamed-a", "-", "-", "report", "no PR"], + [P, "unnamed-b", "-", "-", "report", "no PR"], + [P, "gone", "-", "-", "skip", "worktree quarantined earlier in this run"]]} + self.save_behavior() + self.transcript([("Bash", {"command": "git -C %s log --oneline named-br" % P}, "abc", False), + ("Read", {"file_path": str(wt / "notes.txt")}, "x", False)]) + + def test_gc_human_output_keeps_actions_and_named_rows_and_counts_the_rest(self): + self.gc_rows_fixture() + for args, ref in ((["--dry-run"], "they are in --json"), ([], "full output: ")): + p = self.se("pause", "--repo", str(self.proj), "--wait", "30", *args) + self.assertEqual(p.returncode, 0, p.stdout) + gc = self.section(p.stdout, "branch-gc") + for shown in ("branch-gc ", "feat-done\t-\t#7 MERGED\tremove", "named-br", "dirty worktree", + "gone\t-\t-\tskip", "Summary (remove / report / quarantine / failed):"): + self.assertIn(shown, gc, args) + for hidden in ("unnamed-a", "unnamed-b"): + self.assertNotIn(hidden, gc, "an unnamed report row reached the human output %s" % args) + self.assertIn("2 report-only rows not shown; " + ref, gc) + pj, obj = self.sej("pause", "--repo", str(self.proj), "--wait", "30", *args) + full = self.step(obj, "branch-gc")["output"] + self.assertIn("unnamed-a", full, "--json must keep the full child output %s" % args) + self.assertNotIn("human", self.step(obj, "branch-gc")) + self.assertRegex(gc, r"full output: \S+/session-end/gc/[^/\s]+/run\.log") + + def test_gc_output_that_is_not_the_documented_tsv_is_printed_whole(self): + self.behavior["branch-gc"] = {"raw": "branch-gc: something unexpected\nreport\tonly\tfour\tcols"} + self.save_behavior() + p = self.se("pause", "--dry-run", "--repo", str(self.proj), "--wait", "30") + gc = self.section(p.stdout, "branch-gc") + self.assertIn("branch-gc: something unexpected", gc) + self.assertIn("report\tonly\tfour\tcols", gc) + self.assertNotIn("not shown", gc) + + def test_json_retains_child_output_beyond_the_human_limit(self): + raw = "branch-gc: " + "x" * 70000 + "\nLAST CHILD OUTPUT LINE" + self.behavior["branch-gc"] = {"raw": raw} + self.save_behavior() + for extra in (["--dry-run"], []): + p, obj = self.sej("pause", "--repo", str(self.proj), "--wait", "30", *extra) + self.assertEqual(p.returncode, 0, p.stdout[-1000:]) + full = self.step(obj, "branch-gc")["output"] + self.assertTrue(raw.splitlines()[0] in full, "JSON truncated the child's output") + self.assertIn("LAST CHILD OUTPUT LINE", full) + human = self.se("pause", "--repo", str(self.proj), "--wait", "30", *extra) + self.assertEqual(human.returncode, 0, human.stdout[-1000:]) + self.assertIn("output cut at 65536 characters", human.stdout) + self.assertNotIn("LAST CHILD OUTPUT LINE", human.stdout) + + def test_modes_unknown_is_2_pause_has_no_settle_close_has_no_compact(self): + self.assertEqual(self.se("wrap").returncode, 2) + self.assertEqual(self.se("pause", "--wait", "-1").returncode, 2) + self.assertEqual(self.se("pause", "--wait", "nan").returncode, 2) + self.assertEqual(self.se("pause", "--repo", str(self.tmp / "missing")).returncode, 2) + self.transcript() + p = self.se("pause", "--wait", "30") + self.assertIn("compact-cycle.sh --target %s" % TID, p.stdout) + self.assertIn("Never compact over an unanswered question", p.stdout) + self.assertNotIn("Settle", p.stdout) + c = self.se("close", "--wait", "30") + self.assertNotIn("compact-cycle", c.stdout) + self.assertIn('t3_thread_organize with action "settle"', c.stdout) + self.assertIn("Never both", c.stdout) + self.assertNotIn("settled", c.stdout.replace("unsettled", "")) + for field in ("NEXT ACTION (one step)", "VERIFY FIRST", "DO NOT (with who said so)", "DEAD ENDS", "ASK THE OWNER"): + self.assertIn(field, c.stdout) + + def test_move_reports_the_baton_from_key_sh_in_the_original_cwd(self): + key = str(self.proj).replace("/", "-").lstrip("-") + p = self.se("move", "--wait", "30", cwd=self.proj) + baton = self.cw / ".claude-handoffs" / "pending" / (key + ".md") + self.assertIn("the baton is %s (not written yet)" % baton, p.stdout) + baton.write_text("status: pending\n") + p = self.se("move", "--wait", "30", cwd=self.proj) + self.assertIn("the baton is %s (exists" % baton, p.stdout) + + # --- the transcript, time and ids ------------------------------------------- + + def test_missing_or_foreign_transcript_infers_nothing_and_gives_no_time(self): + p, obj = self.sej("close", "--repo", str(self.proj), "--wait", "30") + self.assertEqual(p.returncode, 0, p.stdout) + self.assertEqual([c["argv"][-1] for c in self.gc_applies()], [str(self.proj)]) + self.assertIn("no time figure", self.step(obj, "time")["summary"]) + self.assertEqual(self.calls("active-minutes"), []) + bad = self.tmp / "foreign.jsonl" + bad.write_text(json.dumps({"type": "user", "sessionId": "another-session", "message": {"content": "x"}}) + "\n") + p, obj = self.sej("close", "--transcript", str(bad), "--wait", "30") + self.assertIn("another session", self.step(obj, "transcript")["summary"]) + self.assertEqual(self.step(obj, "time")["status"], "skipped") + torn = self.tmp / "torn.jsonl" + torn.write_text(json.dumps({"type": "user", "sessionId": SID, "message": {"content": "x"}}) + "\nnot json\n" + + json.dumps({"type": "assistant", "sessionId": SID, "message": {"content": []}}) + "\n") + p, obj = self.sej("close", "--transcript", str(torn), "--wait", "30") + self.assertIn("unsupported format", self.step(obj, "transcript")["summary"]) + self.assertEqual(obj["identity"]["session_id"], SID) + self.assertEqual(obj["identity"]["t3_thread_id"], TID) + self.assertNotIn(str(self.cw), [c["argv"][-1] for c in self.gc_applies()]) + + def test_time_passes_lane_transcripts_and_never_a_silent_total(self): + tx = self.transcript([("Agent", {"prompt": "lane"}, "done", False)]) + base = Path(str(tx)[:-len(".jsonl")]) + (base / "subagents" / "workflows" / "w1").mkdir(parents=True) + lane = base / "subagents" / "agent-a1.jsonl" + lane.write_text("{}\n") + wf = base / "subagents" / "workflows" / "w1" / "agent-b2.jsonl" + wf.write_text("{}\n") + p, obj = self.sej("close", "--wait", "30") + self.assertEqual(self.calls("active-minutes")[0]["argv"], [str(tx), "--also", str(lane), str(wf)]) + t = self.step(obj, "time") + self.assertTrue(t["confident"]) + self.assertIn("evidence, not an amount to enter", t["summary"]) + shutil.rmtree(base) + p, obj = self.sej("close", "--wait", "30") + t = self.step(obj, "time") + self.assertFalse(t["confident"]) + self.assertIn("NOT CONFIDENT", t["summary"]) + self.behavior["active-minutes"] = {"rc": 1, "out": "not enough timestamped events to measure"} + self.save_behavior() + p, obj = self.sej("close", "--wait", "30") + self.assertEqual(p.returncode, 1) + self.assertEqual(self.step(obj, "time")["status"], "failed") + self.assertIn("no time figure", self.step(obj, "time")["summary"]) + + # --- memory ------------------------------------------------------------------- + + def test_memory_pool_backfill_absent_pool_and_failed_rebuild(self): + p, obj = self.sej("pause", "--wait", "30", cwd=self.proj, env=self.env(CLAUDE_PROJECT_DIR=str(self.other))) + self.assertEqual(self.calls("memory-index")[0]["argv"], ["--pool-for", "--cwd", str(self.other), + "--ops", str(self.cw)]) + self.assertEqual(self.calls("memory-index")[1]["argv"], [str(self.pool)]) + self.behavior["memory-index"] = {"pool": str(self.pool), "rebuild_rc": 2} + self.save_behavior() + p, obj = self.sej("pause", "--wait", "30") + self.assertEqual(p.returncode, 0) + self.assertIn("need backfill", self.step(obj, "memory index")["summary"]) + self.behavior["memory-index"] = {"pool": str(self.pool), "rebuild_rc": 1} + self.save_behavior() + p, obj = self.sej("pause", "--wait", "30") + self.assertEqual(p.returncode, 1) + self.assertEqual(self.step(obj, "memory index")["status"], "failed") + self.behavior["memory-index"] = {} + self.save_behavior() + n = len(self.calls("memory-index")) + p, obj = self.sej("pause", "--wait", "30") + self.assertEqual(p.returncode, 0) + self.assertEqual(self.step(obj, "memory index")["status"], "skipped") + self.assertEqual(len(self.calls("memory-index")), n + 1, "a rebuild ran without a pool") + + def test_memory_stewardship_lists_only_entries_in_the_window_and_changes_none(self): + inside = self.pool / "lesson-new.md" + inside.write_text("---\nname: lesson-new\nmetadata:\n type: feedback\n modified: %s\n---\nbody\n" % time.strftime("%Y-%m-%d")) + outside = self.pool / "lesson-old.md" + outside.write_text("---\nname: lesson-old\nmetadata:\n type: feedback\n modified: 2020-01-01\n---\nold\n") + os.utime(outside, (1577880000, 1577880000)) + before = tree_state(self.pool) + self.transcript() + p = self.se("pause", "--wait", "30") + self.assertIn("lesson-new.md", p.stdout) + self.assertNotIn("lesson-old.md", p.stdout) + # The pool is shared by concurrent threads: the label must not claim authorship. + self.assertIn("entries written or changed in this pool during this thread's window, " + "by this thread or another one sharing the pool", p.stdout) + self.assertIn("session-end changed no entry", p.stdout) + self.assertEqual(tree_state(self.pool), before) + + # --- OPS: what this port must agree with --------------------------------------- + + def test_gc_reaches_exactly_the_repos_the_pre_compact_hook_would(self): + # hooks/pre-compact.sh hands branch-gc ~/OPS, ~/OPS/PROJECTS// and + # ~/linuxploitacious by name under the real HOME, wherever the hook itself + # lives. A clone of OPS under another name is not managed, even when this + # command runs from it; ~/OPS still is. + copy = self.home / "ops-copy" + g(self.home, "clone", "-q", str(self.cw), str(copy)) + g(copy, "config", "remote.origin.url", "https://github.com/acme/harness-copy.git") + lx = make_repo(self.home / "linuxploitacious", origin="https://github.com/acme/linuxploitacious.git") + script = copy / ".claude-config" / "bin" / "session-end" + p, obj = self.sej("pause", "--repo", str(copy), "--repo", str(self.cw), "--repo", str(lx), + "--wait", "30", script=script, cwd=copy) + self.assertEqual(p.returncode, 0, p.stdout) + self.assertEqual(sorted(c["argv"][-1] for c in self.gc_applies()), sorted([str(self.cw), str(lx)])) + self.assertIn("not run: %s is not a repo branch-gc manages" % copy, self.step(obj, "branch-gc")["output"]) + + def test_lint_is_verify_ops_quiet_against_this_checkout_and_reads_its_summary(self): + p, obj = self.lint_run(1, "FAIL: check 3: drift\n" + self.LINT_SUMMARY) + self.assertEqual(p.returncode, 0, p.stdout) + call = self.calls("verify-ops.sh")[0] + self.assertEqual(call["argv"], ["--quiet"], "verify-ops.sh has no lint mode; --quiet is the quiet run") + self.assertEqual(call["env"]["OPS_DIR"], str(self.cw), "the gate must check this checkout, not ~/OPS") + self.assertEqual(self.step(obj, "lint")["status"], "findings") + p, obj = self.lint_run(1, "FAIL: check 3: drift\n" + self.LINT_SUMMARY.replace("verify-ops:", "verify-other:")) + self.assertEqual(p.returncode, 1, p.stdout) + self.assertEqual(self.step(obj, "lint")["status"], "failed", "another gate's summary line is not this gate's result") + p, obj = self.lint_run(0, "", "--dry-run") + self.assertIn("would run OPS_DIR=%s %s --quiet" % (self.cw, self.bin / "verify-ops.sh"), + self.step(obj, "lint")["summary"]) + + def test_ops_state_dir_wins_and_a_missing_gate_is_visible(self): + alt = self.tmp / "alt-state" + self.transcript() + p, obj = self.sej("pause", "--wait", "30", env=self.env(OPS_STATE_DIR=str(alt))) + self.assertEqual(p.returncode, 0, p.stdout) + self.assertTrue((alt / "session-end" / (self.key + ".json")).is_file()) + self.assertFalse((self.state / "session-end").exists(), "OPS_STATE_DIR was ignored") + (self.bin / "verify-ops.sh").unlink() + before = len(self.calls("branch-gc")) + p, obj = self.sej("pause", "--wait", "30") + self.assertEqual(p.returncode, 1, p.stdout) + self.assertIn("no gate script beside session-end", self.step(obj, "receipt")["summary"]) + self.assertEqual(len(self.calls("branch-gc")), before, "GC started without a state directory") + self.transcript([("Edit", {"file_path": str(self.cw / ".claude-config" / "bin" / "x")}, "ok", False)]) + p, obj = self.sej("pause", "--wait", "30", env=self.env(OPS_STATE_DIR=str(alt))) + self.assertEqual(p.returncode, 1, p.stdout) + self.assertEqual(self.step(obj, "lint")["status"], "failed") + self.assertIn("no gate script sits beside session-end", self.step(obj, "lint")["summary"]) + + def test_the_stamp_key_and_backend_come_from_ops_hooklib(self): + # T3CODE_HOME alone marks a T3 thread for ops_backend: the key is t3-. + env = self.env(T3CODE_THREAD_ID=None, T3CODE_HOME=str(self.tmp / "t3home")) + f = self.close_then("--logged", "1", env=env) + self.assertEqual(f.returncode, 0, f.stdout) + self.assertEqual(len(self.archive_dirs()), 1) + self.assertFalse((self.run_dir / ("session-start-" + self.key)).exists()) + # A tmux session keys stamps by session name, which finish does not verify. + self.write_exec(self.stubbin / "tmux", "#!/bin/sh\necho fixture-tmux\n") + env = self.env(TMUX="/tmp/fixture-tmux,1,0") + (self.run_dir / "session-start-fixture-tmux").write_bytes(b"tmux window\n") + self.transcript() + self.assertEqual(self.sej("close", "--wait", "30", env=env)[0].returncode, 0) + f = self.se("finish", "--logged", "1", env=env) + self.assertEqual(f.returncode, 1, f.stdout) + self.assertIn("the tmux backend keys stamps by session name", f.stdout) + self.assertEqual((self.run_dir / "session-start-fixture-tmux").read_bytes(), b"tmux window\n") + # A hooklib.sh without ops_backend gives no key at all, and says why. + self.write_exec(self.cw / ".claude-config" / "hooks" / "hooklib.sh", + "work_session_key() { printf t3-x; }\nhook_timeout() { printf gnutimeout; }\n") + before = len(self.calls("branch-gc")) + p, obj = self.sej("pause", "--repo", str(self.proj), "--wait", "30") + self.assertEqual(p.returncode, 1, p.stdout) + self.assertIn("defines no work_session_key or ops_backend", p.stdout) + self.assertEqual(len(self.calls("branch-gc")), before, "GC started without a trusted stamp key") + + def test_memory_pool_lookup_names_the_checkout_the_digest_hook_passes(self): + self.assertEqual(self.sej("pause", "--wait", "30")[0].returncode, 0) + other = self.tmp / "ops-dir" + self.assertEqual(self.sej("pause", "--wait", "30", env=self.env(OPS_DIR=str(other)))[0].returncode, 0) + looks = [c["argv"] for c in self.calls("memory-index") if c["argv"][:1] == ["--pool-for"]] + self.assertEqual(looks, [["--pool-for", "--cwd", str(self.cw), "--ops", str(self.cw)], + ["--pool-for", "--cwd", str(self.cw), "--ops", str(other)]]) + + +if __name__ == "__main__": + unittest.main(verbosity=2) diff --git a/.claude-config/bin/verify-ops.sh b/.claude-config/bin/verify-ops.sh index c6941a4..916ab22 100755 --- a/.claude-config/bin/verify-ops.sh +++ b/.claude-config/bin/verify-ops.sh @@ -874,21 +874,27 @@ check_identity_exclusion() { # memory-init moves memory files into .claude-memory, removes old dirs # deploy.sh runs memory-init; replaces links, rc lines and units # skills-vendor.sh mirrors skill repos into SKILLS/ (rsync --delete) +# session-end starts branch-gc --apply on the thread's repos and moves +# the thread's billing stamps into an archive # Not listed, by the same rule: session-briefing.sh (reads only), # daily-sync.sh (commits and pulls its own checkout; its gc stage is branch-gc, # reached only through a stub in the suites that cover it), and tools that # replace only their own output or state file. -OPS_DESTRUCTIVE_TOOLS=(branch-gc pre-compact.sh memory-init deploy.sh skills-vendor.sh) +OPS_DESTRUCTIVE_TOOLS=(branch-gc pre-compact.sh memory-init deploy.sh skills-vendor.sh session-end) # Suites that must carry the guard although the name check cannot see why. The three # T3 suites: t3-api.sh and compact-cycle.sh delete nothing, but they send messages into # and settle threads on a real T3 server, and the box that runs a suite usually runs one # (T3 Code's default port, 127.0.0.1:3773). Listed, they must start with the guard, and # each also refuses to run with any interface but loopback or with that port answering, # so they run only in sandbox-run --no-net against their own loopback stubs. +# session-end-test.py names its tool today; it is listed as well because it runs a +# copy of a command that archives stamp files and detaches workers under $HOME, so +# a refactor that builds the name at run time must not drop its guard. OPS_SANDBOX_SUITES=( .claude-config/bin/tests/t3-api-test.sh .claude-config/bin/tests/t3-api-v2-safety-test.py .claude-config/bin/tests/compact-cycle-t3-test.sh + .claude-config/bin/tests/session-end-test.py ) check_sandbox_guards() { local b="$OPS/.claude-config/bin" f miss="" out rc summary v t py diff --git a/.claude-config/hooks/git-guard.sh b/.claude-config/hooks/git-guard.sh index f49ea39..b35b2ba 100755 --- a/.claude-config/hooks/git-guard.sh +++ b/.claude-config/hooks/git-guard.sh @@ -17,6 +17,8 @@ # git push from an OPS copy whose origin (would publish the Operator's # origin-private-check cannot prove private memory and notes; see the # or to a remote other than origin push gate at the end) +# session-end other than --dry-run from (the main thread's; neither +# a payload with an agent_id GIT_GUARD=off hatch lifts it) # # WARNED (exit 0, the warning goes to Claude as additionalContext): # a commit that would record merge conflict (see "Conflict markers" for @@ -30,13 +32,18 @@ # and export for the one call). Read-only otherwise; exit 0 = allow. set -uo pipefail -[ "${GIT_GUARD:-on}" = "off" ] && exit 0 +# The session-wide hatch is read now and applied after the session-end rule +# below, which neither hatch lifts. +GUARD_OFF=0; [ "${GIT_GUARD:-on}" = "off" ] && GUARD_OFF=1 HOOK_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" . "$HOOK_DIR/hooklib.sh" RAW_INPUT="$(cat)" if ! TOOL="$(printf '%s' "$RAW_INPUT" | hook_field tool_name)"; then + # The session-wide hatch keeps its old meaning here: with nothing to inspect, + # an exported GIT_GUARD=off still allows the call. + [ "$GUARD_OFF" = 1 ] && exit 0 # No JSON parser (jq/python) available: cannot inspect the command. Fail # CLOSED: these are doctrine hard gates (P3/P6) that must NEVER silently # disable. On Windows the old `python3 -c` resolved to 127 and `|| exit 0` @@ -49,6 +56,77 @@ fi CMD="$(printf '%s' "$RAW_INPUT" | hook_field tool_input.command)" [ -n "$CMD" ] || exit 0 +# session-end belongs to the main thread. An in-process helper agent's shell +# carries its main thread's environment and ids, so session-end cannot tell +# itself from that helper; this payload can (agent_id). A run of session-end +# other than --dry-run from a payload with a non-empty agent_id is blocked. A quoted +# executable path is a real run, including one containing spaces; the name must +# sit at a command position, so an argument that only +# names it (grep session-end, a commit subject "feat(session-end): ...") is not +# blocked. It sits before both GIT_GUARD=off hatches: those approve one git +# action, and a lane ending its main thread's session is not one. +# Limits: the rule reads command text, so a wrapper script that calls +# session-end is unseen, and a pattern argument whose alternation puts the name +# after a | (grep "x\|session-end") reads as a run; with the session-wide hatch +# exported on a box with no JSON parser, nothing is inspected at all (above). +# Shared with the git rules below: an rtk proxy must not hide the actual command. +RTKPRE='(([^[:space:]|;&]*/)?rtk[[:space:]]+(-[^[:space:]]*[[:space:]]+)*((run|err|summary|test|bypass|proxy)[[:space:]]+(-[^[:space:]]*[[:space:]]+)*)?)?' +gg_session_end_run() { # : 0 when it runs session-end without --dry-run + local seg py program + program="(\"[^\"]*/session-end\"|'[^']*/session-end'|[\"']?session-end[\"']?|([^[:space:]|;&()\`]*/)?session-end)" + while IFS= read -r seg; do + [ -n "$seg" ] || continue + py="$(hook_python 2>/dev/null)" || return 0 + # Keep argument boundaries: --dry-run inside a quoted path, a comment or + # a redirection target is not permission to run the main thread's real close. + # No shell text is evaluated. If parsing fails, the candidate stays blocked. + if "$py" - "$seg" <<'PY' +import os, shlex, sys +try: + lexer = shlex.shlex(sys.argv[1], posix=True, punctuation_chars=";&|()<>") + lexer.whitespace_split = True + words, target = [], False + for word in lexer: + if target: + target = False + elif word in ("<", ">", "<<", ">>", "<<<", "<>"): + target = True + else: + words.append(word) +except ValueError: + sys.exit(0) +at = next((i for i, word in enumerate(words) if os.path.basename(word) == "session-end"), None) +if at is None: + sys.exit(0) +args = words[at + 1:] +# finish never accepts --dry-run: it can be text inside --declined's reason. +sys.exit(0 if not args or args[0] == "finish" or "--dry-run" not in args else 1) +PY + then return 0; fi + done < <(printf '%s\n' "$1" \ + | sed 's/[|;&`]/&&/g' \ + | grep -oE '(^|[|;&`]|\$\()[[:space:]]*(([A-Za-z_][A-Za-z0-9_]*=[^[:space:]]*|command|exec|env|nohup|python3?|bash|sh)[[:space:]]+)*'"$RTKPRE$program"'([[:space:]][^|;&)`]*)?([|;&)`]|$)' \ + | sed 's/[|;&)`]$//') + # Duplicate separators before matching: grep consumes a match's trailing + # separator, so the following command otherwise loses its command position. + return 1 +} +case "$CMD" in + *session-end*) + if gg_session_end_run "$CMD"; then + if ! SE_AID="$(printf '%s' "$RAW_INPUT" | hook_field agent_id)"; then + echo "git-guard: BLOCKED: cannot read agent_id to tell a lane from the main thread; session-end is refused" >&2 + exit 2 + fi + if [ -n "$SE_AID" ]; then + echo "git-guard: BLOCKED: session-end belongs to the main thread; return your result instead" >&2 + exit 2 + fi + fi ;; +esac + +[ "$GUARD_OFF" = 1 ] && exit 0 + # The documented escape hatch is an inline prefix on the approved command # (`GIT_GUARD=off `). Hooks run in their OWN process and never # inherit inline assignments from the tool command, so the env check above @@ -91,7 +169,6 @@ deny() { # parses rtk itself, including the -c/--shell string forms. (The rtk string # forms carry their command in quotes, which the git checks strip like any # quoted span, the same known limit as `bash -c ''`.) -RTKPRE='(([^[:space:]|;&]*/)?rtk[[:space:]]+(-[^[:space:]]*[[:space:]]+)*((run|err|summary|test|bypass|proxy)[[:space:]]+(-[^[:space:]]*[[:space:]]+)*)?)?' GITPOS='(^|[|;&][|&]?)[[:space:]]*([A-Z_]+=[^[:space:]]*[[:space:]]+)*(command[[:space:]]+)?'"$RTKPRE"'git[[:space:]]' CMD_RAW="$CMD" CMD="$(printf '%s' "$CMD" | sed -e "s/'[^']*'//g" -e 's/"[^"]*"//g')" diff --git a/.claude-config/hooks/guard-selftest.sh b/.claude-config/hooks/guard-selftest.sh index 2e156b4..2d83963 100755 --- a/.claude-config/hooks/guard-selftest.sh +++ b/.claude-config/hooks/guard-selftest.sh @@ -66,6 +66,79 @@ if [ "$quick" = 1 ]; then echo "guard-selftest --quick: $fails guard(s) NOT enforcing: is jq installed? are the hooks executable (100755)?" exit 1 fi +# session-end belongs to the main thread: a payload with agent_id (an in-process +# helper) may run it only with --dry-run; the main thread runs it freely, and a +# command that only names it in an argument is not a run. Neither GIT_GUARD=off +# hatch lifts the rule, while the env hatch still lifts the git rules (control). +# The command name is spelled session\u002dend inside the JSON (jq decodes it to the +# real name) and left out of the labels: sandbox-lint reads a self-test that names a +# destructive tool as one that runs it, and these probes only feed text to the guard. +probe "git-guard blocks the ending command from a lane" 2 git-guard.sh <<'J' +{"tool_name":"Bash","agent_id":"a1b2c3","tool_input":{"command":"~/OPS/.claude-config/bin/session\u002dend close"}} +J +probe "git-guard blocks a quoted-path ending finish from a lane" 2 git-guard.sh <<'J' +{"tool_name":"Bash","agent_id":"a1b2c3","tool_input":{"command":"\"$HOME/OPS/.claude-config/bin/session\u002dend\" finish --declined none"}} +J +probe "git-guard blocks a real ending after a dry run in one command" 2 git-guard.sh <<'J' +{"tool_name":"Bash","agent_id":"a1b2c3","tool_input":{"command":"session\u002dend pause --dry-run && session\u002dend pause --json | jq .status"}} +J +probe "git-guard blocks an ending after a semicolon" 2 git-guard.sh <<'J' +{"tool_name":"Bash","agent_id":"a1b2c3","tool_input":{"command":"session\u002dend pause --dry-run --json; session\u002dend close"}} +J +probe "git-guard blocks an ending after a pipe" 2 git-guard.sh <<'J' +{"tool_name":"Bash","agent_id":"a1b2c3","tool_input":{"command":"session\u002dend pause --dry-run | session\u002dend close"}} +J +probe "git-guard does not mistake a finish reason for a dry run" 2 git-guard.sh <<'J' +{"tool_name":"Bash","agent_id":"a1b2c3","tool_input":{"command":"session\u002dend finish --declined 'only --dry-run work'"}} +J +probe "git-guard allows a dry ending followed by another command" 0 git-guard.sh <<'J' +{"tool_name":"Bash","agent_id":"a1b2c3","tool_input":{"command":"session\u002dend pause --dry-run; echo done"}} +J +probe "git-guard allows the ending command from the main thread" 0 git-guard.sh <<'J' +{"tool_name":"Bash","tool_input":{"command":"~/OPS/.claude-config/bin/session\u002dend close"}} +J +probe "git-guard allows the ending command's --dry-run from a lane" 0 git-guard.sh <<'J' +{"tool_name":"Bash","agent_id":"a1b2c3","tool_input":{"command":"~/OPS/.claude-config/bin/session\u002dend pause --dry-run --json"}} +J +probe "git-guard allows a lane naming the ending command in an argument" 0 git-guard.sh <<'J' +{"tool_name":"Bash","agent_id":"a1b2c3","tool_input":{"command":"grep -n session\u002dend ~/OPS/.claude-config/bin/README.md; echo \"feat(session\u002dend): see session\u002dend close\""}} +J +probe "git-guard blocks the ending command from a lane behind the GIT_GUARD=off prefix" 2 git-guard.sh <<'J' +{"tool_name":"Bash","agent_id":"a1b2c3","tool_input":{"command":"GIT_GUARD=off ~/OPS/.claude-config/bin/session\u002dend close"}} +J +GIT_GUARD=off probe "git-guard blocks the ending command from a lane under the exported hatch" 2 git-guard.sh <<'J' +{"tool_name":"Bash","agent_id":"a1b2c3","tool_input":{"command":"~/OPS/.claude-config/bin/session\u002dend close"}} +J +GIT_GUARD=off probe "git-guard's exported hatch still allows a force-push (control)" 0 git-guard.sh <<'J' +{"tool_name":"Bash","tool_input":{"command":"git push --force origin main"}} +J +probe "git-guard blocks an ending behind rtk" 2 git-guard.sh <<'J' +{"tool_name":"Bash","agent_id":"a1b2c3","tool_input":{"command":"rtk session\u002dend close"}} +J +probe "git-guard blocks an ending behind an rtk subcommand" 2 git-guard.sh <<'J' +{"tool_name":"Bash","agent_id":"a1b2c3","tool_input":{"command":"command /usr/local/bin/rtk --verbose run --quiet session\u002dend close"}} +J +probe "git-guard allows an rtk dry ending" 0 git-guard.sh <<'J' +{"tool_name":"Bash","agent_id":"a1b2c3","tool_input":{"command":"rtk run session\u002dend pause --dry-run"}} +J +probe "git-guard blocks a dry flag inside a path argument" 2 git-guard.sh <<'J' +{"tool_name":"Bash","agent_id":"a1b2c3","tool_input":{"command":"session\u002dend close --transcript '/tmp/example --dry-run transcript.jsonl'"}} +J +probe "git-guard allows a quoted dry flag and a quoted program path" 0 git-guard.sh <<'J' +{"tool_name":"Bash","agent_id":"a1b2c3","tool_input":{"command":"\"$HOME/Example OPS/bin/session\u002dend\" pause '--dry-run'"}} +J +probe "git-guard blocks a quoted program path containing spaces" 2 git-guard.sh <<'J' +{"tool_name":"Bash","agent_id":"a1b2c3","tool_input":{"command":"\"$HOME/Example OPS/bin/session\u002dend\" close"}} +J +probe "git-guard blocks a dry flag in an inline comment" 2 git-guard.sh <<'J' +{"tool_name":"Bash","agent_id":"a1b2c3","tool_input":{"command":"session\u002dend close # do not pass --dry-run here"}} +J +probe "git-guard blocks a dry flag used as an output filename" 2 git-guard.sh <<'J' +{"tool_name":"Bash","agent_id":"a1b2c3","tool_input":{"command":"session\u002dend close > '--dry-run'"}} +J +probe "git-guard allows a dry ending with redirected output" 0 git-guard.sh <<'J' +{"tool_name":"Bash","agent_id":"a1b2c3","tool_input":{"command":"session\u002dend pause --dry-run > example.json"}} +J # rtk-awareness: every guard reaches the same verdict whether or not the # command carries an rtk prefix (bare, absolute-path, `command rtk`, an rtk # option, the argv form of a command-running subcommand, or rtk after && in a diff --git a/CHANGELOG.md b/CHANGELOG.md index 2275e37..0462f4e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,73 @@ Notable changes to OPS, newest first. Format: the date, then what changed and wh matters. This file starts fresh at the public release; the harness's private prehistory is deliberately not part of it. +## 2026-11-17: one command starts every thread ending + +Pause, move and close each assembled their mechanical steps by hand from prose in three +skills, and a close assembled by hand skipped steps. `bin/session-end` runs them the same +way every time and prints what is left for the agent to judge. + +- **`bin/session-end `**: snapshots git read-only, starts `branch-gc + --apply` on the thread's repos (only those the PreCompact hook would hand to branch-gc, with + its timeout numbers), rebuilds this directory's memory index, lints with `verify-ops.sh + --quiet` when the thread touched `.claude-config/` or `SKILLS/`, lists the thread's open + asks, and prints the remainder: lessons, documents, the resume note, the memory entries + touched in the thread's window, the compact line, the baton path, or for a close the + measured time as evidence, the objects the thread created (listed, never removed) and the + settle route (T3's own settle tool, `t3-api.sh settle-when-idle` only as the fallback). It + never commits, pushes, edits a ticket, logs time, writes a baton, compacts or settles. Lint + FAILs are findings, not a failed run, because on a shared box most of them are other + sessions'. `--dry-run` writes nothing. + A zero lint exit still requires a clean gate summary; empty or contradictory output fails + the receipt instead of allowing `finish` to stamp it. +- **`session-end finish [--logged N | --declined REASON]`**: after knowledge capture, advances + `last-closeout` only when the run was real and nothing failed, and after a close moves this + thread's two billing stamps into a fresh `~/.claude-compact-cycle/reaped/` directory by + rename, never by copy and delete, so a late append cannot be lost. Only a T3 per-thread key + is archived; a shared-cwd or tmux key is refused. +- **Scope**: Claude sessions only, the main thread only (a T3-delegated lane is refused, and + `hooks/git-guard.sh` blocks a run other than `--dry-run` from a payload with an `agent_id`, + under either `GIT_GUARD=off` hatch too, including rtk proxies and quoted executable paths; + a dry-run flag inside a path argument, comment or redirection is not an exemption), Linux only. +- **`memory-index --pool-for [--cwd DIR] [--ops DIR]`**: prints the pool the digest would show + and creates nothing; exit 4 means no pool. +- **Tests**: `bin/tests/session-end-test.py` (63 cases, sandboxed, every tool a recording stub, + a sentinel tree that must survive every case), 22 new probes in `hooks/guard-selftest.sh`, + and a `--pool-for` case in `bin/tests/memory-index-test.sh`. `verify-ops.sh` lists + `session-end` as a destructive tool and its suite as a sandbox suite (check 24). + +## 2026-11-17: the asks register and the active-minutes measure + +Two small commands, both Python standard library only, each with a sandboxed suite that +CI picks up by glob. + +- **`bin/asks`**: the per-thread register of what is waiting on the box's owner. A thread + writes `asks add ""` with an optional recommendation, default and deadline, and + `asks list --all` shows every thread's open asks in one place. Console asks (steps only a + person can do in a vendor's web console) carry their steps and paste text. State lives in + `${OPS_STATE_DIR:-~/.local/state/ops}/asks/`. A secret-shaped value is refused, the same ask + re-added updates instead of duplicating, and resolved asks are pruned after 14 days while + their next numbers are retained. An unreadable register stops pruning and new adds before + they change any asks. It is POSIX only: without `fcntl` it prints one line and exits 1. + `asks list` and the + `session-end` command read the register. Why: an Operator with several threads open had + to poll each one for what it was waiting on. +- **`bin/active-minutes`**: working minutes from a Claude Code transcript, for billing a + thread's time to a ticket. Pauses of 30 minutes or less count; longer gaps are classified + from their evidence and listed with the cause, so a hold or an overnight stop is never billed + silently. It is generic by option: `--time-tool NAME` names the ticketing system's time-entry + tool for the hook mode (default any tool ending in `time_manage`), and `--zone NAME` sets the + display zone (default `$TZ`, then the machine's zone, then UTC), converted per timestamp so a + daylight-saving change cannot shift a printed window. A named zone with no zone database + prints one line and exits 2. + The billing display truncates decimal hours instead of rounding up, and a time-create call + without a ticket or with an explicit error result does not reset the unlogged window. +- **Tests**: `bin/tests/asks-test.py` and `bin/tests/active-minutes-test.py`, unittest, no + pytest. The second exits non-zero on a failure and a case proves it cannot pass without + running a test. `asks-test.py` starts with the sandbox guard; the secret-refusal case builds + its private-key header from parts so `secrets-scan.sh` and gitleaks see no key. Both are + documented in `bin/README.md`. + ## 2026-11-17: skills hold facts, not procedure; twelve template skills retire The owner cut the skill set with one test: a skill holds only what a capable agent with @@ -69,6 +136,7 @@ description costs listing space a live skill needs. its case for a mounted `dynamic-workflows` prelude, which always skipped once nothing mounts it. + ## 2026-11-17: a T3 thread on a box with a harness token compacts itself A T3 thread on a box with a harness token compacts itself; everything else stays manual. diff --git a/DEPLOYMENT.md b/DEPLOYMENT.md index 66204be..df16348 100644 --- a/DEPLOYMENT.md +++ b/DEPLOYMENT.md @@ -489,7 +489,7 @@ Stage 2 deploy scripts. `/compact` (T3 Code's composer, or the terminal). - **Destructive-tool tests run in a sandbox:** every suite that runs a tool - that deletes or moves files (branch-gc, pre-compact, memory-init, deploy, + that deletes or moves files (branch-gc, pre-compact, memory-init, deploy, session-end, skills-vendor) refuses to start outside `.claude-config/bin/sandbox-run`, which needs `bwrap` (bubblewrap; `apt install bubblewrap`). `verify-ops.sh` check 24 fails a suite that names one of those tools