Skip to content

fix(bin): keep handling successors from stranding inbox wakes after counter loss - #6467

Merged
kunchenguid merged 5 commits into
kunchenguid:mainfrom
ulsamern:fix/inbox-successor-wake
Oct 23, 2026
Merged

kunchenguid merged 5 commits into
kunchenguid:mainfrom
ulsamern:fix/inbox-successor-wake

Conversation

@ulsamern

@ulsamern ulsamern commented Oct 3, 2026 •

Copy link
Copy Markdown

Intent

Continue existing PR #6467 on fork ulsamern/firstmate branch fix/inbox-successor-wake. Prevent stranded inbox notifications during handling successors and preserve counter-loss and large-sequence correctness. Starting head bed7da0429746c301d2db5e8979e65f1d2e848df contains all prior reviewed fixes. Reconcile conflicts with latest main, especially ac8a767 (#7466), preserving upstream host handoff settlement and startup-race protection while retaining justified counter-loss, identical-row/new-generation and decimal sequence protections. Inspect both contracts and tests before resolving; raise a decision if semantics cannot be reconciled safely. Keep scope focused. Prior run 01M40CDTX2000A5TFFRZN27YFR is terminal failed daemon shutting down and its worktree is gone; no other active writer. Use this isolated checkout only; preserve original ~/dev/firstmate-inbox-fix and production ~/fm-home, never restart production or change credentials. Update the existing PR only; do not create a duplicate PR, merge, close, or deploy. All review, test, documentation and canonical lint gates required before publication.

What Changed

  • bin/fm-wake-lib.sh: fm_wake_append_locked now sets the next sequence to one more than the larger of the counter and the highest sequence still in the queue. If .wake-queue.seq is missing or malformed, a new row can no longer reuse a queued sequence and get consumed by an outstanding acknowledgement. The comparison works on decimal text, and the increment happens in bash, so large sequences stay exact digit-only integers and never go through awk floats or scientific notation.
  • bin/fm-wake-drain.sh: presented_max_row and ACK_THROUGH now print the matched sequence text instead of max + 0, so the drain no longer reformats large sequence numbers.
  • Tests and docs: tests/fm-watch-arm.test.sh adds test_append_wakes_handling_successor. It covers an external append beside a handling successor's inherited rows: before and after the acknowledgement, with an intact, missing or malformed counter, and with a byte-identical repeat of an inherited row after the acknowledgement. tests/fm-wake-queue.test.sh adds test_large_sequences_stay_exact_decimal_identifiers. docs/watcher-continuity.md describes the successor append contract and lists the new coverage.

🤖 Generated with Claude Code

Risk Assessment

✅ Low: After the rebase, the branch leaves upstream #7466's handling-successor and host-settlement logic in bin/fm-watch.sh untouched, and the branch's protections still hold on top of it. The allocator now numbers past every queued row using exact decimal-text comparison; I traced it with missing and malformed counters, a missing queue file (awk fails before END under gawk, mawk and busybox, so the fallback is taken), and leading zeros. The drain now prints sequences as matched text, so they stay exact. Every append republishes the recovery marker, which covers the identical-row/new-generation case. The tests run real processes, and the only finding is a documentation wording issue.

Testing

I made no new long runs this time. The saved base-vs-HEAD inbox CLI transcripts reproduce the bug on base: under a lost counter, the predecessor's acknowledgement deletes the second captain note. They also show that HEAD keeps the note and allocates large sequences as exact decimals. These are the live-driven scenarios. The watcher-level scenarios were exercised only through test harnesses in fixture homes, so they are not live results: handling successor, recovery loop and supervision-host settlement. Those harness runs passed: watch-arm, including the 8 handling-successor cases; recovery-loop; queue, inbox and drain; and the supervision-host test for an inbox note during a parked successor. The two full supervision-host attempts each hit a different timing-sensitive failure. Run in isolation, both tests passed 3/3 on HEAD and on base, and this branch does not change supervision-host code. Still, supervision-host has never had a green whole-suite run, and none is claimed. The diagnostic copy was saved to evidence and deleted, and the tree is clean. This step changes no UI, so there are no screenshots.

  • Live validation: ✅ go - 3 of 6 scenarios driven live against the product
Scenario Result Live Evidence
Captain queues a second inbox note after the counter is lost while the first is unacknowledged; the predecessor's --ack-through leaves the new note queued ✅ pass live live-inbox-queue-transcript.txt Scenario A (seq 2, survives --ack-through 1) vs baseline transcript (seq 1 reused, note deleted)
A malformed counter still yields a fresh sequence above the queued rows, and drain plus ack empties the queue ✅ pass live live-inbox-queue-transcript.txt Scenario B
Large sequences (2^53-1 queued, 2^63-2 counter) allocate exact digit-only next sequences, and the drain names the exact ack sequence ✅ pass live live-inbox-queue-transcript.txt Scenario C (9007199254740992, 9223372036854775807); tests/fm-wake-queue.test.sh 69/69 rerun
A handling successor announces new inbox work (fresh or byte-identical, before or after the ack, intact, missing or malformed counter) without consuming it or looping, and stays silent for inherited r… ⏸️ untested no The prior payload established no live result. This was exercised only by tests/fm-watch-arm.test.sh in test fixture homes (39 ok, including 8 successor cases), not against a live primary. A live check…
Upstream #7466 startup-race and no-recovery-loop guarantees hold (a row appended during startup is resurfaced; recovery is announced at most once per generation) ⏸️ untested no The prior payload established no live result. This was exercised only by tests/fm-watch-recovery-loop.test.sh in fixture homes (3 ok). This branch does not change watcher code, and no live primary lab…
Host handoff settlement: an inbox note queued while the host is parked on a handled wake's successor rewakes main ⏸️ untested no The prior payload established no live result. This was exercised only by the fm-supervision-host harness with a stub engine, where the test passed. A live Claude primary lab was not started, and the w…
Evidence: HEAD inbox CLI transcript (counter loss, malformed counter, large sequences)

Source: HEAD inbox CLI transcript (counter loss, malformed counter, large sequences)

=== Scenario A: lost counter while an unacknowledged row is queued
$ bin/fm-inbox.sh note first captain note
queued 1792733129-aJKNCr
  first captain note
  firstmate will pick this up at its next check.
[exit 0]
$ bin/fm-wake-drain.sh
1792733129	1	check	inbox:1792733129-aJKNCr	check: captain inbox note 1792733129-aJKNCr - first captain note
[exit 0]
WAKE_ACK_REQUIRED: after handling completes run bin/fm-wake-drain.sh --ack-through 1 --recovery-generation 3966669.1792733129.zwsIND
--- .wake-queue:
1792733129	1	check	inbox:1792733129-aJKNCr	check: captain inbox note 1792733129-aJKNCr - first captain note
--- .wake-queue.seq: 1
# simulate counter loss before the handling turn acknowledges
$ bin/fm-inbox.sh note second captain note after counter loss
queued 1792733135-yI3EHJ
  second captain note after counter loss
  firstmate will pick this up at its next check.
[exit 0]
--- .wake-queue:
1792733129	1	check	inbox:1792733129-aJKNCr	check: captain inbox note 1792733129-aJKNCr - first captain note
1792733135	2	check	inbox:1792733135-yI3EHJ	check: captain inbox note 1792733135-yI3EHJ - second captain note after counter loss
--- .wake-queue.seq: 2
# the predecessor's outstanding acknowledgement must not consume the new note
$ bin/fm-wake-drain.sh --ack-through 1 --recovery-generation 3966669.1792733129.zwsIND
[exit 0]
--- .wake-queue:
1792733135	2	check	inbox:1792733135-yI3EHJ	check: captain inbox note 1792733135-yI3EHJ - second captain note after counter loss
--- .wake-queue.seq: 2
=== Scenario B: malformed counter
$ bin/fm-inbox.sh note third captain note after malformed counter
queued 1792733136-OiM7sr
  third captain note after malformed counter
  firstmate will pick this up at its next check.
[exit 0]
--- .wake-queue:
1792733135	2	check	inbox:1792733135-yI3EHJ	check: captain inbox note 1792733135-yI3EHJ - second captain note after counter loss
1792733136	3	check	inbox:1792733136-OiM7sr	check: captain inbox note 1792733136-OiM7sr - third captain note after malformed counter
--- .wake-queue.seq: 3
$ bin/fm-wake-drain.sh
1792733135	2	check	inbox:1792733135-yI3EHJ	check: captain inbox note 1792733135-yI3EHJ - second captain note after counter loss
1792733136	3	check	inbox:1792733136-OiM7sr	check: captain inbox note 1792733136-OiM7sr - third captain note after malformed counter
[exit 0]
WAKE_ACK_REQUIRED: after handling completes run bin/fm-wake-drain.sh --ack-through 3 --recovery-generation 3966669.1792733129.zwsIND
$ bin/fm-wake-drain.sh --ack-through 3 --recovery-generation 3966669.1792733129.zwsIND
[exit 0]
--- .wake-queue:
--- .wake-queue.seq: 3
=== Scenario C: large sequence (2^53-1 queued, 2^63-2 counter)
$ bin/fm-inbox.sh note note after 2^53-1
queued 1792733139-JGZyLZ
  note after 2^53-1
  firstmate will pick this up at its next check.
[exit 0]
--- .wake-queue:
1700000000	9007199254740991	check	inbox:big	check: big row
1792733139	9007199254740992	check	inbox:1792733139-JGZyLZ	check: captain inbox note 1792733139-JGZyLZ - note after 2^53-1
--- .wake-queue.seq: 9007199254740992
$ bin/fm-wake-drain.sh
1700000000	9007199254740991	check	inbox:big	check: big row
1792733139	9007199254740992	check	inbox:1792733139-JGZyLZ	check: captain inbox note 1792733139-JGZyLZ - note after 2^53-1
[exit 0]
WAKE_ACK_REQUIRED: after handling completes run bin/fm-wake-drain.sh --ack-through 9007199254740992 --recovery-generation 3976685.1792733139.mqlDcT
$ bin/fm-wake-drain.sh --ack-through 9007199254740992 --recovery-generation 3976685.1792733139.mqlDcT
[exit 0]
--- .wake-queue:
--- .wake-queue.seq: 9007199254740992
$ bin/fm-inbox.sh note note after 2^63-2
queued 1792733160-nWfLSd
  note after 2^63-2
  firstmate will pick this up at its next check.
[exit 0]
--- .wake-queue:
1792733161	9223372036854775807	check	inbox:1792733160-nWfLSd	check: captain inbox note 1792733160-nWfLSd - note after 2^63-2
--- .wake-queue.seq: 9223372036854775807
lab removed: yes
Evidence: Base f3252b2 inbox CLI transcript (second note silently consumed)

Source: Base f3252b2 inbox CLI transcript (second note silently consumed)

=== Scenario A: lost counter while an unacknowledged row is queued
$ bin/fm-inbox.sh note first captain note
queued 1792733215-jsaW8D
  first captain note
  firstmate will pick this up at its next check.
[exit 0]
$ bin/fm-wake-drain.sh
1792733215	1	check	inbox:1792733215-jsaW8D	check: captain inbox note 1792733215-jsaW8D - first captain note
[exit 0]
WAKE_ACK_REQUIRED: after handling completes run bin/fm-wake-drain.sh --ack-through 1 --recovery-generation 4055982.1792733215.PcpqFa
--- .wake-queue:
1792733215	1	check	inbox:1792733215-jsaW8D	check: captain inbox note 1792733215-jsaW8D - first captain note
--- .wake-queue.seq: 1
# simulate counter loss before the handling turn acknowledges
$ bin/fm-inbox.sh note second captain note after counter loss
queued 1792733216-KiNo6l
  second captain note after counter loss
  firstmate will pick this up at its next check.
[exit 0]
--- .wake-queue:
1792733215	1	check	inbox:1792733215-jsaW8D	check: captain inbox note 1792733215-jsaW8D - first captain note
1792733216	1	check	inbox:1792733216-KiNo6l	check: captain inbox note 1792733216-KiNo6l - second captain note after counter loss
--- .wake-queue.seq: 1
# the predecessor's outstanding acknowledgement must not consume the new note
$ bin/fm-wake-drain.sh --ack-through 1 --recovery-generation 4055982.1792733215.PcpqFa
[exit 0]
--- .wake-queue:
--- .wake-queue.seq: 1
=== Scenario B: malformed counter
$ bin/fm-inbox.sh note third captain note after malformed counter
queued 1792733216-nowT4t
  third captain note after malformed counter
  firstmate will pick this up at its next check.
[exit 0]
--- .wake-queue:
1792733216	1	check	inbox:1792733216-nowT4t	check: captain inbox note 1792733216-nowT4t - third captain note after malformed counter
--- .wake-queue.seq: 1
$ bin/fm-wake-drain.sh
1792733216	1	check	inbox:1792733216-nowT4t	check: captain inbox note 1792733216-nowT4t - third captain note after malformed counter
[exit 0]
WAKE_ACK_REQUIRED: after handling completes run bin/fm-wake-drain.sh --ack-through 1 --recovery-generation 4056648.1792733216.DEeGDp
$ bin/fm-wake-drain.sh --ack-through 1 --recovery-generation 4056648.1792733216.DEeGDp
[exit 0]
--- .wake-queue:
--- .wake-queue.seq: 1
=== Scenario C: large sequence (2^53-1 queued, 2^63-2 counter)
$ bin/fm-inbox.sh note note after 2^53-1
queued 1792733217-3wbf2U
  note after 2^53-1
  firstmate will pick this up at its next check.
[exit 0]
--- .wake-queue:
1700000000	9007199254740991	check	inbox:big	check: big row
1792733217	1	check	inbox:1792733217-3wbf2U	check: captain inbox note 1792733217-3wbf2U - note after 2^53-1
--- .wake-queue.seq: 1
$ bin/fm-wake-drain.sh
1700000000	9007199254740991	check	inbox:big	check: big row
1792733217	1	check	inbox:1792733217-3wbf2U	check: captain inbox note 1792733217-3wbf2U - note after 2^53-1
[exit 0]
WAKE_ACK_REQUIRED: after handling completes run bin/fm-wake-drain.sh --ack-through 9007199254740991 --recovery-generation 4057235.1792733217.auCH2e
$ bin/fm-wake-drain.sh --ack-through 9007199254740991 --recovery-generation 4057235.1792733217.auCH2e
[exit 0]
--- .wake-queue:
--- .wake-queue.seq: 1
$ bin/fm-inbox.sh note note after 2^63-2
queued 1792733218-ZNT7WW
  note after 2^63-2
  firstmate will pick this up at its next check.
[exit 0]
--- .wake-queue:
1792733218	9223372036854775807	check	inbox:1792733218-ZNT7WW	check: captain inbox note 1792733218-ZNT7WW - note after 2^63-2
--- .wake-queue.seq: 9223372036854775807
lab removed: yes
Evidence: watch-arm suite incl. handling-successor cases

Source: watch-arm suite incl. handling-successor cases

ok - watch-arm: handling successor delivers fresh new inbox work after-ack (intact counter) without consuming or looping
ok - watch-arm: handling successor delivers fresh new inbox work before-ack (intact counter) without consuming or looping
ok - watch-arm: handling successor delivers fresh new inbox work after-ack (missing counter) without consuming or looping
ok - watch-arm: handling successor delivers fresh new inbox work before-ack (missing counter) without consuming or looping
ok - watch-arm: handling successor delivers fresh new inbox work after-ack (malformed counter) without consuming or looping
ok - watch-arm: handling successor delivers fresh new inbox work before-ack (malformed counter) without consuming or looping
ok - watch-arm: handling successor delivers identical new inbox work after-ack (missing counter) without consuming or looping
ok - watch-arm: handling successor delivers identical new inbox work after-ack (malformed counter) without consuming or looping
ok - watch-arm: an attached arm reports the wake its cycle delivered instead of a false failure
ok - watch-arm: a delivered wake consumed by the handling turn still closes the attached arm cleanly
ok - watch-arm: an unusable launch confirm window refuses to arm by name
ok - watch-arm: a disposable validation checkout refuses to arm
ok - watch-arm: a watcher exits when its state directory is removed
ok - watch-arm: a watcher exits when its home is removed
ok - watch-arm: the test reaper stops a watcher armed for a tracked temporary home
ok - watch-arm: a cycle that delivered no wake of its own still fails loudly
ok - watch-arm: an attached arm keeps following a slow live holder and reports its wake
ok - watch-arm: an attached arm hands a holder stalled past the bound to its owner's replacement
~/.no-mistakes/worktrees/d51ae9881507/01M5KH9M6S6M5ZJNAD38NX7ZDR/bin/fm-watch-arm.sh: line 775: 3067967 Killed                  "$WATCH" > "$child_out"
WAKE_ACK_REQUIRED: after handling completes run bin/fm-wake-drain.sh --ack-through 2 --recovery-generation 3069009.1792732176.AhFM2i
ok - watch-arm: re-arm surfaces every queued wake and an open remote decision after downtime
~/.no-mistakes/worktrees/d51ae9881507/01M5KH9M6S6M5ZJNAD38NX7ZDR/bin/fm-watch-arm.sh: line 775: 3078300 Killed                  "$WATCH" > "$child_out"
WAKE_ACK_REQUIRED: after handling completes run bin/fm-wake-drain.sh --ack-through 1 --recovery-generation 3079004.1792732189.64qing
ok - watch-arm: a re-arm whose recovery cycle runs slowly still surfaces it
watcher: recovery state could not be persisted; retaining stale lock evidence
ok - watch-arm: marker publication failure retains stale-lock recovery evidence
WAKE_ACK_REQUIRED: after handling completes run bin/fm-wake-drain.sh --ack-through 2 --recovery-generation 3090479.1792732211.waxXp8
WAKE_ACK_REQUIRED: after handling completes run bin/fm-wake-drain.sh --ack-through 3 --recovery-generation 3096367.1792732218.hS6quC
ok - watch-arm: a wake queued after handling drain is recovered once at successor arm
ok - watch-arm: interrupted handling leaves its wake durable for successor re-drain
WAKE_ACK_REQUIRED: after handling completes run bin/fm-wake-drain.sh --ack-through 0 --recovery-generation 3105572.1792732231.vbgnr4
ok - watch-arm: malformed recovery state is quarantined without a successor loop
WAKE_ACK_REQUIRED: after handling completes run bin/fm-wake-drain.sh --ack-through 1 --recovery-generation 3111948.1792732239.lTABJl
ok - watch-arm: publication after recovery handoff is surfaced
ok - watch-arm: restart publishes recovery before clearing a reused-pid watcher lock
WAKE_ACK_REQUIRED: after handling completes run bin/fm-wake-drain.sh --ack-through 7 --recovery-generation 3117119.1792732248.X9Gbgz
ok - watch-arm: markerless legacy queues are adopted and recovered
ok - watch-arm: an idle Lavish source stays quiet and its real result wakes promptly
ok - watch-arm: appending work reopens an announced empty recovery
ok - watch-arm: a watcher close during handling keeps the printed acknowledgement valid
ok - watch-arm: a moved recovery generation consumes handled rows and names its remedy
ok - watch-arm: downtime marker publication does not follow symlinks
ok - watch-arm: --stop ends only this home's watcher, publishes downtime, and reports when none runs
ok - watch-arm: an already-acknowledged handling confirmation succeeds as a no-op
ok - watch-arm: a churned generation's handling confirmation reports a mismatch and an arm check keeps it
ok - watch-arm: --take-over attaches to a cycle the named arm does not own and leaves it running
ok - watch-arm: --take-over owns a fresh cycle without a recovery wake and still surfaces queued work
watcher: secondmate liveness check failed
ok - watch-arm: takeover preserves self-exit downtime and surfaces a recovery wake
ok - watch-arm: the OpenCode arm plugin decides with the shared supervision predicate
Evidence: recovery-loop / startup-race suite

Source: recovery-loop / startup-race suite

ok - a resurfacing handling successor stays alive and supervises instead of going blind
ok - a handling successor resurfaces a row appended during startup
ok - unacknowledged recovery is announced at most once per generation and the successor stays alive
Evidence: Isolated dialog-resurface HEAD vs base (3/3 each)

Source: Isolated dialog-resurface HEAD vs base (3/3 each)

run=1 side=head elapsed=112s load=7.35 ok - host: dialog a turn never completed with its report (a park boundary, a stopped turn, no report) reaches the next turn 
run=1 side=base elapsed=136s load=7.52 ok - host: dialog a turn never completed with its report (a park boundary, a stopped turn, no report) reaches the next turn 
run=2 side=head elapsed=127s load=8.02 ok - host: dialog a turn never completed with its report (a park boundary, a stopped turn, no report) reaches the next turn 
run=2 side=base elapsed=152s load=6.71 ok - host: dialog a turn never completed with its report (a park boundary, a stopped turn, no report) reaches the next turn 
run=3 side=head elapsed=115s load=5.70 ok - host: dialog a turn never completed with its report (a park boundary, a stopped turn, no report) reaches the next turn 
run=3 side=base elapsed=136s load=5.99 ok - host: dialog a turn never completed with its report (a park boundary, a stopped turn, no report) reaches the next turn 
Evidence: Isolated hook-quiet HEAD vs base (3/3 each)

Source: Isolated hook-quiet HEAD vs base (3/3 each)

run=1 side=head elapsed=16s load=12.42 ok - host+hook: a captain outcome beside a quiet record rewakes the present captain with no away note
run=1 side=base elapsed=10s load=11.46 ok - host+hook: a captain outcome beside a quiet record rewakes the present captain with no away note
run=2 side=head elapsed=17s load=10.29 ok - host+hook: a captain outcome beside a quiet record rewakes the present captain with no away note
run=2 side=base elapsed=13s load=9.32 ok - host+hook: a captain outcome beside a quiet record rewakes the present captain with no away note
run=3 side=head elapsed=11s load=8.34 ok - host+hook: a captain outcome beside a quiet record rewakes the present captain with no away note
run=3 side=base elapsed=22s load=8.77 ok - host+hook: a captain outcome beside a quiet record rewakes the present captain with no away note
Evidence: Preserved diagnostic single-test script (not published to the tree)

Source: Preserved diagnostic single-test script (not published to the tree)

#!/usr/bin/env bash
# Behavior tests for the supervision host (bin/fm-supervision-host.sh,
# docs/supervision-host.md): its report surface (bin/fm-branch-report.sh), its
# dispatch entry (bin/fm-branch-dispatch.mjs), and the host loop itself.
#
# The loop cases run the real host, arm, watcher, wake grant, drain, outcome
# store, and lease scripts in a fixture home. The host runs as a child of a fake
# harness (a bash symlink named "claude") whose pid is the home's session lock,
# and its engine is a stub named by FM_SUPERVISION_ENGINE_CLAUDE_BIN that does
# what a branch turn does through the same scripts, so the real argument
# construction, bounding, and reaping are exercised without a model. A real
# status append drives each wake through the real watcher.
# shellcheck disable=SC2016 # single-quoted scripts expand inside their own shells
set -u

# shellcheck source=tests/wake-helpers.sh
. "$(dirname "${BASH_SOURCE[0]}")/wake-helpers.sh"

