Skip to content

Commit 916c8e2

Browse files
authored
fix(bin): allow safe teardown during watcher recovery (kunchenguid#750)
* fix: allow safe teardown during watcher recovery * no-mistakes(review): Distinguish unsafe-teardown deny guidance via policy reason code * no-mistakes(document): Sync continuity-gate docs to allow teardown recovery * test: mark dynamic teardown fixture literal * no-mistakes(document): docs: add teardown to continuity gate allow list
1 parent ea3ac2e commit 916c8e2

8 files changed

Lines changed: 55 additions & 27 deletions

‎bin/fm-continuity-command-policy.mjs‎

Lines changed: 21 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -3,15 +3,15 @@
33
//
44
// The shared Lexer, program splitter, and command-position resolver remain owned
55
// by fm-arm-command-policy.mjs. This policy only identifies executed firstmate
6-
// fleet scripts and divides them into recovery commands (wake drain and watcher
7-
// arm) versus every other bin/fm-*.sh command. Unparseable or opaque dynamic
6+
// fleet scripts and divides them into recovery commands (wake drain, watcher
7+
// arm, and fail-closed teardown) versus every other bin/fm-*.sh command. Unparseable or opaque dynamic
88
// commands fail open so this gate can never become a blanket shell block.
99

1010
import path from "node:path";
1111
import { fileURLToPath } from "node:url";
1212
import { Lexer, commandPosition, splitProgram } from "./fm-arm-command-policy.mjs";
1313

14-
const RECOVERY_SCRIPTS = new Set(["fm-wake-drain.sh", "fm-watch-arm.sh"]);
14+
const RECOVERY_SCRIPTS = new Set(["fm-wake-drain.sh", "fm-watch-arm.sh", "fm-teardown.sh"]);
1515

1616
function parseArguments(argv) {
1717
const result = { command: "", root: "" };
@@ -55,7 +55,7 @@ function literalShellPayload(position) {
5555
continue;
5656
}
5757
if (word.value === "--" || /^[-+]/.test(word.value)) continue;
58-
return { kind: noExecute ? "none" : "script", value: word.value };
58+
return { kind: noExecute ? "none" : "script", value: word.value, index };
5959
}
6060
return { kind: noExecute ? "none" : "stdin", value: "" };
6161
}
@@ -67,6 +67,13 @@ function literalEvalPayload(position) {
6767
return payloads.map((payload) => payload.value).join(" ");
6868
}
6969

