Skip to content

fix(bin): preserve Claude lock ownership after helper recycling - #4894

Merged
kunchenguid merged 8 commits into
mainfrom
fm/fm-supervision-bg-claude-session-drift-ship-r1
Sep 19, 2026
Merged

kunchenguid merged 8 commits into
mainfrom
fm/fm-supervision-bg-claude-session-drift-ship-r1

Conversation

@kunchenguid

@kunchenguid kunchenguid commented Sep 19, 2026 •

Copy link
Copy Markdown
Owner

Verification disclosure

No live unattended Claude background session ran on the verifying machine, and none of the evidence below is a live pass against that topology.
The "live validation" rows in the Testing section were driven against the shipped scripts inside synthetic process trees, not against a real claude --bg session.
Coverage is the structural ownership predicate plus the executable fixtures: tests/fm-session-lock-ancestry.test.sh (deterministic process table with the ancestry and session-id signals driven apart, plus a real orphaned front-end, daemon, pty-host, and bg-spare tree whose daemon is ended mid-run) and tests/fm-turnend-foreign-owner-repro.py (genuinely foreign owner as the negative control, same-id as the positive control).
The background topology itself is documented by the real process listings in #3902, #2314, #3398, and #4066.
The captain owns the merge; that is the gate that catches this.

Residual: bin/fm-sessionstart-nudge.sh keeps its own private eight-hop ancestry walk.
It only decides whether to print a session-start nudge, so it stays outside this ownership contract and may nudge on a resume in the recycled case.

Out of scope, deliberately: no structured lock format, no guard budget changes, no daemon-identity rejection, no fork lineage.

Intent

Firstmate supervision goes dark under background/unattended Claude sessions because session-lock ownership is decided by process ancestry alone.
When unattended Claude runs the model loop in a transient background helper that is later recycled, the lock's recorded owner pid stays a live process that is no longer in the current session's ancestry, so the Stop auto-arm stands down as a foreign live owner and the watcher never re-arms; every recovery path uses the same ancestry test, so the outage is self-sustaining until a restart.
Fix session-lock ownership so a background Claude session keeps owning its own lock, while never falsely claiming a lock that a genuinely different live session holds.

Implement the refined ownership shape with all five refinements, R4 included:

R1. Ownership is decided by ancestry-membership OR a trusted same-session id, never id-first.
When the session id is absent, re-keyed in-process by /clear, on a legacy lock with no recorded id, or under a non-Claude primary that has no id at all, the existing ancestry verdict must be unchanged.

R2. Trust gate for the id: accept CLAUDE_CODE_SESSION_ID as an ownership signal only when CLAUDE_PID is a member of the current contiguous Claude ancestry run.
An id retained in a helper environment that is not part of the Claude run must be rejected (for example a hand-started Pi or codex primary under a Claude pane that still carries a Claude id it must not own with).
Never read ids from ps argv, because prompts and briefs are argv-visible.

R3. Store the trusted id in a state/.lock-session sidecar, never by changing the .lock line-1 format, because many readers take the whole first line as the pid.
Write the sidecar only from fm-lock.sh under its existing claim lock; refresh it on every confirmed-own acquire including the early "already mine" exit; remove it when no trusted id exists; keep it byte-identical across a same-session confirmation.

R4. Staleness anchor: keep "recorded pid dead reclaims" as the rule, but for Claude sessions record CLAUDE_PID (the model-loop process, verified as a member of the run) on lock line 1 instead of the outermost chain pid, which is the front-end or a shared transient daemon.
This closes the shared-daemon wedge where the daemon stays alive while the session is dead.
A same-session confirmation must NOT rewrite line 1 while the recorded pid is alive, because startup-network compares that pid across its deferred sweeps.

R5. Never fail open: no id means ancestry only; an unreadable or missing sidecar means ancestry only; an id present but with CLAUDE_PID not in the run means ancestry only; a live owner with a different recorded id keeps the existing refusal, with the recorded id added to the diagnostic.
The guard's foreign-owner exit needs no change; it inherits the fix by calling the same predicate.

Two genuinely different live sessions sharing one id is an unsupported state (Claude prevents it for a running --resume, and the auto-arm generation claim plus the watcher singleton lock still bound arming to one cycle).
A --fork-session successor mints a new id and therefore stays a foreign live owner until the pre-fork process exits; that is the safe direction and a documented non-goal.

What Changed

  • Recognize lock ownership through either existing process ancestry or a matching Claude session ID trusted only when CLAUDE_PID belongs to the current Claude run.
  • Persist trusted IDs in a claim-locked .lock-session sidecar and anchor new trusted Claude locks to the model-loop PID without rewriting a live owner PID during same-session confirmation.
  • Extend supervision documentation and regression coverage for recycled helper chains, stale anchors, sidecar publication failures, and foreign-session refusal.

Risk Assessment

✅ Low: The change is bounded to session-lock identity and publication, preserves ancestry-only fallback behavior, and no concrete remaining correctness or intent-conformance defect was found.

Testing

Ran the focused session-lock end-to-end suite and foreign-owner reproduction against the shipped scripts, manually verified status output and unrestricted ID spelling, and injected signals at all three publication phases; every scenario passed and the worktree remained clean.

  • Live validation: ✅ go - 6 of 6 scenarios driven live against the product