HOST="$ROOT/bin/fm-supervision-host.sh"
REPORT="$ROOT/bin/fm-branch-report.sh"
DISPATCH="$ROOT/bin/fm-branch-dispatch.mjs"
CONTRACT="$ROOT/bin/fm-afk-contract.sh"
LEASE="$ROOT/bin/fm-lease.sh"

command -v node >/dev/null 2>&1 || { printf 'skip: node absent\n'; exit 0; }
command -v perl >/dev/null 2>&1 || { printf 'skip: perl absent\n'; exit 0; }

TMP_ROOT=$(fm_test_tmproot fm-supervision-host)
FAKEBIN=$(fm_fakebin "$TMP_ROOT/fakebin")
ln -s /bin/bash "$FAKEBIN/claude"
FAKE_CLAUDE="$FAKEBIN/claude"

# The stub engine. It records its environment and arguments, then acts like a
# branch turn through the real scripts according to $FM_HOME/stub-mode:
#   handle      drain, claim the task's lease, report, acknowledge, release
#   captain     the same as handle, but report verdict captain naming the rows
#               the drain presented
#   hold-lease  the same, but leave the lease held (the host must release it)
#   return      handle, but the captain returns (the record is archived) before
#               the turn ends
#   return-silent the same, but the routine outcome is silent
#   return-fail the same, then exit nonzero without a result
#   return-fail-silent the same, but the routine outcome is silent
#   return-many handle, then seed more than 1,000 same-turn receipts after an
#               early visible outcome
#   return-lookup-fail handle, then corrupt the store before the return lookup
#   return-first the captain returns first, then handle, then block until the
#               host is stopped (an owner killing its host at the turn's end)
#   noack       the same as handle, but skip the acknowledgement
#   held        handle, but first block reading the $FM_HOME/stub-release FIFO
#               until the test writes to it, so the test chooses when the turn
#               ends
#   captain-held the same, but record a captain outcome before the turn ends
#   emptyresult the same as handle, but print {} as its result
#   noreport    drain and exit cleanly without a report
#   go-away     the captain goes away (the record is written) mid-turn, then
#               the turn reports verdict captain
#   fail        exit nonzero at once, with no result and no report (an engine
#               error the latch counts)
#   hang        before anything else, start a descendant in a process group of
#               its own, then block
#   hold-marker the same as handle, but before the result a helper takes the
#               recovery-marker lock for a few seconds, so the host's handled-
#               turn settle is still waiting for it (holding the queue lock)
STUB="$TMP_ROOT/engine-stub"
cat > "$STUB" <<'SH'
#!/usr/bin/env bash
set -u
STATE=${FM_STATE_OVERRIDE:-$FM_HOME/state}
mode=$(cat "$FM_HOME/stub-mode" 2>/dev/null || echo handle)
n=$(( $(ls "$FM_HOME"/engine-call.* 2>/dev/null | wc -l) + 1 ))
{
  printf 'mode=%s\nactor=%s\nholder=%s\nprimary=%s\nturn=%s\n' "$mode" "${FM_SUPERVISION_ACTOR:-}" \
    "${FM_LEASE_HOLDER_PID:-}" "${FM_SUPERVISION_PRIMARY_HARNESS:-}" "${FM_BRANCH_REPORT_TURN:-}"
  for a in "$@"; do printf 'arg=%s\n' "$a"; done
} > "$FM_HOME/engine-call.$n"
case "$mode" in held|captain-held) printf 'ready\n' > "$FM_HOME/stub-ready" ;; esac
# Like Claude, the reported cost is the conversation's running total.
result() {
  printf '{"type":"result","subtype":"success","is_error":false,"num_turns":3,"total_cost_usd":%s,' "$(awk -v n="$n" 'BEGIN { print n * 0.25 }')"
  printf '"usage":{"input_tokens":5,"cache_read_input_tokens":100,"cache_creation_input_tokens":10,"output_tokens":20},"session_id":"stub"}\n'
}
if [ "$mode" = hang ]; then
  perl -e 'setpgrp(0, 0); exec "sleep", $ARGV[0]' "$FM_TEST_STUB_MAX_BLOCK_SECONDS" &
  printf '%s\n' "$!" > "$FM_HOME/orphan-pid"
  sleep "$FM_TEST_STUB_MAX_BLOCK_SECONDS"
  exit 0
fi
drain=$("$FM_REPO/bin/fm-wake-drain.sh" 2>&1)
printf '%s\n' "$drain" > "$FM_HOME/engine-drain.$n"
ack=$(printf '%s\n' "$drain" | sed -n 's/^WAKE_ACK_REQUIRED: after handling completes run bin\/fm-wake-drain.sh //p' | tail -1)
task=$(sed -n 's/^tasks=//p' "$STATE/.supervision-host-turn" | awk '{ print $1 }')
[ -n "$task" ] || task=fleet
verdict=routine
[ "$mode" != go-away ] || verdict=captain
case "$mode" in
  fail) exit 3 ;;
  handle|captain|captain-close-before-return|held|captain-held|hold-lease|hold-marker|return|return-silent|return-fail|return-fail-silent|return-many|return-lookup-fail|return-first|noack|emptyresult|go-away)
    case "$mode" in held|captain-held) read -r _ < "$FM_HOME/stub-release" ;; esac
    [ "$mode" != return-first ] || "$FM_REPO/bin/fm-afk-contract.sh" archive >> "$FM_HOME/engine-return.log" 2>&1
    [ "$mode" != go-away ] || "$FM_REPO/bin/fm-afk-contract.sh" enter --words 'gone mid-turn' >> "$FM_HOME/engine-return.log" 2>&1
    "$FM_REPO/bin/fm-lease.sh" claim "$task" >> "$FM_HOME/engine-lease.log" 2>&1
    if [ "$mode" = captain ] || [ "$mode" = captain-held ] \
      || [ "$mode" = captain-close-before-return ]; then
      "$FM_REPO/bin/fm-branch-report.sh" --task "$task" --verdict captain \
        --summary "stub escalated: $(printf '%s\n' "$drain" | grep -v '^WAKE_' | tr '\n' ' ' | cut -c1-400)" \
        >> "$FM_HOME/engine-report.log" 2>&1
    else
      report_args=(--task "$task" --verdict "$verdict" --summary "stub handled $task")
      case "$mode" in
        return-silent|return-fail-silent)
          report_args=(--task "$task" --verdict routine --summary 'still working; nothing new has happened; no action was taken' --silent true)
          ;;
      esac
      "$FM_REPO/bin/fm-branch-report.sh" "${report_args[@]}" >> "$FM_HOME/engine-report.log" 2>&1
    fi
    if [ "$mode" = return-many ]; then
      awk -v task="$task" 'BEGIN { for (seq = 2; seq <= 1001; seq++)
        printf "{\"seq\":%d,\"epoch\":1,\"task\":\"%s\",\"wake\":\"host test\",\"verdict\":\"routine\",\"summary\":\"bulk silent fixture\",\"silent\":true}\n", seq, task
      }' >> "$STATE/branch-outcomes.jsonl"
      awk -v turn="$FM_BRANCH_REPORT_TURN" -v task="$task" 'BEGIN { for (seq = 2; seq <= 1001; seq++)
        printf "%s\t%d\troutine\t%s\n", turn, seq, task
      }' >> "$STATE/.supervision-host-receipts"
    fi
    if [ "$mode" = return-lookup-fail ]; then
      printf 'not-json\n' >> "$STATE/branch-outcomes.jsonl"
    fi
    # shellcheck disable=SC2086 # the printed acknowledgement arguments
    [ -z "$ack" ] || [ "$mode" = noack ] || "$FM_REPO/bin/fm-wake-drain.sh" $ack >> "$FM_HOME/engine-ack.log" 2>&1
    case "$mode" in captain-close-before-return)
      watcher=$(cat "$STATE/.watch.lock/pid" 2>/dev/null || true)
      [ -z "$watcher" ] || kill -TERM "$watcher" 2>/dev/null || true
      i=0
      while [ -n "$watcher" ] && kill -0 "$watcher" 2>/dev/null && [ "$i" -lt 100 ]; do
        sleep 0.05
        i=$((i + 1))
      done
      ;;
    esac
    [ "$mode" = hold-lease ] || "$FM_REPO/bin/fm-lease.sh" release "$task" >> "$FM_HOME/engine-lease.log" 2>&1
    case "$mode" in
      return|return-silent|return-fail|return-fail-silent|return-many|return-lookup-fail) "$FM_REPO/bin/fm-afk-contract.sh" archive >> "$FM_HOME/engine-return.log" 2>&1 ;;
    esac
    case "$mode" in return-fail|return-fail-silent) exit 3 ;; esac
    [ "$mode" != return-first ] || sleep "$

... [187719 bytes truncated] ...

nal() {  # <home>
  captain_rows_at_least "$1" 2 || grep -qs '	inactive-outcome:' "$1/state/.wake-queue"
}

