Skip to content

fix(bin): let a Claude Stop hook prove it belongs to the lock-owning session - #2424

Closed
Kallas95 wants to merge 5 commits into
kunchenguid:mainfrom
Kallas95:fm/fm-claude-autoarm-inert
Closed

Kallas95 wants to merge 5 commits into
kunchenguid:mainfrom
Kallas95:fm/fm-claude-autoarm-inert

Conversation

@Kallas95

Copy link
Copy Markdown

Intent

GOAL: Fix the Claude Stop-owned watcher auto-arm (bin/fm-claude-stop-autoarm.sh), which NEVER claims the home. Every turn end is blocked by the "TURN WOULD END BLIND" guard, and the captain has seen that error on every exchange for two days.

This changes firstmate's shared tracked material, so .agents/skills/firstmate-coding-guidelines/SKILL.md was read first and applied (knowledge-placement decision tree, one-owner rule, size discipline, harness-dependent-check rule, repo style rules).

ROOT CAUSE (established before this work started; it was NOT to be re-investigated): The Claude Code Stop hook does not run under its session. It runs in the daemon worker chain. Tree observed live on this machine on 2026-08-14: hook shell -> claude bg-spare -> claude bg-pty-host -> claude daemon run (PPID 1). fm_claude_stop_autoarm proved its right to act with fm_session_lock_owned_by_self (bin/fm-session-lock-lib.sh), which walks the current process ancestry and requires the pid recorded in state/.lock to be a member of it. The lock names the real terminal session (e.g. 89187), which is NOT in the daemon chain, so the check failed systematically and the script exited 0 inert, silently. Corroborating evidence: upstream PR 2388 (branch fm/fm-lock-daemon-pid of this repo, already validated) documented this same daemon chain as the suspected cause of this bug while deliberately keeping its own scope to the lock. This task is where it gets treated. Consistent symptoms on the register: the state/.claude-autoarm-epoch ledger frozen on a dead owner, no state/.claude-autoarm.lock ever created, no claim at Stop time, while a manual bin/fm-watch-arm.sh re-arm works every time.

THE REAL PROBLEM TO SOLVE - a design problem, not a patch: how can a Stop hook that runs in the daemon chain PROVE it belongs to the session that holds this home's lock?

NON-NEGOTIABLE CONSTRAINTS:

  • The current guard exists to stop a foreign session from claiming another home's watcher. The replacement must be AT LEAST AS STRICT. A weakening that let a home be claimed by a third-party session would be worse than the bug.
  • It must stay reliable when several firstmate homes coexist on the machine (that is the case here: the main home and the secondmate's).
  • It must not depend on a file any process can write.

LEADS TO INVESTIGATE (not to presume, and not limiting): whether the Claude Code Stop payload's identity fields (notably a session id and the current directory) recorded at lock acquisition and compared at Stop time give a proof at least as strong as ancestry - studying what the payload actually contains on the INSTALLED version rather than assuming; whether there is a valid ancestry path not being exploited, such as an environment variable the session propagates to the hook; whether two proofs should be combined rather than one replaced.

INSTRUMENT FIRST: run bin/fm-claude-stop-autoarm.sh by hand under real conditions with traces, and show exactly which guard exits 0. The instrumented diagnosis is part of the deliverable.

ACCEPTANCE CRITERIA:

  • The automatic mechanism does claim the home on a real Stop of this session, and the turn end is no longer blocked by the guard when supervision is healthy.
  • MANDATORY COUNTER-PROOF: a session that does NOT hold a home's lock still cannot claim its watcher. This test is the heart of the safety property.
  • Tests colocated in tests/ (the fm-claude-stop-autoarm suite already exists; extend it) covering: hook under the daemon chain with a legitimate lock -> claim; hook of a foreign session -> refusal; absent or malformed lock -> refusal; a secondmate's home not claimed by the main home.
  • Shellcheck-clean, script headers kept up to date, one sentence per line in touched docs.
  • Update docs/turnend-guard.md and/or docs/watcher-continuity.md according to what the fix changes in the identity contract, and add the evidence to docs/verification/supervision.md.

WHAT I FOUND WHILE INSTRUMENTING (refines the established root cause rather than contradicting it): Claude Code 2.1.233 was instrumented with a real Stop hook capturing payload, ancestry and environment, in both a headless claude -p session and an interactive pty session. Every Stop hook receives CLAUDE_PID (the session process pid), CLAUDE_CODE_SESSION_ID, and a payload whose session_id equals that environment session id. The reason ancestry is not reliable is that Claude Code serves hook and tool commands from a SHARED per-user worker pool under /tmp/cc-daemon-/, and a pool whose owning session has exited survives with its top process reparented to init. Observed live: 27305 1 claude bg-pty-host ... d6bfe5e1 ... versions/2.1.232, 27316 27305 claude bg-spare, 25610 27316 /bin/zsh -c ... bin/fm-watch-arm.sh. A command served by that pool has a contiguous claude ancestry of {27316, 27305} and no path at all to the live session whose pid the lock records. The affected home's ledger had not advanced for about fourteen hours while work was in flight.

DESIGN DECISIONS AND TRADEOFFS MADE (a reviewer reading only the diff would not know these were deliberate):

  • TWO PROOFS COMBINED, NOT ONE REPLACED. fm_session_lock_owned_by_self (ancestry) is left completely unchanged, and a second ancestry-independent proof, fm_session_lock_owned_by_claude_hook, is accepted as an alternative (logical OR). Deliberately NOT preferring the new proof over ancestry: a legitimate claude-launched-by-claude wrapper chain writes the OUTERMOST pid to the lock while CLAUDE_PID names the inner session, so preferring the new proof would have regressed that case.
  • The new proof is a CONJUNCTION and every part is required: the delivered payload names a session id; the delivering session exported that same session id (so the environment read belongs to the session that emitted THIS event rather than being inherited from an ancestor session); the exported session pid is EXACTLY the pid this home's lock records; and that pid is still a live Claude process. Requiring pid equality is STRICTER than ancestry membership, not weaker, which is how the non-negotiable constraint is met: a foreign session exports its own pid, which is not the pid this home's lock records. It also depends on no file any process can write - only the session lock this repo already owns, plus vendor-delivered process identity.
  • The payload/environment session-id correlation is included specifically because it is the one signal that CANNOT be inherited: a descendant process carrying an inherited CLAUDE_* environment has no matching delivered Stop event.
  • The payload session-id extractor is deliberately plain text and takes NO jq dependency (jq is only a Relay-time requirement in this repo, not a hard one). This is safe because the extracted value is never trusted on its own: its only consumer compares it to the session id the delivering session exported, so a mis-parse can withhold the proof but can never manufacture one. Fail-closed in every direction.
  • Added FM_AUTOARM_TRACE, an opt-in stderr diagnostic naming the gate that ends a run. It changes no decision and is never set in normal operation; the script header documents it as the single exception to the "exit 0 is always silent" contract. This is the instrumented-diagnosis part of the deliverable, kept in the tree so the next occurrence is diagnosable.
  • SCOPE HELD: the stale-lock recovery path still delegates to bin/fm-lock.sh, which elects the outermost contiguous harness pid and can therefore still write daemon-infrastructure pid under an orphaned chain. That is exactly what upstream PR 2388 (still open) fixes, and it was deliberately NOT duplicated here to avoid conflicting with already-validated work.
  • HARNESS-DEPENDENT CHECK RULE (firstmate-coding-guidelines): this verdict comes from vendor-emitted signals, so it needs BOTH a portable regression with real processes and no harness AND a live opt-in guard. tests/fm-claude-stop-autoarm.test.sh gained five portable tests over real processes; tests/fm-claude-stop-autoarm-live-e2e.test.sh gained a guard that fails, naming the harness and version, if Claude stops exporting CLAUDE_PID or CLAUDE_CODE_SESSION_ID, stops naming a session_id in the Stop payload, stops making the two corroborate, or stops matching the pid this session recorded as the home's owner. That live guard was placed BEFORE the pre-existing assertions that depend on the model following the prompt exactly, so a model deviation can never mask a lost vendor signal.
  • KNOWN PRE-EXISTING ISSUE, deliberately not touched: the live e2e's "expected exactly 2 hook-owned arm cycles" assertion is sensitive to how many drains its fixture observes and fails identically on unpatched main (verified by restoring main's bin/ and re-running). It is not a regression from this change and fixing it is out of scope.