Scenario Result Live Evidence
A background Claude session keeps its lock and re-arms supervision after its transient helper chain is recycled ✅ pass live Session-lock ancestry and recycled-helper end-to-end transcript
A different, absent, or untrusted session ID cannot claim another live session's lock and receives the foreign-owner behavior ✅ pass live Turn-end same-session and foreign-owner transcript
A trusted Claude session anchors new and reclaimed locks on CLAUDE_PID without rewriting a still-live owner PID ✅ pass live Session-lock ancestry and recycled-helper end-to-end transcript
A same-process /clear re-key waits through claim-lock contention, while a waiter cannot overwrite a newly published competing owner ✅ pass live Session-lock ancestry and recycled-helper end-to-end transcript
Publication failures and signals preserve fail-closed sidecar state across pre-write, unverified-write, and verified-publication phases ✅ pass live Signal rollback phase transcript and session-lock ancestry transcript
A trusted ID containing punctuation is recorded, while status continues to expose only the live owner PID ✅ pass live Live lock status and punctuation-bearing session ID transcript
Evidence: Session-lock ancestry and recycled-helper end-to-end transcript

Source: Session-lock ancestry and recycled-helper end-to-end transcript

ok - session-lock: a version-named Claude Code session is identified from its install path and argv[0]
ok - session-lock: a harness that is pid 1 of its own namespace is examined, not skipped
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: a trusted same-session id keeps owning a recycled background chain, and nothing weaker does
ok - session-lock: a trusted id anchors the lock on the model-loop process, anything else on the outermost pid
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
ok - session-lock e2e: a background session keeps its lock and its supervision across a recycled helper chain
ok - session-lock: a same-session confirmation waits for the claim lock and refreshes a re-keyed id
ok - session-lock: a waiting confirmation does not steal another session's lock
ok - session-lock: a failed lock write restores the previous sidecar
ok - session-lock: a failed lock write removes a newly created sidecar
ok - session-lock: a verified reclaim keeps the new sidecar beside the new pid
Evidence: Turn-end same-session and foreign-owner transcript

Source: Turn-end same-session and foreign-owner transcript

SETUP live synthetic owner= 99437 lock= 99437
second-session acquisition rc=0 stdout='lock_rc=1\n' stderr='error: another live firstmate session holds the lock (pid 99437); operate read-only until resolved\n'
nonowner autoarm rc=0 stdout='autoarm_rc=0\n' stderr=''
nonowner stop 1 rc=0 stdout='{"systemMessage":"FIRSTMATE SUPERVISION IS OWNED BY ANOTHER LIVE SESSION: this read-only session cannot and should not arm or repair the watcher (lock owner pid 99437). Allowing this turn to end safely; the owning session must restore supervision."}\n' stderr=''
nonowner stop 2 rc=0 stdout='{"systemMessage":"FIRSTMATE SUPERVISION IS OWNED BY ANOTHER LIVE SESSION: this read-only session cannot and should not arm or repair the watcher (lock owner pid 99437). Allowing this turn to end safely; the owning session must restore supervision."}\n' stderr=''
nonowner stop 3 rc=0 stdout='{"systemMessage":"FIRSTMATE SUPERVISION IS OWNED BY ANOTHER LIVE SESSION: this read-only session cannot and should not arm or repair the watcher (lock owner pid 99437). Allowing this turn to end safely; the owning session must restore supervision."}\n' stderr=''
nonowner stop 4 rc=0 stdout='{"systemMessage":"FIRSTMATE SUPERVISION IS OWNED BY ANOTHER LIVE SESSION: this read-only session cannot and should not arm or repair the watcher (lock owner pid 99437). Allowing this turn to end safely; the owning session must restore supervision."}\n' stderr=''
nonowner stop 5 rc=0 stdout='{"systemMessage":"FIRSTMATE SUPERVISION IS OWNED BY ANOTHER LIVE SESSION: this read-only session cannot and should not arm or repair the watcher (lock owner pid 99437). Allowing this turn to end safely; the owning session must restore supervision."}\n' stderr=''
FIXED repeated non-owner Stops: all five ended safely
fresh-beat-only counterfactual rc=0 stdout='{"systemMessage":"FIRSTMATE SUPERVISION IS OWNED BY ANOTHER LIVE SESSION: this read-only session cannot and should not arm or repair the watcher (lock owner pid 99437). Allowing this turn to end safely; the owning session must restore supervision."}\n' stderr=''
COUNTERFACTUAL dead original owner: watcher= 4440
replacement-owned healthy watcher rc=0 stdout='' stderr=''
same-session acquisition rc=0 stdout='lock acquired: harness pid 5533\nlock_rc=0\n' stderr=''
other-session acquisition rc=0 stdout='lock_rc=1\n' stderr='error: another live firstmate session holds the lock (pid 5533, session synthetic-same); operate read-only until resolved\n'
same-session stop rc=2 stdout='' stderr='●━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n●  TURN WOULD END BLIND - SUPERVISION IS OFF\n●  1 task(s) in flight, but no live watcher holds this home lock (last beat: 603s ago).\n●  The Stop-owned auto-arm did not claim this home either, so recovery is NOT already under way.\n●  watcher supervision needs Stop-owned automatic recovery; inspect the hook registration and startup status before ending the turn.\n●━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n'
other-session stop rc=0 stdout='{"systemMessage":"FIRSTMATE SUPERVISION IS OWNED BY ANOTHER LIVE SESSION: this read-only session cannot and should not arm or repair the watcher (lock owner pid 5533). Allowing this turn to end safely; the owning session must restore supervision."}\n' stderr=''
FIXED same-session id owns the lock; a different id is still foreign
single owner, no autoarm firing rc=0 stdout='lock acquired: harness pid 8824\nsingle_owner_verified=1\nsingle_owner_guard_rc=2\n' stderr='●━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n●  TURN WOULD END BLIND - SUPERVISION IS OFF\n●  1 task(s) in flight, but no live watcher holds this home lock (last beat: 604s ago).\n●  The Stop-owned auto-arm did not claim this home either, so recovery is NOT already under way.\n●  watcher supervision needs Stop-owned automatic recovery; inspect the hook registration and startup status before ending the turn.\n●━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n'
COMPLETE
Evidence: Live lock status and punctuation-bearing session ID transcript

Source: Live lock status and punctuation-bearing session ID transcript

