Skip to content

feat(bin): wake-outcome ledger for measured coordinator attention cost - #13

Open
sbracewell64 wants to merge 35 commits into
mainfrom
fm/wake-outcome-ledger
Open

feat(bin): wake-outcome ledger for measured coordinator attention cost#13
sbracewell64 wants to merge 35 commits into
mainfrom
fm/wake-outcome-ledger

Conversation

@sbracewell64

Copy link
Copy Markdown
Owner

Intent

Add a wake-outcome ledger so firstmate's coordinator attention cost becomes measurable rather than estimated, and so the dormant model-promotion system can activate.

Why: the captain's scheduling policy (config/crew-dispatch.json _scheduling.telemetry.must_answer) requires telemetry answering why work was queued or promoted, which threshold fired, wait times, and whether thresholds are tuned right - none of which was collectable. The dormant model-promotion design (data/model-onboarding-policy/report.md sections 10.1/10.3/10.6) names this ledger plus a terminal per-task outcome line as its single named first instrument, and requires that it use no second evidence store and that a later task extend this file format rather than define a competing one. The captain's instrumentation doctrine also governs: the required instrumentation is whatever makes the quantity verifiable after deployment, and a signal used to detect change must be stable under no change.

This work followed a mandatory design review: the design was written to data/wake-outcome-ledger/design.md, reviewed and APPROVED by firstmate before any implementation, with three decisions explicitly ruled. Those three are deliberate and must not be flagged as mistakes:

  1. The ledger lives at data/wake-ledger.tsv, NOT under state/, deviating from the referenced report's suggestion. Ruled because teardown deletes state/.* for every finished task and this evidence must outlive the tasks it describes; AGENTS.md section 2 defines data/ as durable and state/ as volatile.
  2. TWO records per wake (a deterministic wake record written by the drain, plus a coordinator-written outcome record joined on the wake-queue sequence) rather than the report's single combined line. Ruled because one coordinator-written line would make measured attention cost fall whenever the coordinator skipped the recording step, so the metric would move without the underlying quantity moving. The split gives a denominator that is stable under no change and turns missing coverage into a reported number instead of a silent undercount. The extra join is the accepted cost.
  3. Watcher-absorbed wakes are deliberately EXCLUDED. They never reach the coordinator, so they are not part of the quantity being measured, and recording them would mean touching seven call sites in the watcher's hot loop for a number no captain policy asks for. state/.watch-triage.log remains their disposable debug record.