70+
function fleetScriptRecord(name, position, scriptIndex) {
71+
const argumentsAfterScript = position.words.slice(scriptIndex + 1);
72+
const unsafeTeardown = name === "fm-teardown.sh"
73+
&& argumentsAfterScript.some((argument) => argument.value === "--force" || !argument.literal);
74+
return { name, unsafeTeardown };
75+
}
76+
7077
function collectExecutedFleetScripts(command, root, depth = 0) {
7178
if (depth > 12) return [];
7279
const lexed = new Lexer(command).tokenize();
@@ -77,7 +84,7 @@ function collectExecutedFleetScripts(command, root, depth = 0) {
7784
for (const tokens of program.nodes) {
7885
const position = commandPosition(tokens);
7986
const direct = fleetScript(position.command?.value || "", root);
80-
if (direct) scripts.push(direct);
87+
if (direct) scripts.push(fleetScriptRecord(direct, position, position.index));
8188

8289
for (const token of tokens) {
8390
if (token.type === "group") scripts.push(...collectExecutedFleetScripts(token.content, root, depth + 1));
@@ -91,7 +98,7 @@ function collectExecutedFleetScripts(command, root, depth = 0) {
9198
if (shell?.kind === "command") scripts.push(...collectExecutedFleetScripts(shell.value, root, depth + 1));
9299
if (shell?.kind === "script") {
93100
const script = fleetScript(shell.value, root);
94-
if (script) scripts.push(script);
101+
if (script) scripts.push(fleetScriptRecord(script, position, shell.index));
95102
}
96103
if (shell?.kind === "stdin") {
97104
for (const token of tokens) {
@@ -101,10 +108,11 @@ function collectExecutedFleetScripts(command, root, depth = 0) {
101108
}
102109
}
103110

111+
const sourcedIndex = position.index + 1;
104112
const sourced = position.command && [".", "source"].includes(position.command.value)
105-
? fleetScript(position.words[position.index + 1]?.value || "", root)
113+
? fleetScript(position.words[sourcedIndex]?.value || "", root)
106114
: "";
107-
if (sourced) scripts.push(sourced);
115+
if (sourced) scripts.push(fleetScriptRecord(sourced, position, sourcedIndex));
108116
const evaluated = literalEvalPayload(position);
109117
if (evaluated) scripts.push(...collectExecutedFleetScripts(evaluated, root, depth + 1));
110118
}
@@ -114,15 +122,17 @@ function collectExecutedFleetScripts(command, root, depth = 0) {
114122

115123
export function classifyContinuityCommand(command, root) {
116124
const scripts = collectExecutedFleetScripts(command, root);
117-
const blocked = scripts.find((script) => !RECOVERY_SCRIPTS.has(script));
118-
return blocked ? { decision: "deny", script: blocked } : { decision: "allow", script: "" };
125+
const blocked = scripts.find(({ name, unsafeTeardown }) => !RECOVERY_SCRIPTS.has(name) || unsafeTeardown);
126+
if (!blocked) return { decision: "allow", script: "" };
127+
const code = blocked.unsafeTeardown ? "unsafe-teardown" : "other-fleet";
128+
return { decision: "deny", script: blocked.name, code };
119129
}
120130

121131
function main() {
122132
const args = parseArguments(process.argv.slice(2));
123133
if (!args.command || !args.root) return;
124134
const result = classifyContinuityCommand(args.command, args.root);
125-
if (result.decision === "deny") process.stdout.write(`deny\t${result.script}\n`);
135+
if (result.decision === "deny") process.stdout.write(`deny\t${result.script}\t${result.code}\n`);
126136
}
127137

128138
const invokedPath = process.argv[1] ? path.resolve(process.argv[1]) : "";

‎bin/fm-continuity-pretool-check.sh‎

Lines changed: 18 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,11 @@
22
# Claude primary watcher-continuity PreToolUse gate.
33
#
44
# This hook is deliberately narrow. It denies only an executed bin/fm-*.sh fleet
5-
# command other than bin/fm-wake-drain.sh or bin/fm-watch-arm.sh, and only when
6-
# the active primary home has task metadata in flight but no identity-matched
7-
# live watcher holds the home lock. Ordinary shell commands, recovery commands,
8-
# healthy supervision, fleet-idle homes, and child worktrees are always allowed.
5+
# command other than bin/fm-wake-drain.sh, bin/fm-watch-arm.sh, or the
6+
# independently fail-closed bin/fm-teardown.sh, and only when the active primary
7+
# home has task metadata in flight but no identity-matched live watcher holds the
8+
# home lock. Ordinary shell commands, recovery commands, healthy supervision,
9+
# fleet-idle homes, and child worktrees are always allowed.
910
#
1011
# The existing turn-end guard remains the unchanged final backstop. This gate
1112
# closes the long-turn gap before another fleet mutation, but does not replace or
@@ -94,9 +95,19 @@ case "$CLASSIFICATION" in
9495
esac
9596

9697
TAB=$(printf '\t')
97-
BLOCKED_SCRIPT=${CLASSIFICATION#*"$TAB"}
98-
[ -n "$BLOCKED_SCRIPT" ] && [ "$BLOCKED_SCRIPT" != "$CLASSIFICATION" ] || exit 0
99-
REASON="[watcher-continuity] tasks are in flight and no live watcher holds this home lock; run bin/fm-wake-drain.sh, then re-arm with bin/fm-watch-arm.sh as a tracked Claude background task before running other fleet commands (blocked: $BLOCKED_SCRIPT)"
98+
REST=${CLASSIFICATION#*"$TAB"}
99+
[ -n "$REST" ] && [ "$REST" != "$CLASSIFICATION" ] || exit 0
100+
BLOCKED_SCRIPT=${REST%%"$TAB"*}
101+
REASON_CODE=${REST#*"$TAB"}
102+
[ "$REASON_CODE" != "$REST" ] || REASON_CODE=""
103+
case "$REASON_CODE" in
104+
unsafe-teardown)
105+
REASON="[watcher-continuity] tasks are in flight and no live watcher holds this home lock; during recovery only the ordinary literal bin/fm-teardown.sh is allowed, so drop --force and any shell-expanded arguments and retry the literal invocation (blocked: $BLOCKED_SCRIPT)"
106+
;;
107+
*)
108+
REASON="[watcher-continuity] tasks are in flight and no live watcher holds this home lock; drain wakes with bin/fm-wake-drain.sh, use fail-closed bin/fm-teardown.sh for completed tasks when needed, then re-arm with bin/fm-watch-arm.sh as a tracked Claude background task before running other fleet commands (blocked: $BLOCKED_SCRIPT)"
109+
;;
110+
esac
100111
ESCAPED=$(printf '%s' "$REASON" | sed -e 's/\\/\\\\/g' -e 's/"/\\"/g' | tr '\n' ' ')
101112
printf '{"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"deny"},"systemMessage":"%s"}\n' "$ESCAPED" >&2
102113
exit 2

‎docs/architecture.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@ That block owns the live wait shape for the running primary harness: Claude and
5454
On `attached` it stays live across identity-matched successors, and an unexplained clean child close either attaches to a verified healthy successor or becomes the typed nonzero `watcher: FAILED - cycle ended without an actionable reason` result.
5555
The arm layer records one bounded lifecycle row per observed cycle in `state/.watch-cycle-exits.log`; `state/.watch-triage.log` remains exclusively the absorbed-wake debug log.
5656
Pi and OpenCode verify session-lock ownership and launch one singleton successor from their child-close handlers before delivering an actionable wake prompt, with bounded exponential retry for failed restoration.
57-
Claude keeps its tracked background-task protocol and adds a narrow PreToolUse continuity gate that allows drain and arm recovery while refusing only other fleet commands when tasks are in flight and no identity-matched live watcher holds the home lock.
57+
Claude keeps its tracked background-task protocol and adds a narrow PreToolUse continuity gate that allows drain, arm recovery, and fail-closed teardown while refusing only other fleet commands when tasks are in flight and no identity-matched live watcher holds the home lock.
5858
The existing turn-end guard is unchanged and remains the final backstop for all five harness protocols.
5959
Its `--restart` mode signals only the watcher recorded in the current home's `state/.watch.lock`, so restarting one home cannot kill sibling secondmate watchers.
6060
A pull-based guard (`bin/fm-guard.sh`) warns through supervision tool output if the primary checkout is tangled, or if tasks are in flight and that watcher stops running or queued wakes are waiting to be drained.

‎docs/arm-pretool-check.md‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -19,9 +19,9 @@ This policy is not a post-arm liveness guarantee.
1919

2020
Claude also registers `bin/fm-continuity-pretool-check.sh` for Bash PreToolUse events.
2121
This is a separate, tightly bounded recovery gate rather than another watcher-shape policy.
22-
It runs only in a primary home, and it denies only an executed `bin/fm-*.sh` command other than `bin/fm-wake-drain.sh` or `bin/fm-watch-arm.sh` when task metadata is in flight and no identity-matched live watcher holds that home's lock.
23-
Ordinary shell commands, fleet-script names used as data, all commands in an idle fleet, child worktrees, wake drain, and watcher arm remain allowed.
24-
The exact denial tells Claude to run `bin/fm-wake-drain.sh` and then re-arm through a tracked Claude background task before retrying the blocked fleet command.
22+
It runs only in a primary home, and it denies only an executed `bin/fm-*.sh` command other than `bin/fm-wake-drain.sh`, `bin/fm-watch-arm.sh`, or the ordinary literal `bin/fm-teardown.sh` when task metadata is in flight and no identity-matched live watcher holds that home's lock.
23+
Ordinary shell commands, fleet-script names used as data, all commands in an idle fleet, child worktrees, wake drain, watcher arm, and ordinary literal teardown remain allowed.
24+
The denial gives Claude reason-specific recovery guidance — drain, re-arm via a tracked Claude background task, and use fail-closed `bin/fm-teardown.sh` for completed tasks — per the contract in [`watcher-continuity.md`](watcher-continuity.md).
2525
`bin/fm-continuity-command-policy.mjs` reuses this document's shell lexer and command-position analysis but owns the recovery-versus-other-fleet classification.
2626
Malformed transport or opaque dynamic syntax fails open so this narrow gate cannot become a blanket Bash block.
2727
The existing `bin/fm-turnend-guard.sh` Stop integration is unchanged and remains the final backstop.

‎docs/supervision-protocols/claude.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ When this session owns supervision and away mode is not active:
1212
7. Failure or missing cycle only: treat any `watcher: FAILED ...` result as an alarm and repair it before ending the turn.
1313
8. Ordinary wake: when the background task completes with `signal:`, `stale:`, `check:`, or `heartbeat`, drain queued wakes, then start exactly one fresh background task before running other fleet commands to handle the wake.
1414
Do not invent a wake from an attach-status line alone; drain and act only on real wake records or a real watcher reason line.
15-
9. The continuity PreToolUse gate allows wake drain and watcher arm recovery, and refuses only other `bin/fm-*.sh` fleet commands while tasks are in flight and no identity-matched live watcher holds the home lock.
15+
9. The continuity PreToolUse gate allows wake drain, watcher arm recovery, and fail-closed teardown, and refuses only other `bin/fm-*.sh` fleet commands while tasks are in flight and no identity-matched live watcher holds the home lock.
1616
10. The existing turn-end guard remains unchanged as the final backstop and is not replaced by this command gate.
1717
11. Recovery only: if a forced restart is genuinely needed, run `bin/fm-watch-arm.sh --restart` through the same Claude background task mechanism.
1818
12. Do not send idle progress while the watcher is parked.

‎docs/watcher-continuity.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,8 @@ After the configured retry bound is exhausted, it delivers the original wake wit
1919
This is deliberate Option B ordering: the fleet is protected before the model handles the wake whenever restoration succeeds, but the model is never left blind when it does not.
2020

2121
Claude retains its native tracked background-task completion path.
22-
Its new PreToolUse continuity gate allows wake drain and arm recovery but refuses only other fleet commands while tasks are in flight and no identity-matched live watcher holds the home lock.
22+
Its new PreToolUse continuity gate allows wake drain, arm recovery, and independently fail-closed teardown, but refuses other fleet commands while tasks are in flight and no identity-matched live watcher holds the home lock.
23+
Allowing an ordinary literal teardown prevents a terminal wake from creating a recovery circle: forced or dynamically constructed teardown remains blocked, ordinary teardown itself still refuses dirty, unlanded, incomplete-scout, and unresolved-decision cases, and the turn-end guard continues to require supervision for any tasks left in flight.
2324
Codex retains its bounded foreground checkpoint protocol.
2425
Grok retains its tracked background-task notification protocol.
2526
No adapter starts a replacement with shell `&`.

‎tests/fm-claude-continuity-live-e2e.test.sh‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,7 @@ PROMPT='Use Bash with run_in_background=true to run exactly `bin/fm-watch-arm.sh
6868
[ -f "$HOME_DIR/state/claude-arm-ran" ] || fail "Claude did not run the tracked background arm fixture"
6969
[ -f "$HOME_DIR/state/claude-drain-ran" ] || fail "Claude continuity gate blocked the allowed wake drain"
7070
[ ! -f "$HOME_DIR/state/claude-forbidden-ran" ] || fail "Claude continuity gate allowed an unrelated fleet command"
71-
GUIDANCE='[watcher-continuity] tasks are in flight and no live watcher holds this home lock; run bin/fm-wake-drain.sh, then re-arm with bin/fm-watch-arm.sh as a tracked Claude background task before running other fleet commands (blocked: fm-crew-state.sh)'
71+
GUIDANCE='[watcher-continuity] tasks are in flight and no live watcher holds this home lock; drain wakes with bin/fm-wake-drain.sh, use fail-closed bin/fm-teardown.sh for completed tasks when needed, then re-arm with bin/fm-watch-arm.sh as a tracked Claude background task before running other fleet commands (blocked: fm-crew-state.sh)'
7272
grep -F "$GUIDANCE" "$TRANSCRIPT" >/dev/null || fail "Claude transcript omitted the exact continuity recovery guidance"
7373

7474
printf 'ok - Claude %s live E2E refused only the post-completion fleet command with exact re-arm guidance\n' "$CLAUDE_VERSION"

‎tests/fm-continuity-pretool-check.test.sh‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -35,13 +35,13 @@ expect_allow() {
3535
}
3636

3737
expect_deny() {
38-
local label=$1 command=$2 blocked=$3 rc=0 expected actual
38+
local label=$1 command=$2 blocked=$3 expected=${4:-} rc=0 actual
3939
run_command "$command" || rc=$?
4040
[ "$rc" -eq 2 ] || fail "$label must deny with exit 2, got $rc"
4141
[ ! -s "$OUT" ] || fail "$label deny wrote stdout: $(cat "$OUT")"
4242
jq -e '.hookSpecificOutput.hookEventName == "PreToolUse" and .hookSpecificOutput.permissionDecision == "deny"' "$ERR" >/dev/null 2>&1 \
4343
|| fail "$label deny omitted Claude's permission decision: $(cat "$ERR")"
44-
expected="[watcher-continuity] tasks are in flight and no live watcher holds this home lock; run bin/fm-wake-drain.sh, then re-arm with bin/fm-watch-arm.sh as a tracked Claude background task before running other fleet commands (blocked: $blocked)"
44+
[ -n "$expected" ] || expected="[watcher-continuity] tasks are in flight and no live watcher holds this home lock; drain wakes with bin/fm-wake-drain.sh, use fail-closed bin/fm-teardown.sh for completed tasks when needed, then re-arm with bin/fm-watch-arm.sh as a tracked Claude background task before running other fleet commands (blocked: $blocked)"
4545
actual=$(jq -r '.systemMessage' "$ERR")
4646
[ "$actual" = "$expected" ] || fail "$label recovery guidance changed: $actual"
4747
}
@@ -55,6 +55,12 @@ test_gate_scope_and_recovery_exceptions() {
5555
expect_allow "wake drain recovery" 'bin/fm-wake-drain.sh'
5656
expect_allow "watch arm recovery" 'bin/fm-watch-arm.sh'
5757
expect_allow "drain then arm recovery" 'bin/fm-wake-drain.sh; bin/fm-watch-arm.sh'
58+
expect_allow "fail-closed teardown recovery" 'bin/fm-teardown.sh task'
59+
unsafe_teardown_reason='[watcher-continuity] tasks are in flight and no live watcher holds this home lock; during recovery only the ordinary literal bin/fm-teardown.sh is allowed, so drop --force and any shell-expanded arguments and retry the literal invocation (blocked: fm-teardown.sh)'
60+
expect_deny "forced teardown is not recovery" 'bin/fm-teardown.sh task --force' 'fm-teardown.sh' "$unsafe_teardown_reason"
61+
expect_deny "nested forced teardown is not recovery" "bash -lc 'bin/fm-teardown.sh task --force'" 'fm-teardown.sh' "$unsafe_teardown_reason"
62+
# shellcheck disable=SC2016 # single quotes are deliberate: "$TEARDOWN_MODE" is literal test data (an unsafe shell-expanded arg the gate must deny), not an expansion here
63+
expect_deny "dynamic teardown mode is not recovery" 'bin/fm-teardown.sh task "$TEARDOWN_MODE"' 'fm-teardown.sh' "$unsafe_teardown_reason"
5864
expect_deny "unrelated fleet command" 'bin/fm-crew-state.sh task' 'fm-crew-state.sh'
5965
expect_deny "recovery bundled with unrelated fleet command" 'bin/fm-wake-drain.sh; bin/fm-send.sh task hi' 'fm-send.sh'
6066
expect_deny "literal nested fleet command" "bash -lc 'bin/fm-bootstrap.sh'" 'fm-bootstrap.sh'

0 commit comments

Comments
 (0)