lock acquired: harness pid 44032
sidecar=session:with punctuation
lock: held by live harness pid 44032
Evidence: Signal rollback phase transcript

Source: Signal rollback phase transcript

phase A: signal restored OLD beside unchanged pid 1
phase B: signal removed sidecar beside unverified new pid 83246
phase C: signal preserved NEW beside verified new pid 83951
Evidence: Signal publication fault-injection harness

Source: Signal publication fault-injection harness

#!/usr/bin/env bash
set -eu
ROOT=${ROOT:?}
LAB=$(mktemp -d "${TMPDIR:-/tmp}/fm-lock-signal.XXXXXX")
trap 'rm -rf "$LAB"' EXIT
mkdir -p "$LAB/bin"
ln -s /bin/bash "$LAB/claude"

cat > "$LAB/bin/cat" <<'SH'
#!/usr/bin/env bash
if [ "${MODE:-}" = B ] && [ "${1:-}" = "$FM_HOME/state/.lock" ] \
  && [ -f "$FM_HOME/state/.lock-session" ] \
  && [ "$(/bin/cat "$FM_HOME/state/.lock-session")" = NEW ] \
  && [ "$(/bin/cat "$FM_HOME/state/.lock")" != 1 ] \
  && [ ! -e "$FM_HOME/state/ready" ]; then
  : > "$FM_HOME/state/ready"
  while [ ! -e "$FM_HOME/state/release" ]; do sleep 0.01; done
fi
exec /bin/cat "$@"
SH
cat > "$LAB/bin/mv" <<'SH'
#!/usr/bin/env bash
/bin/mv "$@"
rc=$?
if [ "${MODE:-}" = A ] && [ "${!#}" = "$FM_HOME/state/.lock-session" ]; then
  : > "$FM_HOME/state/ready"
  while [ ! -e "$FM_HOME/state/release" ]; do sleep 0.01; done
fi
exit "$rc"
SH
cat > "$LAB/bin/rm" <<'SH'
#!/usr/bin/env bash
/bin/rm "$@"
rc=$?
case " $* " in
  *" $FM_HOME/state/.lock-session.prev "*)
    if [ "${MODE:-}" = C ] && [ -f "$FM_HOME/state/.lock" ] \
      && [ "$(/bin/cat "$FM_HOME/state/.lock")" != 1 ]; then
      : > "$FM_HOME/state/ready"
      while [ ! -e "$FM_HOME/state/release" ]; do sleep 0.01; done
    fi
    ;;
esac
exit "$rc"
SH
chmod +x "$LAB/bin/cat" "$LAB/bin/mv" "$LAB/bin/rm"

run_case() {
  mode=$1
  home="$LAB/$mode"
  mkdir -p "$home/state"
  printf '1\n' > "$home/state/.lock"
  printf 'OLD\n' > "$home/state/.lock-session"
  env -u CLAUDE_CODE_SESSION_ID -u CLAUDE_PID \
    PATH="$LAB/bin:$PATH" MODE="$mode" FM_HOME="$home" FM_LOCK="$ROOT/bin/fm-lock.sh" \
    "$LAB/claude" -c '
      export CLAUDE_CODE_SESSION_ID=NEW CLAUDE_PID=$$
      "$FM_LOCK" > "$FM_HOME/state/output" 2>&1 &
      child=$!
      printf "%s\n" "$child" > "$FM_HOME/state/child"
      wait "$child" || true
      : > "$FM_HOME/state/done"
      :
    ' &
  launcher=$!
  i=0
  while [ ! -e "$home/state/ready" ] && [ "$i" -lt 1000 ]; do sleep 0.01; i=$((i + 1)); done
  [ -e "$home/state/ready" ] || { echo "phase $mode did not reach signal window"; return 1; }
  kill -TERM "$(/bin/cat "$home/state/child")"
  : > "$home/state/release"
  wait "$launcher" || true
  case "$mode" in
    A)
      [ "$(/bin/cat "$home/state/.lock")" = 1 ]
      [ "$(/bin/cat "$home/state/.lock-session")" = OLD ]
      echo "phase A: signal restored OLD beside unchanged pid 1"
      ;;
    B)
      [ "$(/bin/cat "$home/state/.lock")" != 1 ]
      [ ! -e "$home/state/.lock-session" ]
      echo "phase B: signal removed sidecar beside unverified new pid $(/bin/cat "$home/state/.lock")"
      ;;
    C)
      [ "$(/bin/cat "$home/state/.lock")" != 1 ]
      [ "$(/bin/cat "$home/state/.lock-session")" = NEW ]
      echo "phase C: signal preserved NEW beside verified new pid $(/bin/cat "$home/state/.lock")"
      ;;
  esac
}

run_case A
run_case B
run_case C

Pipeline

Updates from git push no-mistakes

✅ **intent** - passed

✅ No issues found.

✅ **Rebase** - passed

✅ No issues found.