VERIFICATION ALREADY PERFORMED: the daemon chain was reproduced with real processes; without exported identity the hook stays inert (the bug), with its own session's identity it claims and arms, with a foreign session's identity it still refuses. The new claim test fails on unpatched main with the captain's exact symptom (exit 0, inert) and passes with the fix. bin/fm-lint.sh is clean, bin/fm-doc-audience-check.sh is clean, and the auto-arm, session-lock-ancestry, turn-end guard, watch-arm, watcher-lock, session-start and daemon suites all pass. The live guard against real Claude Code 2.1.233 confirmed the session records itself as the home's owner, the identity it exports names that same pid, payload and environment session ids match, the ledger records outcome=rewake, and NO turn was blocked for ending blind.

DELIVERY PATH FOR THIS REPO (known constraint, accepted by Firstmate, not to be rediscovered): origin is kunchenguid/firstmate with NO write access; the machine firewall refuses pushes to master/main and refuses git rebase. Deliver like PRs 2329/2367/2387/2388/2396/2419: push ONLY the fm/fm-claude-autoarm-inert branch to the fork https://github.com/Kallas95/firstmate by explicit URL (worktree remotes unchanged), then open the upstream PR against kunchenguid/firstmate:main with gh-axi. The upstream repo runs NO CI on fork PRs, so local validation green plus the upstream PR opened is the terminal state; close the CI wait through the pipeline's supported cancellation command once the PR is open rather than waiting for checks that will never arrive.

What Changed

  • bin/fm-session-lock-lib.sh gains a second, ancestry-independent ownership proof, fm_session_lock_owned_by_claude_hook: a conjunction requiring the delivered Stop payload to name a session_id, the delivering session to have exported that same CLAUDE_CODE_SESSION_ID, its exported CLAUDE_PID to equal exactly the pid recorded in the home's state/.lock, and that pid to still be a live Claude process. The existing ancestry proof is unchanged; a new fm_session_lock_owned_by_this_claude_session disjunction arbitrates between the two and reports the deciding member through FM_SESSION_LOCK_PROOF.
  • bin/fm-claude-stop-autoarm.sh now decides identity through that shared disjunction at both the admission gate and the post-recovery re-verification, so a hook served from Claude Code's shared worker pool (whose ancestry never reaches its own live session) can claim the home instead of exiting 0 inert. It also adds FM_CLAUDE_AUTOARM_TRACE, an opt-in stderr diagnostic that names the gate ending a run inert before the cycle claim; it changes no decision and is documented in the script header and docs/configuration.md.
  • tests/fm-claude-stop-autoarm.test.sh adds five portable regressions over real processes — claim from a detached worker chain, foreign-session refusal, unconfirmed/absent/malformed delivered identity, absent/malformed recorded owner, and a secondmate home refused to the main home's session — and tests/fm-claude-stop-autoarm-live-e2e.test.sh gains a live guard, placed before the model-dependent assertions, that fails by name and version if Claude stops delivering those identity fields on the synchronous or detached asyncRewake path. docs/watcher-continuity.md, docs/verification/supervision.md, docs/scripts.md and the harness-adapters skill record the two-proof identity contract and the measured evidence.

Risk Assessment

✅ Low: Le changement est strictement additif et fail-closed sur la porte d'identité (l'ancestry reste inchangée et prioritaire, la seconde preuve est une conjonction exigeant une égalité de pid plus stricte que l'appartenance à l'ascendance), il est couvert par cinq régressions portables sur de vrais processus incluant la contre-preuve obligatoire et l'indépendance de deux homes, et les trois points restants sont documentaires ou de robustesse d'un garde opt-in.

Testing

I reproduced the reported bug and its fix directly against the hook. Running bin/fm-claude-stop-autoarm.sh by hand under the detached worker-chain shape with FM_CLAUDE_AUTOARM_TRACE=1, the pre-fix code (bin/ restored to base f1a4af4) exits 0 silently for its own lock-owning session with no arm and no epoch ledger — the captain's exact symptom — while the patched code proves identity through the delivering Claude session, exits 2, emits the wake banner and writes outcome=rewake. The mandatory counter-proof holds in every direction: a live foreign session, an exported identity the delivered event does not corroborate, a missing lock, a malformed lock, and the main home's session firing at a secondmate home are all refused with state untouched, and the secondmate's own session still claims its own home. The three trace strings documented in docs/verification/supervision.md reproduce exactly, including the CLAUDE_PID=unset variant. The opt-in live guard against real Claude Code 2.1.233 passed in full — including the "exactly 2 hook-owned arm cycles" assertion the author flagged as fragile, which did not fail here — and it asserts no turn was blocked by TURN WOULD END BLIND. A separate isolated claude -p probe with synchronous and asyncRewake Stop hooks confirms the vendor still delivers CLAUDE_PID, CLAUDE_CODE_SESSION_ID and a matching payload session_id. The targeted suites around the identity contract (auto-arm, session-lock ancestry, turn-end guard, watch-arm, watcher-lock, session-start) ran through the repo's own runner with 6 scripts and 0 failures. This is a shell/CLI change with no rendered surface, so the reviewer-visible evidence is CLI transcripts and persisted state rather than screenshots. Two environment notes with no effect on the verdict: the local firewall refuses bash tests/<x>.test.sh for any script containing chmod, so I used ./bin/fm-test-run.sh; and in the headless claude -p probe the session is the hook's direct parent, so ancestry carried that verdict — the detached shape is covered by the real-process reproduction and the portable suite. The worktree is clean.

Evidence: Instrumented before/after reproduction and safety counter-proofs (CLI transcript)

### A. AVANT le correctif (bin/ de main, f1a4af4) - la session PROPRIÉTAIRE elle-même state/.lock = 15057 CLAUDE_PID exporté = 15057 | (aucune sortie -- silencieux) => code de sortie du hook : 0 état : .lock=15057 | cycles d'armement=0 | ledger=ABSENT ### B. APRÈS le correctif - la même session propriétaire, même chaîne détachée state/.lock = 15058 CLAUDE_PID exporté = 15058 | autoarm-trace: identity: proven by the delivering Claude session (pid 15058) | firstmate watcher wake - one supervision event needs a handling turn now. | signal: fixture watcher closed with actionable work => code de sortie du hook : 2 état : .lock=15058 | cycles d'armement=1 | ledger=epoch=2 owner_pid=15183 outcome=rewake ### C1. CONTRE-PREUVE - une session ÉTRANGÈRE vivante tente de réclamer ce home | autoarm-trace: inert: live session 15059 owns this home and neither identity proof applies (CLAUDE_PID=15069) => code de sortie du hook : 0 état : .lock=15059 | cycles d'armement=0 | ledger=ABSENT ### D. la session du home PRINCIPAL (15061) tire sur le home secondmate (.lock=15063) | autoarm-trace: inert: live session 15063 owns this home and neither identity proof applies (CLAUDE_PID=15061) => code de sortie du hook : 0 la propre session du secondmate (15063) tire ensuite sur son home : | autoarm-trace: identity: proven by the delivering Claude session (pid 15063) => code de sortie du hook : 2 ### E. Verrou absent, puis verrou malformé | autoarm-trace: inert: no usable session lock, and neither identity proof applies => code de sortie du hook : 0 ; .lock=ABSENT (aucun .lock créé) => code de sortie du hook : 0 ; .lock=not-a-pid (conservé, jamais écrasé)