Other deliberate choices a reviewer reading only the diff would not know:

  • The ledger must never block, delay, alter, or fail a wake. Its only drain call site sits below the drain's authoritative print-and-delete boundary, with stdout discarded and failure ignored; the ledger takes no lock and writes one printf-appended line capped at 1024 characters, under the 4096-byte PIPE_BUF atomic-append bound. Two tests pin exactly this: an unwritable ledger leaves the drain's raw rows and exit status untouched, and a deliberately delayed ledger phase never blocks a concurrent wake append.
  • FM_WAKE_LEDGER_TEST_DELAY is an intentional test-only latency seam, deliberately mirroring the existing FM_WAKE_ENRICH_TEST_DELAY seam in fm-wake-lib.sh rather than inventing a new pattern.
  • Teardown writes the terminal record immediately before deleting the task metadata, because that is the last moment the task's harness, model, and effort are recoverable anywhere. That call is best effort on purpose: it warns on stderr but can never fail a teardown, since a telemetry write must never stand between the fleet and cleanup. A test pins that too.
  • The wake count per task is deliberately NOT stored on the terminal record; it is computed from that task's wake records, per the report's no-duplication requirement.
  • fm-wake-ledger.sh sources fm-pr-lib.sh solely to reuse fm_task_id_path_safe rather than restate that predicate, honoring the one-owner rule in the firstmate-coding-guidelines skill.
  • The escalated field intentionally reads unknown until dispatch records it; the field exists and reads from task metadata so it fills in later with no format change. This limitation is stated in the approved design rather than hidden.
  • No prune or rotation command in v1: growth is roughly 1-3 MB per year, and a prune that races an append can lose evidence.
  • AGENTS.md deliberately gains only two lines (a layout entry and one wake-handling sentence) with all mechanics kept in the script header and --help, per the firstmate-coding-guidelines size-discipline and one-owner rules. No new skill was added because there is no situation-specific procedure to load. docs/supervision-protocols/* were deliberately left untouched because the recording step is harness-independent, so duplicating it into six harness files would violate the one-owner rule.

Verification already done locally: the new tests/fm-wake-ledger.test.sh passes all 10 cases; tests/fm-teardown.test.sh passes 35 cases including 3 new ledger cases; fm-backend old-vs-new teardown conformance, teardown-endpoint-safety, gotmp, test-run and lint suites all pass; bin/fm-lint.sh is clean at pinned ShellCheck 0.11.0; bin/fm-doc-audience-check.sh is clean; and the test coverage guard accepts the new test. Three watcher suites (fm-pi-watch-extension, fm-turnend-guard, fm-watcher-lock) fail or hang in this worktree, but that is a known pre-existing fleet defect: a Stop hook keeps re-arming a watcher from the worktree, and those suites are sensitive to an externally armed watcher. I proved this by reverting my drain change and re-running: they fail byte-identically at baseline, so they are unrelated to this change.

What Changed

  • New bin/fm-wake-ledger.sh maintains a durable append-only ledger at data/wake-ledger.tsv (deliberately outside volatile state/) with two records per wake: a deterministic wake record appended by fm-wake-drain.sh below its print-and-delete boundary, and a coordinator-written outcome record joined on (seq, queued) so distinct wakes stay distinct across state resets — the join key was widened from bare seq after the pipeline review flagged silent collapse after a sequence reset. The ledger enforces a closed outcome vocabulary, sanitizes fields, caps lines under the PIPE_BUF atomic-append bound, and can never block, alter, or fail a wake.
  • bin/fm-teardown.sh now writes a best-effort terminal task record (landed/abandoned, with --force mapping to abandoned) immediately before deleting task metadata — the last moment harness/model/effort are recoverable; an unwritable ledger warns on stderr but never fails teardown. A report command surfaces coverage, latency percentiles, outcome mix, and per-profile joins, turning missed coordinator recordings into a reported number instead of a silent undercount.
  • Added tests/fm-wake-ledger.test.sh (11 cases, including unwritable-ledger isolation, delayed-ledger non-blocking, concurrent-append integrity, and reused-seq joins) plus 3 new teardown ledger cases; docs updated in AGENTS.md, docs/architecture.md, docs/configuration.md, and docs/scripts.md. Watcher-absorbed wakes are deliberately excluded — they never reach the coordinator.

Risk Assessment

✅ Low: The round-2 commit implements the requested (seq, queued) join fix exactly as instructed — write side, report dedup, coverage join, unknown-never-dedups rule, docs, and a targeted seq-reuse regression test — without touching the drain path or any captain-ruled decision, leaving no open findings.

Testing

Ran the two targeted suites (tests/fm-wake-ledger.test.sh, tests/fm-teardown.test.sh) — all 47 cases pass including the never-block and best-effort-teardown guarantees — then demonstrated the full workflow end-to-end with the real production scripts, capturing a CLI transcript showing wake records written by the drain, coordinator outcome records joined on (seq, queued), the terminal task record, the durable TSV at data/wake-ledger.tsv, and a report that answers the scheduling policy's telemetry questions (wake volume, coverage with missing outcomes reported not hidden, latency, outcome mix, per-profile model join). No findings.

Evidence: End-to-end ledger workflow transcript (enqueue → drain → outcomes → terminal record → report)

===== 2b. the drain wrote one deterministic wake record per deduped row ===== v1 wake 1785379594 seq=2 kind=signal key=task-demo1.status task=task-demo1 queued=1785379592 latency=2 v1 wake 1785379594 seq=3 kind=heartbeat key=heartbeat task=- queued=1785379592 latency=2 v1 wake 1785379594 seq=4 kind=check key=task-demo2.check.sh task=task-demo2 queued=1785379594 latency=0 ===== 3. out-of-vocabulary token ===== error: unknown outcome token: shrugged (absorbed inspected steered decided escalated repaired false-positive) -> refused, exit 2 ===== 6. fm-wake-ledger.sh report ===== wakes: 3 total, 2 with a recorded outcome, 1 unrecorded (67% coverage) outcomes: by token: absorbed 1 decided 1 tasks: 1 terminal (landed 1) per profile: pi/openai-codex/gpt-5.6-sol/medium tasks 1 wakes/task 1.0 coordinator response latency (queued -> drained), seconds: min 0 median 2 p90 2 max 2


===== 1. Watcher enqueues three wakes (production fm_wake_append) =====
  queued: 1785379592	1	signal	task-demo1.status	signal: task-demo1 needs a decision
  queued: 1785379592	2	signal	task-demo1.status	signal: task-demo1 duplicate (dedupes)
  queued: 1785379592	3	heartbeat	heartbeat	heartbeat
  queued: 1785379594	4	check	task-demo2.check.sh	check: PR poll for task-demo2

===== 2. Coordinator wake: fm-wake-drain.sh drains the queue (rows the coordinator reads) =====
1785379592	2	signal	task-demo1.status	signal: task-demo1 duplicate (dedupes)
1785379592	3	heartbeat	heartbeat	heartbeat
1785379594	4	check	task-demo2.check.sh	check: PR poll for task-demo2

===== 2b. ...and the drain wrote one deterministic wake record per deduped row =====
v1	wake	1785379594	seq=2	kind=signal	key=task-demo1.status	task=task-demo1	queued=1785379592	latency=2
v1	wake	1785379594	seq=3	kind=heartbeat	key=heartbeat	task=-	queued=1785379592	latency=2
v1	wake	1785379594	seq=4	kind=check	key=task-demo2.check.sh	task=task-demo2	queued=1785379594	latency=0

===== 3. Coordinator records outcomes per AGENTS.md (one wake deliberately left uncovered) =====
  drained seqs: 2 3 4
  (seq 4 intentionally not recorded - coverage must report it, not hide it)
  a token outside the closed vocabulary is refused:
error: unknown outcome token: shrugged (absorbed inspected steered decided escalated repaired false-positive)
  -> refused, exit 2

===== 4. Teardown writes the terminal task record (same call bin/fm-teardown.sh makes) =====

===== 5. The ledger file itself (durable evidence, data/wake-ledger.tsv) =====
v1	wake	1785379594	seq=2	kind=signal	key=task-demo1.status	task=task-demo1	queued=1785379592	latency=2
v1	wake	1785379594	seq=3	kind=heartbeat	key=heartbeat	task=-	queued=1785379592	latency=2
v1	wake	1785379594	seq=4	kind=check	key=task-demo2.check.sh	task=task-demo2	queued=1785379594	latency=0
v1	outcome	1785379594	seq=2	queued=1785379592	outcome=decided	task=task-demo1	after=0	note=answered task-demo1 merge gate
v1	outcome	1785379594	seq=3	queued=1785379592	outcome=absorbed	task=-	after=0
v1	task	1785379594	task=task-demo1	harness=pi	model=openai-codex/gpt-5.6-sol	effort=medium	mode=local-only	kind=crewmate	project=demo-proj	backend=tmux	outcome=landed	route=direct	escalated=unknown	findings=unknown	pr=https://github.com/demo/repo/pull/42

===== 6. fm-wake-ledger.sh report - the telemetry the captain's policy asks for =====
wake ledger: /tmp/fm-ledger-e2e.ipd3IO/data/wake-ledger.tsv
window: all records

wakes: 3 total, 2 with a recorded outcome, 1 unrecorded (67% coverage)
  by kind:  signal 1  check 1  heartbeat 1

outcomes: 2 recorded (1 not attributable to a task)
  by token:  absorbed 1  decided 1

tasks: 1 terminal (landed 1)

per profile (harness/model/effort):
  pi/openai-codex/gpt-5.6-sol/medium           tasks 1    wakes/task 1.0    steered 0    repaired 0    escalated 0    false-positive 0

busiest tasks by wake count:
  task-demo1                           1
  task-demo2                           1

coordinator response latency (queued -> drained), seconds: min 0  median 2  p90 2  max 2
Evidence: Reproducible demo script
#!/usr/bin/env bash
# End-to-end demonstration of the wake-outcome ledger, driving the real
# production scripts exactly as the fleet does:
#   1. watcher enqueues wakes (production fm_wake_append)
#   2. fm-wake-drain.sh hands them to the coordinator AND writes wake records
#   3. the coordinator records outcomes per AGENTS.md (fm-wake-ledger.sh outcome)
#   4. teardown-style terminal task record (fm-wake-ledger.sh task)
#   5. fm-wake-ledger.sh report answers the scheduling-telemetry questions
set -u
ROOT=$1
HOME_DIR=$(mktemp -d "${TMPDIR:-/tmp}/fm-ledger-e2e.XXXXXX")
mkdir -p "$HOME_DIR/state" "$HOME_DIR/data"
touch "$HOME_DIR/state/.last-watcher-beat"
export FM_ROOT_OVERRIDE="$HOME_DIR" FM_STATE_OVERRIDE="$HOME_DIR/state" FM_DATA_OVERRIDE="$HOME_DIR/data"
LEDGER_FILE="$HOME_DIR/data/wake-ledger.tsv"

# A task's metadata, so signal keys attribute to a real task id.
cat > "$HOME_DIR/state/task-demo1.meta" <<'META'
window=fm-task-demo1
harness=pi
model=openai-codex/gpt-5.6-sol
effort=medium
META

step() { printf '\n===== %s =====\n' "$1"; }

step "1. Watcher enqueues three wakes (production fm_wake_append)"
enqueue() {
  FM_STATE_OVERRIDE="$HOME_DIR/state" bash -c '
    . "$1"; fm_wake_append "$2" "$3" "$4"' _ "$ROOT/bin/fm-wake-lib.sh" "$2" "$3" "$4"
}
enqueue s signal  "task-demo1.status" "signal: task-demo1 needs a decision"
enqueue s signal  "task-demo1.status" "signal: task-demo1 duplicate (dedupes)"
enqueue s heartbeat heartbeat heartbeat
sleep 2   # real wait so latency is a measured, nonzero number
enqueue s check "task-demo2.check.sh" "check: PR poll for task-demo2"
sed 's/^/  queued: /' "$HOME_DIR/state/.wake-queue"

step "2. Coordinator wake: fm-wake-drain.sh drains the queue (rows the coordinator reads)"
"$ROOT/bin/fm-wake-drain.sh" 2>/dev/null
step "2b. ...and the drain wrote one deterministic wake record per deduped row"
grep -P '\twake\t' "$LEDGER_FILE"

step "3. Coordinator records outcomes per AGENTS.md (one wake deliberately left uncovered)"
seqs=$(grep -oP 'seq=\K[0-9]+' "$LEDGER_FILE" | sort -n)
set -- $seqs
echo "  drained seqs: $*"
"$ROOT/bin/fm-wake-ledger.sh" outcome decided "$1" --note "answered task-demo1 merge gate"
"$ROOT/bin/fm-wake-ledger.sh" outcome absorbed "$2"
echo "  (seq $3 intentionally not recorded - coverage must report it, not hide it)"
echo "  a token outside the closed vocabulary is refused:"
"$ROOT/bin/fm-wake-ledger.sh" outcome shrugged "$1" 2>&1 && echo UNEXPECTED-ACCEPT || echo "  -> refused, exit $?"

step "4. Teardown writes the terminal task record (same call bin/fm-teardown.sh makes)"
"$ROOT/bin/fm-wake-ledger.sh" task task-demo1 --outcome landed \
  --harness pi --model openai-codex/gpt-5.6-sol --effort medium \
  --mode local-only --kind crewmate --project demo-proj --backend tmux \
  --route direct --escalated unknown --pr https://github.com/demo/repo/pull/42

step "5. The ledger file itself (durable evidence, data/wake-ledger.tsv)"
cat "$LEDGER_FILE"

step "6. fm-wake-ledger.sh report - the telemetry the captain's policy asks for"
"$ROOT/bin/fm-wake-ledger.sh" report

rm -rf "$HOME_DIR"

Pipeline

Updates from git push no-mistakes

✅ **intent** - passed

✅ No issues found.

✅ **Rebase** - passed

✅ No issues found.

🔧 **Review** - 2 issues found → auto-fixed ✅
  • ⚠️ bin/fm-wake-ledger.sh:482 - The durable ledger's identity/join key is the wake-queue sequence from state/.wake-queue.seq, but state/ is volatile while data/wake-ledger.tsv is durable evidence spanning weeks. After a state wipe or home rebuild, sequences restart and distinct wakes in the durable file share a seq. cmd_report dedups wake records by seq alone (wake_seen, line 482) and outcome records by seq alone (outcome_seen, line 493), so an all-records report silently collapses distinct wakes/outcomes across a seq reset — undercounting the very denominator the design requires to be stable under no change. The live outcome join is unaffected (the bounded tail read takes the newest matching wake), and wake records already carry queued= which could disambiguate report dedup (seq SUBSEP queued); outcome records carry no second key, so a complete fix would touch the approved seq-as-join-key ruling — hence ask-user rather than auto-fix.
  • ℹ️ bin/fm-teardown.sh:1237 - The terminal outcome vocabulary accepts landed|failed|abandoned, but the only caller (fm-teardown.sh) maps --force to abandoned and everything else to landed, so 'failed' is currently unreachable vocabulary with no writer. This is coherent (teardown refuses un-landed work without --force), but worth confirming that reserving 'failed' for a future caller is intended rather than a missed mapping.

🔧 Fix: join wake outcomes on (seq, queued) across state resets
✅ Re-checked - no issues remain.

✅ **Test** - passed

✅ No issues found.

  • bash tests/fm-wake-ledger.test.sh — all 11 cases pass (record format, closed vocabulary, sanitization, task attribution, drain integration, unwritable-ledger never changes drain rows/exit, delayed ledger never blocks a concurrent wake append, concurrent-append integrity, report counts/coverage, reused-seq (seq,queued) join)
  • bash tests/fm-teardown.test.sh — all 36 cases pass, including the 3 new ledger cases: terminal record with the meta's harness/model/effort written before metadata deletion, --force records outcome=abandoned, unwritable ledger warns on stderr but never fails or halts teardown
  • Manual end-to-end demo (/tmp/no-mistakes-evidence/01KYRDQ3AZH2SPJ0X4CEQ869N5/e2e-demo.sh): enqueued wakes via production fm_wake_lib, drained with the real bin/fm-wake-drain.sh, recorded coordinator outcomes per the new AGENTS.md instruction, wrote the teardown-style terminal task record, verified an out-of-vocabulary token is refused with exit 2, and ran fm-wake-ledger.sh report showing coverage (67% with one deliberately unrecorded wake), latency percentiles, outcome mix, and the per-profile join
  • git status --porcelain — worktree left clean, no transient test artifacts
✅ **Document** - passed

✅ No issues found.

✅ **Lint** - passed

✅ No issues found.

✅ **Push** - passed

✅ No issues found.

kunchenguid and others added 28 commits July 27, 2026 12:28
* feat: add verified pi-signed adapter

* no-mistakes(review): Correct pi-signed maintainer verification date

* no-mistakes(review): Correct remaining pi-signed verification dates

* no-mistakes(review): Preserve authoritative pi-signed runtime identity

* no-mistakes(document): Document pi-signed shared adapter semantics

* no-mistakes: apply CI fixes
* fix(pi): rearm watcher across same-process session transitions

Pi emits session_shutdown for ordinary /new, /resume, and /fork replacement
as well as terminal quit. The primary watcher extension latched a module-level
stopping flag on every shutdown, so a replacement session in the same process
could not arm monitoring until Pi restarted.

Own arm authority per session generation so only the active live generation
may start, stop, or rearm the child. Replacement sessions can arm again without
restarting Pi, stale prior-generation callbacks cannot mutate the active cycle,
and real quit still blocks late rearm.

* no-mistakes(review): Preserve Pi generation isolation and exit cleanup

* no-mistakes(document): Correct Pi watcher transition documentation
* Consume quota-axi pace signals in dispatch profile array selection.

Add quota-array-dispatch as the single owner of the pace-aware candidate
choice, keep AGENTS.md to the intake boundary and load trigger, and cover
the acceptance cases with sanitized schemaVersion 3 fixtures.

* no-mistakes(review): Stop and report genuine quota dispatch ties

* no-mistakes(document): Document quota pace freshness and uncertainty
…nguid#1171)

* fix(grok): adapt Stop continuation to runtime capability

* no-mistakes(review): Reject ambiguous Grok Stop payloads

* no-mistakes(review): Reject duplicate Grok fields and accept spaced tmux sessions

* no-mistakes(review): Enforce exact tmux cleanup selectors

* no-mistakes(test): Fix historical tmux fixture and validate Grok Stop

* no-mistakes: apply CI fixes
* fix(brief): make DOD scaffolding parse-safe on stock macOS Bash 3.2

fm-brief.sh built each Definition-of-done block and the not-enabled
Herdr declaration with `VAR=$(cat <<EOF ... EOF)`. On Bash 3.2 (macOS
/bin/bash) the lexer scans for the command substitution's closing `)`
textually and tracks quote state through the heredoc body, so a single
apostrophe, unbalanced quote, or unbalanced paren in that prose breaks
parsing of the whole script. Every ship-brief scaffold (no-mistakes,
direct-PR, local-only) failed with `unexpected EOF while looking for
matching )`. Bash 4+ parses it fine, so the breakage stayed invisible
everywhere except stock macOS.

Replace all four command-substitution heredocs with
`IFS= read -r -d '' VAR <<EOF || true`. That removes the `$(...)`
wrapper and the entire defect class regardless of future prose, and
preserves the variable expansion the direct-PR and local-only bodies
need. `read` keeps the heredoc's trailing newline that `$(...)` used to
strip, so trim one newline to keep every generated brief byte-identical
to prior output.

Guard the structure, not one historical phrase: a new test rejects any
heredoc nested in a command substitution anywhere in fm-brief.sh, where
the old assertion pinned a single apostrophe phrase and so missed the
reintroduction. Extend the stock-macOS Bash CI job from parsing one
script to the whole maintained shell surface (bin/*.sh,
bin/backends/*.sh, tests/*.sh), matching bin/fm-lint.sh's canonical file
set so parse scope and lint scope cannot drift apart.

* no-mistakes(review): Captain: harden Bash structure and inventory guards

* no-mistakes(document): Align stock macOS Bash contributor checks

* no-mistakes(lint): Suppress deliberate SC2016 literal fixture warnings
* fix(test): pin teardown tmux baseline to historical kill selectors

merge-base HEAD main collapses to HEAD after the exact-selector change
lands on the default branch, so the old teardown fixture was accidentally
exercising current exact targets. Resolve a content-historical permissive
tmux adapter from first-parent history and force that post-squash topology
inside the conformance case so main and feature branches keep the same
old-vs-new contract.

* no-mistakes(lint): Suppress intentional literal-pattern ShellCheck warnings
…id#1197)

Cut the runtime skill to the compact pace-aware selection procedure plus
minimum owner pointers. Keep every distinct decision rule and move expanded
acceptance scenarios to deterministic fixture ownership assertions.

Size: 170/1374/10187 -> 63/544/4068 (about 63%/60%/60% reduction).
…1219)

* Inherit config/backend into secondmate homes with deliberate-override preservation

Add backend to the shared inheritable config allowlist so launch, locked
bootstrap, and config-push converge a primary pin into secondmate homes as each
home local future-spawn default. Track last-inherited bytes in a private state
provenance marker so deliberate per-home overrides survive present and absent
primary convergence, keep --backend and FM_BACKEND stronger, and extend the
existing inheritance tests plus docs and skill claims.

* no-mistakes(review): Preserve equal unprovenanced backend overrides

* no-mistakes(review): Preserve symlink overrides and verify spawn precedence

* no-mistakes(review): Snapshot backend inheritance for consistent provenance

* no-mistakes(review): Simplify backend inheritance to primary-authoritative convergence

* no-mistakes(document): Document inherited backend override preservation

* fix: restore primary-authoritative backend inheritance after document regression

The document step reintroduced provenance and deliberate per-home override
semantics after review had simplified config/backend to plain primary-authoritative
allowlist membership. Restore the primary-always-wins path: present overwrites,
absent removes, no provenance marker, and docs/tests match that contract.

* no-mistakes(review): Add divergent backend precedence regression fixtures

* no-mistakes(document): Document backend inheritance contract
* fix(pi): remove Calm's exclusive Pi upper-version ceiling

tests/fm-calm-pi-extension.test.sh gated on a closed PI_COMPAT_VERSIONS
allowlist ("0.81.1 0.82.0") that refused any other installed Pi, and docs
described that range as "supported" rather than verified evidence. The
Calm CHANGELOG shows no API introduced at either version, so there is no
evidence for a real minimum; the presentation adapters already probe the
exact method they patch rather than checking a version.

Replace the allowlist with dated version evidence that never rejects a
newer Pi, and make each presentation adapter degrade independently with
a diagnostic if a future Pi removes its API, instead of the whole Calm
extension failing to load. Rewrite the feasibility doc's "Pi 0.81.1
through 0.82.0" phrasing to state it as verified evidence, not a
ceiling.

* no-mistakes(review): Probe missing Calm adapter exports safely

* no-mistakes(document): Document Calm's unbounded Pi compatibility
…enguid#1204)

* fix(guard): allow session-local todo tools in the primary

The delegation-shape guard denied TaskCreate and TaskUpdate because their
normalized names contain the `task` stem. Those tools write only the harness's
session-local todo list, which has no executor: it spawns no agent, allocates
no worktree, registers no schedule, and starts nothing that outlives the
session. That is not the unaccounted work the guard exists to stop, so the stem
match was a false positive, and the deny text told the primary to run
bin/fm-brief.sh and bin/fm-spawn.sh to create a todo entry.

Add a separately-reasoned PLAN_ONLY_TOOLS exact-name exclusion rather than
widening OBSERVE_ONLY_TOOLS, whose documented contract is tools that only
observe or stop existing work. Both lists stay exact-name so neither can widen
by substring.

Tests cover the two allowed names and six near-miss names that a substring or
shortened-stem widening would release; both mutations were watched red.

* no-mistakes(review): drop session-local todo tools from recommended deny list

* no-mistakes: apply CI fixes
…claude pid (kunchenguid#1206)

* fix(session-lock): resolve Claude bg-spare ancestry to the outermost claude pid

fm_harness_ancestry_pid() previously returned the first ancestor process
whose command matched a verified harness name. Claude Code's Stop hook
fires as a bg-spare worker several levels below the session's actual
lock-owning claude process (hook shell -> claude bg-spare ->
claude bg-pty-host -> claude -> claude(lock)), so the first match was
the bg-spare worker, not the lock owner. fm_session_lock_owned_by_self()
then never matched state/.lock, and the Claude Stop auto-arm silently
treated its own primary session as an unrelated live owner and never
armed the watcher.

The walk now keeps going past a claude-named match, looking for a still
more ancestral claude-named match, and stops the instant a non-match
follows an already-found match (bounding it to a contiguous run rather
than the literal ancestry top, so an unrelated claude-named process
further up the real process tree is never mistaken for part of this
session's own nested chain). Every other harness keeps the original
first-match-wins behavior, since e.g. Pi's shared signed-wrapper
ancestry actually holds the session at the inner engine pid, not an
outer wrapper pid. Hop limit raised from 8 to 16 to cover the deeper
bg-spare chain.

* no-mistakes(review): Add nested-claude-ancestry regression test; fix nudge doc depth claim

* no-mistakes: apply CI fixes
* fix: confirm watcher startup on MSYS

* no-mistakes(review): gate MSYS arm ready timeout, cache uname, harden locale test

* no-mistakes(review): validate OpenCode ready timeout, make uname cache internal
…d#1195)

* fix(spawn): forward firstmate's CLAUDE_CONFIG_DIR to claude crewmates

Crewmate panes are created by a long-lived tmux/herdr daemon that does not
inherit firstmate's current environment. When firstmate runs under a non-default
CLAUDE_CONFIG_DIR (for example a work-vs-personal subscription split), a bare
`claude` in the crewmate pane fell back to the default ~/.claude store and
launched unauthenticated, blocking the crewmate before it could do any work.

fm-spawn now prefixes the claude launch with firstmate's own resolved
CLAUDE_CONFIG_DIR when set, so the crewmate uses the same credential/config
store firstmate is authenticated with. An unset value is the single-store
default and adds no prefix; non-claude harnesses are unaffected.

Adds three tests in fm-spawn-dispatch-profile.test.sh (forwarded-when-set,
omitted-when-unset, non-claude-ignored) and pins CLAUDE_CONFIG_DIR in the test
helper so launch assertions no longer depend on the developer's environment.

* no-mistakes: apply CI fixes
…guid#1233)

* fix: preserve dispatch harness identity

* no-mistakes(review): Fix Grok counterfactual tuple validation

* no-mistakes(document): Scope dispatch authentication to selected tuple

* fix: restore dispatch instruction budget

* no-mistakes(review): Scope dispatch authentication after candidate selection
* fix(bin): handle dash-leading harness process names (#2)

* fix: handle dash-leading harness process names

* no-mistakes(review): Make dash-leading harness regression hermetic

* fix: preserve secondmate reply routes across relative homes

Resolve relative home, data, and state inputs before durable charter generation, and fail when caller-relative directories cannot be resolved.

Use absolute paths at the related spawn, AFK daemon, and X-mode cross-process handoffs so later processes cannot reinterpret them from another working directory.

* no-mistakes(review): Preserve absolute overrides and normalize relative durable paths

* no-mistakes(review): Normalize relative home before deriving durable paths

* no-mistakes(document): Document relative durable-path normalization

* no-mistakes(review): Captain: Ignore inherited CDPATH during relative path normalization

* no-mistakes(lint): Fix empty CDPATH assignments for ShellCheck
* Add internal status skill

* no-mistakes(document): register /status skill in documentation-audiences inventory

* no-mistakes(lint): replace grep|wc -l with grep -c in status skill test

* test: silence literal status skill patterns

* Refactor bearings default to chat-only

---------

Co-authored-by: Kun Chen <3233006+kunchenguid@users.noreply.github.com>
* docs: add captain-approved project operation exception to hard rule 1

Firstmate stays read-only over projects by default, but when the captain
clearly approves a concrete project operation and scope in the moment,
firstmate may perform exactly that approved operation with its own tools.
The approval is never inferred, broadened, or standing, and it does not
relax the existing force, discard, unlanded-work, or merge-authority
boundaries.

* no-mistakes(review): Clarify captain-approved project operation boundaries

* no-mistakes(document): Clarify captain-approved project operation scope

* docs: cover directories and preserve the operation-or-scope alternative

Widen the captain-approved project operation exception in AGENTS.md to
files or directories, and restore the explicit operation-or-scope
alternative that a prior pipeline auto-fix had collapsed into "and".

Rework project-management SKILL.md's Remove section, which previously
told firstmate to refuse project removal until a guarded helper existed;
that helper was never built, so the text directly contradicted the new
instruction-only exception. It now points at the exception plus the
existing removal preflight it still requires unchanged.

Update the one instruction-owners test assertion that hard-coded the
sentence removed above, so the suite tracks current, not obsolete, text.

* docs: add captain-approved project operation exception to hard rule 1

Firstmate stays read-only over projects by default, but when the captain
clearly approves a concrete project operation and scope in the moment,
firstmate may perform exactly that approved operation with its own tools.
The approval is never inferred, broadened, or standing, and it does not
relax the existing force, discard, unlanded-work, or merge-authority
boundaries.

* no-mistakes(review): Clarify captain-approved project operation boundaries

* no-mistakes(document): Clarify captain-approved project operation scope

* docs: cover directories and preserve the operation-or-scope alternative

Widen the captain-approved project operation exception in AGENTS.md to
files or directories, and restore the explicit operation-or-scope
alternative that a prior pipeline auto-fix had collapsed into "and".

Rework project-management SKILL.md's Remove section, which previously
told firstmate to refuse project removal until a guarded helper existed;
that helper was never built, so the text directly contradicted the new
instruction-only exception. It now points at the exception plus the
existing removal preflight it still requires unchanged.

Update the one instruction-owners test assertion that hard-coded the
sentence removed above, so the suite tracks current, not obsolete, text.

* no-mistakes(review): Align project removal preflight with approved exception

* no-mistakes(document): Align project removal documentation with approved exception

* fix: restore removal test byte-for-byte and preserve the default sentence

tests/fm-instruction-owners.test.sh had been changed to assert different
text; restore it byte-for-byte to origin/main. project-management SKILL.md's
Remove section now keeps the exact default "Never issue a raw removal
command from Firstmate." sentence that test still asserts, immediately
followed by the already-approved captain-operation-or-scope exception, so
the default and the exception both stay explicit and consistent.

* no-mistakes(document): Align project-write boundary documentation
…henguid#1275)

* Route project intake through secondmate scopes

* no-mistakes(test): Guard all main-home project registry mutations

* no-mistakes(document): Consolidate secondmate routing documentation

* no-mistakes: apply CI fixes

* Restore new-project routing scope

* no-mistakes(document): Clarify secondmate routing for new-project intake

* no-mistakes: apply CI fixes
)

* fix: scope validation corrections by accepted behavior

* no-mistakes(review): Classify stale delivery evidence as an autonomous correction
…#1282)

* test: remove source-content assertions

* no-mistakes(review): Replace source assertions with runtime behavior coverage

* no-mistakes(review): Isolate Kimi task temp runtime coverage

* no-mistakes(document): Refresh test cleanup documentation

* no-mistakes: apply CI fixes
…#1286)

* fix(watch): bound how long a busy pane may run with no completed turn

A busy pane (backend busy state or the harness's rendered footer) was
unconditional, unbounded proof of liveness in every escalation path, so a
hung foreground tool call behind a busy signature could run for hours
undetected (2026-07 hibit-agent-focus-nonsteal-r1 incident: a catastrophic-
backtracking regex hung one bash call for 25h behind an unchanging
"Working..." footer).

FM_BUSY_TURN_MAX_SECS (default 3600s) now bounds how long a busy pane may
run with no completed turn (state/<id>.turn-ended, or its spawn record
before any turn has completed). Past the bound, busy_turn_over_age routes
the pane through the existing wedge_timer_check, reusing the identical
stale reason, escalation counter, and demand-deep-inspection marker for
human inspection only - never an automatic interrupt, signal, or restart
of the worker or its tool process. A completed turn resets the age.

Reproduced end-to-end against the real installed Pi TUI: a foreground
`sleep 999999` bash call with no timeout renders the actual busy footer,
and two captures ~15s apart show the elapsed counter changing the pane
hash while the same turn stays unfinished. Running the pre-fix watcher
against the real captures showed it never starts a wedge timer no matter
how long the pane stays busy; the fixed watcher starts and escalates the
timer through the same mechanism, while the real hung process remained
untouched and alive throughout.

* no-mistakes(review): fix: parse enriched AFK stale reasons

* no-mistakes(review): fix: preserve enriched wedges during AFK supervision

* no-mistakes(review): fix: route all enriched AFK wedges

* no-mistakes(document): Clarify busy-turn age supervision documentation
…unchenguid#1261)

A name-by-name list of config/ entries silently stops ignoring any new or
home-local file placed there, which makes the working tree read as dirty and
blocks guarded sync paths that refuse to touch a dirty home. AGENTS.md
already documents config/ as captain-private and gitignored as a category;
this makes .gitignore match that contract.
…al coverage (kunchenguid#1304)

The second assertion in fm-gitignore-config.test.sh (added by kunchenguid#1261) greps
.gitignore for a specific spelling of the config/ ignore pattern. It fails
on a semantically equivalent pattern like config/** and does not prove Git
actually ignores anything, per the completed source-content-test audit.

Replace it with a real git check-ignore control test on a generated
unrelated path, and strengthen the existing directory-coverage test with
generated unpredictable direct and nested config/ paths.
)

* Add bounded startup memory curation

* no-mistakes(review): Record reproducible stow verification evidence

* no-mistakes(review): Validate inherited secondmate stow evidence

* no-mistakes(document): Document editable startup-memory budget propagation
* fix(herdr): place workers in the launching agent's exact workspace

Herdr enforces no workspace-label uniqueness, and spawn resolved its
container by taking the FIRST workspace whose label matched the home
label. With two workspaces both labeled "firstmate", a worker launched
from the second one was created in the first, so it appeared in a
different space than the Firstmate the captain was watching.

Reproduced end to end on Herdr 0.7.5 protocol 17 by running the real
bin/fm-spawn.sh inside a launcher pane in the second "firstmate"
workspace: the worker landed in w1 while its launcher was in w2, with an
unrelated third workspace focused throughout, which also rules out any
dependence on the focused workspace.

Placement now binds to the launching process's own Herdr identity. Herdr
injects HERDR_PANE_ID, HERDR_SESSION, and HERDR_SOCKET_PATH into every
process it manages a pane for, and fm_backend_herdr_launcher_identity
resolves that pane's current owning tab and workspace live from Herdr,
cross-checking the pane against its tab and confirming the workspace
exists exactly once in the session. The injected HERDR_TAB_ID and
HERDR_WORKSPACE_ID are creation-time snapshots and are deliberately not
read as current identity. Labels are no longer placement authority.

A claimed parent identity that is unreadable, contradictory, stale, or
from another named session or Herdr server stops the spawn before any
worker endpoint exists, rather than degrading to a label search. A
launcher with no Herdr ancestry has no workspace to inherit and keeps
the per-home labeled container, which must now resolve to exactly one
workspace; two same-labeled candidates refuse instead of adopting
either. A --secondmate launch keeps standing up that home's own
workspace by design.

With presentation spaces enabled, the projected child is created and
bound under that same exact parent and anchors its ordering on it, so a
duplicated home label no longer makes the layout ambiguous. Projection,
focus restoration, restart binding, and quarantine rules are unchanged,
and children are never collapsed into the parent. tmux, Zellij, cmux,
Orca, and the away-mode daemon terminal were each inspected and are not
affected: none resolves a container by searching mutable labels.

tests/fm-backend-herdr-launcher-workspace-e2e.test.sh drives the real
spawn and teardown against an isolated Herdr lab, with its headline case
running fm-spawn.sh inside a real Herdr pane so the identity comes from
Herdr's own injection. The refusal matrix and the ordering anchor are
covered deterministically in tests/fm-backend-herdr.test.sh.

Eight existing real-Herdr suites inherited the developer terminal's own
Herdr pane into their isolated lab sessions, which the new cross-session
check correctly refuses. tests/herdr-test-safety.sh now owns
herdr_forget_inherited_pane and those suites call it, so what they assert
no longer depends on where they were launched from.

Two unrelated fixes found along the way. tests/fm-secondmate-harness.test.sh
had the same class of environment leak through CLAUDECODE, which outranks
PI_CODING_AGENT in bin/fm-harness.sh and made its pi-signed ancestry case
resolve "claude" whenever the suite ran inside Claude Code. And
fm-spawn.sh's usage() printed a fixed line range that had already been
truncating its own help mid-sentence.

* no-mistakes(review): Enforce exact Herdr launcher and projection identity

* no-mistakes(document): Document exact Herdr launcher workspace placement
* feat(calm): replace Pi's working row with an animated ship while Calm is on

While Calm is active and one logical agent run is under way, Calm now hides
Pi's built-in working row and renders a small two-row SSHHIP-derived boat in
its place. When Calm is off, Pi's stock working row is left untouched.

The presentation uses only public Pi extension API: setWorkingVisible(false)
plus a temporary setWidget() component whose render(width) owns the responsive
geometry and whose timer requests a TUI render. Visibility follows agent_start
through agent_settled, so the boat does not flicker between tool calls,
automatic continuations, retries, or compaction inside the same run, and
settle, abort, and failure all reach the same cleanup.

fm-calm.ts stays the sole owner of the presentation choice and the only caller
of setWorkingVisible(); the new lib owns the sprite geometry and widget.

* no-mistakes(review): Guarded Calm-off lifecycle visibility writes; focused tests pass

* no-mistakes(test): Fixed Calm E2E wait to include tmux scrollback

* no-mistakes(document): Document Calm working boat behavior

* no-mistakes: apply CI fixes

* feat(calm): slow the Calm boat, animate blue water, and make the sail directional

The boat now moves one column every 880ms while a bounded fixed-cell water phase
advances every 220ms, so the water ripples several times between boat steps and
the presentation reads as calm. One scheduler drives both clocks and disposing
the widget stops them together; ticks rather than wall-clock timestamps drive
every state change, so tests seek animation time exactly.

Colors are standard ANSI foreground codes instead of theme lookups: blue for
every water cell and yellow for the complete boat, each run closed with a
default-foreground reset so nothing bleeds into padding or later frames. ANSI
bytes never enter geometry, so visible width stays exact.

The mainsail is directional and trails aft of the mast: <| travelling right and
|> travelling left. Direction reverses the moment the boat lands on an endpoint,
so the endpoint frame already shows the new heading and no frame at or after a
bounce shows the previous sail.

* test(calm): wait for the Ctrl+O expansion redraw this block asserts

* docs(calm): record the revised working-presentation verification evidence

* no-mistakes(document): Fix Calm feasibility document EOF whitespace
…henguid#1349)

* fix(dispatch): scope candidate authentication to its own surface

A locally expired timestamp in one credential store was reported to the
captain as a sign-out, including for dispatch candidates that never read
that store. A `harness=pi, model=xai/grok-*` candidate authenticates
through Pi's own xAI credential, but the only Grok quota reading
available was gated on the standalone Grok CLI's separate token, whose
expiry clock drifts independently. The always-loaded intake rule then
turned that unreadable quota into a mandatory captain escalation.

Add `bin/fm-auth-preflight.sh` as the deterministic owner of the parts
that must not depend on agent memory: it resolves a tuple's
authentication surface from quota-axi's own emitted auth sources rather
than from a harness or model name, so another harness's CLI can never
gate a candidate that does not use it. A vendor CLI is launched only
when the tuple's own harness owns the credential store under test and a
non-destructive discovery command is registered for it, which today is
`grok models` alone. That probe runs at most once with stdin closed and
a hard timeout, reads its verdict from the first stdout line because the
command exits 0 either way, treats unrecognized output as indeterminate,
and never invokes login, logout, or the interactive TUI. Quota is read
at most twice, and unknown headroom never makes a candidate ineligible
on its own.

Update the dispatch procedure to match: usable authentication with
unmeasurable headroom stays eligible at lower preference with the
unknown disclosed, and stop-and-report is reserved for unresolved
authentication, an unresolved relationship, or malformed configuration.
Record that Grok's `credits.remaining` is a prepaid balance rather than
window headroom.

Gate quota-axi at 0.1.16 in bootstrap, the first build reporting
per-credential auth sources. A stale install previously passed the
presence check silently, which is why a fix published two days earlier
was still not in effect.

Replace the orphaned quota-array-dispatch fixtures, which encoded a
`provider: "xai"` shape the tool never emits and had no consumer, with
fixtures shaped like real 0.1.16 output that the new suite drives the
script against. The suite asserts the verdict and, separately, which
vendor CLIs were launched, so a Pi/xAI candidate reaching the Grok CLI
fails. Map `tests/fixtures/<dir>` to its consuming suite so a fixture
change selects the right tests instead of refusing.

* refactor(bootstrap): give the quota-axi floor one owner

The floor was stated twice - once in bootstrap's gate and once inline in
the auth preflight - so bumping it needed two edits that could drift.
Move it to bin/fm-quota-axi-lib.sh alongside its rationale, matching the
existing tasks-axi library, and derive the comparison from the constant
so the number appears exactly once. Bootstrap turns a failing check into
the operator diagnostic; the preflight refuses to emit an unscoped
verdict. Map the new library to both consuming suites so a bump re-runs
them, and record that any usable source means the surface authenticates.

* no-mistakes(review): Captain: bound quota checks and removed Python dependency

* no-mistakes(review): Captain: enforce conservative headroom and exact preflight retry

* no-mistakes(review): Captain: preserve OpenCode eligibility without auth-surface guessing

* no-mistakes(review): Captain: reject malformed OpenCode model relationships

* no-mistakes(review): Captain: exempt verified unmodeled tuples from intake escalation

* no-mistakes(document): Updated dispatch authentication documentation

* no-mistakes: apply CI fixes
@sbracewell64
sbracewell64 force-pushed the fm/wake-outcome-ledger branch from 6d043de to ce77760 Compare July 31, 2026 02:06
…nchenguid#1350)

* feat(x-mode): reconcile promised public replies deterministically

A promised final reply in an X or Discord thread was only kept while the
primary remembered it. Compaction or restart erased that memory, so a typed
public-followup obligation could sit at pending-work after its PR merged and
the original thread never got its reply.

Make the promise durable state instead:

- bin/fm-public-followup-emit.sh reports a typed terminal work result (source
  home, work id, generation, outcome, safe deliverables, bounded public-safe
  text) into the owning home's private inbox. The event id is derived from
  that identity tuple, so duplicate reports and restart replay converge with
  no coordination, and nothing ever parses a free-form done: sentence.
- bin/fm-public-followup.sh registers a commitment, reconciles events through
  tasks-axi public-followup, and runs the idempotent delivery sequence
  (begin-delivery with the payload hash, post, record the posted receipt or a
  typed error) against the stored platform and opaque thread binding. A
  delivery interrupted between post and receipt refuses rather than risk a
  second public reply.
- Session start surfaces unresolved commitments from disk, the existing relay
  poll surfaces a new terminal-result set once, and teardown refuses while
  this home still owes a public reply for that exact work.

tasks-axi public-followup remains the only owner of the obligation state
machine, state/x-context/ the only owner of the private request context, and
fm-x-reply.sh the only thing that posts. Its new optional --receipt-file is
the one addition there, so a caller can record how many messages were sent.

A home that never opted into the myfirstmate relay gates out on a single
[ -f "$FM_HOME/.env" ] test: no tasks-axi call, no backlog or context scan,
no output, and no artifact. Evidence in docs/verification/public-followup.md.

* no-mistakes(review): Hardened public-followup reconciliation and ownership guards

* no-mistakes(review): Hardened typed terminal cleanup and receipt reconciliation

* no-mistakes(review): Automated typed-delivery cleanup and strict backlog validation

* no-mistakes(review): Fail-closed parent resolution and registration-safe delivery

* no-mistakes(review): Harden relay gating and validate secondmate bindings

* no-mistakes(review): Use owner-aware single-gate teardown protection

* no-mistakes(document): Correct public-followup documentation drift

* no-mistakes(lint): Quote done literals to fix ShellCheck warnings

* no-mistakes: apply CI fixes
@sbracewell64
sbracewell64 force-pushed the fm/wake-outcome-ledger branch from ce77760 to f1e0c0f Compare July 31, 2026 02:41
…chenguid#1327)

* feat: add semantic busy-state contract owner and event writer

One owner (bin/fm-busy-lib.sh) for the captain-approved semantic
busy-state redesign: a per-task gen-bound record written only by
bin/fm-busy-event.sh, per-harness trusted-source classification with
explicit source attribution, busy/idle/unknown/dead semantics where
missing, malformed, stale, or untrusted semantic data is unknown -
never idle - and endpoint death is the only process-level override.
The Grok-only rendered-tail fallback and the standalone-Kimi
verification gate live behind the same classifier.

* feat: arm busy-state at spawn and convert Pi to the semantic extension path

fm-spawn arms the busy-state contract for converted adapters and seeds
busy/fm-spawn (the launch brief is a submitted turn). The Pi/pi-signed
per-task extension now reports agent_start -> busy and agent_settled ->
idle confirmed by ctx.isIdle(), covering auto-retries, compaction
retries, tool loops, and queued continuations, while turn_end stays a
wake notification touch. Teardown removes the new record, gen sidecar,
and lock. Live-verified on Pi 0.82.0: seed -> agent-start busy ->
agent-settled idle with the marker still touched.

* feat: convert OpenCode to the semantic session.status plugin path

The per-task plugin (renamed .opencode/plugins/fm-busy-state.js) now
classifies from OpenCode's semantic session.status events - busy and
retry are active, idle is inactive - latched to the worker's own
session so a subagent child session can never clear the worker's busy
state. The session.idle marker touch stays a wake notification.
Teardown removes both the new and the legacy plugin filenames.
Live-verified on OpenCode 1.17.18 in a real TUI pane: seed ->
session-busy -> session-status-idle.

* feat: convert Claude to the full lifecycle hooks path

The per-task settings.local.json now wires UserPromptSubmit -> busy
and Stop, StopFailure, and SessionEnd -> idle, so API-error and
shutdown turn ends can never strand a busy record; Stop keeps the
turn-ended notification touch. A refused (stale-gen) event exits 0 and
stays silent so Claude's own lifecycle is never broken. Live-verified
on Claude Code 2.1.220: UserPromptSubmit fires for the argv launch
prompt, Stop closes each turn, a mid-stream Escape interrupt fires no
closing hook, and the firstmate-controlled idle/fm-interrupt clear
resolves it.

* feat: gate Codex busy state behind verified semantic sources

The approved contract prefers Codex's app-server turn lifecycle with
capability negotiation and sanctions its lifecycle hooks as the
intermediate. Live probes on codex-cli 0.145.0 show neither is usable
for a pane worker: the app-server daemon is unreachable for a TUI
thread and refuses to start outside the managed standalone install,
and firstmate-written project hooks never fired (interactive with
directory trust granted, and exec, both with
--dangerously-bypass-hook-trust) while global hooks fired in the same
runs. Codex therefore classifies unknown codex-unverified behind an
explicit probe rather than falling back to idle or footer text, and
fm-spawn installs no unverified Codex wiring.

* feat: gate standalone Kimi busy state on live verification

Standalone Kimi has no installed binary here, so per the approved
contract its semantic path stays guarded and it classifies unknown
kimi-unverified rather than idle - and never from its locale-sensitive
moon-phase spinner, which the redesign forbids inventing as a state
source. The gate records the preferred source order (Wire prompt
request lifetime, which brackets a turn and reports cancellation, then
the documented hooks including Interrupt because Stop does not fire on
interrupts) and the exact evidence required to open it. Arming without
wiring would seed a busy record nothing could clear, so both land
together behind the same gate.

* feat: route busy consumers through the contract and drop the global OR

The watcher, crew-state reader, and away-mode daemon now decide busy
state through bin/fm-busy-lib.sh: only an exact busy verdict counts as
working, and unknown never becomes working or a silent idle, so a crew
whose semantic state is missing, malformed, stale, or unverified
surfaces instead of being absorbed. Crew-state reports the producing
source in its detail. The watcher's global OR regex default is gone;
Grok keeps its isolated fallback inside the contract. The daemon's
supervisor-pane reader stays rendered-text - that pane is not a
recorded task - but is now scoped to firstmate's own detected harness
instead of every vendor signature. Secondmate pending-reply
observation is deliberately unchanged and documented as a
delivery-confirmation signal, not task state.

* docs: point busy-state documentation at the single contract owner

Adds a maintainer-architecture section naming bin/fm-busy-lib.sh as
the owner of what busy means, with per-adapter sources, the
unknown-never-idle rule, the endpoint-death override, and the two
rendered-text readers that deliberately stay outside the contract.
Replaces the stale regex-first prose in architecture, tmux-backend,
herdr-backend, and configuration; converts the harness-adapters
per-harness rows from UI signatures to the semantic source each
harness uses; and records the live verification evidence, including
why Codex and standalone Kimi stay unknown.

* fix: arm away-launch signal handlers before acquiring the lifecycle lock

fm_afk_launch_main acquired its lock and only then installed the EXIT,
INT, and TERM traps. A signal arriving in that window terminated the
process by default action and left the lock directory behind, which
blocks the next away-mode launch until the stale-owner reclaim path
clears it. The release helper only removes a lock this process owns,
so the handlers are now armed first. The accompanying test also killed
the child whether or not the lock had appeared and sampled cleanup the
instant wait returned; it now requires the lock, then allows a bounded
settle, so it proves the guarantee instead of racing it.

* test: align fleet, Kimi, lifecycle, and detection suites with the contract

The fleet snapshot and wake-daemon lifecycle fixtures now prove a
working crew through its own semantic busy-state record instead of
rendered pane text, which is what those consumers read. The Kimi
watcher test asserts the approved contract directly: a standalone Kimi
task classifies unknown rather than matching its moon-phase spinner,
while Grok's isolated fallback still classifies only Grok. The
pi-signed detection cases clear ambient harness markers, fixing a
pre-existing failure where the running session's own CLAUDECODE
outranked the fixture's marker.

* fix: stop teardown from deleting a project's own Codex hooks file

An intermediate revision wired Codex through a firstmate-written
<worktree>/.codex/hooks.json, and teardown removed it alongside the
other generated wiring. The Codex wiring was dropped when its probes
came back unverified, so that removal now targets a file firstmate
never creates - and a project may legitimately track its own
.codex/hooks.json, which teardown would then delete from a pooled
worktree.

* fix: keep busy-record parsing from disturbing its sourcing caller

The record parser split fields with set -- under a temporary noglob,
which clobbers a sourcing caller's positional parameters and restores
glob expansion even when the caller had disabled it. The watcher, the
daemon, and the crew-state reader all source this library, so it now
reads fields with read -a, which never globs and never touches caller
state.

* docs: state exactly which Claude hook paths were reproduced live

The busy-state record listed all four wired Claude hooks in the source
column, which could read as a claim that every one fired during the
pass. UserPromptSubmit and Stop did; StopFailure and SessionEnd are
wired from hook names confirmed present in the installed binary, but
the abnormal turn ends they cover were not reproduced.

* test: let reset_fakes own the crew-state busy-text fixture lifecycle

The Grok fallback case set FM_FAKE_BUSY_TEXT and cleared it inline, so
the variable's lifetime was owned by one test rather than by the
shared reset that every other fake already uses.

* no-mistakes(review): Fix semantic busy-state lifecycle races

* no-mistakes(review): Make busy-state retirement idempotent

* no-mistakes(review): Enforce semantic state boundaries for status and injection

* no-mistakes(review): Restore harness-scoped away-mode busy guard

* no-mistakes(document): Refresh semantic busy-state documentation

* no-mistakes: apply CI fixes
@sbracewell64
sbracewell64 force-pushed the fm/wake-outcome-ledger branch from f1e0c0f to 1518120 Compare July 31, 2026 03:54
kunchenguid and others added 5 commits July 30, 2026 21:27
…d#1356)

* fix(calm): resume working boat from frozen column across runs

Keep one extension-owned boat animation for the Pi session so settling
freezes column and direction, the next working period resumes there
without hidden-time jumps, and only a fresh session resets to the left edge.

* no-mistakes(review): Freeze Calm boat from last rendered state

* no-mistakes(document): Document Calm boat continuity contract
* fix(dispatch): judge candidate provider relations instead of rejecting them

Firstmate deterministically dropped supported Pi candidates in the
openai-codex family. bin/fm-auth-preflight.sh resolved a harness=pi tuple's
credential surface by constructing the source id `pi:<model-prefix>`, so
`pi + openai-codex/gpt-5.6-terra` looked for a `pi:openai-codex` source. That
source does not exist, because Pi's Codex family authenticates through the
Codex store quota-axi already lists as `auth-json`/`cli-rpc`. The tuple
returned `eligible=no reason=surface-unresolved` while the Pi catalog listed
the model and the Codex provider reported fresh, usable credentials with 64
effective percent remaining on its all-model scope.

The prefix construction was only ever valid where Pi holds its own credential
(`pi:xai`, `pi:kimi-coding`), which is why every previously configured Pi tuple
resolved and the defect stayed hidden until a Codex-family Pi model was
configured.

Retire dispatch eligibility from deterministic shell. The dispatching first
mate now establishes model support and provider family from each harness's
authoritative catalog, applies quota at the granularity the vendor supplies,
and shows that reasoning. Provider-level and all-model evidence bounds every
model established in that family; a named-model window bounds only its own
model. Missing model-level quota, a missing auth source, unmeasurable headroom,
and unmodeled authentication are disclosed uncertainty. Only concrete
contradictory evidence blocks a candidate.

Replace the preflight with bin/fm-vendor-auth-probe.sh, which keeps the
captain's approved bounded probe envelope without any routing knowledge: it
takes no harness, model, or provider, reads no quota, renders no verdict, and
holds only a fixed-argv safety allowlist. Its behavior suite proves the absent
identity surface, the untouched quota, the uniform exit status, the fixed argv
with stdin closed, and a real bound even when the configured bound is zero.

Also fixed along the way: a zero FM_*_TIMEOUT silently removed the hard bound,
the pinned Grok version had drifted to 0.2.117, and --changed selection refused
outright on any deleted bin/ script.

AGENTS.md section 4 and quota-array-dispatch own the corrected policy,
harness-adapters gets the catalog-responsibility correction, and
docs/verification/dispatch-auth.md records the 2026-07-30 evidence on
Pi 0.82.0, quota-axi 0.1.16, and grok 0.2.117.

* no-mistakes(review): Reject all-zero vendor probe timeouts
Supervision attention cost was estimated, never measured, and the dormant
model-promotion system is gated on exactly this instrument plus a terminal
per-task outcome line.

Adds data/wake-ledger.tsv, a per-home append-only evidence record, and
bin/fm-wake-ledger.sh as its single owner of format, closed outcome
vocabulary, and append semantics. Three record kinds: one wake record per
drained wake, one outcome record per handled wake joined on the wake-queue
sequence, and one terminal task record per finished task.

The wake half is written deterministically by the drain and the outcome half
by the coordinator. That split is deliberate: a single coordinator-written
line would make measured attention cost fall whenever the recording step was
skipped, so the metric would move without the underlying quantity moving.
Splitting it gives a denominator that is stable under no change and turns
missing coverage into a reported number instead of a silent undercount.

The ledger cannot block, delay, alter, or fail a wake. Its call site sits
below the drain's authoritative print-and-delete boundary, with stdout
discarded and failure ignored; the ledger takes no lock and writes one
capped line per record. Teardown writes the terminal record immediately
before deleting the task metadata, the last moment that task's harness,
model, and effort are recoverable anywhere.

It lives under data/ rather than state/ because teardown clears
state/<id>.* and this evidence must outlive the tasks it describes.
Watcher-absorbed wakes stay out by design: they never reach the coordinator,
so they are not part of the quantity being measured.
@sbracewell64
sbracewell64 force-pushed the fm/wake-outcome-ledger branch from 1518120 to 083a709 Compare July 31, 2026 11:15
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

9 participants