🔧 **Review** - 3 issues found → auto-fixed (6) ✅
  • 🚨 bin/fm-lock.sh:117 - This contradicts R3’s requirement to “refresh it on every confirmed-own acquire including the early ‘already mine’ exit.” If /clear re-keys S1→S2 while the deferred startup sweep holds .lock.acquire, confirm_own_lock returns success without updating the S1 sidecar. If the helper ancestry later disconnects, S2 no longer matches the sidecar and the supervision outage becomes reachable again. The intentionally nonblocking behavior needs user approval or must be changed so every successful confirmation completes the refresh under the claim lock.
  • ⚠️ bin/fm-lock.sh:174 - The new session sidecar is committed before .lock, but a subsequent lock write or verification failure leaves that sidecar behind. For example, with a writable state directory, a read-only stale .lock, and a dead recorded PID, the new ID is published and the PID write fails. If that stale PID is later reused by another live harness, the matching sidecar makes fm_session_lock_owned_by_self silently accept it through the ID path despite the failed acquisition. Remove the newly published sidecar on lock publication/verification failure so the failure remains ancestry-only and fail-closed.
  • ⚠️ bin/fm-lock.sh:51 - The change adds the recorded Claude session ID to fm-lock.sh status output. The intent requires adding it to the live-owner refusal diagnostic, not to status output; this is an additional disclosure/output component unnecessary for the ownership fix. Remove the session suffix from the status path unless this expanded public output is explicitly desired.

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

  • 🚨 bin/fm-lock.sh:122 - confirm_own_lock waits for .lock.acquire after ownership was checked, then publishes the sidecar without revalidating .lock. If the recorded anchor dies during the wait and another session wins the claim lock first, that session can publish its PID and ID; this waiter can then acquire the claim lock, overwrite the sidecar with its own ID, and report success while line 1 names the other live session. Subsequent hooks can therefore claim the genuinely different session's lock through the mismatched sidecar. Re-read and revalidate ownership under .lock.acquire before refreshing the sidecar, refusing or following the ordinary stale-owner path when the record changed.
  • ⚠️ bin/fm-lock.sh:179 - The rollback only runs on explicit write or verification failures. A HUP, INT, or TERM after publish_lock_session_or_die replaces the sidecar but before lock publication completes exits through a trap that only releases the claim lock, leaving the newly published ID beside the previous stale PID. If that PID is later reused by a live harness, the matching-ID path can accept this failed acquisition. Include conditional sidecar rollback in interrupted exits and clear the rollback flag after a confirmed sidecar-only refresh or verified full publication.

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

  • 🚨 bin/fm-lock.sh:218 - After the new session ID is published and line 1 is successfully rewritten, HUP, INT, or TERM can run the EXIT trap before commit_lock_session at line 222. For a stale S1 lock reclaimed by S2, this leaves S2's live anchor PID paired with restored ID S1; a surviving S1 process outside S2's ancestry then passes the matching-ID ownership path and falsely claims S2's live lock. Ensure the signal rollback cannot restore the previous ID once the new line-1 owner is visible.
  • ⚠️ bin/fm-lock.sh:222 - commit_lock_session clears the backup before the read and structural checks at lines 223-229. Consequently, a verification failure leaves the newly published sidecar in place, contrary to the required fail-closed rollback; if verification detects that line 1 was replaced with another live session's PID, this invocation's ID can subsequently claim that PID through the same-session path. Retain rollback state until all lock-publication verification succeeds.

🔧 Fix applied.
1 error still open:

  • 🚨 bin/fm-lock.sh:233 - A failed printf unconditionally downgrades rollback to phase 1 when a previous sidecar exists, even though a short or late filesystem write error may already have replaced line 1 with the new numeric PID. The EXIT trap then restores the previous session ID beside the new live owner PID, allowing that previous session to claim the new session's lock through the matching-ID path. Keep phase 2 and remove the sidecar unless a read-back proves line 1 remains exactly in its pre-write state; only then is restoring the previous sidecar safe.

🔧 Fix applied.
1 warning still open:

  • ⚠️ bin/fm-session-lock-lib.sh:202 - The new [A-Za-z0-9._-] allowlist, repeated for recorded IDs at line 228, adds an acceptance rule not required by the intent. R2 defines the trust gate through CLAUDE_PID membership, not session-ID spelling; an otherwise trusted product-issued ID containing another character would fall back to ancestry-only and recreate the foreign-owner refusal after helper drift. Remove this syntax restriction unless the narrower ID grammar is explicitly intended.

🔧 Fix applied.
1 warning still open:

  • ⚠️ bin/fm-lock.sh:269 - After line 1 has been read back and structurally verified, rollback remains armed until commit_lock_session finishes deleting the backup. A HUP/INT/TERM before or during that deletion can still run the phase-2 trap and remove .lock-session, leaving the verified PID ancestry-only; after helper-chain drift, the owning background session can again be refused. Clear the rollback phase immediately after the final verification, before best-effort backup cleanup, so phase C is signal-stable.

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

✅ **Test** - passed

✅ No issues found.

  • Live validation: ✅ go - 6 of 6 scenarios driven live against the product
Scenario Result Live Evidence
A background Claude session keeps its lock and re-arms supervision after its transient helper chain is recycled ✅ pass live Session-lock ancestry and recycled-helper end-to-end transcript
A different, absent, or untrusted session ID cannot claim another live session's lock and receives the foreign-owner behavior ✅ pass live Turn-end same-session and foreign-owner transcript
A trusted Claude session anchors new and reclaimed locks on CLAUDE_PID without rewriting a still-live owner PID ✅ pass live Session-lock ancestry and recycled-helper end-to-end transcript
A same-process /clear re-key waits through claim-lock contention, while a waiter cannot overwrite a newly published competing owner ✅ pass live Session-lock ancestry and recycled-helper end-to-end transcript
Publication failures and signals preserve fail-closed sidecar state across pre-write, unverified-write, and verified-publication phases ✅ pass live Signal rollback phase transcript and session-lock ancestry transcript
A trusted ID containing punctuation is recorded, while status continues to expose only the live owner PID ✅ pass live Live lock status and punctuation-bearing session ID transcript
  • bash tests/fm-session-lock-ancestry.test.sh
  • python3 tests/fm-turnend-foreign-owner-repro.py
  • Manual live fm-lock.sh acquisition and status check with a punctuation-bearing trusted session ID
  • ROOT="$PWD" ~/.no-mistakes/evidence/01M2VNXKABNCXYNZG2YDTRZF42/signal-publication-check.sh
✅ **Document** - passed

✅ No issues found.

✅ **Lint** - passed

✅ No issues found.

✅ **Push** - passed

✅ No issues found.