===============================================================================
 bin/fm-claude-stop-autoarm.sh exécuté à la main sous la chaîne de workers
 détachée de Claude Code : shell -> claude(worker) -> hook.
 Le pid propriétaire inscrit dans state/.lock n'est PAS dans cette ascendance.
 FM_CLAUDE_AUTOARM_TRACE=1 : chaque garde qui termine inerte se nomme.
===============================================================================

### A. AVANT le correctif (bin/ de main, f1a4af4) - la session PROPRIÉTAIRE elle-même
    state/.lock = 15057   CLAUDE_PID exporté = 15057
  | (aucune sortie -- silencieux)
  => code de sortie du hook : 0
  état : .lock=15057 | cycles d'armement=0 | ledger=ABSENT
    => sortie 0 muette, aucun armement, aucun ledger : le symptôme du capitaine reproduit.

### B. APRÈS le correctif - la même session propriétaire, même chaîne détachée
    state/.lock = 15058   CLAUDE_PID exporté = 15058
  | autoarm-trace: identity: proven by the delivering Claude session (pid 15058)
  | firstmate watcher wake - one supervision event needs a handling turn now.
  | signal: fixture watcher closed with actionable work
  | Run bin/fm-wake-drain.sh first, handle the wake, then run its exact WAKE_ACK_REQUIRED --ack-through command. Until that post-handling acknowledgement, interruption leaves the wake durable for idempotent re-handling. This Stop hook owns watcher continuity: when the handling turn ends, the next needed cycle arms automatically - do NOT run bin/fm-watch-arm.sh after an ordinary wake.
  => code de sortie du hook : 2
  état : .lock=15058 | cycles d'armement=1 | ledger=epoch=2 owner_pid=15183 outcome=rewake updated_at=1786795415
    => sortie 2, bannière de réveil livrée, ledger outcome=rewake : le home est réclamé.

### C1. CONTRE-PREUVE - une session ÉTRANGÈRE vivante tente de réclamer ce home
    state/.lock = 15059 (session vivante)   CLAUDE_PID exporté par l'intrus = 15069
  | autoarm-trace: inert: live session 15059 owns this home and neither identity proof applies (CLAUDE_PID=15069)
  => code de sortie du hook : 0
  état : .lock=15059 | cycles d'armement=0 | ledger=ABSENT
    => refus : .lock intact, aucun armement, aucun ledger.

### C2. Identité exportée que l'événement livré ne corrobore pas (env héritée d'un ancêtre)
    state/.lock = 15060   CLAUDE_PID = 15060   env session_id != payload session_id
  | autoarm-trace: inert: live session 15060 owns this home and neither identity proof applies (CLAUDE_PID=15060)
  => code de sortie du hook : 0
  état : .lock=15060 | cycles d'armement=0 | ledger=ABSENT
    => refus : la corrélation payload/env est le signal non héritable, sans elle rien ne passe.

### D. Deux homes firstmate sur la même machine
    home secondmate .lock = 15063 ; la session du home PRINCIPAL (15061) tire dessus
  | autoarm-trace: inert: live session 15063 owns this home and neither identity proof applies (CLAUDE_PID=15061)
  => code de sortie du hook : 0
  état : .lock=15063 | cycles d'armement=0 | ledger=ABSENT
    => le home du secondmate n'est pas réclamé par la session du home principal.
    la propre session du secondmate (15063) tire ensuite sur son home :
  | autoarm-trace: identity: proven by the delivering Claude session (pid 15063)
  | firstmate watcher wake - one supervision event needs a handling turn now.
  | signal: fixture watcher closed with actionable work
  | Run bin/fm-wake-drain.sh first, handle the wake, then run its exact WAKE_ACK_REQUIRED --ack-through command. Until that post-handling acknowledgement, interruption leaves the wake durable for idempotent re-handling. This Stop hook owns watcher continuity: when the handling turn ends, the next needed cycle arms automatically - do NOT run bin/fm-watch-arm.sh after an ordinary wake.
  => code de sortie du hook : 2
  état : .lock=15063 | cycles d'armement=1 | ledger=epoch=2 owner_pid=15699 outcome=rewake updated_at=1786795416
    => elle réclame bien SON home. Les deux homes restent indépendants.

### E. Verrou absent, puis verrou malformé
  | autoarm-trace: inert: no usable session lock, and neither identity proof applies
  => code de sortie du hook : 0
  état : .lock=ABSENT | cycles d'armement=0 | ledger=ABSENT
    => refus, et aucun .lock n'est créé.
  | autoarm-trace: inert: no usable session lock, and neither identity proof applies
  => code de sortie du hook : 0
  état : .lock=not-a-pid | cycles d'armement=0 | ledger=ABSENT
    => refus, et le .lock malformé est conservé tel quel, jamais écrasé.

===============================================================================
### Cas "aucune identite exportee" (CLAUDE_PID absent) - c'est le bug d'origine
state/.lock = 5159 (session vivante), le hook n'a aucun chemin d'ascendance vers elle
  | autoarm-trace: inert: live session 5159 owns this home and neither identity proof applies (CLAUDE_PID=60207)
  => code de sortie = 0 ; armements = 0
    idem avec CLAUDE_PID reellement absent de l'environnement :
  | autoarm-trace: inert: live session 7711 owns this home and neither identity proof applies (CLAUDE_PID=unset)
  => code de sortie = 0
    (les trois lignes de trace documentees dans docs/verification/supervision.md sont reproduites)
Evidence: Live opt-in guard against real Claude Code 2.1.233

$ FM_CLAUDE_LIVE_E2E=1 bash tests/fm-claude-stop-autoarm-live-e2e.test.sh ok - Claude 2.1.233 (Claude Code) live E2E reclaimed a stale session lock through session start, completed two tokenless Stop-owned rewake cycles, preserved the competing-live-owner boundary, and still delivers the session identity the ownership proof depends on

ok - Claude 2.1.233 (Claude Code) live E2E reclaimed a stale session lock through session start, completed two tokenless Stop-owned rewake cycles, preserved the competing-live-owner boundary, and still delivers the session identity the ownership proof depends on
Evidence: Real Claude Stop-hook identity, ancestry and hook run (live probe)

=== chemin de livraison : async === CLAUDE_PID exporté = 37849 CLAUDE_CODE_SESSION_ID = 278c6641-e4de-4bae-a1ea-c3c71851fdc7 payload livré = {"session_id":"278c6641-e4de-4bae-a1ea-c3c71851fdc7", ... ,"hook_event_name":"Stop","stop_hook_active":false, ...} -- ascendance réelle du processus hook (pid ppid commande) -- 40205 37849 bash .../probe.sh async 37849 37846 claude -p Reply with exactly OK and stop. Use no tools. --dangerously-skip-permissions --effort low == state/.lock écrit par la session = 37849 == autoarm-trace: identity: proven by harness ancestry firstmate watcher wake - one supervision event needs a handling turn now. == code de sortie du hook = 2 (2 = réveil livré) == == ledger state/.claude-autoarm-epoch : epoch=2 owner_pid=40274 outcome=rewake ==

=== chemin de livraison : sync ===
CLAUDE_PID exporté        = 37849
CLAUDE_CODE_SESSION_ID    = 278c6641-e4de-4bae-a1ea-c3c71851fdc7
payload livré             = {"session_id":"278c6641-e4de-4bae-a1ea-c3c71851fdc7","transcript_path":"/Users/max/.claude/projects/-private-tmp-fm-live-probe-2biq6K-project/278c6641-e4de-4bae-a1ea-c3c71851fdc7.jsonl","cwd":"/private/tmp/fm-live-probe-2biq6K/project","prompt_id":"40c117de-7351-43a1-8c67-7c3d2b282bfb","permission_mode":"bypassPermissions","effort":{"level":"low"},"hook_event_name":"Stop","stop_hook_active":false,"last_assistant_message":"OK","background_tasks":[],"session_crons":[]}