test_unchanged_held_outcome_reaches_the_captain_once_until_a_new_event() {
  local home cycle old pid watcher
  home=$(make_home away-held-once away)
  echo captain > "$home/stub-mode"
  mkdir -p "$home/projects/held"
  git -C "$home/projects/held" init -q
  git -C "$home/projects/held" -c user.name=fmtest -c [email protected] \
    commit -q --allow-empty -m init
  fm_write_meta "$home/state/held.meta" \
    'window=fm-held' "worktree=$home/projects/held" "project=$home/projects/held" \
    'harness=claude' 'kind=ship' 'mode=no-mistakes' 'yolo=off' 'spawn_gen=g1' \
    'pr=https://example.test/o/r/pull/153'
  printf 'done: PR https://example.test/o/r/pull/153 open, green, mergeable\n' > "$home/state/held.status"
  old=$(( $(date +%s) - 600 ))
  perl -e 'my $t = shift; utime $t, $t, @ARGV or exit 1' "$old" \
    "$home/state/held.meta" "$home/state/held.status" \
    || fail "fixture: could not age the held task's records"
  prime_status_seen "$home/state" "$home/state/held.status"

  export FM_FAKE_CREW_STATE_held='state: done · source: fake'
  export FM_INACTIVE_CREW_STATE_BIN="$home/fakebin/fm-crew-state.sh" FM_INACTIVE_RECONCILE_SECS=60
  start_host "$home"
  wait_until 250 captain_rows_at_least "$home" 1 \
    || fail "held: the first cadence never escalated the held outcome: $(cat "$home/state/.supervision-host.log" 2>/dev/null)"
  assert_grep 'child=held' "$home/state/branch-outcomes.jsonl" "held: the escalation did not name the held task's outcome: $(cat "$home"/engine-drain.* "$home/state/.supervision-host.log")"
  wait_until 150 handled_at_least "$home" 1 || fail "held: the escalating turn never finished"
  assert_no_grep '	inactive-outcome:' "$home/state/.wake-queue" "held: the branch acknowledgement left the presentation row queued"

  for cycle in 1 2 3 4; do
    old=$(( $(date +%s) - 120 ))
    perl -e 'my $t = shift; utime $t, $t, @ARGV or exit 1' "$old" "$home/state/.inactive-outcome-reconcile" \
      || fail "held: could not age the scan marker before cadence $cycle"
    wait_until 150 scan_ran "$home" || fail "held: cadence $cycle never rescanned"
    wait_until 150 scan_idle "$home" || fail "held: cadence $cycle never finished its scan"
    ! wait_until 10 flood_signal "$home" \
      || fail "held: cadence $cycle re-escalated the unchanged held outcome: $(cat "$home/state/branch-outcomes.jsonl")"
  done
  [ "$(captain_rows "$home")" -eq 1 ] || fail "held: the unchanged situation reached the captain $(captain_rows "$home") times"
  [ -s "$home/host.rc" ] && fail "held: the host handed a wake to main: $(cat "$home/host.out")"

  printf 'needs-decision [key=merge-153]: merge PR 153 now or hold it for the return?\n' >> "$home/state/held.status"
  wait_until 250 captain_rows_at_least "$home" 2 \
    || fail "held: the new decision never reached the captain path: $(cat "$home/state/branch-outcomes.jsonl")"
  [ "$(captain_rows "$home")" -eq 2 ] || fail "held: the decision escalated $(captain_rows "$home") rows, not one"
  [ "$(FM_HOME="$home" "$ROOT/bin/fm-branch-outcome.sh" list --recent 1 | sed -n 's/.*"task":"\([^"]*\)".*"verdict":"\([a-z]*\)".*/\1 \2/p')" = 'held captain' ] \
    || fail "held: the decision was not recorded as a captain outcome for the held task: $(cat "$home/state/branch-outcomes.jsonl")"
  unset FM_FAKE_CREW_STATE_held FM_INACTIVE_CREW_STATE_BIN FM_INACTIVE_RECONCILE_SECS
  # Stop the host and its watcher here, so no cadence scan is still writing
  # into this home while the suite's cleanup removes it.
  pid=$(awk -F '\t' '$1 == "host" { print $2 }' "$home/state/.supervision-host")
  watcher=$(cat "$home/state/.watch.lock/pid")
  kill -TERM "$pid"
  wait_until 200 host_exited "$home" || fail "held: the host did not stop on TERM"
  wait_until 100 sh -c '! kill -0 "$1" 2>/dev/null' _ "$watcher" || fail "held: a stopped host left its watcher running"
  pass "host: an unchanged held outcome reaches the captain once across cadences, and a later decision on the task still does"
}

test_unverified_engine_hands_every_away_wake_to_main() {
  local home
  home=$(make_home no-engine away 'pi')
  start_host "$home"
  wait_until 150 watcher_live "$home" || fail "no engine: the host never started a watcher cycle"
  append_status "$home" 'anything'
  wait_until 200 host_exited "$home" || fail "no engine: the wake did not reach main"
  assert_re "^supervision-host: no supervision engine runs here: config/supervision-host names 'pi', which is not a verified supervision engine" \
    "$home/host.out" "an unverified engine must be named on the wake it hands to main"
  ! ls "$home"/engine-call.* >/dev/null 2>&1 || fail "no engine: an engine ran"
  pass "host: a home naming an unverified engine hands every away wake to main with the reason"
}

test_host_outside_the_lock_owner_stands_down() {
  local home out rc other
  home=$(make_home not-owner attended)
  "$FAKE_CLAUDE" -c 'sleep 30' &
  other=$!
  printf '%s\n' "$other" >> "$home/claude-pids"
  printf '%s\n' "$other" > "$home/state/.lock"
  out=$(FM_HOME="$home" PATH="$home/fakebin:$PATH" "$HOST" park 2>&1); rc=$?
  expect_code 0 "$rc" "a host that does not own supervision exits 0"
  assert_contains "$out" "supervision-host stood down: this session does not own supervision" "the stand-down must say why"
  watcher_live "$home" && fail "a host that does not own supervision started a watcher"
  kill -TERM "$other" 2>/dev/null || true
  pass "host: a host outside the session-lock owner stands down without arming"
}

test_superseded_host_leaves_the_owner_untouched() {
  local home owner watcher lock_pid
  home=$(make_home superseded away)
  # One fake harness runs the owner host, then, on a signal file, a second host
  # under an auto-arm generation the ledger has already superseded.
  FM_HOME="$home" FM_CREW_STATE_BIN="$home/fakebin/fm-crew-state.sh" PATH="$home/fakebin:$PATH" \
    "$FAKE_CLAUDE" -c '
      printf "%s\n" "$$" > "$FM_HOME/state/.lock"
      printf "%s\n" "$$" >> "$FM_HOME/claude-pids"
      "$0" park > "$FM_HOME/host.out" 2>&1 &
      while [ ! -e "$FM_HOME/go-second" ]; do sleep 0.1; done
      FM_SUPERVISION_HOST_AUTOARM_GEN=1 FM_SUPERVISION_HOST_OWNER_PID=$$ "$0" park > "$FM_HOME/host2.out" 2>&1
      printf "%s\n" "$?" > "$FM_HOME/host2.rc"
      wait
    ' "$HOST" 2>> "$home/claude.err" &
  wait_until 150 watcher_live "$home" || fail "superseded: the owner host never started a watcher cycle"
  owner=$(awk -F '\t' '$1 == "host" { print $2 }' "$home/state/.supervision-host")
  watcher=$(cat "$home/state/.watch.lock/pid")
  lock_pid=$(cat "$home/state/.lock")
  printf 'epoch=2 owner_pid=%s outcome=arming\n' "$lock_pid" > "$home/state/.claude-autoarm-epoch"
  FM_HOME="$home" FM_SUPERVISION_ACTOR=branch FM_LEASE_HOLDER_PID="$lock_pid" "$LEASE" claim demo >/dev/null 2>&1 \
    || fail "fixture: could not hold a branch lease"
  : > "$home/go-second"
  wait_until 200 sh -c '[ -s "$1" ]' _ "$home/host2.rc" || fail "superseded: the second host did not return"
  expect_code 0 "$(cat "$home/host2.rc")" "a superseded host exits 0"
  assert_grep 'supervision-host stood down: this session does not own supervision' "$home/host2.out" "the stand-down must say why"
  kill -0 "$owner" 2>/dev/null || fail "a superseded host stopped the owner host"
  [ "$(awk -F '\t' '$1 == "host" { print $2 }' "$home/state/.supervision-host")" = "$owner" ] \
    || fail "a superseded host took the owner's host record"
  if [ "$(cat "$home/state/.watch.lock/pid" 2>/dev/null)" != "$watcher" ] || ! kill -0 "$watcher" 2>/dev/null; then
    fail "a superseded host stopped the owner's watcher"
  fi
  FM_HOME="$home" "$LEASE" check demo 2>/dev/null | grep -q '^branch ' || fail "a superseded host released the owner's branch leases"
  kill -TERM "$owner"
  wait_until 200 sh -c '! kill -0 "$1" 2>/dev/null && ! kill -0 "$2" 2>/dev/null' _ "$owner" "$watcher" \
    || fail "superseded: the owner host did not stop on TERM"
  pass "host: a host under a superseded auto-arm generation stands down without touching the owner"
}

test_undelivered_dialog_is_fed_again_on_the_next_turn
- Outcome: ⚠️ 2 infos across 3 runs (1h1m36s)

Pipeline

Updates from git push no-mistakes

✅ **intent** - passed

✅ No issues found.

🔧 **Rebase** - 2 issues found → auto-fixed ✅
  • ⚠️ bin/fm-watch.sh - merge conflict rebasing onto origin/main
  • ⚠️ docs/watcher-continuity.md - merge conflict rebasing onto origin/main

🔧 Fix applied.
✅ Re-checked - no issues remain.

⚠️ **Review** - 1 info
  • ℹ️ docs/watcher-continuity.md:197 - The four new sentences (lines 197-200) were inserted between "A handling successor does not re-announce..." and "It enters its poll loop immediately and keeps scanning signals, stale panes, and checks." As a result, "It" at line 201 now seems to point back to "Notification" or "acknowledgement" instead of the handling successor. Fix: move the inserted block below line 201, or change "It" to "The successor". This is wording only; behavior is unaffected.
⚠️ **Test** - 2 infos
  • ⚠️ The Test agent did not finish within its invocation budget. Reported: agent run tests timed out after 30m0s: agent last produced output 1s ago (79 observed); agent reported: claude parse events: context deadline exceeded. This is a budget or provider-slowness cut, not a code failure. Re-running the same request costs another full budget, so no further attempt is made automatically. If this repository's targeted tests or evidence gathering routinely approach the default 30m0s, raise test_agent_timeout in global config. Respond with fix to spend another budget: a repair turn runs only for selected findings other than this budget cut, then validation re-runs. Or abort and retry after raising the budget.

🔧 No changes applied.
2 issues (1 error, 1 warning) still open:

  • ⚠️ The Test agent did not finish within its invocation budget. Reported: agent run tests timed out after 30m0s: agent last produced output 773ms ago (68 observed); agent reported: claude parse events: context deadline exceeded. This is a budget or provider-slowness cut, not a code failure. Re-running the same request costs another full budget, so no further attempt is made automatically. If this repository's targeted tests or evidence gathering routinely approach the default 30m0s, raise test_agent_timeout in global config. Respond with fix to spend another budget: a repair turn runs only for selected findings other than this budget cut, then validation re-runs. Or abort and retry after raising the budget.
  • 🚨 Approval is refused: the run worktree at ~/.no-mistakes/worktrees/d51ae9881507/01M5KH9M6S6M5ZJNAD38NX7ZDR holds work no Test turn validated, and the steps after Test would commit and publish it. It holds uncommitted changes to tests/zz-single.test.sh (inspect with git -C ~/.no-mistakes/worktrees/d51ae9881507/01M5KH9M6S6M5ZJNAD38NX7ZDR status and git -C ~/.no-mistakes/worktrees/d51ae9881507/01M5KH9M6S6M5ZJNAD38NX7ZDR diff). Respond with fix to validate it, or abort.

🔧 No changes applied.
2 infos still open:

  • ℹ️ tests/fm-supervision-host.test.sh - Full fm-supervision-host runs under load each hit a timing-sensitive failure: 'hook quiet: the Stop hook never closed' and 'the watcher's downtime resurface did not reach main'. Run in isolation, each passed 3/3 on both HEAD and base f3252b2, and this branch does not change supervision-host or watcher code. That points to flakiness under load, but the root cause is unproven and there is no green whole-suite run. Remote CI owns the full-suite confirmation.
  • ℹ️ tests/fm-wake-queue.test.sh - The first fm-wake-queue run failed with 'concurrent append/drain subprocess failed' under parallel load, and the rerun passed 69/69. This looks like intermittent lock contention, not a regression.
  • Live validation: ✅ go - 3 of 6 scenarios driven live against the product
Scenario Result Live Evidence
Captain queues a second inbox note after the counter is lost while the first is unacknowledged; the predecessor's --ack-through leaves the new note queued ✅ pass live live-inbox-queue-transcript.txt Scenario A (seq 2, survives --ack-through 1) vs baseline transcript (seq 1 reused, note deleted)
A malformed counter still yields a fresh sequence above the queued rows, and drain plus ack empties the queue ✅ pass live live-inbox-queue-transcript.txt Scenario B
Large sequences (2^53-1 queued, 2^63-2 counter) allocate exact digit-only next sequences, and the drain names the exact ack sequence ✅ pass live live-inbox-queue-transcript.txt Scenario C (9007199254740992, 9223372036854775807); tests/fm-wake-queue.test.sh 69/69 rerun
A handling successor announces new inbox work (fresh or byte-identical, before or after the ack, intact, missing or malformed counter) without consuming it or looping, and stays silent for inherited r… ⏸️ untested no The prior payload established no live result. This was exercised only by tests/fm-watch-arm.test.sh in test fixture homes (39 ok, including 8 successor cases), not against a live primary. A live check…
Upstream #7466 startup-race and no-recovery-loop guarantees hold (a row appended during startup is resurfaced; recovery is announced at most once per generation) ⏸️ untested no The prior payload established no live result. This was exercised only by tests/fm-watch-recovery-loop.test.sh in fixture homes (3 ok). This branch does not change watcher code, and no live primary lab…
Host handoff settlement: an inbox note queued while the host is parked on a handled wake's successor rewakes main ⏸️ untested no The prior payload established no live result. This was exercised only by the fm-supervision-host harness with a stub engine, where the test passed. A live Claude primary lab was not started, and the w…
  • Read saved evidence in ~/.no-mistakes/evidence/01M5KH9M6S6M5ZJNAD38NX7ZDR (produced earlier in this run at head 9bd8b71)
  • git diff --stat f3252b2 HEAD: confirmed the change touches only fm-wake-lib.sh, fm-wake-drain.sh, the docs and the queue/watch-arm tests
  • Base vs HEAD real inbox CLI transcripts in a disposable lab home (bin/fm-inbox.sh note, bin/fm-wake-drain.sh, --ack-through): live-inbox-queue-transcript.txt vs baseline-f3252b2-inbox-queue-transcript.txt
  • tests/fm-watch-arm.test.sh: 39 ok, including 8 handling-successor counter/identical-row cases (after-fm-watch-arm.log)
  • tests/fm-watch-recovery-loop.test.sh: 3 ok (after-fm-watch-recovery-loop.log)
  • tests/fm-wake-queue.test.sh: 69/69 on rerun after one concurrent-append lock-contention failure on the first run
  • fm-inbox and all four fm-wake-drain-* suites: all ok
  • tests/fm-supervision-host.test.sh partial runs, plus isolated 3x HEAD-vs-base runs of the dialog-resurface and hook-quiet tests (all 12 ok)
  • Saved tests/zz-single.test.sh to evidence as diagnostic-zz-single-dialog-resurface.test.sh.txt, deleted it, and confirmed git status --short is empty
✅ **Document** - passed

✅ No issues found.

✅ **Lint** - passed

✅ No issues found.

✅ **Push** - passed

✅ No issues found.

@greptile-apps

greptile-apps Bot commented Oct 3, 2026 •

Copy link
Copy Markdown

RetriggerConfidence Score: 5/5

[Critical risk] Fixes sequence numbering and notification logic in the queue and watcher system.

The PR appears safe to merge; no new actionable issue was established.

Reviews (3) · Last reviewed commit: "no-mistakes(ci): Fixed both Greptile fin..."

Comment thread bin/fm-watch.sh Resolved
Comment thread bin/fm-watch.sh Resolved
Comment thread bin/fm-wake-lib.sh Resolved
@kunchenguid

Copy link
Copy Markdown
Owner

Speaking as Kun's firstmate: first stamp vs tip 1f3e7696.

HEAD 39c10114c178f8cda113f9152c9d4af87c992fb7. Attestation MATCH. Greptile SUCCESS (confidence 5/5; prior P1s addressed including seq-counter restart + large decimal identifiers). Fork CI/NM were action_required; approved this pass after diff review (no security risk): CI 37114818707, NM 37114818695. MERGEABLE/UNSTABLE pending those runs. No Fixes/Closes in author body (unstamped; no verified closes).

contract-class: restore — concrete existing handling-successor path in fm-watch.sh stranded inbox appends newer than inherited rows while the beacon stayed fresh; tip snapshots inherited rows + recovery generation under the queue lock and resurfaces only newer rows. Not a new wake class/default-on surface.

VISION (per rule):

  1. One captain, one interface — aligns (inbox wakes reach the captain instead of being stranded).
  2. Authority explicit — aligns (no new autonomy grant).
  3. Scripts vs agents — aligns (watcher scripts own the mechanic).
  4. Restart non-event — aligns (durable queue + recovery generation).
  5. Delegation with spine — n/a.
  6. Fleet outlives vendor — aligns (harness-agnostic watcher continuity).
  7. Scope — aligns (watcher/inbox command layer).

Waiting-ci until approved CI/NM go green. No Firstmate flag. Do not merge yet.

1yian pushed a commit to 1yian/firstmate that referenced this pull request Oct 6, 2026
…herited sequence (kunchenguid#6467)

Brought into this fork ahead of upstream from kunchenguid#6467
(head 39c10114c1, still open upstream). Fixes kunchenguid#5967:
a captain inbox note (for example a Firstmate board action) never woke an
idle primary whose watcher was a handling successor, because
resurface_after_downtime returned early for the successor's whole lifetime.
A successor now holds back only the rows and recovery generation it
inherited, so any newer append surfaces a check: rearm-resurface wake.

* fix: notify handling successors about newer inbox wakes
* no-mistakes(document): document handling-successor inbox regression
* no-mistakes(ci): fix Greptile P1 on the startup snapshot
* no-mistakes(ci): fix both Greptile findings on PR kunchenguid#6467

tests/fm-watch-arm.test.sh takes only the PR's added test and its calls;
the neighbouring upstream e31bc6e tests that the merge context carried
are not in this fork yet.
@1yian

1yian commented Oct 6, 2026

Copy link
Copy Markdown

Just wanted to note that wakes/inboxes were broken for me until I incorporated this fix.

@ulsamern
ulsamern force-pushed the fix/inbox-successor-wake branch from 39c1011 to bed7da0 Compare October 7, 2026 23:18
@ulsamern ulsamern changed the title fix(bin): wake handling successors for inbox rows newer than their inherited sequence fix: notify handling successors about newer inbox wakes Oct 7, 2026
@kunchenguid

Copy link
Copy Markdown
Owner

Speaking as Kun's firstmate: thanks @ulsamern for rebasing this, and @1yian for the field confirmation. I re-read head bed7da04 against main 0ec1c5a4. The content matches the earlier review: the handling successor snapshots its inherited rows and recovery generation under the queue lock and announces only newer rows, and the allocator numbers past every queued sequence.

Contract-class: restore, unchanged. This is the existing handling-successor path, which stranded inbox wakes that arrived after it started. No new wake class or default-on surface is added. The VISION per-rule read from my first stamp stands.

Gates: the attestation matches bed7da04. Security review: no network calls, secrets or workflow edits. I approved this head's fork runs: CI 37701551462, no-mistakes 37701551603 and 37701588897. Nothing is needed from you unless CI fails. If it's green, it can be auto-merged as restore.

…uccessor could miss a new inbox wake when `.wake-queue.seq` was missing or malformed. What must always hold: a row added after the successor took its snapshot must be announced and must never be consumed by an older acknowledgement. Two places were breaking this: 1. `bin/fm-watch.sh`: the successor only recorded the highest inherited sequence number. If the counter was reset, a new row could get a number at or below that and be treated as already covered. This now stays silent forever once the inherited rows are acknowledged and the queue drains. 2. `bin/fm-wake-lib.sh` `fm_wake_append_locked`: a reset counter reused the sequence number of a row still in the queue. The predecessor's pending `--ack-through` consumes rows by sequence number, so it deleted the new row before anyone handled it. This was a gap in the existing allocator, and it is what made the before-ack cases fail even after fix 1. Fixes: - Watcher: the successor now snapshots the inherited rows themselves instead of their highest sequence. On each poll it announces if any queued row is not in that snapshot. It still never consumes rows, and inherited rows alone stay silent. - Allocator: the next sequence is now one more than the larger of the counter and the highest sequence still queued, so a new row can't land inside an outstanding acknowledgement's range. - `docs/watcher-continuity.md`: the paragraph and coverage list are updated to match. Tests: `test_append_wakes_handling_successor` in `tests/fm-watch-arm.test.sh` now inherits two rows and takes a counter state (intact, missing, malformed). The four new cases are after-ack and before-ack with a missing or malformed counter, and they run real watcher, arm and drain processes. In after-ack the queue is fully drained before the new append. Evidence: - Before any production change (on 92c724d), all four new cases failed: "not ok - handling successor stranded the second inbox wake" for after-ack and before-ack. - With only the watcher fix, the after-ack cases passed and the before-ack cases still failed, which shows the allocator fix is needed. - With both fixes, all four pass. Full results: `fm-watch-arm` 36/36 (including the intact after-ack and before-ack cases, so ordinary silence and fresh-beacon delivery still hold), `fm-watch-recovery-loop` 2/2, `fm-inbox` 16/16, `fm-pi-watch-extension` 60/60, `fm-wake-queue` 67/67, and all four `fm-wake-drain-*` suites passed (9, 9, 18, 14). Canonical `bin/fm-lint.sh` with `PATH=/home/nino/.local/bin:$PATH` passed: ShellCheck clean, actionlint 1.7.12, 3 workflows valid. That lint run was in local changed-file mode with ShellCheck source following disabled. In a first run of all nine suites in parallel, `fm-wake-queue` failed on "presentation lock delayed the drain for 10s" and one `fm-pi-watch-extension` timing test failed. Both passed in full when rerun on their own, so I read that as load contention, not this change. Design decision to flag: the allocator change sits in the shared wake library, so it goes beyond the watcher comparison the bot pointed at. It is a one-expression change, and the before-ack tests can't pass without it, because otherwise the predecessor's acknowledgement deletes the new message. Not done, per the phase boundary: nothing committed, pushed or posted, and the live fleet was not touched. Evidence logs are in /tmp/fmci, not in a pipeline logs/evidence directory
… Nothing was committed, pushed or posted, and the live fleet was not touched. **ci-1 (4172409813): a new wake was mistaken for an inherited one.** - Invariant that must hold: a successor treats a row as covered only if it is an unchanged inherited row in the inherited recovery episode. - Cause: after the predecessor's acknowledgement and a lost counter, a re-append with the same kind, key, payload and epoch was byte-identical to the snapshot row, so the successor stayed silent. - Fix (`bin/fm-watch.sh`): I used the existing recovery generation rather than a new identity scheme. Any append after an acknowledgement mints a new generation. The successor records the generation with its row snapshot, under the queue lock and in arm-check's lock order. Each poll counts the queue as newer if a row is not in the snapshot, or if the queue is non-empty and the generation changed. The existing arm-check then decides whether to announce. No rows are consumed, and inherited rows alone stay silent. - The row snapshot is still needed for before-ack, because an append before the acknowledgement keeps the same generation. **ci-2 (4172409821): large sequence numbers became unusable.** - Invariant that must hold: sequence numbers are always exact digit-only decimals. - Fix (`bin/fm-wake-lib.sh`): the allocator picks the largest of the counter and the queued sequences by comparing decimal text (length, then string order, leading zeros stripped), then adds 1 in bash with `$((10#$seq + 1))`. This restores the 64-bit exactness of the original bash counter. - Same fix at two places in `bin/fm-wake-drain.sh` that print sequences: `presented_max_row` and `ACK_THROUGH` print the matched text instead of `max + 0`. **Tests** - `tests/fm-watch-arm.test.sh`: two new `identical` cases, after-ack with a missing and with a malformed counter. A fake `date` pins the epoch, and the test asserts the row is byte-identical, then checks timely notification, preservation until its own acknowledgement, and no repeat notification. - `tests/fm-wake-queue.test.sh`: new `test_large_sequences_stay_exact_decimal_identifiers` starts from 2147483647, 9007199254740991 and 9223372036854775806, each with an intact, missing and malformed counter. It checks the next sequence is exact and digit-only. For the first two it also checks a real drain shows both rows, names the exact acknowledgement sequence, and acknowledging empties the queue. - `docs/watcher-continuity.md` now describes the generation check. **Evidence** (in `/home/nino/.no-mistakes/evidence/01M40CDTX2000A5TFFRZN27YFR/ci-round3/`) - Before, on 050a5fc: both identical cases failed with "handling successor stranded the second inbox wake (after-ack)". The large-sequence test failed with "advanced to '9223372036854775808', not 9223372036854775807". - After the fix, all three pass (`after-*.log`). - All nine suites passed, each run on its own, all with 0 not ok (`final-results.txt`): `fm-wake-queue` 68/68, `fm-watch-arm` 38/38, `fm-watch-recovery-loop` 2/2, `fm-inbox` 16/16, `fm-pi-watch-extension` 60/60, `fm-wake-drain-open-decisions-cursor` 9/9, `fm-wake-drain-open-decisions` 9/9, `fm-wake-drain-outcome-backstop` 18/18, `fm-wake-drain-unread-status` 14/14. - `bin/fm-lint.sh` with `PATH=/home/nino/.local/bin:$PATH` passes: ShellCheck clean, actionlint 1.7.12, 3 workflows valid (local changed-file mode). **Not run** - The only OpenCode suite is an opt-in live test, so I did not run it. **Limits** - The 2.14748e+09 symptom doesn't reproduce with the awks here (gawk, mawk 1.3.4, busybox). The failure reproduced locally is the precision loss at 64-bit values. - The drain's awk comparisons are only exact up to 2^53. That predates this PR and I left it alone, so the drain test stops at 2^53
@ulsamern
ulsamern force-pushed the fix/inbox-successor-wake branch from bed7da0 to a7975f9 Compare October 23, 2026 06:47
@ulsamern ulsamern changed the title fix: notify handling successors about newer inbox wakes fix(bin): keep handling successors from stranding inbox wakes after counter loss Oct 23, 2026
@kunchenguid

Copy link
Copy Markdown
Owner

Speaking as Kun's firstmate: thanks @ulsamern for bringing this up to date. Head a7975f94 rebases onto current main, and on top of the reviewed fix it adds a document-step wording tweak. The attestation binds this head, and there are no workflow or secret changes, so I've approved this head's fork runs (CI 39913704210, no-mistakes 39913704155, 39913747757). My contract-class read is still restore: it's the existing handling-successor inbox path, with no new wake class or default-on surface. Once CI is green on this head, this is on the auto-merge path. Nothing is needed from you right now.

@ulsamern

Copy link
Copy Markdown
Author

@kunchenguid Thanks for approving the runs. On unchanged head a7975f94aa616c25bbd8095cf1bf0f21c6725584, 19 checks passed; only Behavior portable serial 1 lacks a verdict. Its annotation says it exceeded the 30-minute execution limit. The log shows supervision-host tests continuing to pass immediately before cancellation; this does not establish a full-suite pass or the timeout's root cause.

Could a maintainer rerun that job once? There is no rerun outstanding. Our single-job rerun request was refused with HTTP 403 (“Must have admin rights to Repository”). No code or workflow changes were made, and the cancelled check has not been waived. The other checks do not need rerunning.

@kunchenguid
kunchenguid merged commit cfe91b0 into kunchenguid:main Oct 23, 2026
36 of 37 checks passed
@kunchenguid

kunchenguid commented Oct 23, 2026 •

Copy link
Copy Markdown
Owner

Speaking as Kun's firstmate: this is merged. Thank you @ulsamern — really appreciate you taking the time on this.

Context: on head a7975f94 the actual delta against main is the queue allocator numbering past every queued row, plus the exact-decimal ack. Your CLI transcripts drove that part live on base and on HEAD, and @1yian's field report backs it up. The watcher-side successor behavior is already on main. Contract-class: restore. 18 of 19 checks passed. Serial 1 was cancelled at the 30-minute cap with 0 failures, which is a known runner limit. I've also queued a rerun of that job for the record.

prishsu0730 pushed a commit to prishsu0730/firstmate that referenced this pull request Oct 29, 2026
…ounter loss (kunchenguid#6467)

* fix: notify handling successors about newer inbox wakes

* no-mistakes(document): Document handling-successor inbox regression in watcher coverage list

* no-mistakes(ci): Fixed Greptile P1 (comment 4172295712): a handling successor could miss a new inbox wake when `.wake-queue.seq` was missing or malformed. What must always hold: a row added after the successor took its snapshot must be announced and must never be consumed by an older acknowledgement. Two places were breaking this: 1. `bin/fm-watch.sh`: the successor only recorded the highest inherited sequence number. If the counter was reset, a new row could get a number at or below that and be treated as already covered. This now stays silent forever once the inherited rows are acknowledged and the queue drains. 2. `bin/fm-wake-lib.sh` `fm_wake_append_locked`: a reset counter reused the sequence number of a row still in the queue. The predecessor's pending `--ack-through` consumes rows by sequence number, so it deleted the new row before anyone handled it. This was a gap in the existing allocator, and it is what made the before-ack cases fail even after fix 1. Fixes: - Watcher: the successor now snapshots the inherited rows themselves instead of their highest sequence. On each poll it announces if any queued row is not in that snapshot. It still never consumes rows, and inherited rows alone stay silent. - Allocator: the next sequence is now one more than the larger of the counter and the highest sequence still queued, so a new row can't land inside an outstanding acknowledgement's range. - `docs/watcher-continuity.md`: the paragraph and coverage list are updated to match. Tests: `test_append_wakes_handling_successor` in `tests/fm-watch-arm.test.sh` now inherits two rows and takes a counter state (intact, missing, malformed). The four new cases are after-ack and before-ack with a missing or malformed counter, and they run real watcher, arm and drain processes. In after-ack the queue is fully drained before the new append. Evidence: - Before any production change (on 92c724d), all four new cases failed: "not ok - handling successor stranded the second inbox wake" for after-ack and before-ack. - With only the watcher fix, the after-ack cases passed and the before-ack cases still failed, which shows the allocator fix is needed. - With both fixes, all four pass. Full results: `fm-watch-arm` 36/36 (including the intact after-ack and before-ack cases, so ordinary silence and fresh-beacon delivery still hold), `fm-watch-recovery-loop` 2/2, `fm-inbox` 16/16, `fm-pi-watch-extension` 60/60, `fm-wake-queue` 67/67, and all four `fm-wake-drain-*` suites passed (9, 9, 18, 14). Canonical `bin/fm-lint.sh` with `PATH=/home/nino/.local/bin:$PATH` passed: ShellCheck clean, actionlint 1.7.12, 3 workflows valid. That lint run was in local changed-file mode with ShellCheck source following disabled. In a first run of all nine suites in parallel, `fm-wake-queue` failed on "presentation lock delayed the drain for 10s" and one `fm-pi-watch-extension` timing test failed. Both passed in full when rerun on their own, so I read that as load contention, not this change. Design decision to flag: the allocator change sits in the shared wake library, so it goes beyond the watcher comparison the bot pointed at. It is a one-expression change, and the before-ack tests can't pass without it, because otherwise the predecessor's acknowledgement deletes the new message. Not done, per the phase boundary: nothing committed, pushed or posted, and the live fleet was not touched. Evidence logs are in /tmp/fmci, not in a pipeline logs/evidence directory

* no-mistakes(ci): Fixed both Greptile findings on PR kunchenguid#6467. Nothing was committed, pushed or posted, and the live fleet was not touched. **ci-1 (4172409813): a new wake was mistaken for an inherited one.** - Invariant that must hold: a successor treats a row as covered only if it is an unchanged inherited row in the inherited recovery episode. - Cause: after the predecessor's acknowledgement and a lost counter, a re-append with the same kind, key, payload and epoch was byte-identical to the snapshot row, so the successor stayed silent. - Fix (`bin/fm-watch.sh`): I used the existing recovery generation rather than a new identity scheme. Any append after an acknowledgement mints a new generation. The successor records the generation with its row snapshot, under the queue lock and in arm-check's lock order. Each poll counts the queue as newer if a row is not in the snapshot, or if the queue is non-empty and the generation changed. The existing arm-check then decides whether to announce. No rows are consumed, and inherited rows alone stay silent. - The row snapshot is still needed for before-ack, because an append before the acknowledgement keeps the same generation. **ci-2 (4172409821): large sequence numbers became unusable.** - Invariant that must hold: sequence numbers are always exact digit-only decimals. - Fix (`bin/fm-wake-lib.sh`): the allocator picks the largest of the counter and the queued sequences by comparing decimal text (length, then string order, leading zeros stripped), then adds 1 in bash with `$((10#$seq + 1))`. This restores the 64-bit exactness of the original bash counter. - Same fix at two places in `bin/fm-wake-drain.sh` that print sequences: `presented_max_row` and `ACK_THROUGH` print the matched text instead of `max + 0`. **Tests** - `tests/fm-watch-arm.test.sh`: two new `identical` cases, after-ack with a missing and with a malformed counter. A fake `date` pins the epoch, and the test asserts the row is byte-identical, then checks timely notification, preservation until its own acknowledgement, and no repeat notification. - `tests/fm-wake-queue.test.sh`: new `test_large_sequences_stay_exact_decimal_identifiers` starts from 2147483647, 9007199254740991 and 9223372036854775806, each with an intact, missing and malformed counter. It checks the next sequence is exact and digit-only. For the first two it also checks a real drain shows both rows, names the exact acknowledgement sequence, and acknowledging empties the queue. - `docs/watcher-continuity.md` now describes the generation check. **Evidence** (in `/home/nino/.no-mistakes/evidence/01M40CDTX2000A5TFFRZN27YFR/ci-round3/`) - Before, on 050a5fc: both identical cases failed with "handling successor stranded the second inbox wake (after-ack)". The large-sequence test failed with "advanced to '9223372036854775808', not 9223372036854775807". - After the fix, all three pass (`after-*.log`). - All nine suites passed, each run on its own, all with 0 not ok (`final-results.txt`): `fm-wake-queue` 68/68, `fm-watch-arm` 38/38, `fm-watch-recovery-loop` 2/2, `fm-inbox` 16/16, `fm-pi-watch-extension` 60/60, `fm-wake-drain-open-decisions-cursor` 9/9, `fm-wake-drain-open-decisions` 9/9, `fm-wake-drain-outcome-backstop` 18/18, `fm-wake-drain-unread-status` 14/14. - `bin/fm-lint.sh` with `PATH=/home/nino/.local/bin:$PATH` passes: ShellCheck clean, actionlint 1.7.12, 3 workflows valid (local changed-file mode). **Not run** - The only OpenCode suite is an opt-in live test, so I did not run it. **Limits** - The 2.14748e+09 symptom doesn't reproduce with the awks here (gawk, mawk 1.3.4, busybox). The failure reproduced locally is the precision loss at 64-bit values. - The drain's awk comparisons are only exact up to 2^53. That predates this PR and I left it alone, so the drain test stops at 2^53

* no-mistakes(document): Reattach successor poll-loop sentence to its subject

(cherry picked from commit cfe91b0)
ywplee added a commit to ywplee/firstmate that referenced this pull request Nov 12, 2026
* fix: correct Rex secondmate grouping and lifecycle (#7656)

* Fix Rex secondmate session lifecycle

* no-mistakes(review): Retire Rex secondmate sessions under the owning home identity

* no-mistakes(review): Limit Rex FM_ROOT label override to secondmate launches

* no-mistakes(document): Clarify Rex secondmate grouping and lifecycle documentation

* feat(opencode): add OpenCode 2 support with version-gated launch, plugins, and exit (#7336)

* feat(opencode): add OpenCode 2 support with version-gated launch and plugins

OpenCode 2 dropped the v1 server-plugin hook API, so the five fm.primary.*
plugins now export a default definition with an id and a setup function
alongside their legacy OpenCode 1 server export, backed by a new shared
lib/fm-opencode2.js helper; the turn-end guard, watch-arm, cd-check,
pretool-check, and sessionstart-nudge install their behavior from setup(ctx)
on OpenCode 2 and keep the server entrypoint for OpenCode 1.

fm-spawn probes the resolved opencode executable's --version once and branches
the launch, model flag, reasoning config, exit key, and busy-state plugin off
the detected major. A parsed major >= 2 takes the OpenCode 2 shape (no --model,
the model pinned through OPENCODE_CONFIG_CONTENT, a raw Ctrl-C exit, the
session.execution.* busy plugin); OpenCode 1.x and any undetected or
unparseable version fall back to the 1.x shape (--model, 1.x config, /exit)
everywhere. The worker busy-state plugin is always provisioned, but OpenCode 1
keeps the pre-port session.status/session.idle plugin so its busy-state wiring
is unchanged, and only a major >= 2 gets the session.execution plugin. Adapter
and supervision docs, OpenCode 2 live fixtures, and regression tests for the
unknown->1.x launch path and the version-gated busy-plugin shape are included.

* no-mistakes(review): gate OpenCode 2 busy plugin turn-end touch on notifyTurnEnd

* feat(opencode): launch detected OpenCode 2 workers with --standalone

OpenCode 2's default launch attaches to the shared background service, which
hosts plugins with the service's environment and ignores the pane's
OPENCODE_CONFIG_CONTENT. A private server keeps per-worker model, permissions,
FM_HOME, and lock ancestry correct. 1.x and undetected versions are unchanged.

Ported from https://github.com/kunchenguid/firstmate/pull/5143.

Co-authored-by: Girik Bajaj <[email protected]>

* fix(opencode): resolve the OpenCode 2 project location and treat every terminal turn as a turn end

OpenCode 2.0.x hands plugins the project only as ctx.location.project.directory
and takes ctx.session.prompt({ sessionID, text }), so the V2 setup path never
found its root or delivered a prompt. Interrupted and failed turns now end a
turn like a succeeded one, while a server shutdown does not.

Ported from https://github.com/kunchenguid/firstmate/pull/5143.

Co-authored-by: Girik Bajaj <[email protected]>

* test(opencode): add a token-free OpenCode 2 native plugin fixture to the live e2e

A private opencode serve plus a loopback provider proves the five primary
plugins load and act on OpenCode 2: startup nudge, cd and watcher-redirection
guards, turn-end guard, watcher arming across succeeded, interrupted, and
failed turns. The fixture declares the complete model capabilities object,
which OpenCode 2.0.11 requires and 2.0.22 accepts. FM_OPENCODE_LIVE_BINS runs
it across several OpenCode 2 executables. The credentialed half now picks its
run flags and session tables by detected major, so it keeps working on 1.x.

Fixture ported from https://github.com/kunchenguid/firstmate/pull/5143.

Co-authored-by: Girik Bajaj <[email protected]>

* feat(opencode): send one Enter when an OpenCode 2 launch leaves the brief unsent

OpenCode 2.0.11 prefills the --prompt brief without submitting it, while 2.0.22 submits it.
After launch, fm-spawn waits for the worker's busy-state plugin to report the turn start, sends one Enter only if it has not started and the composer is not empty, and fails the spawn if the turn never starts.

* docs(opencode): document the OpenCode 2 launch, delivery gate, and standalone primary homes

Records the 2.0.11 and 2.0.22 live evidence for the native plugin fixture and the post-launch brief delivery gate.

* no-mistakes(review): Trim OpenCode 2 adapter shapes and harden Ctrl-C exit

* no-mistakes(review): Record OpenCode 2 live seatbelt and exit evidence

* no-mistakes(test): Document OpenCode 2.0.22 wide-pane sidebar exit refusal limitation

* no-mistakes(document): Refresh OpenCode 2 exit-key and seatbelt payload docs

* test(opencode): verify OpenCode 1.x live with the dual-export plugins

Pin the live e2e TUI panes to the resolved opencode executable, and record
OpenCode 1.15.7, 1.18.20, and 1.18.31 evidence for plugin loading, the
turn-end guard, watcher continuity, and 1.x worker launch and exit.

* no-mistakes(review): Defer OpenCode 2 Enter on unknown composer; widen turn-end docs

* no-mistakes(document): Document OpenCode 2 delivery gate unknown-composer test outcomes

---------

Co-authored-by: Niranjan <[email protected]>
Co-authored-by: Girik Bajaj <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>

* fix(bin): resolve the tmux container from firstmate's own session, not the most recent group member (#7662)

* fix(bin): resolve the tmux container from the caller's own session, not the most recent group member

* no-mistakes(test): Fall back when the $TMUX session id is stale

* no-mistakes(document): Document tmux container choice under grouped sessions

* fix(bin): read a fully dim Cursor idle placeholder as an empty composer (#7647)

* fix(bin): read a fully dim Cursor placeholder as an empty composer

cursor-agent 2026.10.19 draws the composer glyph and its idle placeholder
as one SGR 2 run with no reverse-video cell, so ghost stripping empties the
row and the empty-content guard returned unknown. Relaunch and exit then
refused on every idle Cursor pane on tmux.

When a styled bare row strips to empty and the plain row is an agent glyph
followed by an anchored idle placeholder, read it empty. Bright typed text,
other dim text, and unstyled rows keep their existing verdicts.

Fixes #7413

* docs(verification): record the fully dim Cursor placeholder verdict and refresh command

* fix(bin): say why away-mode inject deferred and pin named Claude idle composer as empty (#6163)

* fix(bin): recognize a named Claude session's titled composer rule on cursorless backends

`claude -n <name>` right-aligns the session name in the rule above the
composer. Cursorless backends (Herdr) accepted only solid rules, so the
scan saw the lower rule alone, the idle composer read `unknown`, and
away-mode delivery to a named Claude primary deferred until return.

A rule carrying one right-aligned title now opens a separator pair. It
never closes one, the pair it opens counts only over an agent-glyph row,
and it is never a valid Pi pair, so Pi's verdict is unchanged.

The away-mode composer deferral now names which refusal it was:
unsubmitted text, or no composer shape recognized.

* no-mistakes(review): Reword composer deferral reason to cover busy harness

* no-mistakes(ci): ci-3 (Greptile, user chose to fix): The rule that must always hold is that Claude's titled opening rule is accepted for any non-empty session name that doesn't start with a space and doesn't contain the rule glyph `─`, including a multiword name. The only place that check lives is the title `case` in `_fm_composer_titled_rule_row` (bin/fm-composer-lib.sh). It now reads `case "$title" in ''|' '*|*─*) return 1 ;; esac`, as the user asked, and the comment above the function mentions multiword titles. I added regression fixtures to `test_matrix_claude_named_session_titled_rule` in tests/fm-composer-lib.test.sh, next to the existing single-word `Andrew` cases. They use the title `Andrew Chen` and check that an idle composer on herdr reads `empty` and a composer with typed text reads `pending`. Something you should know: the old pattern already accepted a title with a space in the middle. It only rejected a title ending in a space. So the new multiword fixtures also pass against the old code, and the bot's failure scenario did not actually happen for "Andrew Chen". What the fix really changes is that it drops the trailing-space rejection, as instructed. Checks run: tests/fm-composer-lib.test.sh and tests/fm-composer-ghost.test.sh both pass (exit 0, no failures), and `shellcheck -x` is clean on both changed files

* no-mistakes(review): Match unnamed-ghost fixture rule width to the partner rule

* fix(bin): stop watcher arms whose ground is removed and reap Pi test process groups (#7666)

* fix(tests): reap Pi test process groups and stop arms whose ground is removed

Orphaned stub-arm pollers from tests/fm-pi-watch-extension.test.sh outlived
a failed case: they waited for release/stop files the failed driver never
wrote, teardown only removed the temp root, and the loops had no other exit.

Run each node driver in its own recorded process group and reap those groups
in teardown before the root is removed; end every blocking stub loop once its
own script is gone. bin/fm-watch-arm.sh now exits with a typed ground-removed
line within one poll when its script, state directory, or home is deleted,
instead of polling through the successor window.

* no-mistakes(document): Document arm exit when its ground is removed

* feat(bin): defer wedge escalation while a crew's no-mistakes run is validating (#5947)

* fix(bin): defer wedge escalation while an attributed validation run is running or fixing

While a no-mistakes run executes a round, the worker is correctly idle behind
its own blocking drive call, yet the watcher's wedge timer escalated a possible
wedge every FM_STALE_ESCALATE_SECS. The timer now consults the attributed run
step before escalating: a run the current-state reader reports as
validating (running) or validating (fixing) for a named run defers onto the
FM_PAUSE_RESURFACE_SECS recheck cadence, aged from a marker bound to that run
id. Parked, terminal, ci-monitoring, coarse, runless, absent and unreadable
runs keep the unchanged escalation ladder.

* test: count only the validating-run read in the unarmed parked-gate probe

* no-mistakes(document): add .validating-* to watcher-internals marker inventory

* no-mistakes(document): Update fm-watch.sh comments for validating-deferral chain

* no-mistakes(document): Document validating-run deferral in guard and handoff docs

* feat(watch): gate the validating-run wedge deferral behind config/wedge-defer-validating

The deferral changed the default for every home, unlike the comparable
config/wedge-defer-parked-gate and config/wedge-defer-worker-wait waits.
Absent the new presence flag the wedge timer spends no current-state read
for it and keeps the unchanged ladder.

* fix: identify Windows/Git Bash harness sessions for the session lock (#6300)

* fix(session-lock): identify a harness session on Windows/Git Bash

Every session start on Cygwin (Git for Windows) refused the fleet lock and
dropped to read-only with "cannot locate harness process in ancestry", so
spawning, steering, merging, the wake-queue drain, and supervision repair were
skipped on every start. Two independent causes, both on the identity path.

Cygwin's ps has no -o option at all and fails the whole invocation with
"unknown option -- o", so the ancestry walk aborted on its first hop. The walk
now reads comm, args, and ppid through accessors that fall back to Cygwin's
fixed ps columns, leaving the procps/BSD path unchanged.

That alone does not resolve the session: the parent link from a shell the
harness spawns does not cross the Cygwin boundary, and Cygwin reports that
shell's PPID as 1, so no walk can reach a harness that is a native Windows
process. Identity is instead taken from the session pid the harness publishes
and confirmed against the Windows process table before it is used - the pid
must still be live and its executable must independently identify a verified
harness - so an absent, stale, or non-harness value is discarded rather than
bound.

Walking the real Windows parent chain was implemented and then removed as
unsafe. MSYS emulates exec by spawning a fresh Windows process and exiting the
old one, so intermediate shells vanish and a child's recorded parent is
routinely a pid that no longer exists; Windows never reparents an orphan, so
that dangling id stays and can be reissued to an unrelated process. Following
it can bind a home's lock to the wrong process, which is the failure this file
exists to prevent. A harness that publishes nothing stays unresolved, which
leaves the session read-only exactly as before.

Windows pids are tagged rather than stored bare. They are a different namespace:
kill -0 reports a live Windows process as dead, and the number can collide with
an unrelated live Cygwin pid. The tag makes the value non-numeric, so a consumer
that treats it as a local pid - including a future kill - refuses it instead of
acting on the wrong process.

fm-sessionstart-nudge.sh carried a private second copy of the ownership walk and
so stayed wrong after the owner was fixed, nudging a session that already held
the lock. It now asks the owning function.

Verified on Windows 11 (Git Bash, Cygwin ps 3.4.10): the lock is acquired,
reports its holder, is idempotent, and refuses a bogus, dead, or non-harness
published pid. Regressions cover both platform departures behind a fake process
table, so they run on Linux and macOS CI too. The pre-existing e2e failure in
this suite on Windows is unchanged from main; it cannot exec its symlinked
fixture.

Refs #3396

Claude-Session: https://claude.ai/code/session_01F9T29YDqYSkQeDTC2Nfi7h
(cherry picked from commit 8b281b7b5507c342ac7870e8ccbefa56c55d05eb)

* fix(session-lock): keep the nudge's own ancestry question intact

Delegating the nudge to fm_session_lock_owned_by_self changed the question it
asks. The nudge asks whether a process in this ancestry took the lock; the
ownership predicate additionally requires a verified harness in that ancestry,
so a session whose lock was written by a plain shell started being nudged to
run session start again. tests/fm-sessionstart-nudge.test.sh pins the looser
contract deliberately.

The walk stays local, now reading ppid through the portable accessor so it also
survives a ps with no -o option, and defers to the ownership predicate only for
a Windows-tagged holder, which is not in this process table at all.

(cherry picked from commit 0baf64f71ffea275292a0fd88d033caccc041fc9)

* fix(session-lock): accept a tagged identity in every gate that reads the lock

The Windows identity added in this branch introduced a second shape into
state/.lock. Six gates read that field, and each one answered "is this value
usable" with its own inline numeric test, so every one of them read a valid
Windows holder as malformed.

The visible cost was concentrated in startup completion: the record was never
written, and the clear/compact check that consumes it could never match, so
every clear or compact on Windows repeated the full startup sequence. The
deferred network sweeps reported ownership as changed when it had not, and the
Stop auto-arm treated a dead Windows session as an unreadable lock rather than
a recoverable one. fm-lease.sh was the outlier: rather than refusing a value it
could not use, `tr -cd '0-9'` reduced the tag to its digits and produced a
number naming an unrelated process in the local table. It happened to fail
closed downstream, but deriving a wrong-namespace pid is precisely what the tag
exists to prevent, so it now takes the value whole and requires a local pid.

fm_session_pid_valid is now the single owner of that question and every gate
delegates to it, so a third identity shape cannot split them again.

Verified against the shipped bytes of each gate with a tagged lock: startup
completion now records and is recognized (main's gate reruns the full startup
on the same input), both network-ownership gates authorize their sweeps, and a
tagged lock yields no lease holder pid instead of 7204.

(cherry picked from commit 92561828fb9540ab6c77437def67a954e44b0418)

* fix(session-lock): gate the tagged identity on Windows and read it in every lock reader

Accept win:<digits> only where fm_win_boundary_applies, with an all-digit
remainder, so a Linux/macOS reader of a win:N lock stays inert as before.
The sessionstart nudge routes its tagged case through fm_win_untag_pid.
fm_session_lock_foreign_owner_live and fm_session_lock_inspect now validate
through fm_session_pid_valid and resolve a tagged holder through
fm_harness_pid_alive, so a live win:N holder reads as a live foreign owner
and as held; unverifiable tagged holders stay unknown.

* no-mistakes(document): Document Windows tagged session-lock identity in nudge and scripts docs

* fix(session-lock): keep task leases and stale detection working for a tagged holder

A Windows session can now hold the session lock as win:<pid>, but the task
lease still accepted only a local pid: the claim recorded the short-lived
fm-lease.sh process instead, and fm_lease_live rejected the tagged lock, so
the lease was never live and the other supervision actor could clear it and
act on the same task. The lease now records a live tagged lock holder whole
and treats it as live while it is still the lock holder and a verified
harness in the Windows process table. The session-lock library is loaded
only for a win:-shaped value, so POSIX lease verdicts are unchanged.

fm_session_lock_inspect left an exited tagged holder unknown, because
fm_win_command could not tell an absent pid from an unreadable table. It now
returns 1 only when a readable table proves the pid absent and 2 when the
table cannot be read, so inspection matches the local-pid contract: absent
is stale, a live non-harness is unknown with no live harness, and an
unreadable table stays unknown.

* no-mistakes(review): Restrict caller-supplied lease holder pid to local numeric

* no-mistakes(review): Pass tagged session-lock holder whole to task lease

* no-mistakes(review): Make tagged lease-holder regression tests fail without their fixes

* fix(session-lock): take a Windows CLAUDE_PID only with its session id

On Windows the session identity comes from CLAUDE_PID, which every process
started from a Claude pane inherits, so an unrelated process carrying a copy
could take the lock as that session and both would own it. The bridge now
accepts CLAUDE_PID only together with CLAUDE_CODE_SESSION_ID. The trusted
session-id gate matches the tagged win:<pid> form, so that id is recorded
beside the lock, and the anchor stays tagged. fm-lock.sh and the ownership
readers refuse the same tagged pid under a different recorded id as another
live session's. A non-Claude primary hand-started from a Claude pane inherits
both values and still resolves as that session; that remains a known
limitation. POSIX behavior is unchanged: every new branch applies only to a
tagged pid.

* fix(session-lock): let a Windows /clear re-key its own lock

/clear keeps the Claude process, so CLAUDE_PID stays while the session id
changes. Refusing the same tagged pid under a different recorded id locked a
session out of its own lock after /clear, which POSIX handles by re-keying
the sidecar. Drop that refusal: a Windows CLAUDE_PID is still taken only
together with its CLAUDE_CODE_SESSION_ID, and that id is still recorded
beside the lock and re-keyed on /clear as on POSIX.

* no-mistakes(review): Give tagged host test a session id; clarify Windows lock error

* no-mistakes(document): Point the trust-gate comment to the Windows limitation

---------

Co-authored-by: Lloyd <[email protected]>

* feat(bin): add opt-in local Claude usage threshold warner (#7421)

* feat(bin): add opt-in local Claude usage threshold warner

A usage window is exhausted without warning: work is cut off mid-run
rather than stopping deliberately, and nothing says a window is close to
its cap until it is already gone.

bin/fm-usage-warner.sh is a threshold warner, not a usage viewer.
quota-axi is already the one Claude-quota reader this repo depends on
(bin/fm-quota-axi-lib.sh), so the warner runs that existing read rather
than adding a second reader that could drift from it: one bounded
`quota-axi --provider claude --json --full --no-credential-refresh`, the
snapshot validated with fm_quota_json_valid, and the provider row picked
with the same FM_QUOTA_ROW_JQ join the dispatch consumers use, under
schema 5 and schema 6 alike.

Thresholds are `<window-id>:<percent>` directives in config/usage-warner,
naming quota-axi's own window ids (five_hour, seven_day, model:<name>)
rather than a second vocabulary, and compared against each window's own
percentUsed. Naming the window is the point: the session and weekly
windows exhaust at very different times, so a figure that does not say
which window is close misleads.

One read with two callers and no new schedule: `check` is what a human
runs on demand and what the watcher runs on its ordinary check-shim
cadence once `arm` registers state/usage-warner.check.sh through
bin/fm-check-register.sh. There is no daemon.

Warnings post through macOS Notification Center with the same osascript
call bin/fm-supervise-daemon.sh's wedge alarm makes, without sourcing or
coupling to that daemon's away-mode-specific config and rate limiting.
Delivery is edge-triggered against state/.usage-warner: a crossing warns
once, stays quiet while it holds, and re-arms when the window next reads
back below its threshold, the same standing-report contract
fm-mail-check.sh and fm-tool-update-check.sh already use.

bin/fm-procevent-quota.sh already reads the same snapshot, so docs name
the boundary rather than leaving two similar surfaces unexplained. That
source fires at most once, wakes firstmate with a durable check event,
and compares a provider's aggregate effectivePercentRemaining. This
warner is the standing, human-facing half: per-window, delivered to the
person through Notification Center, and self-re-arming. Neither replaces
the other and arming both is reasonable.

Opt-in is load-bearing and enforced in code. With no valid directive,
`check` returns before any read and `arm` refuses, so an unconfigured
home gains no behaviour change, no new failure mode, and no new hard
dependency at dispatch. Notification Center is macOS-only, so `arm`
refuses on other platforms instead of registering a check that could
never speak.

The warner only warns. It does not stop or pace dispatch, and its
coverage is exactly what quota-axi can see locally, so a plan or
organisation spend cap quota-axi does not report is not covered; the doc
says so rather than implying coverage it does not have.

The new test script carries no measured CI duration hint yet, so the
portable-serial lane balances it on the conservative default until the
hints are next refreshed from a green run, per docs/fm-test-portable-shards.md.

* no-mistakes(review): Key usage-warner de-dupe on window and threshold; fix docs

* no-mistakes(review): Keep absent-window crossings recorded; stub osascript in tests

* no-mistakes(document): Document absent-window de-dupe carry-forward in usage-warner header

* fix: correct Rex secondmate grouping and lifecycle (#7656)

* Fix Rex secondmate session lifecycle

* no-mistakes(review): Retire Rex secondmate sessions under the owning home identity

* no-mistakes(review): Limit Rex FM_ROOT label override to secondmate launches

* no-mistakes(document): Clarify Rex secondmate grouping and lifecycle documentation

* feat(opencode): add OpenCode 2 support with version-gated launch, plugins, and exit (#7336)

* feat(opencode): add OpenCode 2 support with version-gated launch and plugins

OpenCode 2 dropped the v1 server-plugin hook API, so the five fm.primary.*
plugins now export a default definition with an id and a setup function
alongside their legacy OpenCode 1 server export, backed by a new shared
lib/fm-opencode2.js helper; the turn-end guard, watch-arm, cd-check,
pretool-check, and sessionstart-nudge install their behavior from setup(ctx)
on OpenCode 2 and keep the server entrypoint for OpenCode 1.

fm-spawn probes the resolved opencode executable's --version once and branches
the launch, model flag, reasoning config, exit key, and busy-state plugin off
the detected major. A parsed major >= 2 takes the OpenCode 2 shape (no --model,
the model pinned through OPENCODE_CONFIG_CONTENT, a raw Ctrl-C exit, the
session.execution.* busy plugin); OpenCode 1.x and any undetected or
unparseable version fall back to the 1.x shape (--model, 1.x config, /exit)
everywhere. The worker busy-state plugin is always provisioned, but OpenCode 1
keeps the pre-port session.status/session.idle plugin so its busy-state wiring
is unchanged, and only a major >= 2 gets the session.execution plugin. Adapter
and supervision docs, OpenCode 2 live fixtures, and regression tests for the
unknown->1.x launch path and the version-gated busy-plugin shape are included.

* no-mistakes(review): gate OpenCode 2 busy plugin turn-end touch on notifyTurnEnd

* feat(opencode): launch detected OpenCode 2 workers with --standalone

OpenCode 2's default launch attaches to the shared background service, which
hosts plugins with the service's environment and ignores the pane's
OPENCODE_CONFIG_CONTENT. A private server keeps per-worker model, permissions,
FM_HOME, and lock ancestry correct. 1.x and undetected versions are unchanged.

Ported from https://github.com/kunchenguid/firstmate/pull/5143.

Co-authored-by: Girik Bajaj <[email protected]>

* fix(opencode): resolve the OpenCode 2 project location and treat every terminal turn as a turn end

OpenCode 2.0.x hands plugins the project only as ctx.location.project.directory
and takes ctx.session.prompt({ sessionID, text }), so the V2 setup path never
found its root or delivered a prompt. Interrupted and failed turns now end a
turn like a succeeded one, while a server shutdown does not.

Ported from https://github.com/kunchenguid/firstmate/pull/5143.

Co-authored-by: Girik Bajaj <[email protected]>

* test(opencode): add a token-free OpenCode 2 native plugin fixture to the live e2e

A private opencode serve plus a loopback provider proves the five primary
plugins load and act on OpenCode 2: startup nudge, cd and watcher-redirection
guards, turn-end guard, watcher arming across succeeded, interrupted, and
failed turns. The fixture declares the complete model capabilities object,
which OpenCode 2.0.11 requires and 2.0.22 accepts. FM_OPENCODE_LIVE_BINS runs
it across several OpenCode 2 executables. The credentialed half now picks its
run flags and session tables by detected major, so it keeps working on 1.x.

Fixture ported from https://github.com/kunchenguid/firstmate/pull/5143.

Co-authored-by: Girik Bajaj <[email protected]>

* feat(opencode): send one Enter when an OpenCode 2 launch leaves the brief unsent

OpenCode 2.0.11 prefills the --prompt brief without submitting it, while 2.0.22 submits it.
After launch, fm-spawn waits for the worker's busy-state plugin to report the turn start, sends one Enter only if it has not started and the composer is not empty, and fails the spawn if the turn never starts.

* docs(opencode): document the OpenCode 2 launch, delivery gate, and standalone primary homes

Records the 2.0.11 and 2.0.22 live evidence for the native plugin fixture and the post-launch brief delivery gate.

* no-mistakes(review): Trim OpenCode 2 adapter shapes and harden Ctrl-C exit

* no-mistakes(review): Record OpenCode 2 live seatbelt and exit evidence

* no-mistakes(test): Document OpenCode 2.0.22 wide-pane sidebar exit refusal limitation

* no-mistakes(document): Refresh OpenCode 2 exit-key and seatbelt payload docs

* test(opencode): verify OpenCode 1.x live with the dual-export plugins

Pin the live e2e TUI panes to the resolved opencode executable, and record
OpenCode 1.15.7, 1.18.20, and 1.18.31 evidence for plugin loading, the
turn-end guard, watcher continuity, and 1.x worker launch and exit.

* no-mistakes(review): Defer OpenCode 2 Enter on unknown composer; widen turn-end docs

* no-mistakes(document): Document OpenCode 2 delivery gate unknown-composer test outcomes

---------

Co-authored-by: Niranjan <[email protected]>
Co-authored-by: Girik Bajaj <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>

* feat(bin): add opt-in local Claude usage threshold warner

A usage window is exhausted without warning: work is cut off mid-run
rather than stopping deliberately, and nothing says a window is close to
its cap until it is already gone.

bin/fm-usage-warner.sh is a threshold warner, not a usage viewer.
quota-axi is already the one Claude-quota reader this repo depends on
(bin/fm-quota-axi-lib.sh), so the warner runs that existing read rather
than adding a second reader that could drift from it: one bounded
`quota-axi --provider claude --json --full --no-credential-refresh`, the
snapshot validated with fm_quota_json_valid, and the provider row picked
with the same FM_QUOTA_ROW_JQ join the dispatch consumers use, under
schema 5 and schema 6 alike.

Thresholds are `<window-id>:<percent>` directives in config/usage-warner,
naming quota-axi's own window ids (five_hour, seven_day, model:<name>)
rather than a second vocabulary, and compared against each window's own
percentUsed. Naming the window is the point: the session and weekly
windows exhaust at very different times, so a figure that does not say
which window is close misleads.

One read with two callers and no new schedule: `check` is what a human
runs on demand and what the watcher runs on its ordinary check-shim
cadence once `arm` registers state/usage-warner.check.sh through
bin/fm-check-register.sh. There is no daemon.

Warnings post through macOS Notification Center with the same osascript
call bin/fm-supervise-daemon.sh's wedge alarm makes, without sourcing or
coupling to that daemon's away-mode-specific config and rate limiting.
Delivery is edge-triggered against state/.usage-warner: a crossing warns
once, stays quiet while it holds, and re-arms when the window next reads
back below its threshold, the same standing-report contract
fm-mail-check.sh and fm-tool-update-check.sh already use.

bin/fm-procevent-quota.sh already reads the same snapshot, so docs name
the boundary rather than leaving two similar surfaces unexplained. That
source fires at most once, wakes firstmate with a durable check event,
and compares a provider's aggregate effectivePercentRemaining. This
warner is the standing, human-facing half: per-window, delivered to the
person through Notification Center, and self-re-arming. Neither replaces
the other and arming both is reasonable.

Opt-in is load-bearing and enforced in code. With no valid directive,
`check` returns before any read and `arm` refuses, so an unconfigured
home gains no behaviour change, no new failure mode, and no new hard
dependency at dispatch. Notification Center is macOS-only, so `arm`
refuses on other platforms instead of registering a check that could
never speak.

The warner only warns. It does not stop or pace dispatch, and its
coverage is exactly what quota-axi can see locally, so a plan or
organisation spend cap quota-axi does not report is not covered; the doc
says so rather than implying coverage it does not have.

The new test script carries no measured CI duration hint yet, so the
portable-serial lane balances it on the conservative default until the
hints are next refreshed from a green run, per docs/fm-test-portable-shards.md.

* no-mistakes(review): Key usage-warner de-dupe on window and threshold; fix docs

* no-mistakes(review): Keep absent-window crossings recorded; stub osascript in tests

* no-mistakes(document): Document absent-window de-dupe carry-forward in usage-warner header

* no-mistakes(review): Serialize usage-warner check, dedupe directives, drop vacuous greps

* no-mistakes(document): List usage-warner check lock in state layout

---------

Co-authored-by: Kun Chen <[email protected]>
Co-authored-by: Kostadin Pop-Kochev <[email protected]>
Co-authored-by: Niranjan <[email protected]>
Co-authored-by: Girik Bajaj <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>

* fix(bin): stabilize remote worker process identity (#6440)

* fix(bin): use clock-stable /proc starttime for remote job worker ownership

Linux remote job ownership compared ps lstart, which drifts on WSL2 while
/proc starttime stays fixed, so ensure treated a healthy worker as dead and
started another supervisor on every call. fm_remote_job_process_start now emits
a proc-starttime token when /proc is readable and falls back to ps lstart
otherwise. The Linux start path hands a live worker of the configured root
whose lock still records a legacy start over to one replacement, checked
against the recorded and live command so no unrelated pid is signaled.

Fixes #2921

* no-mistakes(review): Treat legacy lstart claim starts as indeterminate, not mismatched

* no-mistakes(test): Assert legacy handoff interrupts job once

* no-mistakes(test): Remove scratch debug test; legacy job case git-tracked

* no-mistakes(test): Revert legacy start comparator; simplify legacy handoff test

* fix(bin): drop automatic legacy worker upgrade; document manual one-time restart

* chore: remove stray file

* no-mistakes(document): Drop stale handoff mention from remote worker docs

* fix(bin): verify pre-update remote job workers via legacy lstart

When a recorded start lacks the proc-starttime= prefix, compare it against
ps -o lstart= without LC_ALL=C so a healthy pre-update worker still verifies.
The ordinary code-identity path then replaces it once instead of piling
supervisors. Add regression coverage for the bare-lstart cookie and the
lock upgrade path.

* no-mistakes(document): Clarify legacy remote-job start verification docs

* no-mistakes(review): Preserve C-locale legacy cookie verification, captain

* no-mistakes(document): Clarify legacy process identity cookie compatibility

* no-mistakes(lint): Replace deprecated fgrep with lint-compliant grep -F

---------

Co-authored-by: Pitch Perfekt Collective <[email protected]>
Co-authored-by: mehulbhagwani <[email protected]>

* feat(bin): add persistent managed-approval failover for Codex and Claude (#6722)

* fix: use managed-compatible worker approval modes

* no-mistakes(document): update codex and claude worker approval mode docs

* no-mistakes(ci): Fixed two test files that weren't updated when the PR changed the default claude permission mode from `--dangerously-skip-permissions` (bypass) to `--permission-mode auto`. Changes: - `tests/fm-claude-trust.test.sh` lines 664 and 696: updated two `assert_grep` assertions from `claude --dangerously-skip-permissions` → `claude --permission-mode auto` - `tests/fm-backend-orca.test.sh` line 568: updated one `assert_contains` assertion from `claude --dangerously-skip-permissions` → `claude --permission-mode auto` Both tests now pass locally (orca: exit=0, backend-dispatch/claude-trust: exit=0)

* fix: remove stray scratch directories from tests/

tests/.tmp-managed-approvals-test.bBuGhY/ and tests/.tmp-managed-approvals2.exz2qr/
were accidentally committed as worktree-local scratch dirs and do not belong in the repo.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>

* fix: preserve bypass defaults with persistent managed approval failover

* no-mistakes(review): fix approve-for-me fixture and bypass diagnostic messages

* no-mistakes(review): restore absent-Claude-default test and fix pass messages

* fix: recognize managed Codex approval prompts in the C locale

* no-mistakes(review): Fix managed approval failover bounds, authorization, inheritance, and capture

* Simplify managed approval recovery to persistent explicit failover

* no-mistakes(review): Guard failover authorization and unlink staging before recovery

* no-mistakes(document): Correct managed approval documentation and consolidate owner references

* no-mistakes(document): Correct managed-approval references and stale hook guarantees

* fix: require approval and inherit managed modes from primary

* no-mistakes(document): Clarify live hook verification scope

* no-mistakes(review): Remove dead approval_configured key from relaunch metadata

* fix: resurface queued wakes from handling successors (#7466)

* fix(bin): resurface wakes appended while a handling successor is parked

The supervision host parks on the handling successor it starts for a wake
its engine handled, and a handling successor never resurfaced recovery, so
a row another script appended during the park (a captain inbox note from
the Basecamp integration) sat queued until an unrelated close - four hours
in the observed case.

A handling successor now records the newest queued sequence at its start
and closes once with the recovery wake while a newer row is still queued;
a newer row already consumed only advances that mark, so the predecessor's
delivered episode is still never re-announced.

Follow-ups, not built here:
- A row appended in the short window between a handled close and its
  successor's start (about a second) is below the successor's mark; if the
  engine handles that close without claiming the row, the row waits for the
  next close. Closing that window needs the host to treat rows left queued
  after a handled attended turn as main's, which is a separate host change.
- After a machine reboot the primary session does not restart on its own,
  so queued wakes wait until it is resumed by hand. Either auto-resume the
  primary session after boot, or alert the owner when the primary session
  is down while wakes are queued.

* no-mistakes(review): Close handling-successor startup wake race

* no-mistakes(test): Stabilize parked-host inbox wake regression timeout

* no-mistakes(document): Clarify handling-successor wake continuity guarantees

* no-mistakes(ci): Stabilized the flaky remote secondmate lifecycle test by extending the auto-relaunch watcher deadline from ~30 to ~60 seconds. The CI runner exceeded the old deadline by about 3 seconds; the changed production branch was not reachable in this fixture. `bash -n` and `git diff --check` pass. The full test was attempted but exceeded the 600-second local execution limit before reaching this case

* no-mistakes(ci): Fixed flaky concurrent Herdr recovery testing by retrying only documented session-lock contention after both competitors finish. Cleanup now handles fixture-owned read-only hooks. Targeted E2E passed; bash syntax and diff checks passed. Shellcheck reported only existing SC1091 source-following notices

* no-mistakes(test): Preserve successor wake boundaries across handoffs

* no-mistakes(test): Revert successor boundaries and drain teardown fixture wake

* no-mistakes(test): Notify main when downtime handback publication fails

* no-mistakes(test): Revert downtime handback notification changes

* no-mistakes(document): Correct stale supervision wake routing documentation

* fix(bin): stop the supervision host deadlocking and re-announcing handed-back closes

Two defects in this branch's handling-successor changes surfaced as the
"Behavior portable serial 2" shard hanging at its 30-minute limit.

A TERM that lands while the host settles a handled turn's successor handoff
left the host holding the wake-queue and recovery-marker locks; its exit
cleanup then waited forever on the queue lock it still owned. The cleanup now
releases those locks if this process owns them before releasing its grant.

When an accepted close turns main-only at its turn, the host hands it back and
leaves the successor running, but republished the episode as pending
downtime, so that successor re-announced the same close and exited. The
handback now republishes the episode as already announced; a later durable
append still opens a pending episode the successor recovers.

* no-mistakes(test): Park on successor after handling settlement failure

* no-mistakes(test): Use tab-delimited handled-settlement failure logs

---------

Co-authored-by: Caleb LeNoir <[email protected]>

* fix(bin): preserve accents in pending-reply summaries (#7618)

* fix(bin): keep accented letters in pending-reply request summaries

fm_pending_reply_summarize deleted every byte outside printable ASCII, so a Portuguese summary lost its accents: "não faça a correção" was stored as "no faa a correo". It now removes control characters only. The 120-character cap counts UTF-8 characters from lead bytes, so it never splits a letter under any caller locale, including the C locale.

* no-mistakes(document): Documentar preservação de acentos nos resumos

---------

Co-authored-by: Alexandre Custodio <[email protected]>

* feat: add OpenRouter support for typed dispatch resolution (#7149)

* Add explicit OpenRouter Jev dispatch resolution

* no-mistakes(document): Clarify dispatch documentation and remove stale duplicates

* chore: exclude local Stele binding from PR

* no-mistakes(document): Correct dispatch help and never-send documentation

* ci: retrigger CI after a timed-out test shard

* no-mistakes(document): Correct dispatch architecture documentation ownership

* feat(bin): publish lane capacity facts with beat pressure and keyed limits (#6983)

Opt-in: fm-watch.sh publishes state/lane-capacity.json via bin/fm-capacity.sh --publish only while config/lane-capacity exists; adds beat pressure and keyed limits to fm-capacity.sh. Unconfigured fm-capacity output unchanged.

* fix(bin): propagate contribution input assembly failures (#5359)

* fix(bin): transport contribution-input JSON through slurpfile, not argjson

bin/fm-fleet-snapshot.sh --contribution-input passed the full backlog and
task-record JSON to jq through --argjson. A single --argjson argument is
capped by the kernel's MAX_ARG_STRLEN (131072 bytes on Linux), so a large
enough backlog made the kernel refuse to exec jq while the script still
exited 0 with a broken result.

Transport both documents through temporary files and --slurpfile, matching
the pattern the default snapshot path already uses, and propagate a
non-zero exit when that jq invocation fails.

Fixes #5349

* test: narrow contribution-input regression to final assembly failure

The ARG_MAX transport is already fixed on main by #6830, so keep only the regression proving a failing final jq assembly exits non-zero.

* fix: correct Rex secondmate grouping and lifecycle (#7656)

* Fix Rex secondmate session lifecycle

* no-mistakes(review): Retire Rex secondmate sessions under the owning home identity

* no-mistakes(review): Limit Rex FM_ROOT label override to secondmate launches

* no-mistakes(document): Clarify Rex secondmate grouping and lifecycle documentation

* feat(opencode): add OpenCode 2 support with version-gated launch, plugins, and exit (#7336)

* feat(opencode): add OpenCode 2 support with version-gated launch and plugins

OpenCode 2 dropped the v1 server-plugin hook API, so the five fm.primary.*
plugins now export a default definition with an id and a setup function
alongside their legacy OpenCode 1 server export, backed by a new shared
lib/fm-opencode2.js helper; the turn-end guard, watch-arm, cd-check,
pretool-check, and sessionstart-nudge install their behavior from setup(ctx)
on OpenCode 2 and keep the server entrypoint for OpenCode 1.

fm-spawn probes the resolved opencode executable's --version once and branches
the launch, model flag, reasoning config, exit key, and busy-state plugin off
the detected major. A parsed major >= 2 takes the OpenCode 2 shape (no --model,
the model pinned through OPENCODE_CONFIG_CONTENT, a raw Ctrl-C exit, the
session.execution.* busy plugin); OpenCode 1.x and any undetected or
unparseable version fall back to the 1.x shape (--model, 1.x config, /exit)
everywhere. The worker busy-state plugin is always provisioned, but OpenCode 1
keeps the pre-port session.status/session.idle plugin so its busy-state wiring
is unchanged, and only a major >= 2 gets the session.execution plugin. Adapter
and supervision docs, OpenCode 2 live fixtures, and regression tests for the
unknown->1.x launch path and the version-gated busy-plugin shape are included.

* no-mistakes(review): gate OpenCode 2 busy plugin turn-end touch on notifyTurnEnd

* feat(opencode): launch detected OpenCode 2 workers with --standalone

OpenCode 2's default launch attaches to the shared background service, which
hosts plugins with the service's environment and ignores the pane's
OPENCODE_CONFIG_CONTENT. A private server keeps per-worker model, permissions,
FM_HOME, and lock ancestry correct. 1.x and undetected versions are unchanged.

Ported from https://github.com/kunchenguid/firstmate/pull/5143.

Co-authored-by: Girik Bajaj <[email protected]>

* fix(opencode): resolve the OpenCode 2 project location and treat every terminal turn as a turn end

OpenCode 2.0.x hands plugins the project only as ctx.location.project.directory
and takes ctx.session.prompt({ sessionID, text }), so the V2 setup path never
found its root or delivered a prompt. Interrupted and failed turns now end a
turn like a succeeded one, while a server shutdown does not.

Ported from https://github.com/kunchenguid/firstmate/pull/5143.

Co-authored-by: Girik Bajaj <[email protected]>

* test(opencode): add a token-free OpenCode 2 native plugin fixture to the live e2e

A private opencode serve plus a loopback provider proves the five primary
plugins load and act on OpenCode 2: startup nudge, cd and watcher-redirection
guards, turn-end guard, watcher arming across succeeded, interrupted, and
failed turns. The fixture declares the complete model capabilities object,
which OpenCode 2.0.11 requires and 2.0.22 accepts. FM_OPENCODE_LIVE_BINS runs
it across several OpenCode 2 executables. The credentialed half now picks its
run flags and session tables by detected major, so it keeps working on 1.x.

Fixture ported from https://github.com/kunchenguid/firstmate/pull/5143.

Co-authored-by: Girik Bajaj <[email protected]>

* feat(opencode): send one Enter when an OpenCode 2 launch leaves the brief unsent

OpenCode 2.0.11 prefills the --prompt brief without submitting it, while 2.0.22 submits it.
After launch, fm-spawn waits for the worker's busy-state plugin to report the turn start, sends one Enter only if it has not started and the composer is not empty, and fails the spawn if the turn never starts.

* docs(opencode): document the OpenCode 2 launch, delivery gate, and standalone primary homes

Records the 2.0.11 and 2.0.22 live evidence for the native plugin fixture and the post-launch brief delivery gate.

* no-mistakes(review): Trim OpenCode 2 adapter shapes and harden Ctrl-C exit

* no-mistakes(review): Record OpenCode 2 live seatbelt and exit evidence

* no-mistakes(test): Document OpenCode 2.0.22 wide-pane sidebar exit refusal limitation

* no-mistakes(document): Refresh OpenCode 2 exit-key and seatbelt payload docs

* test(opencode): verify OpenCode 1.x live with the dual-export plugins

Pin the live e2e TUI panes to the resolved opencode executable, and record
OpenCode 1.15.7, 1.18.20, and 1.18.31 evidence for plugin loading, the
turn-end guard, watcher continuity, and 1.x worker launch and exit.

* no-mistakes(review): Defer OpenCode 2 Enter on unknown composer; widen turn-end docs

* no-mistakes(document): Document OpenCode 2 delivery gate unknown-composer test outcomes

---------

Co-authored-by: Niranjan <[email protected]>
Co-authored-by: Girik Bajaj <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>

* fix(bin): resolve the tmux container from firstmate's own session, not the most recent group member (#7662)

* fix(bin): resolve the tmux container from the caller's own session, not the most recent group member

* no-mistakes(test): Fall back when the $TMUX session id is stale

* no-mistakes(document): Document tmux container choice under grouped sessions

* fix(bin): read a fully dim Cursor idle placeholder as an empty composer (#7647)

* fix(bin): read a fully dim Cursor placeholder as an empty composer

cursor-agent 2026.10.19 draws the composer glyph and its idle placeholder
as one SGR 2 run with no reverse-video cell, so ghost stripping empties the
row and the empty-content guard returned unknown. Relaunch and exit then
refused on every idle Cursor pane on tmux.

When a styled bare row strips to empty and the plain row is an agent glyph
followed by an anchored idle placeholder, read it empty. Bright typed text,
other dim text, and unstyled rows keep their existing verdicts.

Fixes #7413

* docs(verification): record the fully dim Cursor placeholder verdict and refresh command

* fix(bin): say why away-mode inject deferred and pin named Claude idle composer as empty (#6163)

* fix(bin): recognize a named Claude session's titled composer rule on cursorless backends

`claude -n <name>` right-aligns the session name in the rule above the
composer. Cursorless backends (Herdr) accepted only solid rules, so the
scan saw the lower rule alone, the idle composer read `unknown`, and
away-mode delivery to a named Claude primary deferred until return.

A rule carrying one right-aligned title now opens a separator pair. It
never closes one, the pair it opens counts only over an agent-glyph row,
and it is never a valid Pi pair, so Pi's verdict is unchanged.

The away-mode composer deferral now names which refusal it was:
unsubmitted text, or no composer shape recognized.

* no-mistakes(review): Reword composer deferral reason to cover busy harness

* no-mistakes(ci): ci-3 (Greptile, user chose to fix): The rule that must always hold is that Claude's titled opening rule is accepted for any non-empty session name that doesn't start with a space and doesn't contain the rule glyph `─`, including a multiword name. The only place that check lives is the title `case` in `_fm_composer_titled_rule_row` (bin/fm-composer-lib.sh). It now reads `case "$title" in ''|' '*|*─*) return 1 ;; esac`, as the user asked, and the comment above the function mentions multiword titles. I added regression fixtures to `test_matrix_claude_named_session_titled_rule` in tests/fm-composer-lib.test.sh, next to the existing single-word `Andrew` cases. They use the title `Andrew Chen` and check that an idle composer on herdr reads `empty` and a composer with typed text reads `pending`. Something you should know: the old pattern already accepted a title with a space in the middle. It only rejected a title ending in a space. So the new multiword fixtures also pass against the old code, and the bot's failure scenario did not actually happen for "Andrew Chen". What the fix really changes is that it drops the trailing-space rejection, as instructed. Checks run: tests/fm-composer-lib.test.sh and tests/fm-composer-ghost.test.sh both pass (exit 0, no failures), and `shellcheck -x` is clean on both changed files

* no-mistakes(review): Match unnamed-ghost fixture rule width to the partner rule

* fix: use managed-compatible worker approval modes

* no-mistakes(document): update codex and claude worker approval mode docs

* no-mistakes(ci): Fixed two test files that weren't updated when the PR changed the default claude permission mode from `--dangerously-skip-permissions` (bypass) to `--permission-mode auto`. Changes: - `tests/fm-claude-trust.test.sh` lines 664 and 696: updated two `assert_grep` assertions from `claude --dangerously-skip-permissions` → `claude --permission-mode auto` - `tests/fm-backend-orca.test.sh` line 568: updated one `assert_contains` assertion from `claude --dangerously-skip-permissions` → `claude --permission-mode auto` Both tests now pass locally (orca: exit=0, backend-dispatch/claude-trust: exit=0)

* fix: remove stray scratch directories from tests/

tests/.tmp-managed-approvals-test.bBuGhY/ and tests/.tmp-managed-approvals2.exz2qr/
were accidentally committed as worktree-local scratch dirs and do not belong in the repo.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>

* fix: preserve bypass defaults with persistent managed approval failover

* no-mistakes(review): fix approve-for-me fixture and bypass diagnostic messages

* no-mistakes(review): restore absent-Claude-default test and fix pass messages

* fix: recognize managed Codex approval prompts in the C locale

* no-mistakes(review): Fix managed approval failover bounds, authorization, inheritance, and capture

* Simplify managed approval recovery to persistent explicit failover

* no-mistakes(review): Guard failover authorization and unlink staging before recovery

* no-mistakes(document): Correct managed approval documentation and consolidate owner references

* no-mistakes(document): Correct managed-approval references and stale hook guarantees

* fix: require approval and inherit managed modes from primary

* no-mistakes(document): Clarify live hook verification scope

* no-mistakes(review): Remove dead approval_configured key from relaunch metadata

---------

Co-authored-by: Claude Sonnet 4.6 <[email protected]>
Co-authored-by: Caleb LeNoir <[email protected]>
Co-authored-by: Caleb LeNoir <[email protected]>
Co-authored-by: Alexandre Custodio <[email protected]>
Co-authored-by: Alexandre Custodio <[email protected]>
Co-authored-by: Pedro Guimarães <[email protected]>
Co-authored-by: Konner Moshier <[email protected]>
Co-authored-by: Oscar Santis Brante <[email protected]>
Co-authored-by: Kun Chen <[email protected]>
Co-authored-by: Kostadin Pop-Kochev <[email protected]>
Co-authored-by: Niranjan <[email protected]>
Co-authored-by: Girik Bajaj <[email protected]>
Co-authored-by: Tomas Perez <[email protected]>
Co-authored-by: Cameron Aragon <[email protected]>
Co-authored-by: Brian <[email protected]>

* fix(bin): keep handling successors from stranding inbox wakes after counter loss (#6467)

* fix: notify handling successors about newer inbox wakes

* no-mistakes(document): Document handling-successor inbox regression in watcher coverage list

* no-mistakes(ci): Fixed Greptile P1 (comment 4172295712): a handling successor could miss a new inbox wake when `.wake-queue.seq` was missing or malformed. What must always hold: a row added after the successor took its snapshot must be announced and must never be consumed by an older acknowledgement. Two places were breaking this: 1. `bin/fm-watch.sh`: the successor only recorded the highest inherited sequence number. If the counter was reset, a new row could get a number at or below that and be treated as already covered. This now stays silent forever once the inherited rows are acknowledged and the queue drains. 2. `bin/fm-wake-lib.sh` `fm_wake_append_locked`: a reset counter reused the sequence number of a row still in the queue. The predecessor's pending `--ack-through` consumes rows by sequence number, so it deleted the new row before anyone handled it. This was a gap in the existing allocator, and it is what made the before-ack cases fail even after fix 1. Fixes: - Watcher: the successor now snapshots the inherited rows themselves instead of their highest sequence. On each poll it announces if any queued row is not in that snapshot. It still never consumes rows, and inherited rows alone stay silent. - Allocator: the next sequence is now one more than the larger of the counter and the highest sequence still queued, so a new row can't land inside an outstanding acknowledgement's range. - `docs/watcher-continuity.md`: the paragraph and coverage list are updated to match. Tests: `test_append_wakes_handling_successor` in `tests/fm-watch-arm.test.sh` now inherits two rows and takes a counter state (intact, missing, malformed). The four new cases are after-ack and before-ack with a missing or malformed counter, and they run real watcher, arm and drain processes. In after-ack the queue is fully drained before the new append. Evidence: - Before any production change (on 92c724d), all four new cases failed: "not ok - handling successor stranded the second inbox wake" for after-ack and before-ack. - With only the watcher fix, the after-ack cases passed and the before-ack cases still failed, which shows the allocator fix is needed. - With both fixes, all four pass. Full results: `fm-watch-arm` 36/36 (including the intact after-ack and before-ack cases, so ordinary silence and fresh-beacon delivery still hold), `fm-watch-recovery-loop` 2/2, `fm-inbox` 16/16, `fm-pi-watch-extension` 60/60, `fm-wake-queue` 67/67, and all four `fm-wake-drain-*` suites passed (9, 9, 18, 14). Canonical `bin/fm-lint.sh` with `PATH=/home/nino/.local/bin:$PATH` passed: ShellCheck clean, actionlint 1.7.12, 3 workflows valid. That lint run was in local changed-file mode with ShellCheck source following disabled. In a first run of all nine suites in parallel, `fm-wake-queue` failed on "presentation lock delayed the drain for 10s" and one `fm-pi-watch-extension` timing test failed. Both passed in full when rerun on their own, so I read that as load contention, not this change. Design decision to flag: the allocator change sits in the shared wake library, so it goes beyond the watcher comparison the bot pointed at. It is a one-expression change, and the before-ack tests can't pass without it, because otherwise the predecessor's acknowledgement deletes the new message. Not done, per the phase boundary: nothing committed, pushed or posted, and the live fleet was not touched. Evidence logs are in /tmp/fmci, not in a pipeline logs/evidence directory

* no-mistakes(ci): Fixed both Greptile findings on PR #6467. Nothing was committed, pushed or posted, and the live fleet was not touched. **ci-1 (4172409813): a new wake was mistaken for an inherited one.** - Invariant that must hold: a successor treats a row as covered only if it is an unchanged inherited row in the inherited recovery episode. - Cause: after the predecessor's acknowledgement and a lost counter, a re-append with the same kind, key, payload and epoch was byte-identical to the snapshot row, so the successor stayed silent. - Fix (`bin/fm-watch.sh`): I used the existing recovery generation rather than a new identity scheme. Any append after an acknowledgement mints a new generation. The successor records the generation with its row snapshot, under the queue lock and in arm-check's lock order. Each poll counts the queue as newer if a row is not in the snapshot, or if the queue is non-empty and the generation changed. The existing arm-check then decides whether to announce. No rows are consumed, and inherited rows alone stay silent. - The row snapshot is still needed for before-ack, because an append before the acknowledgement keeps the same generation. **ci-2 (4172409821): large sequence numbers became unusable.** - Invariant that must hold: sequence numbers are always exact digit-only decimals. - Fix (`bin/fm-wake-lib.sh`): the allocator picks the largest of the counter and the queued sequences by comparing decimal text (length, then string order, leading zeros stripped), then adds 1 in bash with `$((10#$seq + 1))`. This restores the 64-bit exactness of the original bash counter. - Same fix at two places in `bin/fm-wake-drain.sh` that print sequences: `presented_max_row` and `ACK_THROUGH` print the matched text instead of `max + 0`. **Tests** - `tests/fm-watch-arm.test.sh`: two new `identical` cases, after-ack with a missing and with a malformed counter. A fake `date` pins the epoch, and the test asserts the row is byte-identical, then checks timely notification, preservation until its own acknowledgement, and no repeat notification. - `tests/fm-wake-queue.test.sh`: new `test_large_sequences_stay_exact_decimal_identifiers` starts from 2147483647, 9007199254740991 and 9223372036854775806, each with an intact, missing and malformed counter. It checks the next sequence is exact and digit-only. For the first two it also checks a real drain shows both rows, names the exact acknowledgement sequence, and acknowledging empties the queue. - `docs/watcher-continuity.md` now describes the generation check. **Evidence** (in `/home/nino/.no-mistakes/evidence/01M40CDTX2000A5TFFRZN27YFR/ci-round3/`) - Before, on 050a5fc: both identical cases failed with "handling successor stranded the second inbox wake (after-ack)". The large-sequence test failed with "advanced to '9223372036854775808', not 9223372036854775807". - After the fix, all three pass (`after-*.log`). - All nine suites passed, each run on its own, all with 0 not ok (`final-results.txt`): `fm-wake-queue` 68/68, `fm-watch-arm` 38/38, `fm-watch-recovery-loop` 2/2, `fm-inbox` 16/16, `fm-pi-watch-extension` 60/60, `fm-wake-drain-open-decisions-cursor` 9/9, `fm-wake-drain-open-decisions` 9/9, `fm-wake-drain-outcome-backstop` 18/18, `fm-wake-drain-unread-status` 14/14. - `bin/fm-lint.sh` with `PATH=/home/nino/.local/bin:$PATH` passes: ShellCheck clean, actionlint 1.7.12, 3 workflows valid (local changed-file mode). **Not run** - The only OpenCode suite is an opt-in live test, so I did not run it. **Limits** - The 2.14748e+09 symptom doesn't reproduce with the awks here (gawk, mawk 1.3.4, busybox). The failure reproduced locally is the precision loss at 64-bit values. - The drain's awk comparisons are only exact up to 2^53. That predates this PR and I left it alone, so the drain test stops at 2^53

* no-mistakes(document): Reattach successor poll-loop sentence to its subject

* fix(bin): stop lock waits and test fixtures from spinning after their directory is removed (#7685)

* fix(tests): bound lock waits on removed dirs and reap fixture-root processes

A lock wait spun every 0.1s forever once its directory was removed, so a
watcher or reconcile scan of a deleted test home never reached its own
home-gone exit. fm_lock_acquire_wait now returns within 0.2s once the
lock's parent directory is gone.

Test teardown now signals every process naming the exact fixture root
(TERM, then KILL) before removing it, in both fm_test_cleanup and the
orphan sweep. The supervision-host fake harness sessions stop once their
home is gone or the suite pid has died, so a hard-killed runner no longer
leaves them polling under init.

Fixes #7672

* fix(tests): bound the session-lock concurrency barrier

Forty workers polled a find pipeline every 0.01s to wait for each other,
so the barrier alone launched thousands of processes a second, and once a
stopped run removed the barrier directory the workers polled forever under
init. Count entries with a builtin glob every 0.05s, and end the wait once
the directory is gone, the suite has died, or the stub block bound passes.

Refs #7672

* fix: watch review-bot findings on owned pull requests (#7499)

* fix(bin): admit listed review-bot comments as contribution signals

* no-mistakes(review): Persist review-bot config in contribution check shim

* no-mistakes(review): Classify allowlisted collaborators as review bots

* no-mistakes(document): Document review-bot contribution signals

* no-mistakes(review): Preserve review-bot config and re-raise classification

* no-mistakes(review): Prevent acknowledged bot signals replaying after allowlist changes

* no-mistakes(document): Document configurable review-bot contribution watching

* no-mistakes(document): Clarify review-bot thread documentation

* fix(bin): make review-bot contribution watching opt-in

* docs(bin): state review-bot allowlist has no built-in default

* no-mistakes(document): Document per-home review-bot configuration

---------

Co-authored-by: Caleb LeNoir <[email protected]>

* fix(brief): drop undefined heavy-test slot from the Waiting section (#7674)

The generated Waiting section told workers to wait on a heavy-test slot that nothing in the repository defines. Remove the phrase and assert that a brief generated with config/wait-no-turns does not name one.

* fix(bin): read the no_ci ci-monitor marker as no-checks (#7675)

* fix(bin): read the no_ci ci-monitor marker as no-checks instead of validating

Fixes #7644

* no-mistakes(document): Rewrap nm_ci_checks_state no_ci comment

* feat(bin): add opt-in restricted permission mode for Codex workers (#7683)

* feat: add opt-in restricted permissions for Codex workers

* no-mistakes(review): Document restricted Codex network and git approval limits

* fix(test): keep serial packing at-budget fixture stable with unhinted scripts (#7699)

* fix(test): keep serial packing at-budget when a script has no hint

tests/fm-approval-failover.test.sh landed without a serial duration hint,
so the at-budget packing fixture overflowed by 1040ms. Record a measured
5410ms hint and give the fixture its own complete hint table so unmeasured
defaults cannot join the boundary shard.

Co-authored-by: Kun Chen <[email protected]>

* docs: note the local approval-failover packing hint

Record the 5410 ms provisional local sample for the next CI refresh,
and describe the packi…
jredgard added a commit to jredgard/firstmate that referenced this pull request Nov 15, 2026
…cts (#57)

* feat(bin): add opt-in local Claude usage threshold warner (#7421)

* feat(bin): add opt-in local Claude usage threshold warner

A usage window is exhausted without warning: work is cut off mid-run
rather than stopping deliberately, and nothing says a window is close to
its cap until it is already gone.

bin/fm-usage-warner.sh is a threshold warner, not a usage viewer.
quota-axi is already the one Claude-quota reader this repo depends on
(bin/fm-quota-axi-lib.sh), so the warner runs that existing read rather
than adding a second reader that could drift from it: one bounded
`quota-axi --provider claude --json --full --no-credential-refresh`, the
snapshot validated with fm_quota_json_valid, and the provider row picked
with the same FM_QUOTA_ROW_JQ join the dispatch consumers use, under
schema 5 and schema 6 alike.

Thresholds are `<window-id>:<percent>` directives in config/usage-warner,
naming quota-axi's own window ids (five_hour, seven_day, model:<name>)
rather than a second vocabulary, and compared against each window's own
percentUsed. Naming the window is the point: the session and weekly
windows exhaust at very different times, so a figure that does not say
which window is close misleads.

One read with two callers and no new schedule: `check` is what a human
runs on demand and what the watcher runs on its ordinary check-shim
cadence once `arm` registers state/usage-warner.check.sh through
bin/fm-check-register.sh. There is no daemon.

Warnings post through macOS Notification Center with the same osascript
call bin/fm-supervise-daemon.sh's wedge alarm makes, without sourcing or
coupling to that daemon's away-mode-specific config and rate limiting.
Delivery is edge-triggered against state/.usage-warner: a crossing warns
once, stays quiet while it holds, and re-arms when the window next reads
back below its threshold, the same standing-report contract
fm-mail-check.sh and fm-tool-update-check.sh already use.

bin/fm-procevent-quota.sh already reads the same snapshot, so docs name
the boundary rather than leaving two similar surfaces unexplained. That
source fires at most once, wakes firstmate with a durable check event,
and compares a provider's aggregate effectivePercentRemaining. This
warner is the standing, human-facing half: per-window, delivered to the
person through Notification Center, and self-re-arming. Neither replaces
the other and arming both is reasonable.

Opt-in is load-bearing and enforced in code. With no valid directive,
`check` returns before any read and `arm` refuses, so an unconfigured
home gains no behaviour change, no new failure mode, and no new hard
dependency at dispatch. Notification Center is macOS-only, so `arm`
refuses on other platforms instead of registering a check that could
never speak.

The warner only warns. It does not stop or pace dispatch, and its
coverage is exactly what quota-axi can see locally, so a plan or
organisation spend cap quota-axi does not report is not covered; the doc
says so rather than implying coverage it does not have.

The new test script carries no measured CI duration hint yet, so the
portable-serial lane balances it on the conservative default until the
hints are next refreshed from a green run, per docs/fm-test-portable-shards.md.

* no-mistakes(review): Key usage-warner de-dupe on window and threshold; fix docs

* no-mistakes(review): Keep absent-window crossings recorded; stub osascript in tests

* no-mistakes(document): Document absent-window de-dupe carry-forward in usage-warner header

* fix: correct Rex secondmate grouping and lifecycle (#7656)

* Fix Rex secondmate session lifecycle

* no-mistakes(review): Retire Rex secondmate sessions under the owning home identity

* no-mistakes(review): Limit Rex FM_ROOT label override to secondmate launches

* no-mistakes(document): Clarify Rex secondmate grouping and lifecycle documentation

* feat(opencode): add OpenCode 2 support with version-gated launch, plugins, and exit (#7336)

* feat(opencode): add OpenCode 2 support with version-gated launch and plugins

OpenCode 2 dropped the v1 server-plugin hook API, so the five fm.primary.*
plugins now export a default definition with an id and a setup function
alongside their legacy OpenCode 1 server export, backed by a new shared
lib/fm-opencode2.js helper; the turn-end guard, watch-arm, cd-check,
pretool-check, and sessionstart-nudge install their behavior from setup(ctx)
on OpenCode 2 and keep the server entrypoint for OpenCode 1.

fm-spawn probes the resolved opencode executable's --version once and branches
the launch, model flag, reasoning config, exit key, and busy-state plugin off
the detected major. A parsed major >= 2 takes the OpenCode 2 shape (no --model,
the model pinned through OPENCODE_CONFIG_CONTENT, a raw Ctrl-C exit, the
session.execution.* busy plugin); OpenCode 1.x and any undetected or
unparseable version fall back to the 1.x shape (--model, 1.x config, /exit)
everywhere. The worker busy-state plugin is always provisioned, but OpenCode 1
keeps the pre-port session.status/session.idle plugin so its busy-state wiring
is unchanged, and only a major >= 2 gets the session.execution plugin. Adapter
and supervision docs, OpenCode 2 live fixtures, and regression tests for the
unknown->1.x launch path and the version-gated busy-plugin shape are included.

* no-mistakes(review): gate OpenCode 2 busy plugin turn-end touch on notifyTurnEnd

* feat(opencode): launch detected OpenCode 2 workers with --standalone

OpenCode 2's default launch attaches to the shared background service, which
hosts plugins with the service's environment and ignores the pane's
OPENCODE_CONFIG_CONTENT. A private server keeps per-worker model, permissions,
FM_HOME, and lock ancestry correct. 1.x and undetected versions are unchanged.

Ported from https://github.com/kunchenguid/firstmate/pull/5143.

Co-authored-by: Girik Bajaj <[email protected]>

* fix(opencode): resolve the OpenCode 2 project location and treat every terminal turn as a turn end

OpenCode 2.0.x hands plugins the project only as ctx.location.project.directory
and takes ctx.session.prompt({ sessionID, text }), so the V2 setup path never
found its root or delivered a prompt. Interrupted and failed turns now end a
turn like a succeeded one, while a server shutdown does not.

Ported from https://github.com/kunchenguid/firstmate/pull/5143.

Co-authored-by: Girik Bajaj <[email protected]>

* test(opencode): add a token-free OpenCode 2 native plugin fixture to the live e2e

A private opencode serve plus a loopback provider proves the five primary
plugins load and act on OpenCode 2: startup nudge, cd and watcher-redirection
guards, turn-end guard, watcher arming across succeeded, interrupted, and
failed turns. The fixture declares the complete model capabilities object,
which OpenCode 2.0.11 requires and 2.0.22 accepts. FM_OPENCODE_LIVE_BINS runs
it across several OpenCode 2 executables. The credentialed half now picks its
run flags and session tables by detected major, so it keeps working on 1.x.

Fixture ported from https://github.com/kunchenguid/firstmate/pull/5143.

Co-authored-by: Girik Bajaj <[email protected]>

* feat(opencode): send one Enter when an OpenCode 2 launch leaves the brief unsent

OpenCode 2.0.11 prefills the --prompt brief without submitting it, while 2.0.22 submits it.
After launch, fm-spawn waits for the worker's busy-state plugin to report the turn start, sends one Enter only if it has not started and the composer is not empty, and fails the spawn if the turn never starts.

* docs(opencode): document the OpenCode 2 launch, delivery gate, and standalone primary homes

Records the 2.0.11 and 2.0.22 live evidence for the native plugin fixture and the post-launch brief delivery gate.

* no-mistakes(review): Trim OpenCode 2 adapter shapes and harden Ctrl-C exit

* no-mistakes(review): Record OpenCode 2 live seatbelt and exit evidence

* no-mistakes(test): Document OpenCode 2.0.22 wide-pane sidebar exit refusal limitation

* no-mistakes(document): Refresh OpenCode 2 exit-key and seatbelt payload docs

* test(opencode): verify OpenCode 1.x live with the dual-export plugins

Pin the live e2e TUI panes to the resolved opencode executable, and record
OpenCode 1.15.7, 1.18.20, and 1.18.31 evidence for plugin loading, the
turn-end guard, watcher continuity, and 1.x worker launch and exit.

* no-mistakes(review): Defer OpenCode 2 Enter on unknown composer; widen turn-end docs

* no-mistakes(document): Document OpenCode 2 delivery gate unknown-composer test outcomes

---------

Co-authored-by: Niranjan <[email protected]>
Co-authored-by: Girik Bajaj <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>

* feat(bin): add opt-in local Claude usage threshold warner

A usage window is exhausted without warning: work is cut off mid-run
rather than stopping deliberately, and nothing says a window is close to
its cap until it is already gone.

bin/fm-usage-warner.sh is a threshold warner, not a usage viewer.
quota-axi is already the one Claude-quota reader this repo depends on
(bin/fm-quota-axi-lib.sh), so the warner runs that existing read rather
than adding a second reader that could drift from it: one bounded
`quota-axi --provider claude --json --full --no-credential-refresh`, the
snapshot validated with fm_quota_json_valid, and the provider row picked
with the same FM_QUOTA_ROW_JQ join the dispatch consumers use, under
schema 5 and schema 6 alike.

Thresholds are `<window-id>:<percent>` directives in config/usage-warner,
naming quota-axi's own window ids (five_hour, seven_day, model:<name>)
rather than a second vocabulary, and compared against each window's own
percentUsed. Naming the window is the point: the session and weekly
windows exhaust at very different times, so a figure that does not say
which window is close misleads.

One read with two callers and no new schedule: `check` is what a human
runs on demand and what the watcher runs on its ordinary check-shim
cadence once `arm` registers state/usage-warner.check.sh through
bin/fm-check-register.sh. There is no daemon.

Warnings post through macOS Notification Center with the same osascript
call bin/fm-supervise-daemon.sh's wedge alarm makes, without sourcing or
coupling to that daemon's away-mode-specific config and rate limiting.
Delivery is edge-triggered against state/.usage-warner: a crossing warns
once, stays quiet while it holds, and re-arms when the window next reads
back below its threshold, the same standing-report contract
fm-mail-check.sh and fm-tool-update-check.sh already use.

bin/fm-procevent-quota.sh already reads the same snapshot, so docs name
the boundary rather than leaving two similar surfaces unexplained. That
source fires at most once, wakes firstmate with a durable check event,
and compares a provider's aggregate effectivePercentRemaining. This
warner is the standing, human-facing half: per-window, delivered to the
person through Notification Center, and self-re-arming. Neither replaces
the other and arming both is reasonable.

Opt-in is load-bearing and enforced in code. With no valid directive,
`check` returns before any read and `arm` refuses, so an unconfigured
home gains no behaviour change, no new failure mode, and no new hard
dependency at dispatch. Notification Center is macOS-only, so `arm`
refuses on other platforms instead of registering a check that could
never speak.

The warner only warns. It does not stop or pace dispatch, and its
coverage is exactly what quota-axi can see locally, so a plan or
organisation spend cap quota-axi does not report is not covered; the doc
says so rather than implying coverage it does not have.

The new test script carries no measured CI duration hint yet, so the
portable-serial lane balances it on the conservative default until the
hints are next refreshed from a green run, per docs/fm-test-portable-shards.md.

* no-mistakes(review): Key usage-warner de-dupe on window and threshold; fix docs

* no-mistakes(review): Keep absent-window crossings recorded; stub osascript in tests

* no-mistakes(document): Document absent-window de-dupe carry-forward in usage-warner header

* no-mistakes(review): Serialize usage-warner check, dedupe directives, drop vacuous greps

* no-mistakes(document): List usage-warner check lock in state layout

---------

Co-authored-by: Kun Chen <[email protected]>
Co-authored-by: Kostadin Pop-Kochev <[email protected]>
Co-authored-by: Niranjan <[email protected]>
Co-authored-by: Girik Bajaj <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>

* fix(bin): stabilize remote worker process identity (#6440)

* fix(bin): use clock-stable /proc starttime for remote job worker ownership

Linux remote job ownership compared ps lstart, which drifts on WSL2 while
/proc starttime stays fixed, so ensure treated a healthy worker as dead and
started another supervisor on every call. fm_remote_job_process_start now emits
a proc-starttime token when /proc is readable and falls back to ps lstart
otherwise. The Linux start path hands a live worker of the configured root
whose lock still records a legacy start over to one replacement, checked
against the recorded and live command so no unrelated pid is signaled.

Fixes #2921

* no-mistakes(review): Treat legacy lstart claim starts as indeterminate, not mismatched

* no-mistakes(test): Assert legacy handoff interrupts job once

* no-mistakes(test): Remove scratch debug test; legacy job case git-tracked

* no-mistakes(test): Revert legacy start comparator; simplify legacy handoff test

* fix(bin): drop automatic legacy worker upgrade; document manual one-time restart

* chore: remove stray file

* no-mistakes(document): Drop stale handoff mention from remote worker docs

* fix(bin): verify pre-update remote job workers via legacy lstart

When a recorded start lacks the proc-starttime= prefix, compare it against
ps -o lstart= without LC_ALL=C so a healthy pre-update worker still verifies.
The ordinary code-identity path then replaces it once instead of piling
supervisors. Add regression coverage for the bare-lstart cookie and the
lock upgrade path.

* no-mistakes(document): Clarify legacy remote-job start verification docs

* no-mistakes(review): Preserve C-locale legacy cookie verification, captain

* no-mistakes(document): Clarify legacy process identity cookie compatibility

* no-mistakes(lint): Replace deprecated fgrep with lint-compliant grep -F

---------

Co-authored-by: Pitch Perfekt Collective <[email protected]>
Co-authored-by: mehulbhagwani <[email protected]>

* feat(bin): add persistent managed-approval failover for Codex and Claude (#6722)

* fix: use managed-compatible worker approval modes

* no-mistakes(document): update codex and claude worker approval mode docs

* no-mistakes(ci): Fixed two test files that weren't updated when the PR changed the default claude permission mode from `--dangerously-skip-permissions` (bypass) to `--permission-mode auto`. Changes: - `tests/fm-claude-trust.test.sh` lines 664 and 696: updated two `assert_grep` assertions from `claude --dangerously-skip-permissions` → `claude --permission-mode auto` - `tests/fm-backend-orca.test.sh` line 568: updated one `assert_contains` assertion from `claude --dangerously-skip-permissions` → `claude --permission-mode auto` Both tests now pass locally (orca: exit=0, backend-dispatch/claude-trust: exit=0)

* fix: remove stray scratch directories from tests/

tests/.tmp-managed-approvals-test.bBuGhY/ and tests/.tmp-managed-approvals2.exz2qr/
were accidentally committed as worktree-local scratch dirs and do not belong in the repo.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>

* fix: preserve bypass defaults with persistent managed approval failover

* no-mistakes(review): fix approve-for-me fixture and bypass diagnostic messages

* no-mistakes(review): restore absent-Claude-default test and fix pass messages

* fix: recognize managed Codex approval prompts in the C locale

* no-mistakes(review): Fix managed approval failover bounds, authorization, inheritance, and capture

* Simplify managed approval recovery to persistent explicit failover

* no-mistakes(review): Guard failover authorization and unlink staging before recovery

* no-mistakes(document): Correct managed approval documentation and consolidate owner references

* no-mistakes(document): Correct managed-approval references and stale hook guarantees

* fix: require approval and inherit managed modes from primary

* no-mistakes(document): Clarify live hook verification scope

* no-mistakes(review): Remove dead approval_configured key from relaunch metadata

* fix: resurface queued wakes from handling successors (#7466)

* fix(bin): resurface wakes appended while a handling successor is parked

The supervision host parks on the handling successor it starts for a wake
its engine handled, and a handling successor never resurfaced recovery, so
a row another script appended during the park (a captain inbox note from
the Basecamp integration) sat queued until an unrelated close - four hours
in the observed case.

A handling successor now records the newest queued sequence at its start
and closes once with the recovery wake while a newer row is still queued;
a newer row already consumed only advances that mark, so the predecessor's
delivered episode is still never re-announced.

Follow-ups, not built here:
- A row appended in the short window between a handled close and its
  successor's start (about a second) is below the successor's mark; if the
  engine handles that close without claiming the row, the row waits for the
  next close. Closing that window needs the host to treat rows left queued
  after a handled attended turn as main's, which is a separate host change.
- After a machine reboot the primary session does not restart on its own,
  so queued wakes wait until it is resumed by hand. Either auto-resume the
  primary session after boot, or alert the owner when the primary session
  is down while wakes are queued.

* no-mistakes(review): Close handling-successor startup wake race

* no-mistakes(test): Stabilize parked-host inbox wake regression timeout

* no-mistakes(document): Clarify handling-successor wake continuity guarantees

* no-mistakes(ci): Stabilized the flaky remote secondmate lifecycle test by extending the auto-relaunch watcher deadline from ~30 to ~60 seconds. The CI runner exceeded the old deadline by about 3 seconds; the changed production branch was not reachable in this fixture. `bash -n` and `git diff --check` pass. The full test was attempted but exceeded the 600-second local execution limit before reaching this case

* no-mistakes(ci): Fixed flaky concurrent Herdr recovery testing by retrying only documented session-lock contention after both competitors finish. Cleanup now handles fixture-owned read-only hooks. Targeted E2E passed; bash syntax and diff checks passed. Shellcheck reported only existing SC1091 source-following notices

* no-mistakes(test): Preserve successor wake boundaries across handoffs

* no-mistakes(test): Revert successor boundaries and drain teardown fixture wake

* no-mistakes(test): Notify main when downtime handback publication fails

* no-mistakes(test): Revert downtime handback notification changes

* no-mistakes(document): Correct stale supervision wake routing documentation

* fix(bin): stop the supervision host deadlocking and re-announcing handed-back closes

Two defects in this branch's handling-successor changes surfaced as the
"Behavior portable serial 2" shard hanging at its 30-minute limit.

A TERM that lands while the host settles a handled turn's successor handoff
left the host holding the wake-queue and recovery-marker locks; its exit
cleanup then waited forever on the queue lock it still owned. The cleanup now
releases those locks if this process owns them before releasing its grant.

When an accepted close turns main-only at its turn, the host hands it back and
leaves the successor running, but republished the episode as pending
downtime, so that successor re-announced the same close and exited. The
handback now republishes the episode as already announced; a later durable
append still opens a pending episode the successor recovers.

* no-mistakes(test): Park on successor after handling settlement failure

* no-mistakes(test): Use tab-delimited handled-settlement failure logs

---------

Co-authored-by: Caleb LeNoir <[email protected]>

* fix(bin): preserve accents in pending-reply summaries (#7618)

* fix(bin): keep accented letters in pending-reply request summaries

fm_pending_reply_summarize deleted every byte outside printable ASCII, so a Portuguese summary lost its accents: "não faça a correção" was stored as "no faa a correo". It now removes control characters only. The 120-character cap counts UTF-8 characters from lead bytes, so it never splits a letter under any caller locale, including the C locale.

* no-mistakes(document): Documentar preservação de acentos nos resumos

---------

Co-authored-by: Alexandre Custodio <[email protected]>

* feat: add OpenRouter support for typed dispatch resolution (#7149)

* Add explicit OpenRouter Jev dispatch resolution

* no-mistakes(document): Clarify dispatch documentation and remove stale duplicates

* chore: exclude local Stele binding from PR

* no-mistakes(document): Correct dispatch help and never-send documentation

* ci: retrigger CI after a timed-out test shard

* no-mistakes(document): Correct dispatch architecture documentation ownership

* feat(bin): publish lane capacity facts with beat pressure and keyed limits (#6983)

Opt-in: fm-watch.sh publishes state/lane-capacity.json via bin/fm-capacity.sh --publish only while config/lane-capacity exists; adds beat pressure and keyed limits to fm-capacity.sh. Unconfigured fm-capacity output unchanged.

* fix(bin): propagate contribution input assembly failures (#5359)

* fix(bin): transport contribution-input JSON through slurpfile, not argjson

bin/fm-fleet-snapshot.sh --contribution-input passed the full backlog and
task-record JSON to jq through --argjson. A single --argjson argument is
capped by the kernel's MAX_ARG_STRLEN (131072 bytes on Linux), so a large
enough backlog made the kernel refuse to exec jq while the script still
exited 0 with a broken result.

Transport both documents through temporary files and --slurpfile, matching
the pattern the default snapshot path already uses, and propagate a
non-zero exit when that jq invocation fails.

Fixes #5349

* test: narrow contribution-input regression to final assembly failure

The ARG_MAX transport is already fixed on main by #6830, so keep only the regression proving a failing final jq assembly exits non-zero.

* fix: correct Rex secondmate grouping and lifecycle (#7656)

* Fix Rex secondmate session lifecycle

* no-mistakes(review): Retire Rex secondmate sessions under the owning home identity

* no-mistakes(review): Limit Rex FM_ROOT label override to secondmate launches

* no-mistakes(document): Clarify Rex secondmate grouping and lifecycle documentation

* feat(opencode): add OpenCode 2 support with version-gated launch, plugins, and exit (#7336)

* feat(opencode): add OpenCode 2 support with version-gated launch and plugins

OpenCode 2 dropped the v1 server-plugin hook API, so the five fm.primary.*
plugins now export a default definition with an id and a setup function
alongside their legacy OpenCode 1 server export, backed by a new shared
lib/fm-opencode2.js helper; the turn-end guard, watch-arm, cd-check,
pretool-check, and sessionstart-nudge install their behavior from setup(ctx)
on OpenCode 2 and keep the server entrypoint for OpenCode 1.

fm-spawn probes the resolved opencode executable's --version once and branches
the launch, model flag, reasoning config, exit key, and busy-state plugin off
the detected major. A parsed major >= 2 takes the OpenCode 2 shape (no --model,
the model pinned through OPENCODE_CONFIG_CONTENT, a raw Ctrl-C exit, the
session.execution.* busy plugin); OpenCode 1.x and any undetected or
unparseable version fall back to the 1.x shape (--model, 1.x config, /exit)
everywhere. The worker busy-state plugin is always provisioned, but OpenCode 1
keeps the pre-port session.status/session.idle plugin so its busy-state wiring
is unchanged, and only a major >= 2 gets the session.execution plugin. Adapter
and supervision docs, OpenCode 2 live fixtures, and regression tests for the
unknown->1.x launch path and the version-gated busy-plugin shape are included.

* no-mistakes(review): gate OpenCode 2 busy plugin turn-end touch on notifyTurnEnd

* feat(opencode): launch detected OpenCode 2 workers with --standalone

OpenCode 2's default launch attaches to the shared background service, which
hosts plugins with the service's environment and ignores the pane's
OPENCODE_CONFIG_CONTENT. A private server keeps per-worker model, permissions,
FM_HOME, and lock ancestry correct. 1.x and undetected versions are unchanged.

Ported from https://github.com/kunchenguid/firstmate/pull/5143.

Co-authored-by: Girik Bajaj <[email protected]>

* fix(opencode): resolve the OpenCode 2 project location and treat every terminal turn as a turn end

OpenCode 2.0.x hands plugins the project only as ctx.location.project.directory
and takes ctx.session.prompt({ sessionID, text }), so the V2 setup path never
found its root or delivered a prompt. Interrupted and failed turns now end a
turn like a succeeded one, while a server shutdown does not.

Ported from https://github.com/kunchenguid/firstmate/pull/5143.

Co-authored-by: Girik Bajaj <[email protected]>

* test(opencode): add a token-free OpenCode 2 native plugin fixture to the live e2e

A private opencode serve plus a loopback provider proves the five primary
plugins load and act on OpenCode 2: startup nudge, cd and watcher-redirection
guards, turn-end guard, watcher arming across succeeded, interrupted, and
failed turns. The fixture declares the complete model capabilities object,
which OpenCode 2.0.11 requires and 2.0.22 accepts. FM_OPENCODE_LIVE_BINS runs
it across several OpenCode 2 executables. The credentialed half now picks its
run flags and session tables by detected major, so it keeps working on 1.x.

Fixture ported from https://github.com/kunchenguid/firstmate/pull/5143.

Co-authored-by: Girik Bajaj <[email protected]>

* feat(opencode): send one Enter when an OpenCode 2 launch leaves the brief unsent

OpenCode 2.0.11 prefills the --prompt brief without submitting it, while 2.0.22 submits it.
After launch, fm-spawn waits for the worker's busy-state plugin to report the turn start, sends one Enter only if it has not started and the composer is not empty, and fails the spawn if the turn never starts.

* docs(opencode): document the OpenCode 2 launch, delivery gate, and standalone primary homes

Records the 2.0.11 and 2.0.22 live evidence for the native plugin fixture and the post-launch brief delivery gate.

* no-mistakes(review): Trim OpenCode 2 adapter shapes and harden Ctrl-C exit

* no-mistakes(review): Record OpenCode 2 live seatbelt and exit evidence

* no-mistakes(test): Document OpenCode 2.0.22 wide-pane sidebar exit refusal limitation

* no-mistakes(document): Refresh OpenCode 2 exit-key and seatbelt payload docs

* test(opencode): verify OpenCode 1.x live with the dual-export plugins

Pin the live e2e TUI panes to the resolved opencode executable, and record
OpenCode 1.15.7, 1.18.20, and 1.18.31 evidence for plugin loading, the
turn-end guard, watcher continuity, and 1.x worker launch and exit.

* no-mistakes(review): Defer OpenCode 2 Enter on unknown composer; widen turn-end docs

* no-mistakes(document): Document OpenCode 2 delivery gate unknown-composer test outcomes

---------

Co-authored-by: Niranjan <[email protected]>
Co-authored-by: Girik Bajaj <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>

* fix(bin): resolve the tmux container from firstmate's own session, not the most recent group member (#7662)

* fix(bin): resolve the tmux container from the caller's own session, not the most recent group member

* no-mistakes(test): Fall back when the $TMUX session id is stale

* no-mistakes(document): Document tmux container choice under grouped sessions

* fix(bin): read a fully dim Cursor idle placeholder as an empty composer (#7647)

* fix(bin): read a fully dim Cursor placeholder as an empty composer

cursor-agent 2026.10.19 draws the composer glyph and its idle placeholder
as one SGR 2 run with no reverse-video cell, so ghost stripping empties the
row and the empty-content guard returned unknown. Relaunch and exit then
refused on every idle Cursor pane on tmux.

When a styled bare row strips to empty and the plain row is an agent glyph
followed by an anchored idle placeholder, read it empty. Bright typed text,
other dim text, and unstyled rows keep their existing verdicts.

Fixes #7413

* docs(verification): record the fully dim Cursor placeholder verdict and refresh command

* fix(bin): say why away-mode inject deferred and pin named Claude idle composer as empty (#6163)

* fix(bin): recognize a named Claude session's titled composer rule on cursorless backends

`claude -n <name>` right-aligns the session name in the rule above the
composer. Cursorless backends (Herdr) accepted only solid rules, so the
scan saw the lower rule alone, the idle composer read `unknown`, and
away-mode delivery to a named Claude primary deferred until return.

A rule carrying one right-aligned title now opens a separator pair. It
never closes one, the pair it opens counts only over an agent-glyph row,
and it is never a valid Pi pair, so Pi's verdict is unchanged.

The away-mode composer deferral now names which refusal it was:
unsubmitted text, or no composer shape recognized.

* no-mistakes(review): Reword composer deferral reason to cover busy harness

* no-mistakes(ci): ci-3 (Greptile, user chose to fix): The rule that must always hold is that Claude's titled opening rule is accepted for any non-empty session name that doesn't start with a space and doesn't contain the rule glyph `─`, including a multiword name. The only place that check lives is the title `case` in `_fm_composer_titled_rule_row` (bin/fm-composer-lib.sh). It now reads `case "$title" in ''|' '*|*─*) return 1 ;; esac`, as the user asked, and the comment above the function mentions multiword titles. I added regression fixtures to `test_matrix_claude_named_session_titled_rule` in tests/fm-composer-lib.test.sh, next to the existing single-word `Andrew` cases. They use the title `Andrew Chen` and check that an idle composer on herdr reads `empty` and a composer with typed text reads `pending`. Something you should know: the old pattern already accepted a title with a space in the middle. It only rejected a title ending in a space. So the new multiword fixtures also pass against the old code, and the bot's failure scenario did not actually happen for "Andrew Chen". What the fix really changes is that it drops the trailing-space rejection, as instructed. Checks run: tests/fm-composer-lib.test.sh and tests/fm-composer-ghost.test.sh both pass (exit 0, no failures), and `shellcheck -x` is clean on both changed files

* no-mistakes(review): Match unnamed-ghost fixture rule width to the partner rule

* fix: use managed-compatible worker approval modes

* no-mistakes(document): update codex and claude worker approval mode docs

* no-mistakes(ci): Fixed two test files that weren't updated when the PR changed the default claude permission mode from `--dangerously-skip-permissions` (bypass) to `--permission-mode auto`. Changes: - `tests/fm-claude-trust.test.sh` lines 664 and 696: updated two `assert_grep` assertions from `claude --dangerously-skip-permissions` → `claude --permission-mode auto` - `tests/fm-backend-orca.test.sh` line 568: updated one `assert_contains` assertion from `claude --dangerously-skip-permissions` → `claude --permission-mode auto` Both tests now pass locally (orca: exit=0, backend-dispatch/claude-trust: exit=0)

* fix: remove stray scratch directories from tests/

tests/.tmp-managed-approvals-test.bBuGhY/ and tests/.tmp-managed-approvals2.exz2qr/
were accidentally committed as worktree-local scratch dirs and do not belong in the repo.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>

* fix: preserve bypass defaults with persistent managed approval failover

* no-mistakes(review): fix approve-for-me fixture and bypass diagnostic messages

* no-mistakes(review): restore absent-Claude-default test and fix pass messages

* fix: recognize managed Codex approval prompts in the C locale

* no-mistakes(review): Fix managed approval failover bounds, authorization, inheritance, and capture

* Simplify managed approval recovery to persistent explicit failover

* no-mistakes(review): Guard failover authorization and unlink staging before recovery

* no-mistakes(document): Correct managed approval documentation and consolidate owner references

* no-mistakes(document): Correct managed-approval references and stale hook guarantees

* fix: require approval and inherit managed modes from primary

* no-mistakes(document): Clarify live hook verification scope

* no-mistakes(review): Remove dead approval_configured key from relaunch metadata

---------

Co-authored-by: Claude Sonnet 4.6 <[email protected]>
Co-authored-by: Caleb LeNoir <[email protected]>
Co-authored-by: Caleb LeNoir <[email protected]>
Co-authored-by: Alexandre Custodio <[email protected]>
Co-authored-by: Alexandre Custodio <[email protected]>
Co-authored-by: Pedro Guimarães <[email protected]>
Co-authored-by: Konner Moshier <[email protected]>
Co-authored-by: Oscar Santis Brante <[email protected]>
Co-authored-by: Kun Chen <[email protected]>
Co-authored-by: Kostadin Pop-Kochev <[email protected]>
Co-authored-by: Niranjan <[email protected]>
Co-authored-by: Girik Bajaj <[email protected]>
Co-authored-by: Tomas Perez <[email protected]>
Co-authored-by: Cameron Aragon <[email protected]>
Co-authored-by: Brian <[email protected]>

* fix(bin): keep handling successors from stranding inbox wakes after counter loss (#6467)

* fix: notify handling successors about newer inbox wakes

* no-mistakes(document): Document handling-successor inbox regression in watcher coverage list

* no-mistakes(ci): Fixed Greptile P1 (comment 4172295712): a handling successor could miss a new inbox wake when `.wake-queue.seq` was missing or malformed. What must always hold: a row added after the successor took its snapshot must be announced and must never be consumed by an older acknowledgement. Two places were breaking this: 1. `bin/fm-watch.sh`: the successor only recorded the highest inherited sequence number. If the counter was reset, a new row could get a number at or below that and be treated as already covered. This now stays silent forever once the inherited rows are acknowledged and the queue drains. 2. `bin/fm-wake-lib.sh` `fm_wake_append_locked`: a reset counter reused the sequence number of a row still in the queue. The predecessor's pending `--ack-through` consumes rows by sequence number, so it deleted the new row before anyone handled it. This was a gap in the existing allocator, and it is what made the before-ack cases fail even after fix 1. Fixes: - Watcher: the successor now snapshots the inherited rows themselves instead of their highest sequence. On each poll it announces if any queued row is not in that snapshot. It still never consumes rows, and inherited rows alone stay silent. - Allocator: the next sequence is now one more than the larger of the counter and the highest sequence still queued, so a new row can't land inside an outstanding acknowledgement's range. - `docs/watcher-continuity.md`: the paragraph and coverage list are updated to match. Tests: `test_append_wakes_handling_successor` in `tests/fm-watch-arm.test.sh` now inherits two rows and takes a counter state (intact, missing, malformed). The four new cases are after-ack and before-ack with a missing or malformed counter, and they run real watcher, arm and drain processes. In after-ack the queue is fully drained before the new append. Evidence: - Before any production change (on 92c724d), all four new cases failed: "not ok - handling successor stranded the second inbox wake" for after-ack and before-ack. - With only the watcher fix, the after-ack cases passed and the before-ack cases still failed, which shows the allocator fix is needed. - With both fixes, all four pass. Full results: `fm-watch-arm` 36/36 (including the intact after-ack and before-ack cases, so ordinary silence and fresh-beacon delivery still hold), `fm-watch-recovery-loop` 2/2, `fm-inbox` 16/16, `fm-pi-watch-extension` 60/60, `fm-wake-queue` 67/67, and all four `fm-wake-drain-*` suites passed (9, 9, 18, 14). Canonical `bin/fm-lint.sh` with `PATH=/home/nino/.local/bin:$PATH` passed: ShellCheck clean, actionlint 1.7.12, 3 workflows valid. That lint run was in local changed-file mode with ShellCheck source following disabled. In a first run of all nine suites in parallel, `fm-wake-queue` failed on "presentation lock delayed the drain for 10s" and one `fm-pi-watch-extension` timing test failed. Both passed in full when rerun on their own, so I read that as load contention, not this change. Design decision to flag: the allocator change sits in the shared wake library, so it goes beyond the watcher comparison the bot pointed at. It is a one-expression change, and the before-ack tests can't pass without it, because otherwise the predecessor's acknowledgement deletes the new message. Not done, per the phase boundary: nothing committed, pushed or posted, and the live fleet was not touched. Evidence logs are in /tmp/fmci, not in a pipeline logs/evidence directory

* no-mistakes(ci): Fixed both Greptile findings on PR #6467. Nothing was committed, pushed or posted, and the live fleet was not touched. **ci-1 (4172409813): a new wake was mistaken for an inherited one.** - Invariant that must hold: a successor treats a row as covered only if it is an unchanged inherited row in the inherited recovery episode. - Cause: after the predecessor's acknowledgement and a lost counter, a re-append with the same kind, key, payload and epoch was byte-identical to the snapshot row, so the successor stayed silent. - Fix (`bin/fm-watch.sh`): I used the existing recovery generation rather than a new identity scheme. Any append after an acknowledgement mints a new generation. The successor records the generation with its row snapshot, under the queue lock and in arm-check's lock order. Each poll counts the queue as newer if a row is not in the snapshot, or if the queue is non-empty and the generation changed. The existing arm-check then decides whether to announce. No rows are consumed, and inherited rows alone stay silent. - The row snapshot is still needed for before-ack, because an append before the acknowledgement keeps the same generation. **ci-2 (4172409821): large sequence numbers became unusable.** - Invariant that must hold: sequence numbers are always exact digit-only decimals. - Fix (`bin/fm-wake-lib.sh`): the allocator picks the largest of the counter and the queued sequences by comparing decimal text (length, then string order, leading zeros stripped), then adds 1 in bash with `$((10#$seq + 1))`. This restores the 64-bit exactness of the original bash counter. - Same fix at two places in `bin/fm-wake-drain.sh` that print sequences: `presented_max_row` and `ACK_THROUGH` print the matched text instead of `max + 0`. **Tests** - `tests/fm-watch-arm.test.sh`: two new `identical` cases, after-ack with a missing and with a malformed counter. A fake `date` pins the epoch, and the test asserts the row is byte-identical, then checks timely notification, preservation until its own acknowledgement, and no repeat notification. - `tests/fm-wake-queue.test.sh`: new `test_large_sequences_stay_exact_decimal_identifiers` starts from 2147483647, 9007199254740991 and 9223372036854775806, each with an intact, missing and malformed counter. It checks the next sequence is exact and digit-only. For the first two it also checks a real drain shows both rows, names the exact acknowledgement sequence, and acknowledging empties the queue. - `docs/watcher-continuity.md` now describes the generation check. **Evidence** (in `/home/nino/.no-mistakes/evidence/01M40CDTX2000A5TFFRZN27YFR/ci-round3/`) - Before, on 050a5fc: both identical cases failed with "handling successor stranded the second inbox wake (after-ack)". The large-sequence test failed with "advanced to '9223372036854775808', not 9223372036854775807". - After the fix, all three pass (`after-*.log`). - All nine suites passed, each run on its own, all with 0 not ok (`final-results.txt`): `fm-wake-queue` 68/68, `fm-watch-arm` 38/38, `fm-watch-recovery-loop` 2/2, `fm-inbox` 16/16, `fm-pi-watch-extension` 60/60, `fm-wake-drain-open-decisions-cursor` 9/9, `fm-wake-drain-open-decisions` 9/9, `fm-wake-drain-outcome-backstop` 18/18, `fm-wake-drain-unread-status` 14/14. - `bin/fm-lint.sh` with `PATH=/home/nino/.local/bin:$PATH` passes: ShellCheck clean, actionlint 1.7.12, 3 workflows valid (local changed-file mode). **Not run** - The only OpenCode suite is an opt-in live test, so I did not run it. **Limits** - The 2.14748e+09 symptom doesn't reproduce with the awks here (gawk, mawk 1.3.4, busybox). The failure reproduced locally is the precision loss at 64-bit values. - The drain's awk comparisons are only exact up to 2^53. That predates this PR and I left it alone, so the drain test stops at 2^53

* no-mistakes(document): Reattach successor poll-loop sentence to its subject

* fix(bin): stop lock waits and test fixtures from spinning after their directory is removed (#7685)

* fix(tests): bound lock waits on removed dirs and reap fixture-root processes

A lock wait spun every 0.1s forever once its directory was removed, so a
watcher or reconcile scan of a deleted test home never reached its own
home-gone exit. fm_lock_acquire_wait now returns within 0.2s once the
lock's parent directory is gone.

Test teardown now signals every process naming the exact fixture root
(TERM, then KILL) before removing it, in both fm_test_cleanup and the
orphan sweep. The supervision-host fake harness sessions stop once their
home is gone or the suite pid has died, so a hard-killed runner no longer
leaves them polling under init.

Fixes #7672

* fix(tests): bound the session-lock concurrency barrier

Forty workers polled a find pipeline every 0.01s to wait for each other,
so the barrier alone launched thousands of processes a second, and once a
stopped run removed the barrier directory the workers polled forever under
init. Count entries with a builtin glob every 0.05s, and end the wait once
the directory is gone, the suite has died, or the stub block bound passes.

Refs #7672

* fix: watch review-bot findings on owned pull requests (#7499)

* fix(bin): admit listed review-bot comments as contribution signals

* no-mistakes(review): Persist review-bot config in contribution check shim

* no-mistakes(review): Classify allowlisted collaborators as review bots

* no-mistakes(document): Document review-bot contribution signals

* no-mistakes(review): Preserve review-bot config and re-raise classification

* no-mistakes(review): Prevent acknowledged bot signals replaying after allowlist changes

* no-mistakes(document): Document configurable review-bot contribution watching

* no-mistakes(document): Clarify review-bot thread documentation

* fix(bin): make review-bot contribution watching opt-in

* docs(bin): state review-bot allowlist has no built-in default

* no-mistakes(document): Document per-home review-bot configuration

---------

Co-authored-by: Caleb LeNoir <[email protected]>

* fix(brief): drop undefined heavy-test slot from the Waiting section (#7674)

The generated Waiting section told workers to wait on a heavy-test slot that nothing in the repository defines. Remove the phrase and assert that a brief generated with config/wait-no-turns does not name one.

* fix(bin): read the no_ci ci-monitor marker as no-checks (#7675)

* fix(bin): read the no_ci ci-monitor marker as no-checks instead of validating

Fixes #7644

* no-mistakes(document): Rewrap nm_ci_checks_state no_ci comment

* feat(bin): add opt-in restricted permission mode for Codex workers (#7683)

* feat: add opt-in restricted permissions for Codex workers

* no-mistakes(review): Document restricted Codex network and git approval limits

* fix(test): keep serial packing at-budget fixture stable with unhinted scripts (#7699)

* fix(test): keep serial packing at-budget when a script has no hint

tests/fm-approval-failover.test.sh landed without a serial duration hint,
so the at-budget packing fixture overflowed by 1040ms. Record a measured
5410ms hint and give the fixture its own complete hint table so unmeasured
defaults cannot join the boundary shard.

Co-authored-by: Kun Chen <[email protected]>

* docs: note the local approval-failover packing hint

Record the 5410 ms provisional local sample for the next CI refresh,
and describe the packing-boundary fixture as independent of unhinted
scripts.

Co-authored-by: Kun Chen <[email protected]>

---------

Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: Kun Chen <[email protected]>

* fix(inbox): newline-terminate steering records (#6309)

* fix: terminate steering inbox records with newline

* no-mistakes(ci): Fixed Greptile P2 by updating the shared generated `INBOX_SECTION` in `bin/fm-brief.sh`, which is the single guidance source consumed by ship, scout, and secondmate scaffolds. The guidance now tells workers to prefer `fm_task_inbox_body`, explains that `body-terminator=1` marks exactly one synthetic record-termination newline that is not logical body content, and says to remove only that marked terminator while preserving intentional trailing newlines and legacy EOF bodies. Added generated-brief behavioral coverage for all three scaffold paths in `tests/fm-brief.test.sh`. Verified with `./tests/fm-brief.test.sh && bash ./tests/fm-task-inbox.test.sh`

* fix: print fm-send help before resolving FM_HOME (#6402)

* fix(bin): make fm-send.sh --help print usage before FM_HOME resolution

* fix: parse list-form Lavish results without dropping answers (#5404)

* fix(bin): parse Lavish list-form results and refuse unparsed blocks

Lavish emits its queued prompts in TOON list form instead of table form as
soon as the items stop being uniform, for example when some annotations carry
a nested target object or a message carries an attachments table. The adapter
only recognized the table header, so read reported a complete, empty result
and answers closed nothing.

Move the result parsing into one shared reader used by read, answers, and
reconciles that accepts both forms, keeps only column-zero headers, skips
nested structures only beneath the field that opened them, and counts
anything it cannot account for as malformed. An unrecognized header naming
the block is now malformed rather than an empty result, answers and
reconciles exit nonzero when the result is not fully accounted for, and the
queued-content check treats a list header as content.

Refs #4726

* no-mistakes(document): Document Lavish capture formats and incomplete-result handling

* test: expect captain_message_count for the open-board list-form capture

* fix: correct Pi wake ownership and processing-turn handling (#5835)

* fix(pi): let the supervision branch claim Orca stale wakes

The watcher keys Orca endpoints by terminal=, but the branch dispatcher
only indexed window=, so every Orca stale row vetoed the wake scan and
went to main. Index both endpoint fields.

Local hotfix ahead of upstream; refs kunchenguid/firstmate#5623.

* test(pi): cover terminal-keyed Orca stale rows in branch dispatch

Pins the terminal= endpoint lookup: a terminal-keyed stale row queued with
another eligible row must resolve to its task in both routine and heartbeat
scans, instead of vetoing the wake to main.

* no-mistakes(document): Update supervision dispatch doc for Orca terminal-keyed stale rows

* fix(pi): reject conflicting wake endpoint ownership

Index task keys and window/terminal aliases through one ownership check.
Ambiguous records must leave the wake on MAIN instead of selecting the
last task and possibly bypassing another owner's open decision.

Cover duplicate terminals and collisions with window and task keys in
both record orders while preserving unique terminal routing.

* no-mistakes(document): Document conflicting alias ownership as scope corruption

* fix(pi): retain ownership claims from incomplete task records

Check endpoint and task alias ownership before project eligibility so a
projectless record cannot lose its open decision to another terminal owner.
Require project context before decision filtering can grant routing scope.

Cover missing and empty project fields in both record orders, and preserve
refusal for a uniquely mapped terminal without project context.

* no-mistakes(review): Fix canonical routing ownership and custom SDK event handling

* no-mistakes(review): Preserve dedicated custom processing run ownership

* no-mistakes(document): Clarify Pi event handling and fail-closed routing documentation

* feat(bin): add a forge=external review rail that never pushes task branches (#7368)

* feat(bin): add a forge=external review rail that never pushes task branches

A project whose review tool uploads its own snapshot of the worker's local
commits can now be registered [direct-PR forge=external]. Workers on such a
project never need to push a branch to publish, and must never push a task
branch to the shared origin.

- fm-project-mode.sh: external joins the closed forge set; never detected,
  refused on local-only, and +yolo reports yolo=off with a refusal.
- fm-dod-lib.sh: external ships direct-PR only; its first rule forbids origin
  and task-prefixed pushes, its Definition of done renders the home's
  config/external-review.md adapter verbatim, and the ready-report gate
  accepts `done: review <url> uploaded for review` on the URL alone or, with a
  recorded backup remote, once HEAD is on the backup namespace.
- fm-git-push-guard.sh (new): per-task pre-push guard refusing pushes to
  origin or a URL matching origin's, task-branch and task-prefixed refs on any
  remote, and refs outside the backup prefix on the backup remote.
- fm-git-strip-ai-trailers.sh: install gains --push-guard and --no-strip.
- fm-spawn.sh: refuses yolo, a missing adapter, and an unusable backup
  remote before launch; installs the guard even under keep-ai-trailers; and
  records forge=external, backup_remote=, and backup_prefix=.
- fm-review-check.sh (new): records review= and review_head= with no merge
  watch, and publishes the child's ready line in a secondmate home.
- fm-promote.sh refuses promotion onto forge=external, because a scout
  launches without the guard.
- Docs: docs/external-review-forge.md (design), configuration.md's new
  "External review tool" section, scripts.md, and the ship-landing and
  project-management skills.

* no-mistakes(review): Drop string-grep hook assertion from external-review spawn test

* no-mistakes(document): Note forge=external contract token and direct-PR-only composition

* test(pi): Lauf ohne prompt in before_agent_start festnageln (#7387)

Ein Lauf, den sendCustomMessage startet, traegt eine Custom-Nachricht und
keinen prompt. Das Lesen des prompt an dieser Stelle warf, womit jeder
solche Lauf mit einem Fehler auftauchte statt zu starten.

Die Verengung dagegen steht seit 8c9c67de im Zweig, ein Test, der sie
benennt, fehlte: die einzige Abdeckung lag beilaeufig in einem
Abbruch-Fall der Abwesenheits-Haltung und verschwindet mit ihm. Der neue
Fall erweitert den bestehenden Mirror-Test und prueft, dass ein solcher
Lauf weder wirft noch als Dialog gespiegelt wird.

Gegenprobe: ohne die Verengung wirft genau dieser Fall mit
"Cannot read properties of undefined (reading 'trim')".

Co-authored-by: thelad-dev <[email protected]>

* fix(bin): stop tmux target checks reporting gone windows as alive (#7409)

* fix(tmux): verify exact endpoint membership

* fix(tmux): preserve exact target forms

* test(tmux): align endpoint fixture lifecycles

* test(tmux): guard isolated cleanup and shell reader

* no-mistakes(review): Limit tmux .pane target split to window indexes

* fix(composer): prove opencode 1.19 de-emphasised mode footer from the plain row (#7395)

* fix(bin): stop misreading opencode's own footer as pending composer text

An idle OpenCode composer classified as `pending`, and that verdict gates every
typed-plane action firstmate owns: fm-send skips the doorbell, and fm-control
refuses both relaunch and exit. A firstmate operator lost a full session to it and
had to type into worker panes by hand three times.

Root cause: opencode 1.19 draws the mode/model footer's identifying cells
de-emphasised (mode word RGB 67;133;190, middle-dot separators 111;110;105,
luminances ~119.8 and ~109.7, both under fm_composer_strip_ghost's 128
threshold). That helper exists to answer "what did the human type?", so it
deleted exactly the cells that identify the footer. The `^(Build|Plan)` anchor
then became unreachable on every styled backend - tmux, Herdr, and Zellij - not
just one pane, because the unstyled row keeps its styling bytes everywhere.

The fix proves the footer from both forms of that row: the ghost-stripped
content and the ANSI-stripped plain row. Proving it on the form ghost stripping
cannot reach is the whole repair.

What makes that safe, and why the previous argument was not: the earlier draft
argued safety by noting that on a plain capture the two forms collapse to one
string, so the verdict is unchanged. That is true and carries no weight, because
styled=0 is the only configuration where the new proof does nothing. The
exemption is safe because a row reaches the plain form only when the
ghost-stripped row still fails the pattern, which means the stripped content is
non-empty while its own leading Build/Plan cell was deleted as ghost. Nothing
opencode draws de-emphasises a typed row's leading cells - only its furniture is
drawn dimmed - so the only rows the plain form admits beyond the stripped one
are de-emphasised furniture, and the mode footer is the only furniture opencode
draws that opens with a mode word. That is self-confirming rather than asserted,
and it is the argument to recheck when a new opencode release moves a colour.

A review also caught a second change riding along in the same diff: the footer
pattern had been widened from `[[:space:]]+` to `[[:space:]]*`, admitting
`Build ·x` and a bare `Build ·`. Both read as more typeable than the footer, so
they moved the verdict in exactly the direction this rule exists to prevent. No
recorded opencode footer ends at the dot, so the original `+` matches every real
capture and the widening is reverted.

Verification:
- fm-lint.sh exit 0 on pinned shellcheck 0.11.0 and actionlint 1.7.12.
- fm-doc-audience-check.sh ok across 119 surfaces and 757 local links.
- tests/fm-composer-lib.test.sh green via bin/fm-test-run.sh.
- The new regression case fails on exactly one assertion when this change is
  reverted: "opencode 1.19.0 de-emphasised footer row: expected empty, got
  'pending'", which is the reported symptom.
- Confirmed end to end against live panes rather than only fixtures: a real idle
  opencode 1.19.0 worker classified empty after the change and pending before,
  and firstmate reached the worker over the steer channel afterwards.

* no-mistakes(review): fix(bin): apply leftbar footer rule in content extractor; correct cursorless claim

* no-mistakes(document): document opencode 1.19 footer furniture and extractor coverage

* no-mistakes(document): document ghost-luma knob coupling to opencode footer furniture

* no-mistakes(document): document opencode de-emphasised footer recognition invariant

* no-mistakes(review): fix(docs,bin): correct ghost-luma knob direction, gate plain-row extraction

* no-mistakes(review): fix(docs,bin,tests): correct ghost-luma knob wording, share plain-content helper, cover Herdr/Zellij idle

* no-mistakes(document): narrow overstated backend coverage claim in runtime-backends.md

* no-mistakes(document): document leftbar footer override and opencode 1.19 pointer

* test(send): codex im Tuerklingel-Test hook-frei starten (#7406)

Der Kopf des Tests sagt, jedes Programm werde so gestartet, wie
bin/fm-spawn.sh es startet. Im codex-Zweig von launch_cmd fehlte dabei
--disable hooks, das fm-spawn im crewmate- und scout-Pfad setzt.

Ohne den Schalter parkt codex auf dem Hook-Vertrauensdialog ("N hooks
are new or changed"), dessen Auswahl auf "Review hooks" aufsetzt und der
mit der Tastenebene dieses Werkzeugs nicht beantwortbar ist. Der Lauf
meldet dann die Tuerklingel als nicht befolgt, obwohl er ueber die
Tuerklingel gar nichts ausgesagt hat - und das auf jedem Checkout, weil
schon die projekteigene .codex/hooks.json den Dialog aufzieht.

Dazu eine knappe Zusicherung am Startrezept, damit der Schalter beim
naechsten Umbau nicht wieder still ausfaellt.

Co-authored-by: ladwein <[email protected]>

* fix(bin): store only classified review fields in contribution records (#7096)

* fix(bin): store only classified review fields in contribution records

A pull observation stored GitHub's raw reviews payload, so a PR with a few
hundred reviews wrote a record past the 1 MiB read cap and every pending,
verdict and ack read then refused the whole home. Project each stored review
to id, state, submitted_at, commit_id and user.login, the only fields the
classifier reads, and add a many-review regression.

* no-mistakes(document): clarify contribution record read cap in script header

* fix: handle Pi 1.1 and 1.2 supervision events correctly (#7216)

* fix(pi): retain custom-event handling and processing cancellation

* fix(pi): identify custom triggers before legacy prompt narrowing

* no-mistakes(test): Correct branch fixture retirement and verify real notification ownership

* no-mistakes(document): Clarify Pi event boundaries and verification scope

* fix(pi): retain custom-event handling and processing cancellation

* fix(pi): identify custom triggers before legacy prompt narrowing

* no-mistakes(test): Correct branch fixture retirement and verify real notification ownership

* no-mistakes(document): Clarify Pi event boundaries and verification scope

* no-mistakes(review): Fix SDK1.1 prompt staging and verify branch context

* no-mistakes(document): Clarify SDK prompt compatibility and branch-context verification

* no-mistakes(test): Require dual-SDK compiler checks; execution remains pending

* no-mistakes(document): Correct SDK typecheck documentation and stale dependency claims

* no-mistakes(document): Correct stale Pi typecheck documentation and ownership pointers

* no-mistakes(ci): Fixed SC2329 in tests/fm-pi-primary-types.test.sh by inlining EXIT cleanup. Also fixed a reproduced macOS npm-prefix/lockfile path failure without changing dependency pins or assertions. Canonical targeted lint, strict TypeScript 5.9.3 checks against Pi 1.1.0 and 1.2.0, and success/failure cleanup checks pass. Both behavior-shard failures were upstream npm ETARGET errors in workflow steps unchanged from base; no workflow/runtime changes warranted. Hosted CI remains for the outer executor

* fix(test): reconcile queued processing probes after rebase

* no-mistakes(document): Correct Pi compiler-phase documentation and stale CI comments

* fix(bin): verify cursor launch binaries with a bounded probe (#6380)

* fix(cursor): verify cursor-agent by running it, not by name

Cursor's installer writes its `cursor` IDE shim through the
~/.local/bin/cursor -> cursor-agent symlink, which can replace a versioned
cursor-agent with a script that only prints "No Cursor IDE installation
found" and exits non-zero. That file keeps Cursor's own name and install-tree
path, so the name shortcut (and the structural check alone) accepted it and
every Cursor spawn launched the broken file instead of the working agent alias.

A launch candidate now has to print Cursor's CLI identity under the bounded
probe, or carry the structural evidence and run --help successfully. Hosts
without a bounded runner keep the structural verdict, as before.

* no-mistakes(document): Align cursor launch-verify docs with runtime

* no-mistakes: apply CI fixes

* test: restore fm-watch-triage ack_stopped_cycle assertion

The CI fix round loosened ack_stopped_cycle so a drain that prints no
acknowledgement command and exits zero counts as success. That test is
unrelated to the Cursor executable verification this branch changes, so
restore its original assertion rather than mask a watcher failure here.

* no-mistakes: apply CI fixes

* no-mistakes: apply CI fixes

* no-mistakes: apply CI fixes

* fix(bin): restore fm-afk-contract clock sampling

A CI fix round changed how fm_afk_contract_cmd_enter samples its epoch.
That away-mode behavior is unrelated to the Cursor executable verification
this branch changes, so restore it here and leave any fix to its own change.

* fix(cursor): load the timeout library only when a probe runs

Sourcing bin/fm-timeout-lib.sh at load time made every consumer of
fm-cursor-lib.sh, including the session-lock and turn-end hook paths that
never probe, depend on that file being next to it. Load it lazily from the
probe instead.

* no-mistakes: apply CI fixes

* no-mistakes: apply CI fixes

* no-mistakes: apply CI fixes

* test: restore herdr focus-flash e2e test

A CI fix round edited this Herdr end-to-end test, which is unrelated to the
Cursor executable verification this branch changes. Restore it here and leave
any fix to its own change.

---------

Co-authored-by: ladwein <[email protected]>

* fix: require actual PR references in CI-ready ship notes (#7422)

* fix(dod): require a PR reference in CI-ready notes

* no-mistakes(review): Recognize Forgejo plural pull request URLs

* feat(herdr): opt-in project groups with status tags and a sorted agents view (#7434)

* feat(herdr): opt-in project groups with status tags and a sorted agents view

Add config/herdr-project-groups (absent or off: unchanged behavior). When on,
Firstmate tags each Herdr task pane, and its own projected workspace, with
display-only fm_group/fm_state/fm_task/fm_sort tokens, sets a Herdr agents
view sorted by group then status (needs-captain, problem, running, done), and
places a new projected task at the end of its own group inside the parent
block with the same single verified move as before.

The watcher reconciles tags once per poll and a spawn tags its task at once;
bin/fm-herdr-groups.sh also previews (plan), clears, and prints or appends
suggested sidebar rows with a backup. The agents view helper needs python3.
The only test-runner change is the serial weight hint for the new suite.

* docs(herdr): record the live lab check of project groups

The four hand checks for tags, the sorted agents view, placement at the
end of the group, and clear passed against a real Herdr 0.9.5 server
(protocol 22) in a guarded lab session.

* docs(herdr): align project group verification notes with the live check

* fix(bin): pin LC_ALL=C for remote job process identity reads (#7410)

ps -o lstart= renders in the caller's locale, so a lock or claim owner
recorded under one locale (de_DE renders "Di Okt 13 ...") failed identity
verification under another, was declared dead, and a second worker split
the queue: two serve loops reclaimed and reaped each other's live jobs,
which vanished mid-claim and failed staged jobs with exit 125 and no
output. Pin LC_ALL=C in fm_remote_job_process_start and pin the
cross-locale invariant with a regression test.

Co-authored-by: researchworldwide2026 <[email protected]>

* fix(opencode): ignore child stdin EPIPE in guard and encoder (#7447)

* fix(bin): ignore crew state overrides for other tasks (#5881)

* Guard fm-crew-state overrides by task-name basename

bin/fm-crew-state.sh honours FM_CREW_STATE_META_OVERRIDE and FM_CREW_STATE_STATUS_OVERRIDE only when the override's basename is the requested task's own .meta or .status file name.
An override naming a different task, for example one inherited through a server started inside another task's snapshot child, falls through to the task's own records under the state directory.
A snapshot's own override, which names the task it was captured for, is still honoured.
This is complementary to #5622, which keeps the overrides out of the Herdr server launch: whatever path leaks an override, the reader never trusts one that names a different task.
Regression tests cover a mismatched over…
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.

3 participants