Session-lock ownership was decided by process ancestry alone. Under an
unattended Claude session the model loop runs in a transient bg-spare
bridged to the front-end by a shared daemon; when that bridge is
recycled the contiguous claude-named ancestry from a hook to the
recorded owner breaks while the owner pid stays alive, so the Stop
auto-arm stood down as a foreign live owner, the turn-end guard ended
every turn with its read-only diagnostic, and fm-lock.sh refused - a
self-sustaining outage until restart.

Ownership is now ancestry membership OR a trusted same-session id,
never id-first:

- fm-session-lock-lib.sh accepts CLAUDE_CODE_SESSION_ID only when
  CLAUDE_PID is a Claude-shaped member of the current contiguous run,
  compares it against the id recorded in state/.lock-session, and
  requires the recorded pid to still be a live harness. No id, no
  sidecar, an untrusted id, a different id, or a dead recorded pid
  leaves the ancestry verdict unchanged. Ids are never read from ps
  argv.
- fm-lock.sh accepts a same-session holder at both refusal sites,
  writes, refreshes, and clears the sidecar only under its claim lock
  (including the early already-mine exit, skipped only while the
  deferred startup sweep leases that lock), keeps it byte-identical
  across a same-session confirmation, records CLAUDE_PID on lock line 1
  for a session with a trusted id so a shared daemon or front-end that
  outlives the session never keeps a dead session's lock alive, never
  rewrites a live line 1 on a same-session confirmation, and names the
  recorded id in the live-owner refusal.
- The .lock line-1 format is unchanged, so every reader that takes the
  whole first line as the pid keeps working; the guard's foreign-owner
  exit is unchanged and inherits the fix through the shared predicate.

Tests: the ancestry suite drives the ancestry and id signals apart in a
deterministic process table (asserting the divergence) and runs a real
orphaned front-end/daemon/pty-host/spare tree through six phases with
the real lock, auto-arm, and guard scripts; the foreign-owner repro
keeps its negative control and adds a same-id positive control.

Disclosure: no live unattended Claude background session ran on the
verifying machine. The topology is documented by the real process
listings in #3902, #2314, #3398, and #4066; coverage is the structural
predicate plus the executable fixtures, not a live pass.

Residual: bin/fm-sessionstart-nudge.sh keeps its own private ancestry
walk (it only decides whether to print a nudge) and may nudge on a
resume in the recycled case.