-- ascendance réelle du processus hook (pid ppid commande) --
40204 37849 bash /private/tmp/fm-live-probe-2biq6K/project/probe.sh sync
37849 37846 claude -p Reply with exactly OK and stop. Use no tools. --dangerously-skip-permissions --effort low
37846 60207 /bin/zsh -c source /Users/max/.claude/shell-snapshots/snapshot-zsh-1786795084064-zfyoi3.sh 2>/dev/null || true && setopt NO_EXTENDED_GLOB 
60207  1157 claude -p --verbose --output-format stream-json --setting-sources user --json-schema {\012\011"type": "object",\012\011"properties": {\012
 1157     1 /Users/max/.no-mistakes/bin/no-mistakes daemon run --root /Users/max/.no-mistakes
-- fin ascendance : le pid de session 37849 y figure-t-il ? --

=== chemin de livraison : async ===
CLAUDE_PID exporté        = 37849
CLAUDE_CODE_SESSION_ID    = 278c6641-e4de-4bae-a1ea-c3c71851fdc7
payload livré             = {"session_id":"278c6641-e4de-4bae-a1ea-c3c71851fdc7","transcript_path":"/Users/max/.claude/projects/-private-tmp-fm-live-probe-2biq6K-project/278c6641-e4de-4bae-a1ea-c3c71851fdc7.jsonl","cwd":"/private/tmp/fm-live-probe-2biq6K/project","prompt_id":"40c117de-7351-43a1-8c67-7c3d2b282bfb","permission_mode":"bypassPermissions","effort":{"level":"low"},"hook_event_name":"Stop","stop_hook_active":false,"last_assistant_message":"OK","background_tasks":[],"session_crons":[]}

-- ascendance réelle du processus hook (pid ppid commande) --
40205 37849 bash /private/tmp/fm-live-probe-2biq6K/project/probe.sh async
37849 37846 claude -p Reply with exactly OK and stop. Use no tools. --dangerously-skip-permissions --effort low
37846 60207 /bin/zsh -c source /Users/max/.claude/shell-snapshots/snapshot-zsh-1786795084064-zfyoi3.sh 2>/dev/null || true && setopt NO_EXTENDED_GLOB 
60207  1157 claude -p --verbose --output-format stream-json --setting-sources user --json-schema {\012\011"type": "object",\012\011"properties": {\012
 1157     1 /Users/max/.no-mistakes/bin/no-mistakes daemon run --root /Users/max/.no-mistakes
-- fin ascendance : le pid de session 37849 y figure-t-il ? --

== state/.lock écrit par la session = 37849 ==
== exécution réelle de bin/fm-claude-stop-autoarm.sh, FM_CLAUDE_AUTOARM_TRACE=1 ==
autoarm-trace: identity: proven by harness ancestry
firstmate watcher wake - one supervision event needs a handling turn now.
signal: live-probe actionable close
Run bin/fm-wake-drain.sh first, handle the wake, then run its exact WAKE_ACK_REQUIRED --ack-through command. Until that post-handling acknowledgement, interruption leaves the wake durable for idempotent re-handling. This Stop hook owns watcher continuity: when the handling turn ends, the next needed cycle arms automatically - do NOT run bin/fm-watch-arm.sh after an ordinary wake.

== code de sortie du hook = 2 (2 = réveil livré) ==
== ledger state/.claude-autoarm-epoch : epoch=2 owner_pid=40274 outcome=rewake updated_at=1786795558 ==

== contenu final de state/ ==
probe-async.log
probe-sync.log
task.meta

== contenu final de state/ (dotfiles inclus) ==
.
..
.claude-autoarm-epoch
.lock
probe-async.log
probe-sync.log
task.meta

NOTE: dans cette session headless `claude -p`, la session est le parent DIRECT du hook,
donc c' est la preuve d'ascendance qui a porte le verdict. La forme detachee
(worker pool partage, sans chemin vers la session) est reproduite avec de vrais
processus dans tests/fm-claude-stop-autoarm.test.sh et dans manual-repro-transcript.txt.
Evidence: Auto-arm portable suite (27 cases, owner of the changed behavior)

ok - auto-arm: claims the home from a worker chain that cannot reach its own session ok - auto-arm: a session that does not hold the lock still cannot claim the home ok - auto-arm: an unconfirmed, absent, or malformed session identity never claims the home ok - auto-arm: a missing or malformed recorded owner is refused through every identity path ok - auto-arm: two homes on one machine stay independent under the session-identity proof

ok - auto-arm: inert in a linked child worktree even when in-flight
ok - auto-arm: inert with no session lock
ok - auto-arm: a demonstrably dead recorded session owner is reclaimed through fm-lock.sh before arming
ok - auto-arm: inert without arm, rewake, or lock replacement when another live harness owns the home
ok - auto-arm: inert while AFK owns supervision
ok - auto-arm: stale-owner recovery leaves the AFK and supervision-need gates unchanged
ok - auto-arm: resolves the outermost pid of a nested contiguous claude ancestry (bg-spare chain)
ok - auto-arm: claims the home from a worker chain that cannot reach its own session
ok - auto-arm: a session that does not hold the lock still cannot claim the home
ok - auto-arm: an unconfirmed, absent, or malformed session identity never claims the home
ok - auto-arm: a missing or malformed recorded owner is refused through every identity path
ok - auto-arm: two homes on one machine stay independent under the session-identity proof
ok - auto-arm: inert with nothing in flight and no X-mode need
ok - auto-arm: actionable close translates to exactly one exit-2 rewake with reason
ok - auto-arm: actionable close survives a healthy successor without duplicate delivery
ok - auto-arm: bounded failure verification emits one automatic-mechanism alarm
ok - auto-arm: consecutive failures keep Stop-owned retry without repeating notice
ok - auto-arm: unverified clean close exhausts retries and fails closed
ok - auto-arm: post-alarm actionable outcomes cannot continue or reset failure state
ok - auto-arm: benign cycle end with a live watcher and fresh beacon stays silent across the next cycle
ok - auto-arm: budget contention preserves the episode and forces a reset retry
ok - auto-arm: X-mode poll need arms the cycle even with no tasks in flight
ok - auto-arm: concurrent firings admit one owner and one rewake translation
ok - auto-arm: need vanishing mid-cycle closes without a rewake
ok - auto-arm: mid-cycle AFK hands triage to the daemon with no rewake
ok - auto-arm: active in a marked secondmate home
ok - fm-lock: shared session-lock lib preserves the status path
Evidence: Targeted suites around the identity contract

FM_TEST_END tests/fm-claude-stop-autoarm.test.sh exit=0 FM_TEST_END tests/fm-session-lock-ancestry.test.sh exit=0 FM_TEST_END tests/fm-turnend-guard.test.sh exit=0 FM_TEST_END tests/fm-watch-arm.test.sh exit=0 FM_TEST_END tests/fm-watcher-lock.test.sh exit=0 FM_TEST_END tests/fm-session-start.test.sh exit=0 FM_TEST_SUMMARY total=6 failed=0 skipped_gate=0

FM_TEST_BEGIN 2026-08-15T12:07:24Z tests/fm-claude-stop-autoarm.test.sh family=unclassified expected_gate_skip=none
ok - auto-arm: inert in a linked child worktree even when in-flight
ok - auto-arm: inert with no session lock
ok - auto-arm: a demonstrably dead recorded session owner is reclaimed through fm-lock.sh before arming
ok - auto-arm: inert without arm, rewake, or lock replacement when another live harness owns the home
ok - auto-arm: inert while AFK owns supervision
ok - auto-arm: stale-owner recovery leaves the AFK and supervision-need gates unchanged
ok - auto-arm: resolves the outermost pid of a nested contiguous claude ancestry (bg-spare chain)
ok - auto-arm: claims the home from a worker chain that cannot reach its own session
ok - auto-arm: a session that does not hold the lock still cannot claim the home
ok - auto-arm: an unconfirmed, absent, or malformed session identity never claims the home
ok - auto-arm: a missing or malformed recorded owner is refused through every identity path
ok - auto-arm: two homes on one machine stay independent under the session-identity proof
ok - auto-arm: inert with nothing in flight and no X-mode need
ok - auto-arm: actionable close translates to exactly one exit-2 rewake with reason
ok - auto-arm: actionable close survives a healthy successor without duplicate delivery
ok - auto-arm: bounded failure verification emits one automatic-mechanism alarm
ok - auto-arm: consecutive failures keep Stop-owned retry without repeating notice
ok - auto-arm: unverified clean close exhausts retries and fails closed
ok - auto-arm: post-alarm actionable outcomes cannot continue or reset failure state
ok - auto-arm: benign cycle end with a live watcher and fresh beacon stays silent across the next cycle
ok - auto-arm: budget contention preserves the episode and forces a reset retry
ok - auto-arm: X-mode poll need arms the cycle even with no tasks in flight
ok - auto-arm: concurrent firings admit one owner and one rewake translation
ok - auto-arm: need vanishing mid-cycle closes without a rewake
ok - auto-arm: mid-cycle AFK hands triage to the daemon with no rewake
ok - auto-arm: active in a marked secondmate home
ok - fm-lock: shared session-lock lib preserves the status path
FM_TEST_END 2026-08-15T12:08:26Z tests/fm-claude-stop-autoarm.test.sh exit=0 duration_ms=61136 gate_skip=false
FM_TEST_BEGIN 2026-08-15T12:08:26Z tests/fm-session-lock-ancestry.test.sh family=watcher-wake-lock expected_gate_skip=none
ok - session-lock: a version-named Claude Code session is identified from its install path and argv[0]
ok - session-lock: ordinary script paths under a harness directory are not harness processes
ok - session-lock: ownership stops at the first non-harness gap above the contiguous run
ok - session-lock: a live version-named session holding the lock is not mistaken for a stale owner
ok - session-lock e2e: a version-named session claims the home and arms supervision
ok - session-lock e2e: a session parented by a harness-named daemon claims the home and arms supervision
ok - session-lock e2e: a version-named session under a harness-named daemon keeps its own lock
FM_TEST_END 2026-08-15T12:08:29Z tests/fm-session-lock-ancestry.test.sh exit=0 duration_ms=3156 gate_skip=false
FM_TEST_BEGIN 2026-08-15T12:08:29Z tests/fm-turnend-guard.test.sh family=watcher-wake-lock expected_gate_skip=none
ok - fm_supervision_unhealthy: false with no state/*.meta at all
ok - fm_supervision_unhealthy: true with in-flight task and no beacon ever
ok - fm_supervision_unhealthy: true with in-flight task and a beacon far outside the grace window
ok - fm_supervision_unhealthy: false with in-flight task and a fresh beacon
ok - fm_supervision_status: FM_SUP_QUEUE_PENDING tracks state/.wake-queue
ok - fm_supervision_needed: X-mode relay poll needs supervision
ok - fm_supervision_unhealthy: source-only home needs supervision
ok - fm-turnend-guard: silent no-op with nothing in flight
ok - fm-turnend-guard: blocks when a fresh beacon has no live watcher lock
ok - fm-turnend-guard: non-Claude path blocks a source-only home
ok - fm-turnend-guard: blocks on a dead watcher lock even when the beacon is fresh
ok - fm-turnend-guard: silent no-op with a live watcher lock and fresh beacon
ok - fm-turnend-guard: healthy non-Claude harness paths ignore Claude episode contention
ok - fm-turnend-guard: blocks on a live watcher lock with an ancient beacon
ok - fm-turnend-guard: blocks with the exact required reason in the primary when unhealthy
ok - fm-turnend-guard: blocks from active FM_HOME state, not only repo-root state
ok - fm-turnend-guard: X-mode repair reason sources the cadence config
ok - fm-turnend-guard: X-mode-only supervision remains guarded in default mode
ok - fm-turnend-guard: ignores stale repo-root state when FM_HOME is set
ok - fm-turnend-guard: uses FM_STATE_OVERRIDE ahead of FM_HOME/state
ok - fm-turnend-guard: stop_hook_active=true always allows the stop (never blocks twice in one turn)
ok - fm-turnend-guard: blocks a blind turn end in a secondmate's own home (.fm-secondmate-home no longer excludes it)
ok - fm-turnend-guard: idle-by-default - silent in a secondmate home with nothing in flight
ok - fm-turnend-guard: stop_hook_active=true allows the stop in a secondmate home (never blocks twice in one turn)
ok - fm-turnend-guard: secondmate deferred-death recovery - silent while watched, forces re-arm once the watcher exits
ok - fm-turnend-guard: inert in a secondmate's own child worktree (linked git worktree) even when unhealthy
ok - fm-turnend-guard: blocks a blind turn end in a treehouse-leased LINKED secondmate home (marker force-include)
ok - fm-turnend-guard: an invalid (empty) marker cannot spoof inclusion; linked worktree stays exempt
ok - fm-turnend-guard: a non-ASCII marker cannot spoof inclusion; linked worktree stays exempt
ok - fm-turnend-guard: inert in a crewmate/scout task worktree (linked git worktree) even when unhealthy
ok - fm-turnend-guard: fails open (never blocks) when jq is missing
ok - fm-turnend-guard: silent no-op on empty stdin
ok - fm-turnend-guard: runs well under the generous timing margin (0s)
ok - fm-turnend-guard-grok: forces one explicitly marked same-session resume when the shared predicate blocks
ok - fm-turnend-guard-grok: legacy environment loop guard prevents a nested resume loop
ok - fm-turnend-guard-grok: native false delegates blocking feedback with zero resume processes
ok - fm-turnend-guard-grok: native true remains bounded and starts no resume process
ok - fm-turnend-guard-grok: both spellings are typed and camelCase has deterministic precedence
ok - fm-turnend-guard-grok: malformed, invalidly typed, and missing-prerequisite payloads start neither path
ok - fm-turnend-guard-grok: missing jq and no-supervision-needed stops stay silent and bounded
ok - tracked .claude/settings.json entries: 5 inert under grok, the documented subagent exception still armed, all live under Claude
ok - .codex/hooks.json: Stop hook uses hook process root when payload cwd is outside
ok - .codex/hooks.json: Stop hook ignores nested git root guard scripts
ok - .opencode primary plugin: guard path is anchored to worktree, not directory
ok - .pi primary extension: no-tool and multi-tool runs each inject exactly one guard follow-up
ok - .pi primary extension: delivery failure resets the logical-run latch
ok - fm-turnend-guard --claude: re-blocks a loop-guarded stop while unhealthy and unclaimed (incident regression)
ok - fm-turnend-guard --claude: X-mode-only homes re-block when auto-arm recovery is absent
ok - fm-turnend-guard --claude: a live arming epoch advances once and repeated observation is idempotent
ok - fm-turnend-guard --claude: repeated failed-to-arming races make bounded monotonic progress
ok - fm-turnend-guard --claude: terminal owner boundary excludes a concurrent start without deadlock
ok - fm-turnend-guard --claude: fresh rewake epoch prevents a duplicate continuation for the same event
ok - fm-turnend-guard --claude: fresh failed epochs preserve and advance monotonic fail-open progression
ok - fm-turnend-guard --claude: integrated fresh failures reach one bounded fail-open, stop continuation, and re

... [3263 bytes truncated] ...

-arm: downtime marker publication does not follow symlinks
FM_TEST_END 2026-08-15T12:10:05Z tests/fm-watch-arm.test.sh exit=0 duration_ms=61152 gate_skip=false
FM_TEST_BEGIN 2026-08-15T12:10:05Z tests/fm-watcher-lock.test.sh family=watcher-wake-lock expected_gate_skip=none
ok - simultaneous watcher starts leave exactly one live process
ok - fm_pid_identity real ps fallback is locale-invariant
ok - fm_pid_identity is locale-invariant across LC_ALL/LC_TIME
ok - /proc process identity ignores simulated btime changes
ok - /proc process identity detects pid reuse
ok - MSYS /proc process identity regression skipped on non-Windows host
ok - killed watcher stale lock is reclaimed
tests/fm-watcher-lock.test.sh: line 1038: 23262 Killed: 9               FM_STATE_OVERRIDE="$state" bash -c '
    . "$1"
    fm_lock_remove_path() {
      if [ "$1" = "$STATE/.watch.lock" ]; then
        kill -KILL "${BASHPID:-$$}"
      fi
      return 1
    }
    fm_lock_try_acquire "$2"
  ' _ "$LIB" "$lockdir" > /dev/null 2>&1
ok - stale watcher reclaim publishes durable recovery evidence before clear
ok - live watcher lock with stale heartbeat is actionable
ok - guard banner leads when down with pending wakes (repair-after-drain) and stays silent when live and fresh
ok - concurrent fm_lock_try_acquire yields exactly one winner
ok - dead-pid stale lock is reclaimed by a single acquirer
ok - concurrent stale-lock steal yields exactly one winner
ok - live steal mutex is not reclaimed
ok - live-held lock is not stolen
ok - empty mid-acquire lock keeps a minimum grace
ok - late original claimant cannot claim a recreated lock
ok - paused mid-acquire claimant backs off to active stealer
ok - watch restart preserves recovery without signaling a reused pid
ok - watch restart attaches to a verified healthy peer and later surfaces a successor gap
ok - watcher self-evicts when the lock pid no longer names it
ok - arm turns clean self-eviction without a successor into a typed failure
ok - arm attaches to a live fresh watcher and fails loudly when that cycle has no successor
ok - attached arm signals record a classified lifecycle entry
ok - arm starts cleanly and resurfaces recovery after a dead-pid lock
ok - arm cleans child watcher and temp output on HUP
WAKE_ACK_REQUIRED: after handling completes run bin/fm-wake-drain.sh --ack-through 1 --recovery-generation 37492.1786795837.mruAF3
ok - arm propagates an immediate watcher wake before confirmation
ok - arm attaches to a peer watcher after child stands down and surfaces a missing successor
watcher: lock held by live pid 39014 but heartbeat is stale for 840114641s (>300s); inspect or stop that watcher before re-arming.
ok - arm reports FAILED and exits non-zero when no fresh watcher can be confirmed
ok - cycle-exit ledger links a verified successor and remains size-capped
ok - SIGSTOP distinguishes live PID from stale beacon and termination records the exit class
FM_TEST_END 2026-08-15T12:11:20Z tests/fm-watcher-lock.test.sh exit=0 duration_ms=74983 gate_skip=false
FM_TEST_BEGIN 2026-08-15T12:11:20Z tests/fm-session-start.test.sh family=session-bootstrap expected_gate_skip=none
ok - context digest distinguishes ABSENT, empty-but-present, and populated files
ok - a lock refusal prints a loud read-only banner, skips every mutating step, and still completes the digest
ok - session start stays read-only when lock ownership cannot be published
ok - locked session start freezes trace context and lock refusal leaves it unchanged
ok - concurrent session-lock acquisition admits exactly one live harness
ok - digest sections are ordered safety-preamble first, live fleet state before curated memory
ok - the read-once contract is stated once, ahead of the sources it governs
ok - session start: configured and auto-detected Herdr homes never require tmux
ok - session start: an absent recorded tmux window relaunches its Pi secondmate exactly once, off the blocking path
ok - session start: a deferred relaunch is always reported, so the digest's stale endpoint record cannot stand
ok - session start: an unreachable host delays a reported check, not the digest
ok - session start: a deferred result the digest outran still reaches the agent as a wake
ok - session start: a read-only session declares its skipped network checks rather than dropping them
ok - session start: the tasks-axi compatibility verdict is computed once and reused
ok - session start: an existing ambiguous Pi process prevents duplicate recovery
ok - session start: transient tmux unreadability never licenses a relaunch
ok - session start: the proven bare-shell recovery path remains intact
ok - session start: a confirmed Herdr husk is closed and relaunched
ok - status tail is bounded to the configured line count, with the full log path always printed
ok - status tail lines are capped with a truncation marker while the full log stays reachable
ok - orphan status logs are printed once with bounded tails
ok - tmux endpoint liveness is reported per task: alive for a live window, dead for a gone one
ok - herdr endpoint liveness is reported per task: alive for a live pane, dead for a gone one
ok - fm-session-start.sh composes the real fm-lock.sh, fm-bootstrap.sh, and fm-wake-drain.sh output verbatim
ok - compatible tasks-axi backlog rendering drops done rows and keeps every in-flight, held, and blocked row
ok - the startup backlog bound cuts only dispatchable queued rows and discloses the remainder exactly
ok - manual backlog rendering drops done rows, keeps every held or blocked title line, and bounds the rest
ok - unavailable or incompatible tasks-axi falls back to compact manual backlog rendering
ok - an empty fleet reports (none) for in-flight tasks and an absent AFK flag
ok - session start emits X-mode cadence guidance in the harness supervision block
ok - next step delegates watcher ownership to the AFK daemon
ok - session start emits exactly one detected harness block and reports Pi extension load state
ok - session start preserves pi-signed primary identity while applying Pi extension guarantees
ok - session start rejects stale Pi loaded markers
ok - session start accepts current Pi markers written before lock acquisition
ok - session start rejects Pi sessions missing the turn-end guard marker
ok - session start rejects Pi loaded markers from previous sessions
ok - the pure-Bash watchdog bounds session start, kills its hung grandchild, and emits the truncation contract
ok - the portable timeout path force-kills a command that ignores TERM
ok - a session start inside its budget prints no truncation banner
ok - the runtime bound leaves enough ancestry headroom for a deeply nested session to take the lock
ok - --reemit reprints the digest without repeating startup's mutating sweeps and still drains queued wakes
ok - true-start AGENTS baselines stay immutable while every drifted Pi compact re-emits the current contract
ok - read-only Pi compact refreshes against the rebuilding session identity without mutation
ok - Codex reset sources do not claim an unavailable instruction-refresh channel
ok - instruction baselines require SHA-256 and successful startup completion
ok - --reemit re-verifies lock ownership and keeps repair ownership with whoever holds it
# fm-session-start.test.sh: all assertions passed
FM_TEST_END 2026-08-15T12:14:30Z tests/fm-session-start.test.sh exit=0 duration_ms=190738 gate_skip=false
FM_TEST_SUMMARY total=6 failed=0 skipped_gate=0 duration_ms=425863
FM_TEST_SUMMARY_FAMILY family=session-bootstrap count=1 duration_ms=190738 failed=0
FM_TEST_SUMMARY_FAMILY family=unclassified count=1 duration_ms=61136 failed=0
FM_TEST_SUMMARY_FAMILY family=watcher-wake-lock count=4 duration_ms=173748 failed=0
FM_TEST_SLOWEST rank=1 script=tests/fm-session-start.test.sh duration_ms=190738
FM_TEST_SLOWEST rank=2 script=tests/fm-watcher-lock.test.sh duration_ms=74983
FM_TEST_SLOWEST rank=3 script=tests/fm-watch-arm.test.sh duration_ms=61152
FM_TEST_SLOWEST rank=4 script=tests/fm-claude-stop-autoarm.test.sh duration_ms=61136
FM_TEST_SLOWEST rank=5 script=tests/fm-turnend-guard.test.sh duration_ms=34457
FM_TEST_SLOWEST rank=6 script=tests/fm-session-lock-ancestry.test.sh duration_ms=3156

Pipeline

Updates from git push no-mistakes

... (4 earlier update rounds omitted to keep the PR body within GitHub's 65536-char limit; full history is in the run log.)

⚠️ **Review** - 3 infos

🔧 Fix: guard the detached Stop path, rename autoarm trace flag
4 issues (1 warning, 3 infos) still open:

  • ⚠️ docs/verification/supervision.md:487 - L'entrée de preuve atteste un passage du garde live qui ne correspond plus au test présent dans l'arbre. Le paragraphe « The live guard ran against Claude Code 2.1.233 on the same date » et sa liste « Observed: ... » ont été écrits dans d8236d1, où le garde ne mesurait que le chemin Stop SYNCHRONE. Le commit 630eb13 (tour de correction du pipeline) a ensuite ajouté 62 lignes à tests/fm-claude-stop-autoarm-live-e2e.test.sh — tout le bloc d'alarme sur le chemin asyncRewake détaché, lignes 190-218 — et n'a pas touché ce paragraphe. Le même commit a aussi réécrit les chaînes de trace citées en 476-478 sans nouvelle exécution instrumentée. Conséquence concrète : un mainteneur qui lit cette page conclut que l'alarme détachée a été exercée contre Claude Code 2.1.233, alors que c'est la seule assertion neuve couvrant le chemin sur lequel bin/fm-claude-stop-autoarm.sh tourne réellement, et qu'elle n'a jamais été exécutée. Le tier 5 de l'arbre de placement (.agents/skills/firstmate-coding-guidelines/SKILL.md:30-31) réserve cette page aux commandes et sorties EXACTES, et la règle des harness-dependent checks fait du garde live opt-in une pièce obligatoire du livrable. Deux issues acceptables : relancer FM_CLAUDE_LIVE_E2E=1 tests/fm-claude-stop-autoarm-live-e2e.test.sh et enregistrer le résultat réel, ou qualifier l'entrée en disant explicitement que l'alarme du chemin détaché et les chaînes de trace actuelles n'ont pas encore été observées en live. Point supplémentaire à trancher par le propriétaire : la sonde asyncRewake ajoutée porte le nombre de hooks asyncRewake du labo à deux (l'auto-arm suivi de la sonde), alors qu'aucun fait fournisseur vérifié du dépôt n'établit que Claude Code en exécute plus d'un par Stop — docs/turnend-guard.md:52 et .agents/skills/harness-adapters/SKILL.md:207 ne documentent qu'une seule inscription asyncRewake.
  • ℹ️ docs/verification/supervision.md:292 - Phrase de contrat au présent devenue fausse : « Session-lock ownership in bin/fm-session-lock-lib.sh is decided against a session's whole contiguous harness ancestry rather than one chosen pid ». Depuis ce changement, la propriété peut précisément être décidée par UN pid choisi : fm_session_lock_owned_by_claude_hook (bin/fm-session-lock-lib.sh:217) exige lock_pid = CLAUDE_PID, une égalité stricte, et la disjonction de bin/fm-session-lock-lib.sh:265 l'accepte comme preuve alternative. C'est exactement la même classe de péremption que le tour 2 a corrigée dans docs/scripts.md:39 et dans l'en-tête de la lib, mais ce site frère a été manqué. La correction est d'une phrase : ajouter que la propriété se décide désormais par appartenance à l'ascendance OU par l'identité de session livrée avec l'événement, et renvoyer à docs/watcher-continuity.md:15-19 qui possède le contrat, sans en recopier la substance.
  • ℹ️ .agents/skills/harness-adapters/SKILL.md:205 - Deux faits fournisseur nouvellement vérifiés par ce travail ne sont enregistrés nulle part chez leur propriétaire. Le bloc « Primary-session guard fact » de ce skill est déjà le propriétaire des faits Claude Code vérifiés de cette exacte nature — il porte la sémantique de stop_hook_active dans la charge utile Stop (208), la résolution de la racine projet (209) et l'exécution des commandes de hook via /bin/sh (210). Les deux faits manquants sont : (a) tout hook Stop reçoit CLAUDE_PID et CLAUDE_CODE_SESSION_ID, et le session_id de la charge utile égale l'identifiant exporté ; (b) Claude Code sert les commandes de hook et d'outil depuis un pool de travailleurs partagé par utilisateur sous /tmp/cc-daemon-<uid>/, dont le processus de tête est réparenté à init et survit à la session qui l'a démarré. Le fait (b) est le plus important car il déborde largement ce hook : il invalide toute décision fondée sur l'ascendance dans la flotte. Aujourd'hui ces deux faits n'existent que dans docs/verification/supervision.md, une page de preuves (tier 5), et dans les deux fichiers source qui les consomment — alors que l'arbre de placement les range au tier 2, le skill agent. L'intent déclare explicitement que cet arbre a été appliqué. Ajouter les deux faits, datés et versionnés comme leurs voisins, au bloc existant.
  • ℹ️ bin/fm-sessionstart-run.sh:78 - Note de suivi, hors périmètre déclaré, à ne pas traiter dans ce changement. Le même fait fournisseur laisse deux appelants qui décident encore sur l'ascendance seule, et le chemin y est concret. session_start_completed() appelle fm_session_lock_owned_by_self : si le hook SessionStart est servi par un pool orphelin, le prédicat échoue, la fonction rend 1, et le routage clear|compact (bin/fm-sessionstart-run.sh:117-120) relance un digest COMPLET au lieu du --reemit prévu — donc un balayage de démarrage complet à chaque /clear et chaque /compact. Ce n'est pas la panne d'origine et la direction est fail-safe, l'en-tête du fichier assume d'ailleurs la redondance comme « cheap and idempotent ». Même remarque pour bin/fm-startup-network.sh:199 et :397, qui dégradent en locked=0 plutôt que d'échouer. Aucun risque de sûreté, aucune revendication étrangère possible : je le signale uniquement pour que le capitaine sache que la deuxième preuve d'identité n'est aujourd'hui câblée que sur le hook Stop, et que ces deux sites restent sensibles au même pool si le symptôme réapparaît ailleurs. L'intent limite explicitement ce travail à l'auto-arm Stop, donc ne pas élargir ici.

🔧 Fix: record the measured live-guard evidence and vendor facts
3 infos still open:

  • ℹ️ docs/verification/supervision.md:474 - La seule commande de diagnostic documentée pour cette panne se bloque telle qu'écrite. La ligne 474 présente FM_CLAUDE_AUTOARM_TRACE=1 bin/fm-claude-stop-autoarm.sh comme la façon de diagnostiquer un hook inerte, mais le hook consomme sa charge utile en ligne 107 avec PAYLOAD=$(cat 2&gt;/dev/null || true). Lancée depuis un terminal sans redirection, la commande attend indéfiniment sur l'entrée standard : l'opérateur ne voit aucune trace tant qu'il n'a pas deviné qu'il faut envoyer Ctrl-D. L'intent fait explicitement du diagnostic instrumenté une pièce du livrable (« INSTRUMENT FIRST: run bin/fm-claude-stop-autoarm.sh by hand under real conditions with traces »), et le tier 5 de l'arbre de placement réserve cette page aux commandes EXACTES. La forme complète manque aussi le contexte que la ligne 483 suppose : il faut viser une home de fixture. Correctif d'une ligne : documenter la commande sous une forme exécutable, par exemple printf &#39;{&#34;session_id&#34;:&#34;x&#34;}&#39; | FM_HOME=&lt;fixture&gt; FM_CLAUDE_AUTOARM_TRACE=1 bin/fm-claude-stop-autoarm.sh, ou au minimum ajouter &lt;/dev/null.
  • ℹ️ docs/verification/supervision.md:292 - La phrase corrigée au tour 3 est exacte sur la bibliothèque mais généralise à toute la flotte une propriété qui n'appartient qu'au hook Stop de Claude. « Session-lock ownership in bin/fm-session-lock-lib.sh is decided by either of two proofs » se lit comme le contrat de propriété du verrou de session en général, alors que le seul appelant de la disjonction est bin/fm-claude-stop-autoarm.sh (lignes 133 et 183). Tous les autres décident encore sur l'ascendance seule : bin/fm-lock.sh, bin/fm-sessionstart-run.sh:78, bin/fm-turnend-guard-cursor.sh:235/241/246, bin/fm-startup-network.sh:199/397. Un mainteneur qui debug le ré-emit du digest après /clear ou la fenêtre read-only du démarrage réseau conclura de cette page que la seconde preuve s'y applique déjà, ce qui est faux. Une subordonnée suffit : préciser que la disjonction est aujourd'hui câblée sur le hook Stop de Claude, les autres appelants restant sur la preuve d'ascendance.
  • ℹ️ tests/fm-claude-stop-autoarm-live-e2e.test.sh:102 - Le format de journal de la sonde rend l'alarme fournisseur fragile dans le sens qui accuse à tort. La sonde écrit printf &#39;payload=%s\n&#39; &#34;$PAYLOAD&#34; et les deux blocs de vérification relisent avec sed -n &#39;s/^payload=//p&#39; | sed -n &#39;1p&#39; (lignes 168 et 207), donc seule la PREMIÈRE ligne de la charge utile est relue. J'ai vérifié empiriquement que fm_claude_payload_session_id gère parfaitement un JSON pretty-printed (il rend bien pretty-1 sur un payload multiligne) : si une version future de Claude Code passe le payload Stop en multiligne, le code de production continue de fonctionner, mais le garde relit { seul, l'extraction échoue et le test accuse le fournisseur d'avoir cessé de nommer un session_id, en imprimant un payload tronqué à un seul caractère. C'est un faux positif sur la seule alarme qui protège ce chemin, et le message oriente vers la mauvaise hypothèse. Correctif local à la sonde, sans toucher aux assertions : normaliser la charge utile sur une ligne avant l'écriture, par exemple printf &#39;payload=%s\n&#39; &#34;$(printf &#39;%s&#39; &#34;$PAYLOAD&#34; | tr -d &#39;\n&#39;)&#34;.
✅ **Test** - passed

✅ No issues found.

  • tests/fm-claude-stop-autoarm.test.sh — 27 cases green including the 5 new detached-chain identity cases
  • Manual instrumented reproduction: bin/fm-claude-stop-autoarm.sh run by hand under a simulated detached Claude worker chain with FM_CLAUDE_AUTOARM_TRACE=1, real live lock-owner processes, before/after bin/ swapped between f1a4af4 and the branch
  • Counter-proof scenarios in the same reproduction: foreign live session, payload/env session-id mismatch, missing lock, malformed lock, main-home session firing at a secondmate home
  • Reproduced all three trace strings documented in docs/verification/supervision.md, including the CLAUDE_PID=unset variant via env -u CLAUDE_PID -u CLAUDE_CODE_SESSION_ID
  • FM_CLAUDE_LIVE_E2E=1 bash tests/fm-claude-stop-autoarm-live-e2e.test.sh against real Claude Code 2.1.233 — passed in full
  • Live probe: isolated claude -p session with synchronous + asyncRewake Stop hooks capturing CLAUDE_PID, CLAUDE_CODE_SESSION_ID, payload session_id and full process ancestry, then running the real hook
  • ./bin/fm-test-run.sh tests/fm-claude-stop-autoarm.test.sh tests/fm-session-lock-ancestry.test.sh tests/fm-turnend-guard.test.sh tests/fm-watch-arm.test.sh tests/fm-watcher-lock.test.sh tests/fm-session-start.test.sh — total=6 failed=0
⚠️ **Document** - 2 issues (1 warning, 1 info)
  • ⚠️ docs/sessionstart-nudge.md:61 - Suivi hors périmètre (contradiction révélée, pas corrigée ici car elle exigerait un changement de comportement) : .agents/skills/harness-adapters/SKILL.md:213 enregistre désormais la règle générale « a hook's contiguous harness ancestry does not reliably contain its own live session and no fleet decision may assume it does », alors que docs/sessionstart-nudge.md:61-62 documente encore une décision de flotte fondée uniquement sur l'ascendance : le wrapper SessionStart (bin/fm-sessionstart-run.sh, enregistré comme hook Claude dans .claude/settings.json) marche au plus huit parents depuis son propre pid et reste silencieux seulement si state/.lock nomme un pid vivant de cette ascendance. Servi depuis le pool de workers partagé, ce hook peut manquer sa propre session et rejouer le nudge alors que fm-session-start.sh a déjà tourné. La direction d'échec est bénigne (nudge redondant, jamais un refus d'ouverture de session), donc rien n'est faux dans le code aujourd'hui décrit par ce document — mais l'invariant nouvellement écrit et cette page divergent. Le traiter demande de décider si le nudge doit adopter la seconde preuve d'identité, ce qui est un changement de comportement interdit à cette phase.
  • ℹ️ docs/supervision-protocols/claude.md:13 - Décision de placement assumée : docs/supervision-protocols/claude.md:13 dit toujours « If the Stop hook does not claim the home or reports an exhausted failure, inspect its registration and watcher startup path before ending blind », sans pointer vers FM_CLAUDE_AUTOARM_TRACE, qui est pourtant le diagnostic exact de ce symptôme. Je ne l'ai pas ajouté : cette surface est un contrat agent-runtime rendu dans chaque bloc de session (et figé par tests/fm-supervision-instructions.test.sh, que cette phase ne peut pas toucher), la phrase existante reste vraie, et le drapeau a déjà un propriétaire unique dans docs/configuration.md avec ses preuves dans docs/verification/supervision.md. Ajouter le pointeur ici dupliquerait un fait déjà possédé ailleurs dans une instruction toujours chargée.
✅ **Lint** - passed

✅ No issues found.

✅ **Push** - passed

✅ No issues found.

…session

The Stop-owned watcher auto-arm proved its right to act with harness
ancestry alone: state/.lock had to name one of the hook process's own
contiguous harness ancestors. Claude Code serves hook and tool commands
from a shared per-user worker pool (claude bg-spare -> claude bg-pty-host
-> claude daemon run), and a pool whose owning session has since exited
survives with its top process reparented to init. A hook served by such a
pool has a contiguous claude ancestry that never reaches the live session,
so the check failed for the session's own hook and the script exited 0
silently. Watcher continuity then depended entirely on the synchronous
guard, which blocked every turn end instead.

Add a second, ancestry-independent membership proof in the lib that owns
this decision, and accept either. The new proof is a conjunction: the
delivered payload names a session id, the delivering session exported that
same session id, the session pid it exported is exactly the pid this
home's lock records, and that pid is still a live Claude process. Pid
equality is stricter than ancestry membership, so a session that does not
hold the lock still cannot claim the home, and separate firstmate homes on
one machine stay independent. Nothing is removed: the ancestry proof and
every other gate are unchanged.

Add FM_AUTOARM_TRACE, an opt-in stderr diagnostic that names the gate
ending a run, so an inert hook can be diagnosed under real hook conditions
without changing any decision.

Tests cover a hook that cannot reach its own session claiming its home, a
foreign session refused, an unconfirmed or malformed identity refused, a
missing or malformed recorded owner refused, and two homes on one machine
staying independent. The opt-in live guard additionally fails, naming the
harness and version, if Claude stops delivering the identity the proof
depends on or stops matching the recorded owner.
@devin-ai-integration

Copy link
Copy Markdown

Closed as superseded — this work already landed on main by another change.

— Kun's Firstmate

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.

1 participant