Out of scope, deliberately: no structured lock format, no guard budget
changes, no daemon-identity rejection, no fork lineage.
@kunchenguid
kunchenguid merged commit 4812db8 into main Sep 19, 2026
20 checks passed
@kunchenguid
kunchenguid deleted the fm/fm-supervision-bg-claude-session-drift-ship-r1 branch September 19, 2026 06:03
RajeshRajendiran added a commit to RajeshRajendiran/firstmate that referenced this pull request Sep 19, 2026
* fix: disable compact adviser for spawned agents (kunchenguid#4877)

* feat(bin): launch every spawned agent with the compact adviser disabled

Every crewmate, scout, and secondmate Firstmate launches now starts with
COMPACT_ADVISER_DISABLE=1, on a fresh spawn and on a relaunch alike, so an
unattended session never activates the compact adviser.
The value is unconditional: no configuration file gates it and there is no
override, unlike the trace carrier beside it.

Three carriers deliver it, because no single one covers every launch shape.
The pane shell receives an export beside GOTMPDIR, so the agent's own children
inherit it too.
The launch command carries an explicit assignment, prepended outermost so it
wins over any ambient value the pane already held.
The cleared launch environment sets it again at the `env -i` boundary and keeps
COMPACT_ADVISER_DISABLE in the fixed operational floor, which is what preserves
the switch when config/launch-env-allowlist empties the environment, and what
delivers it on a remote host that never had the value.

bin/fm-control.sh relaunch, the bootstrap secondmate relaunch, and the remote
secondmate transport all rebuild their launch through bin/fm-spawn.sh, so they
inherit the same floor.
The captain's own primary session is untouched.

The two new suites drive the real spawn and then execute the launch command the
pane actually received, with the harness replaced by a probe that prints its own
environment, rather than matching script text.
They cover ship and secondmate launches with the allowlist absent and enabled,
the pane export and its ordering, fm-control.sh relaunch, and the full parent to
remote-host chain.

* no-mistakes(review): Export compact-adviser disable across compound launches

* no-mistakes(document): Document spawned-agent compact-adviser environment guarantee

* fix(bin): preserve Claude lock ownership after helper recycling (kunchenguid#4894)

* fix(bin): let a background Claude session keep owning its session lock

Session-lock ownership was decided by process ancestry alone. Under an
unattended Claude session the model loop runs in a transient bg-spare
bridged to the front-end by a shared daemon; when that bridge is
recycled the contiguous claude-named ancestry from a hook to the
recorded owner breaks while the owner pid stays alive, so the Stop
auto-arm stood down as a foreign live owner, the turn-end guard ended
every turn with its read-only diagnostic, and fm-lock.sh refused - a
self-sustaining outage until restart.

Ownership is now ancestry membership OR a trusted same-session id,
never id-first:

- fm-session-lock-lib.sh accepts CLAUDE_CODE_SESSION_ID only when
  CLAUDE_PID is a Claude-shaped member of the current contiguous run,
  compares it against the id recorded in state/.lock-session, and
  requires the recorded pid to still be a live harness. No id, no
  sidecar, an untrusted id, a different id, or a dead recorded pid
  leaves the ancestry verdict unchanged. Ids are never read from ps
  argv.
- fm-lock.sh accepts a same-session holder at both refusal sites,
  writes, refreshes, and clears the sidecar only under its claim lock
  (including the early already-mine exit, skipped only while the
  deferred startup sweep leases that lock), keeps it byte-identical
  across a same-session confirmation, records CLAUDE_PID on lock line 1
  for a session with a trusted id so a shared daemon or front-end that
  outlives the session never keeps a dead session's lock alive, never
  rewrites a live line 1 on a same-session confirmation, and names the
  recorded id in the live-owner refusal.
- The .lock line-1 format is unchanged, so every reader that takes the
  whole first line as the pid keeps working; the guard's foreign-owner
  exit is unchanged and inherits the fix through the shared predicate.

Tests: the ancestry suite drives the ancestry and id signals apart in a
deterministic process table (asserting the divergence) and runs a real
orphaned front-end/daemon/pty-host/spare tree through six phases with
the real lock, auto-arm, and guard scripts; the foreign-owner repro
keeps its negative control and adds a same-id positive control.

Disclosure: no live unattended Claude background session ran on the
verifying machine. The topology is documented by the real process
listings in kunchenguid#3902, kunchenguid#2314, kunchenguid#3398, and kunchenguid#4066; coverage is the structural
predicate plus the executable fixtures, not a live pass.

Residual: bin/fm-sessionstart-nudge.sh keeps its own private ancestry
walk (it only decides whether to print a nudge) and may nudge on a
resume in the recycled case.

Out of scope, deliberately: no structured lock format, no guard budget
changes, no daemon-identity rejection, no fork lineage.

* no-mistakes(review): Wait for claim lock; revert failed sidecars

* no-mistakes(review): Revalidate ownership after wait; restore sidecars

* no-mistakes(review): Roll back sidecar by publication phase

* no-mistakes(review): Restore sidecar only if lock line is unchanged

* no-mistakes(review): Trust session ids without a spelling allowlist

* no-mistakes(review): Disarm sidecar rollback before backup cleanup

* no-mistakes(document): Updated session-lock ownership documentation

* Add Telegram plane: fm-telegram.sh, engine, docs, and tests

* no-mistakes(review): Fix Telegram poll offset advance and send exit codes

* no-mistakes(document): Document Telegram send stops and fails on first bad chunk

* no-mistakes(review): Keep Telegram token out of argv; preserve text splitting

* no-mistakes(document): Add Telegram scripts to inventory; dedupe state list

* no-mistakes(review): Commit Telegram record before wake

---------

Co-authored-by: Kun Chen <[email protected]>
Authentis added a commit to Authentis/firstmate-upstream that referenced this pull request Sep 19, 2026
Absorbs:
- 4812db8 fix(bin): preserve Claude lock ownership after helper recycling (kunchenguid#4894)
- 65a3bac feat: park main under the away posture on Pi (kunchenguid#4889)
- 2bcb88c ci: standardize workflow timeouts into three tiers (kunchenguid#4910)
Ye1806431561 pushed a commit to Ye1806431561/firstmate that referenced this pull request Sep 20, 2026
…henguid#4894)

* fix(bin): let a background Claude session keep owning its session lock

Session-lock ownership was decided by process ancestry alone. Under an
unattended Claude session the model loop runs in a transient bg-spare
bridged to the front-end by a shared daemon; when that bridge is
recycled the contiguous claude-named ancestry from a hook to the
recorded owner breaks while the owner pid stays alive, so the Stop
auto-arm stood down as a foreign live owner, the turn-end guard ended
every turn with its read-only diagnostic, and fm-lock.sh refused - a
self-sustaining outage until restart.

Ownership is now ancestry membership OR a trusted same-session id,
never id-first:

- fm-session-lock-lib.sh accepts CLAUDE_CODE_SESSION_ID only when
  CLAUDE_PID is a Claude-shaped member of the current contiguous run,
  compares it against the id recorded in state/.lock-session, and
  requires the recorded pid to still be a live harness. No id, no
  sidecar, an untrusted id, a different id, or a dead recorded pid
  leaves the ancestry verdict unchanged. Ids are never read from ps
  argv.
- fm-lock.sh accepts a same-session holder at both refusal sites,
  writes, refreshes, and clears the sidecar only under its claim lock
  (including the early already-mine exit, skipped only while the
  deferred startup sweep leases that lock), keeps it byte-identical
  across a same-session confirmation, records CLAUDE_PID on lock line 1
  for a session with a trusted id so a shared daemon or front-end that
  outlives the session never keeps a dead session's lock alive, never
  rewrites a live line 1 on a same-session confirmation, and names the
  recorded id in the live-owner refusal.
- The .lock line-1 format is unchanged, so every reader that takes the
  whole first line as the pid keeps working; the guard's foreign-owner
  exit is unchanged and inherits the fix through the shared predicate.

Tests: the ancestry suite drives the ancestry and id signals apart in a
deterministic process table (asserting the divergence) and runs a real
orphaned front-end/daemon/pty-host/spare tree through six phases with
the real lock, auto-arm, and guard scripts; the foreign-owner repro
keeps its negative control and adds a same-id positive control.

Disclosure: no live unattended Claude background session ran on the
verifying machine. The topology is documented by the real process
listings in kunchenguid#3902, kunchenguid#2314, kunchenguid#3398, and kunchenguid#4066; coverage is the structural
predicate plus the executable fixtures, not a live pass.

Residual: bin/fm-sessionstart-nudge.sh keeps its own private ancestry
walk (it only decides whether to print a nudge) and may nudge on a
resume in the recycled case.

Out of scope, deliberately: no structured lock format, no guard budget
changes, no daemon-identity rejection, no fork lineage.

* no-mistakes(review): Wait for claim lock; revert failed sidecars

* no-mistakes(review): Revalidate ownership after wait; restore sidecars

* no-mistakes(review): Roll back sidecar by publication phase

* no-mistakes(review): Restore sidecar only if lock line is unchanged

* no-mistakes(review): Trust session ids without a spelling allowlist

* no-mistakes(review): Disarm sidecar rollback before backup cleanup

* no-mistakes(document): Updated session-lock ownership documentation
Ivory2024 pushed a commit to Ivory2024/firstmate that referenced this pull request Sep 20, 2026
…henguid#4894)

* fix(bin): let a background Claude session keep owning its session lock

Session-lock ownership was decided by process ancestry alone. Under an
unattended Claude session the model loop runs in a transient bg-spare
bridged to the front-end by a shared daemon; when that bridge is
recycled the contiguous claude-named ancestry from a hook to the
recorded owner breaks while the owner pid stays alive, so the Stop
auto-arm stood down as a foreign live owner, the turn-end guard ended
every turn with its read-only diagnostic, and fm-lock.sh refused - a
self-sustaining outage until restart.

Ownership is now ancestry membership OR a trusted same-session id,
never id-first:

- fm-session-lock-lib.sh accepts CLAUDE_CODE_SESSION_ID only when
  CLAUDE_PID is a Claude-shaped member of the current contiguous run,
  compares it against the id recorded in state/.lock-session, and
  requires the recorded pid to still be a live harness. No id, no
  sidecar, an untrusted id, a different id, or a dead recorded pid
  leaves the ancestry verdict unchanged. Ids are never read from ps
  argv.
- fm-lock.sh accepts a same-session holder at both refusal sites,
  writes, refreshes, and clears the sidecar only under its claim lock
  (including the early already-mine exit, skipped only while the
  deferred startup sweep leases that lock), keeps it byte-identical
  across a same-session confirmation, records CLAUDE_PID on lock line 1
  for a session with a trusted id so a shared daemon or front-end that
  outlives the session never keeps a dead session's lock alive, never
  rewrites a live line 1 on a same-session confirmation, and names the
  recorded id in the live-owner refusal.
- The .lock line-1 format is unchanged, so every reader that takes the
  whole first line as the pid keeps working; the guard's foreign-owner
  exit is unchanged and inherits the fix through the shared predicate.

Tests: the ancestry suite drives the ancestry and id signals apart in a
deterministic process table (asserting the divergence) and runs a real
orphaned front-end/daemon/pty-host/spare tree through six phases with
the real lock, auto-arm, and guard scripts; the foreign-owner repro
keeps its negative control and adds a same-id positive control.

Disclosure: no live unattended Claude background session ran on the
verifying machine. The topology is documented by the real process
listings in kunchenguid#3902, kunchenguid#2314, kunchenguid#3398, and kunchenguid#4066; coverage is the structural
predicate plus the executable fixtures, not a live pass.

Residual: bin/fm-sessionstart-nudge.sh keeps its own private ancestry
walk (it only decides whether to print a nudge) and may nudge on a
resume in the recycled case.

Out of scope, deliberately: no structured lock format, no guard budget
changes, no daemon-identity rejection, no fork lineage.

* no-mistakes(review): Wait for claim lock; revert failed sidecars

* no-mistakes(review): Revalidate ownership after wait; restore sidecars

* no-mistakes(review): Roll back sidecar by publication phase

* no-mistakes(review): Restore sidecar only if lock line is unchanged

* no-mistakes(review): Trust session ids without a spelling allowlist

* no-mistakes(review): Disarm sidecar rollback before backup cleanup

* no-mistakes(document): Updated session-lock ownership documentation
Ivory2024 added a commit to Ivory2024/firstmate that referenced this pull request Sep 20, 2026
#9)

* fix(bin): preserve Claude lock ownership after helper recycling (kunchenguid#4894)

* fix(bin): let a background Claude session keep owning its session lock

Session-lock ownership was decided by process ancestry alone. Under an
unattended Claude session the model loop runs in a transient bg-spare
bridged to the front-end by a shared daemon; when that bridge is
recycled the contiguous claude-named ancestry from a hook to the
recorded owner breaks while the owner pid stays alive, so the Stop
auto-arm stood down as a foreign live owner, the turn-end guard ended
every turn with its read-only diagnostic, and fm-lock.sh refused - a
self-sustaining outage until restart.

Ownership is now ancestry membership OR a trusted same-session id,
never id-first:

- fm-session-lock-lib.sh accepts CLAUDE_CODE_SESSION_ID only when
  CLAUDE_PID is a Claude-shaped member of the current contiguous run,
  compares it against the id recorded in state/.lock-session, and
  requires the recorded pid to still be a live harness. No id, no
  sidecar, an untrusted id, a different id, or a dead recorded pid
  leaves the ancestry verdict unchanged. Ids are never read from ps
  argv.
- fm-lock.sh accepts a same-session holder at both refusal sites,
  writes, refreshes, and clears the sidecar only under its claim lock
  (including the early already-mine exit, skipped only while the
  deferred startup sweep leases that lock), keeps it byte-identical
  across a same-session confirmation, records CLAUDE_PID on lock line 1
  for a session with a trusted id so a shared daemon or front-end that
  outlives the session never keeps a dead session's lock alive, never
  rewrites a live line 1 on a same-session confirmation, and names the
  recorded id in the live-owner refusal.
- The .lock line-1 format is unchanged, so every reader that takes the
  whole first line as the pid keeps working; the guard's foreign-owner
  exit is unchanged and inherits the fix through the shared predicate.

Tests: the ancestry suite drives the ancestry and id signals apart in a
deterministic process table (asserting the divergence) and runs a real
orphaned front-end/daemon/pty-host/spare tree through six phases with
the real lock, auto-arm, and guard scripts; the foreign-owner repro
keeps its negative control and adds a same-id positive control.

Disclosure: no live unattended Claude background session ran on the
verifying machine. The topology is documented by the real process
listings in kunchenguid#3902, kunchenguid#2314, kunchenguid#3398, and kunchenguid#4066; coverage is the structural
predicate plus the executable fixtures, not a live pass.

Residual: bin/fm-sessionstart-nudge.sh keeps its own private ancestry
walk (it only decides whether to print a nudge) and may nudge on a
resume in the recycled case.

Out of scope, deliberately: no structured lock format, no guard budget
changes, no daemon-identity rejection, no fork lineage.

* no-mistakes(review): Wait for claim lock; revert failed sidecars

* no-mistakes(review): Revalidate ownership after wait; restore sidecars

* no-mistakes(review): Roll back sidecar by publication phase

* no-mistakes(review): Restore sidecar only if lock line is unchanged

* no-mistakes(review): Trust session ids without a spelling allowlist

* no-mistakes(review): Disarm sidecar rollback before backup cleanup

* no-mistakes(document): Updated session-lock ownership documentation

* feat: park main under the away posture on Pi (kunchenguid#4889)

* feat: park main under the away posture on Pi

While the away-posture record exists on a Pi primary, the supervision branch
takes every actionable wake, no processing turn opens on main, captain rows
accumulate for the return brief, and main's standing authority relocates to
the branch through the existing guarded scripts.

- lib/fm-branch-dispatch.ts: read the record at every routing decision; while
  it exists claim check, decision-owned, and heartbeat rows too, keeping the
  two broken-queue vetoes; expose checkSeqs so a claimed check row lifts task
  scoping.
- fm-primary-pi-watch.ts: offer every actionable row under the record; a
  declined wake and every watcher-failure alarm still reach main.
- fm-branch-supervision.ts: drop the legacy .afk decline; append a fixed
  POSTURE: AWAY tail carrying the record's read-back verbatim per wake; open no
  processing request while the record exists, re-checked immediately before a
  request would open and at every run boundary; present the accumulated rows
  at the first run boundary after archive.
- fm-lease-lib.sh: fm_lease_forbid_branch passes the branch for opted-in
  actions only while fm-afk-contract.sh validate succeeds on a confirmed live
  record; PR merge, fresh spawn, and decision answer opt in, local landing
  never does.
- fm-send.sh: a --resolve-key naming an open needs-decision or captain-held
  task is a decision answer and meets the partition; blocked: keys stay
  steering.
- fm-spawn.sh: enforce the record's spend cap for a fresh ordinary spawn by
  either actor; relaunches and secondmates exempt.
- fm-branch-prompt.sh: fixed Postures section and the verbatim
  ask-user-authority policy; the prefix stays byte-stable.
- fm-afk-return.sh: count what the away session handled from the store.
- docs, afk skill, AGENTS.md stub: main parked on Pi, green merge gate
  absolute while away.
- tests: watcher and branch extension suites, fleet-record, merge, and
  decision-answer suites cover the relocation, the vetoes, the tail, the
  parked processing turn, the cancellation, the re-presentation, and the
  spend cap; dated live-guard evidence recorded.

* no-mistakes(review): Refuse branch merge after preflight archive race

* no-mistakes(review): Fix away wake, spawn, and processing races

* no-mistakes(review): Suppress parked processing; narrow away-only rejection

* no-mistakes(review): Abort dedicated processing; gate branch spawn once

* no-mistakes(review): Stamp away-only on the dispatch offer

* no-mistakes(review): Treat invalid away records as spend-cap absence

* no-mistakes(review): Drop spawn test hook; abort processing-opened runs

* no-mistakes(review): Bind abort to opening prompt; cap-read absence

* no-mistakes(review): Limit away branch spawn to queued work only

* no-mistakes(document): Correct AFK posture documentation

* ci: standardize workflow timeouts into three tiers (kunchenguid#4910)

* ci: simplify CI job timeouts to a three-tier policy

Replace the scattered per-job timeout values (10m parallel, 25m lint, 30m
serial, 10m macOS) with three readable tiers, each a hang tripwire with
headroom rather than a packing estimate:

- fast (5m): coverage guard, repo invariants, timing aggregate
- normal (30m, one shared budget): lint partitions, portable parallel
  shards, portable serial shards, macOS stock Bash
- heavy (Herdr only): 20m step tripwire on the family run so always()
  cleanup still runs, under a 75m job-level last-resort backstop

The workflow's header comment states the policy and points at
docs/fm-test-portable-shards.md "Timeouts", which now owns it, and each
job names its tier beside timeout-minutes. tests/fm-ci-workflow.test.sh
asserts the policy against the parsed workflow instead of the old
per-job minute values: every job joins exactly one tier, exactly three
distinct job-level values exist, the fast tier stays within 5-10
minutes, the normal budget stays at least double the modeled parallel
lane sum reported by fm-test-run.sh --check-coverage, and the Herdr step
tripwire stays below its job backstop with an always() cleanup after it.

Concurrency supersession, shard counts, lane membership, and fail-fast
settings are unchanged.

* no-mistakes(review): Decouple the normal timeout from packing estimates

* no-mistakes(review): Assert Herdr teardown follows the family run

* no-mistakes(review): Pin Herdr family-run timeout to 20 minutes

* no-mistakes(review): Ignore comments when identifying Herdr steps

* no-mistakes(review): Identify Herdr steps by declarative ids

* no-mistakes(document): Clarify authoritative three-tier timeout policy

* fix(guard): allow root x-mode config paths

* fix(tests): resolve timing race in remote backlog handoff test

* no-mistakes(review): Fix conflict marker and Orca reaping; unrelated focused test failure

* no-mistakes(review): Fix validated reaping, PR fallback, and config test mappings

* no-mistakes(review): Restore active-home-only x-mode approval

* no-mistakes(document): Correct layout reference ownership label

---------

Co-authored-by: Kun Chen <[email protected]>
Co-authored-by: irene <[email protected]>
Ivory2024 added a commit to Ivory2024/firstmate that referenced this pull request Sep 20, 2026