Skip to content

fix(bin): make Codex turn-end guard progress-aware instead of one-block-per-turn - #6407

Closed
timur wants to merge 8 commits into
kunchenguid:mainfrom
timur:fm/codex-loop-guard-fix
Closed

timur wants to merge 8 commits into
kunchenguid:mainfrom
timur:fm/codex-loop-guard-fix

Conversation

@timur

@timur timur commented Oct 2, 2026 •

Copy link
Copy Markdown

Intent

"ja mach es so" - Zustimmung zum Vorschlag, die Reparatur der Stop-Sicherung fuer Codex als PR an den Firstmate-Betreuer einzureichen (neben einer privaten Pruefung, die nicht Teil dieses Auftrags ist).

Kontext (Befund aus einer Untersuchung vom 02.10.2026): Der Turn-End-Guard laesst im Codex-Modus jeden Stop ohne Pruefung durch, sobald Codex stop_hook_active=true meldet (bin/fm-turnend-guard.sh, Codex-Zweig, Kommentar "never block twice in the same turn"), in der Annahme, das sei nur der unmittelbare zweite Versuch nach einem Block. Codex (0.158.0) setzt stop_hook_active aber pro Turn genau einmal auf true und setzt es bis zum Turn-Ende nie zurueck (codex-rs/core/src/session/turn.rs: let mut stop_hook_active = false; beim Turn-Start, stop_hook_active = true; nach einem Block). Weil Eingaben waehrend eines laufenden Codex-Turns in diesen Turn einfliessen, laufen Turns stundenlang; nach dem ersten Block ist der Guard fuer den Rest des Turns wirkungslos. Folge: Ein Codex-Supervisor (hier ein Remote-Second-Mate) beendete nach einem ruhigen Checkpoint den Turn, ohne den naechsten Checkpoint zu starten, der Guard liess den Stop durch, und die Supervision lag stundenlang still; seit 28.09. endeten 23 von 23 solchen Turns ueber genau diesen Pfad, mit 11 Luecken ueber 30 Minuten (max. 5 h 12 min). Der Stop-Payload von Codex enthaelt session_id und turn_id. Der Claude-Modus hat diese Fehlerklasse bereits mit einem Block-Budget geloest (FM_CLAUDE_TURNEND_BLOCK_BUDGET in bin/fm-turnend-guard.sh).

Gewuenschte Reparatur: den Codex-Loop-Guard turn-bewusst machen - erneut blocken, wenn seit dem letzten Block Fortschritt passiert ist (es lief ein Checkpoint, z. B. erkennbar am weitergelaufenen Watcher-Beacon), und mit einem harten Budget gegen Endlosschleifen beim unmittelbaren Wiederholungsversuch ohne Fortschritt.

What Changed

  • bin/fm-turnend-guard.sh: in default (Codex) mode, Stop payloads that carry turn_id no longer get an automatic allow just because stop_hook_active=true. Each session now has its own ledger under $STATE, keyed by session, that stores the turn id, the time of the last block, the watcher-beacon mtime and a block count. The guard checks the stop again whenever any of these is true:

    • the watcher beacon has moved since the last block (a checkpoint ran);
    • the turn has changed;
    • more than FM_CODEX_TURNEND_RETRY_WINDOW seconds (default 120) have passed since the last block.

    Retries with no progress are capped by FM_CODEX_TURNEND_BLOCK_BUDGET (default 3). Once the cap is reached, the guard allows the stop and prints a message to stderr. Healthy and idle stops are still allowed silently without touching the budget. Payloads without turn_id keep the old one-block allow.

  • tests/fm-turnend-guard.test.sh: new coverage for the turn-aware Codex path: re-blocking after beacon progress, the budget running out without progress, separate ledgers per session, the retry window expiring (using an aged ledger so the test is deterministic) and the legacy fallback when turn_id is missing.

  • Docs (docs/turnend-guard.md and the Claude and Codex harness-adapter references) now describe the new Codex loop-guard behavior and the two new environment variables.

Risk Assessment

⚠️ Medium: The change does what the intent asks: Codex retries are checked again, the budget resets on watcher-beacon progress, and the hard no-progress budget is in place. However, the single per-home ledger lets concurrent Codex sessions reset each other's counts, which brings back an unbounded block loop in that rarer case.

Testing

I drove the real Codex CLI (0.160.0, normal login) against a disposable lab primary whose Stop hook is the tracked .codex/hooks.json command running the guard under test. The lab had supervision needed and no watcher. Codex's interactive folder-trust prompt would have written to ~/.codex, so I used codex exec with an isolated lab CODEX_HOME instead. The base guard blocked only once per turn. The HEAD guard blocked again on the stop_hook_active=true retry until the budget ran out, then allowed the stop. A beacon advance earned a fresh budget each time. A retry after the window expired was blocked again, while an immediate retry stayed bounded. The ledger recorded Codex's real session_id and turn_id. The targeted guard test file passed, covering per-session ledgers and the legacy payload without turn_id, but those cases were not driven live. Codex JSONL transcripts, the ledger and a summary table are saved as evidence. The lab was torn down afterwards.

  • Live validation: ✅ go - 4 of 5 scenarios driven live against the product
Scenario Result Live Evidence
Codex supervisor ends a turn blind, is blocked, and tries to stop again in the same turn with stop_hook_active=true: guard blocks again (bug reproduced on base, fixed on HEAD) ✅ pass live codex-live-base-guard.jsonl (2 replies = 1 block) vs codex-live-new-guard.jsonl (3 replies = 2 blocks with budget 2); codex-live-summary.md
Adversarial: agent keeps retrying the stop without running a checkpoint, and the hard budget releases the turn instead of looping forever ✅ pass live codex-live-new-guard.jsonl: after the 2nd block the 3rd stop was allowed and the turn completed; ledger count=2 with real Codex session_id/turn_id
A checkpoint runs between stops (watcher beacon advances), so the next stop in the same turn is checked and blocked again with a fresh budget ✅ pass live codex-live-progress.jsonl: with budget 1, 3 blocks, each after a beacon touch; the following no-progress retry was allowed
The exhausted no-progress state expires after the retry window, so a later stop in the same turn without a healthy watcher is blocked again with a fresh budget ✅ pass live codex-live-retry-window.jsonl: budget 1, window 8s; the stop after sleep 15 was blocked again and the immediate retry was allowed
Interleaved Codex sessions in one home keep separate budgets; a legacy payload without turn_id keeps the one-block allow; secondmate homes are guarded the same way ⏸️ untested no The prior payload did not establish a live result for this scenario. It was covered only by the unit test file tests/fm-turnend-guard.test.sh, which is not live. Two concurrent real Codex sessions sto…
Evidence: Live Codex run summary table (base vs HEAD, progress, retry window)

Source: Live Codex run summary table (base vs HEAD, progress, retry window)

# Live Codex Stop-hook runs (codex-cli 0.160.0, real login, disposable lab FM_HOME + lab CODEX_HOME)
Lab primary = plain git checkout with AGENTS.md, bin/ from the commit under test, and the tracked .codex/hooks.json Stop hook.
Lab state has task1.meta (supervision needed) and no watcher, so every stop is "unhealthy".
Each agent reply after the first = one stop the guard blocked in the SAME Codex turn.

| run | guard | budget | window | agent replies | blocks in turn | jsonl |
|---|---|---|---|---|---|---|
| no progress | base 65e2aa44 | 2 | - | 2 | 1 (stop_hook_active=true waved through) | codex-live-base-guard.jsonl |
| no progress | HEAD 04c594b3 | 2 | 120 | 3 | 2 then budget release | codex-live-new-guard.jsonl |
| beacon touched after blocks 1,2 | HEAD | 1 | 120 | 4 | 3 then release on no-progress retry | codex-live-progress.jsonl |
| sleep 15s after block 1 | HEAD | 1 | 8 | 3 | 2 then release on immediate retry | codex-live-retry-window.jsonl |

Final ledger of the HEAD no-progress run (real Codex session_id/turn_id):
`` `
session=01a0fced-85cf-7f63-937f-fa2710fa7690
turn=01a0fced-88bb-7fa0-a25e-d50d2298a3f3
time=1790949830
beacon=missing
count=2
`` `
Evidence: Base-commit guard: real Codex turn, only 1 block then stop allowed

Source: Base-commit guard: real Codex turn, only 1 block then stop allowed

{"type":"thread.started","thread_id":"01a0fced-e0d9-7042-8a22-0357ef8b281a"}
{"type":"item.completed","item":{"id":"item_0","type":"error","message":"`--dangerously-bypass-hook-trust` is enabled. Enabled hooks may run without review for this invocation."}}
{"type":"item.completed","item":{"id":"item_1","type":"error","message":"`--dangerously-bypass-hook-trust` is enabled. Enabled hooks may run without review for this invocation."}}
{"type":"turn.started"}
{"type":"item.completed","item":{"id":"item_2","type":"agent_message","text":"OK"}}
{"type":"item.completed","item":{"id":"item_3","type":"agent_message","text":"OK"}}
{"type":"turn.completed","usage":{"input_tokens":31177,"cached_input_tokens":27648,"cache_write_input_tokens":0,"output_tokens":10,"reasoning_output_tokens":0}}
Evidence: HEAD guard: real Codex turn, 2 blocks (budget 2) then release

Source: HEAD guard: real Codex turn, 2 blocks (budget 2) then release

{"type":"thread.started","thread_id":"01a0fced-85cf-7f63-937f-fa2710fa7690"}
{"type":"item.completed","item":{"id":"item_0","type":"error","message":"`--dangerously-bypass-hook-trust` is enabled. Enabled hooks may run without review for this invocation."}}
{"type":"item.completed","item":{"id":"item_1","type":"error","message":"`--dangerously-bypass-hook-trust` is enabled. Enabled hooks may run without review for this invocation."}}
{"type":"turn.started"}
{"type":"item.completed","item":{"id":"item_2","type":"agent_message","text":"OK"}}
{"type":"item.completed","item":{"id":"item_3","type":"agent_message","text":"OK"}}
{"type":"item.completed","item":{"id":"item_4","type":"agent_message","text":"OK"}}
{"type":"turn.completed","usage":{"input_tokens":46998,"cached_input_tokens":40064,"cache_write_input_tokens":0,"output_tokens":15,"reasoning_output_tokens":0}}
Evidence: HEAD guard ledger written during real Codex turn

Source: HEAD guard ledger written during real Codex turn

session=01a0fced-85cf-7f63-937f-fa2710fa7690
turn=01a0fced-88bb-7fa0-a25e-d50d2298a3f3
time=1790949830
beacon=missing
count=2
Evidence: HEAD guard: beacon progress re-arms blocks (budget 1, 3 blocks)

Source: HEAD guard: beacon progress re-arms blocks (budget 1, 3 blocks)

{"type":"thread.started","thread_id":"01a0fcee-55bd-7ac0-8c2f-794399969311"}
{"type":"item.completed","item":{"id":"item_0","type":"error","message":"`--dangerously-bypass-hook-trust` is enabled. Enabled hooks may run without review for this invocation."}}
{"type":"item.completed","item":{"id":"item_1","type":"error","message":"`--dangerously-bypass-hook-trust` is enabled. Enabled hooks may run without review for this invocation."}}
{"type":"turn.started"}
{"type":"item.completed","item":{"id":"item_2","type":"agent_message","text":"OK"}}
{"type":"item.started","item":{"id":"item_3","type":"command_execution","command":"/bin/zsh -lc 'sleep 1; touch \"/private/var/folders/46/qpqgfq513dgf_579qvkwwpq40000gn/T/fm-lab.3ytHOU/state/.last-watcher-beat\"'","aggregated_output":"","exit_code":null,"status":"in_progress"}}
{"type":"item.completed","item":{"id":"item_3","type":"command_execution","command":"/bin/zsh -lc 'sleep 1; touch \"/private/var/folders/46/qpqgfq513dgf_579qvkwwpq40000gn/T/fm-lab.3ytHOU/state/.last-watcher-beat\"'","aggregated_output":"","exit_code":0,"status":"completed"}}
{"type":"item.completed","item":{"id":"item_4","type":"agent_message","text":"OK"}}
{"type":"item.started","item":{"id":"item_5","type":"command_execution","command":"/bin/zsh -lc 'sleep 1; touch \"/private/var/folders/46/qpqgfq513dgf_579qvkwwpq40000gn/T/fm-lab.3ytHOU/state/.last-watcher-beat\"'","aggregated_output":"","exit_code":null,"status":"in_progress"}}
{"type":"item.completed","item":{"id":"item_5","type":"command_execution","command":"/bin/zsh -lc 'sleep 1; touch \"/private/var/folders/46/qpqgfq513dgf_579qvkwwpq40000gn/T/fm-lab.3ytHOU/state/.last-watcher-beat\"'","aggregated_output":"","exit_code":0,"status":"completed"}}
{"type":"item.completed","item":{"id":"item_6","type":"agent_message","text":"OK"}}
{"type":"item.completed","item":{"id":"item_7","type":"agent_message","text":"OK"}}
{"type":"turn.completed","usage":{"input_tokens":100131,"cached_input_tokens":85632,"cache_write_input_tokens":0,"output_tokens":156,"reasoning_output_tokens":0}}
Evidence: HEAD guard: retry window expiry re-blocks a later stop

Source: HEAD guard: retry window expiry re-blocks a later stop

{"type":"thread.started","thread_id":"01a0fcef-2680-79b0-bcb2-86c4c6d372a9"}
{"type":"item.completed","item":{"id":"item_0","type":"error","message":"`--dangerously-bypass-hook-trust` is enabled. Enabled hooks may run without review for this invocation."}}
{"type":"item.completed","item":{"id":"item_1","type":"error","message":"`--dangerously-bypass-hook-trust` is enabled. Enabled hooks may run without review for this invocation."}}
{"type":"turn.started"}
{"type":"item.completed","item":{"id":"item_2","type":"agent_message","text":"OK"}}
{"type":"item.started","item":{"id":"item_3","type":"command_execution","command":"/bin/zsh -lc 'sleep 15'","aggregated_output":"","exit_code":null,"status":"in_progress"}}
{"type":"item.completed","item":{"id":"item_3","type":"command_execution","command":"/bin/zsh -lc 'sleep 15'","aggregated_output":"","exit_code":0,"status":"completed"}}
{"type":"item.completed","item":{"id":"item_4","type":"agent_message","text":"OK"}}
{"type":"item.completed","item":{"id":"item_5","type":"agent_message","text":"OK"}}
{"type":"turn.completed","usage":{"input_tokens":62958,"cached_input_tokens":55424,"cache_write_input_tokens":0,"output_tokens":43,"reasoning_output_tokens":0}}
Evidence: Targeted turn-end guard test output

Source: Targeted turn-end guard test output

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_supervision_needed: a registered custom check needs supervision with no task in flight
ok - fm_supervision_needed: a registered check whose bytes drifted still needs supervision
ok - fm_supervision_needed: false for a check.sh with no registration binding
ok - fm_supervision_needed: a task PR poll without a trust binding is not a registered custom check
ok - fm_supervision_status: the relay shim is not counted as a registered custom check
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: registered-check-only supervision is named in the block banner
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 Codex retry is rechecked within its turn budget
ok - fm-turnend-guard: Codex stop is rechecked after watcher-beacon progress
ok - fm-turnend-guard: Codex retry budget bounds repeated stops without checkpoint progress
ok - fm-turnend-guard: interleaved Codex sessions in one home keep separate retry budgets
ok - fm-turnend-guard: exhausted Codex retry budget expires after the retry window
ok - fm-turnend-guard: payload without turn_id preserves legacy stop_hook_active behavior
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 Codex retry is rechecked in a secondmate home
ok - fm-turnend-guard: turn-aware Codex recheck applies to secondmate homes
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: 7 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: an abandoned auto-arm claim no longer allows a blind stop (incident regression)
ok - fm-turnend-guard --claude: a claim whose pid was reused stops counting as recovery even while its entry reads arming
ok - fm-turnend-guard --claude: a hung owner frozen at arming with no watcher beat no longer allows a blind stop
ok - fm-turnend-guard --claude: a live open generation claim owns recovery with no lock held
ok - fm-turnend-guard --claude: a stuck generation claim no longer allows a blind stop
ok - fm-turnend-guard --claude: the terminal path clears an abandoned claim instead of stepping aside silently
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 reset on recovery
ok - fm-turnend-guard --claude: an inert auto-arm's frozen epoch reaches one bounded fail-open and resets on recovery
ok - fm-turnend-guard --claude: a frozen unverified epoch spends the budget yet still blocks
ok - fm-turnend-guard --claude: reset contention preserves all episode state until retry
ok - fm-turnend-guard --claude: concurrent auto-arm and guard resets are idempotent and deadlock-free
ok - fm-turnend-guard --claude: stale rewake epoch does not allow a blind stop
ok - fm-turnend-guard --claude: budget exhaustion alone cannot permit a blind stop
ok - fm-turnend-guard --claude: verified fail-open is loud, bounded, attended, and non-repeating
ok - fm-turnend-guard --claude: fail-open requires both exhausted retries and consumed notice
ok - fm-turnend-guard --claude: away ownership excludes the Stop-autoarm fail-open
ok - fm-turnend-guard --claude: positive watcher recovery resets failure episode state
ok - fm-turnend-guard --claude: bounded claim wait avoids a token-consuming forced continuation
ok - fm-turnend-guard --claude: secondmate home re-blocks unclaimed and allows auto-arm-claimed stops
ok - fm-turnend-guard: a live away-mode daemon satisfies supervision with no watcher holding the lock
ok - fm-turnend-guard: away-mode daemon ownership survives a leftover dead watcher lock
ok - fm-turnend-guard: away mode with no daemon and no watcher still blocks
ok - fm-turnend-guard: away mode blocks on a dead away-mode daemon
ok - fm-turnend-guard: away mode blocks on a pid-reused away-mode daemon lock
ok - fm-turnend-guard: away-mode daemon ownership never substitutes for a fresh beacon
ok - fm-turnend-guard: a daemon lock proves nothing while away mode is off
ok - fm-turnend-guard: away-mode beacon freshness uses the poll-derived grace, not the flat default
ok - fm-turnend-guard: a dead away-mode daemon still blocks under the poll-derived grace
ok - fm-turnend-guard: the poll-derived grace is bounded, not unlimited
ok - fm-turnend-guard: with away mode off, the poll-derived grace never applies

Pipeline

Updates from git push no-mistakes

✅ **intent** - passed

✅ No issues found.

✅ **Rebase** - passed

✅ No issues found.

⚠️ **Review** - 2 infos
  • ⚠️ bin/fm-turnend-guard.sh:197 - The Codex retry ledger is one file per home ($STATE/.turnend-codex-ledger) holding a single session/turn record, but the budget only counts when session, turn and beacon all match. Two Codex sessions stopping in the same primary home, both with no watcher, overwrite each other's record. Sequence: A blocks (ledger=A,count=1), B blocks (ledger=B,count=1), A retries (ledger session≠A, so not exhausted; block writes A,count=1), B retries (same thing), and so on. Neither count ever reaches FM_CODEX_TURNEND_BLOCK_BUDGET, so both sessions get an unbounded block loop with no checkpoint progress. That is exactly the endless loop the intent's hard budget is meant to rule out, and the old one-block allow did not have this problem. Fix: key the ledger by session (for example a file name derived from a hash of session_id, or one line per session/turn inside the lock), so one session's record cannot reset another's count. Same invariant at: codex_retry_budget_exhausted session/turn compare (bin/fm-turnend-guard.sh:226-229) and the count reset in codex_ledger_record_block (bin/fm-turnend-guard.sh:243-249).
  • ℹ️ bin/fm-turnend-guard.sh:209 - Progress is detected from the beacon's mtime at whole-second resolution (fm_path_mtime uses stat %m / %Y). If a checkpoint's watcher touches .last-watcher-beat in the same wall-clock second the block was recorded, the touch does not count as progress and the stop is charged against the no-progress budget. With the default budget of 3 the impact is small, since it at most uses up one retry early.
  • ℹ️ tests/fm-turnend-guard.test.sh:610 - The test test_hook_secondmate_codex_retry_rechecks_after_progress uses the default budget of 3, so its second call would block (exit 2) even with no beacon progress. It therefore does not exercise progress detection at all. Running it with FM_CODEX_TURNEND_BLOCK_BUDGET=1 (block, touch beacon, retry still blocks; plus a control case where a retry without the touch is allowed) would make it prove the reset. The main-home variant at tests/fm-turnend-guard.test.sh:537 only proves the reset through the persisted count=1 ledger line, and would get the same improvement from budget=1.

🔧 Fix applied.
4 issues (1 warning, 3 infos) still open:

  • ⚠️ bin/fm-turnend-guard.sh:197 - The Codex retry ledger is one file per home ($STATE/.turnend-codex-ledger) holding a single session/turn record, but the budget only counts when session, turn and beacon all match. Two Codex sessions stopping in the same primary home, both with no watcher, overwrite each other's record. Sequence: A blocks (ledger=A,count=1), B blocks (ledger=B,count=1), A retries (ledger session≠A, so not exhausted; block writes A,count=1), B retries (same thing), and so on. Neither count ever reaches FM_CODEX_TURNEND_BLOCK_BUDGET, so both sessions get an unbounded block loop with no checkpoint progress. That is exactly the endless loop the intent's hard budget is meant to rule out, and the old one-block allow did not have this problem. Fix: key the ledger by session (for example a file name derived from a hash of session_id, or one line per session/turn inside the lock), so one session's record cannot reset another's count. Same invariant at: codex_retry_budget_exhausted session/turn compare (bin/fm-turnend-guard.sh:226-229) and the count reset in codex_ledger_record_block (bin/fm-turnend-guard.sh:243-249).
  • ℹ️ bin/fm-turnend-guard.sh:209 - Progress is detected from the beacon's mtime at whole-second resolution (fm_path_mtime uses stat %m / %Y). If a checkpoint's watcher touches .last-watcher-beat in the same wall-clock second the block was recorded, the touch does not count as progress and the stop is charged against the no-progress budget. With the default budget of 3 the impact is small, since it at most uses up one retry early.
  • ℹ️ .agents/skills/harness-adapters/references/harness/claude.md:76 - This reference still says "default Codex mode keeps it [stop_hook_active] as a one-block loop guard". After this change that is wrong for Codex payloads that carry turn_id: those are rechecked against watcher-beacon progress and FM_CODEX_TURNEND_BLOCK_BUDGET (bin/fm-turnend-guard.sh:151-163, 297-305). The sibling docs were updated (docs/turnend-guard.md:305-308, harness/codex.md:45-47) but this line was left behind. Reword it to point at the turn-aware Codex budget, keeping the legacy one-block allow only for payloads without turn_id.
  • ℹ️ bin/fm-turnend-guard.sh:193 - The round-1 fix keyed the ledger per session ($STATE/.turnend-codex-ledger.<cksum(session_id)>), which correctly stops sessions from resetting each other's counts. Nothing ever deletes these files, though. The healthy, idle and budget-exhausted allow paths all exit without removing the session's ledger, so every Codex session that was blocked even once leaves a small hidden file in state/ for good. Nothing else in bin/ reads these files, so this is clutter, not a functional bug. If you want to fix it, have the allow paths, or the next block for a new turn, remove the current session's ledger.

🔧 Fix applied.
4 issues (2 warnings, 2 infos) still open:

  • ⚠️ bin/fm-turnend-guard.sh:197 - The Codex retry ledger is one file per home ($STATE/.turnend-codex-ledger) holding a single session/turn record, but the budget only counts when session, turn and beacon all match. Two Codex sessions stopping in the same primary home, both with no watcher, overwrite each other's record. Sequence: A blocks (ledger=A,count=1), B blocks (ledger=B,count=1), A retries (ledger session≠A, so not exhausted; block writes A,count=1), B retries (same thing), and so on. Neither count ever reaches FM_CODEX_TURNEND_BLOCK_BUDGET, so both sessions get an unbounded block loop with no checkpoint progress. That is exactly the endless loop the intent's hard budget is meant to rule out, and the old one-block allow did not have this problem. Fix: key the ledger by session (for example a file name derived from a hash of session_id, or one line per session/turn inside the lock), so one session's record cannot reset another's count. Same invariant at: codex_retry_budget_exhausted session/turn compare (bin/fm-turnend-guard.sh:226-229) and the count reset in codex_ledger_record_block (bin/fm-turnend-guard.sh:243-249).
  • ℹ️ bin/fm-turnend-guard.sh:209 - Progress is detected from the beacon's mtime at whole-second resolution (fm_path_mtime uses stat %m / %Y). If a checkpoint's watcher touches .last-watcher-beat in the same wall-clock second the block was recorded, the touch does not count as progress and the stop is charged against the no-progress budget. With the default budget of 3 the impact is small, since it at most uses up one retry early.
  • ℹ️ bin/fm-turnend-guard.sh:193 - The round-1 fix keyed the ledger per session ($STATE/.turnend-codex-ledger.<cksum(session_id)>), which correctly stops sessions from resetting each other's counts. Nothing ever deletes these files, though. The healthy, idle and budget-exhausted allow paths all exit without removing the session's ledger, so every Codex session that was blocked even once leaves a small hidden file in state/ for good. Nothing else in bin/ reads these files, so this is clutter, not a functional bug. If you want to fix it, have the allow paths, or the next block for a new turn, remove the current session's ledger.
  • ⚠️ bin/fm-turnend-guard.sh:222 - Once a turn's no-progress budget runs out, the ledger stays at count>=budget with the same session, turn and beacon. After that, codex_retry_budget_exhausted allows every later stop_hook_active=true stop in that turn with no time limit, until the watcher beacon changes. Concrete sequence: the watcher is dead and the agent ignores three blocks, so the budget is exhausted and the stop is allowed. Codex keeps the same turn_id while user input flows into the turn for hours (the scenario in the intent). The agent never runs a checkpoint, so the beacon mtime never changes, and every later stop in that turn passes with only a stderr diagnostic. This is the same failure class as before (the guard goes inert for the rest of a long turn), just after 3 blocks instead of 1. The intent asks for a hard budget against the immediate retry without progress ("beim unmittelbaren Wiederholungsversuch ohne Fortschritt"). A stop much later in the turn is arguably not an immediate retry. The ledger already records time= but nothing reads it. Possible fix: expire the exhausted state after a window (for example AFK_GRACE or a new FM_CODEX_TURNEND_RETRY_WINDOW) so the guard rearms. Asking the user because this is a product-behavior choice: a longer-lived rearm could block more often, while the current design accepts permanent inertness after exhaustion.

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

  • ℹ️ bin/fm-turnend-guard.sh:209 - Progress is detected from the beacon's mtime at whole-second resolution (fm_path_mtime uses stat %m / %Y). If a checkpoint's watcher touches .last-watcher-beat in the same wall-clock second the block was recorded, the touch does not count as progress and the stop is charged against the no-progress budget. With the default budget of 3 the impact is small, since it at most uses up one retry early.
  • ℹ️ bin/fm-turnend-guard.sh:193 - The round-1 fix keyed the ledger per session ($STATE/.turnend-codex-ledger.<cksum(session_id)>), which correctly stops sessions from resetting each other's counts. Nothing ever deletes these files, though. The healthy, idle and budget-exhausted allow paths all exit without removing the session's ledger, so every Codex session that was blocked even once leaves a small hidden file in state/ for good. Nothing else in bin/ reads these files, so this is clutter, not a functional bug. If you want to fix it, have the allow paths, or the next block for a new turn, remove the current session's ledger.
  • ⚠️ tests/fm-turnend-guard.test.sh:558 - The round-3 regression test test_hook_codex_exhausted_budget_expires_after_retry_window, added by the fixer, sets FM_CODEX_TURNEND_RETRY_WINDOW=2. Its second call (the 'immediate' retry, expected to exit 0) only passes if date +%s minus the ledger's time= value is under 2 whole seconds. The ledger time is written near the end of the first guard run, and the check uses integer seconds, so crossing one second boundary costs 1 second of the window. On a loaded CI runner, two full guard runs (each sources libs and calls jq, stat and git) can easily take more than ~1s. When that happens the retry is counted as a fresh block (exit 2) and the test fails even though the code is correct. This is the same timing-dependency class as open issue Flaky test: fm-remote-delta-read same-ctime-second rewrite depends on runner timing #6404. Fix: keep the expiry trigger deterministic. Use the default or a large window for the immediate-retry steps, and simulate expiry by rewriting the persisted ledger's time= line (the guard's own state contract) to a past epoch instead of sleep 3. Alternatively, use a much wider window with a matching sleep. The production code change itself (codex_ledger_continues at bin/fm-turnend-guard.sh:214-219, used by both codex_retry_budget_exhausted at :234 and codex_ledger_record_block at :250) matches the user's round-3 instruction: the exhausted state expires after a configurable window, defaulting to 120s, and the stop is then re-blocked with a fresh budget.

🔧 Fix applied.
2 infos still open:

  • ℹ️ bin/fm-turnend-guard.sh:209 - Progress is detected from the beacon's mtime at whole-second resolution (fm_path_mtime uses stat %m / %Y). If a checkpoint's watcher touches .last-watcher-beat in the same wall-clock second the block was recorded, the touch does not count as progress and the stop is charged against the no-progress budget. With the default budget of 3 the impact is small, since it at most uses up one retry early.
  • ℹ️ bin/fm-turnend-guard.sh:193 - The round-1 fix keyed the ledger per session ($STATE/.turnend-codex-ledger.<cksum(session_id)>), which correctly stops sessions from resetting each other's counts. Nothing ever deletes these files, though. The healthy, idle and budget-exhausted allow paths all exit without removing the session's ledger, so every Codex session that was blocked even once leaves a small hidden file in state/ for good. Nothing else in bin/ reads these files, so this is clutter, not a functional bug. If you want to fix it, have the allow paths, or the next block for a new turn, remove the current session's ledger.
✅ **Test** - passed

✅ No issues found.

  • Live validation: ✅ go - 4 of 5 scenarios driven live against the product
Scenario Result Live Evidence
Codex supervisor ends a turn blind, is blocked, and tries to stop again in the same turn with stop_hook_active=true: guard blocks again (bug reproduced on base, fixed on HEAD) ✅ pass live codex-live-base-guard.jsonl (2 replies = 1 block) vs codex-live-new-guard.jsonl (3 replies = 2 blocks with budget 2); codex-live-summary.md
Adversarial: agent keeps retrying the stop without running a checkpoint, and the hard budget releases the turn instead of looping forever ✅ pass live codex-live-new-guard.jsonl: after the 2nd block the 3rd stop was allowed and the turn completed; ledger count=2 with real Codex session_id/turn_id
A checkpoint runs between stops (watcher beacon advances), so the next stop in the same turn is checked and blocked again with a fresh budget ✅ pass live codex-live-progress.jsonl: with budget 1, 3 blocks, each after a beacon touch; the following no-progress retry was allowed
The exhausted no-progress state expires after the retry window, so a later stop in the same turn without a healthy watcher is blocked again with a fresh budget ✅ pass live codex-live-retry-window.jsonl: budget 1, window 8s; the stop after sleep 15 was blocked again and the immediate retry was allowed
Interleaved Codex sessions in one home keep separate budgets; a legacy payload without turn_id keeps the one-block allow; secondmate homes are guarded the same way ⏸️ untested no The prior payload did not establish a live result for this scenario. It was covered only by the unit test file tests/fm-turnend-guard.test.sh, which is not live. Two concurrent real Codex sessions sto…
  • bin/fm-lab-home.sh create $LAB plus a disposable primary-shaped plain git checkout carrying bin/ from HEAD (and a second one from base 65e2aa44) and the tracked .codex/hooks.json Stop hook; lab state had task1.meta and no watcher
  • Probe of the tracked Stop hook command (bash -lc …fm-turnend-guard.sh) with Codex-shaped payloads against the lab FM_HOME (block, block, budget allow)
  • Real codex exec --json --dangerously-bypass-hook-trust (codex-cli 0.160.0, normal login via a disposable lab CODEX_HOME that symlinks auth.json and trusts only the lab dirs), run as the session command on the lab's private tmux -L fm-lab socket: base guard vs HEAD guard, FM_CODEX_TURNEND_BLOCK_BUDGET=2, no progress
  • Real Codex, HEAD guard, budget=1: agent touches state/.last-watcher-beat after hook feedback 1 and 2, then stops without progress
  • Real Codex, HEAD guard, budget=1, FM_CODEX_TURNEND_RETRY_WINDOW=8: agent sleeps 15s after the first block, then retries immediately
  • bash tests/fm-turnend-guard.test.sh (targeted guard test file: per-session ledger, legacy payload without turn_id, secondmate homes, aged-ledger window, hook root anchoring)
  • Teardown: tmux -L fm-lab kill-server, rm -rf $LAB; worktree left clean
✅ **Document** - passed

✅ No issues found.

⚠️ **Lint** - 1 warning
  • ⚠️ linter found issues (exit code 1)
✅ **Push** - passed

✅ No issues found.

@greptile-apps

greptile-apps Bot commented Oct 2, 2026 •

Copy link
Copy Markdown

RetriggerConfidence Score: 5/5

[High risk] Changes turn-end blocking logic for Codex integration.

The PR appears safe to merge; the remaining finding is a non-blocking test-coverage gap.

Reviews (4) · Last reviewed commit: "no-mistakes(ci): I fixed the Greptile cl..."

Comment thread bin/fm-turnend-guard.sh Resolved
Comment thread bin/fm-turnend-guard.sh Resolved
@kunchenguid

Copy link
Copy Markdown
Owner

Speaking as Kun's firstmate: first stamp. Whole thread + tip-vs-main diff reviewed (5 files; workflow-zero).

HEAD 04c594b31719d619cd8562a4f53bad34ad8e6a95. MERGEABLE/UNSTABLE. Attestation: MATCH. Greptile FAILURE P1: same-second watcher-beacon mtime can miss progress (whole-second fm_path_mtime; with budget 1 the next blind stop is allowed). P2: session ledgers accumulate (non-blocking). Author timur not blocked.

Closes: no Fixes/Closes in body (why=unstamped). Intent: Codex stop_hook_active stays true for the whole turn, so main's one-block-allow made the turn-end guard blind after the first block on long multi-checkpoint turns.

Contract-class: restore (own tip-vs-main). The turn-end guard's existing job is to keep blocking AFK/supervision-threatening stops; Codex's stop_hook_active=true → allow was loop safety for an immediate retry, but Codex never clears the flag within a long turn, so the path was broken in the field (23/23 blind stops). Tip restores re-check after beacon/turn/window progress with FM_CODEX_TURNEND_BLOCK_BUDGET, matching Claude's already-shipped pattern; payloads without turn_id keep legacy one-block allow. Not a new always-on surface — same Stop hook, corrected allow/block.

VISION.md (per-rule)

  1. One captain, one interface — aligns (supervision does not go silent mid-turn).
  2. Authority explicit — aligns (no new autonomy grant).
  3. Scripts/agents — aligns (deterministic ledger + beacon progress).
  4. Restart non-event — aligns (durable per-session ledger under $STATE).
  5. Delegation with spine — aligns (remote secondmate supervision continuity).
  6. Fleet outlives vendor — aligns (binds to Codex turn_id/session_id actually exposed; legacy path kept).
  7. Scope — aligns (harness adapter / turn-end guard).

This pass: approved fork CI 37018012713 and Require no-mistakes 37018011690. Waiting on author for Greptile P1 (same-second progress marker) before merge consideration; CI/NM now queued after approve. Firstmate flag no. waiting-author.

…structions for this round. ci-1 (same-second progress). The invariant: any beacon write at or after the last block must count as progress. Before the fix, progress was an exact match on the beacon mtime, so a same-second update was missed. Progress is now checked in one place, `codex_ledger_continues` in `bin/fm-turnend-guard.sh`, which both `codex_retry_budget_exhausted` and `codex_ledger_record_block` use. It treats the retry as having no progress only when the beacon mtime is less than the saved block time. That means beacon mtime >= block time counts as progress, so the stop is checked again and blocked. This stays bounded by the existing budget and retry window. The ledger's `beacon=` line and the `codex_beacon_stand` helper are no longer needed and were removed. The watcher is unchanged. ci-2 (ledgers pile up). The invariant: each home has at most one Codex ledger. It now lives at the fixed path `$STATE/.turnend-codex-ledger` and holds session, turn, time and count. A new session or turn overwrites it, because the count resets to 1 and the file is rewritten. `allow_supervised_stop` deletes it on the healthy pass-through path in Codex mode, which covers both the live watcher and the away-mode daemon. As the user decided in this round, this replaces the earlier per-session ledger files. The interleaved-session test that depended on them was replaced. Tests in `tests/fm-turnend-guard.test.sh`: - New `test_hook_codex_same_second_beacon_counts_as_progress`: pins the ledger time to the beacon's mtime, checks that the stop is blocked again, then that the next retry without progress is allowed. - New `test_hook_codex_ledger_is_single_per_home`: runs three sessions and checks there is at most one ledger file and the latest session wrote it, then checks that a healthy live watcher removes it. - The window test now uses the fixed ledger path. - The two progress tests now touch the beacon and then sleep 1 second. This makes "no further progress" deterministic under the new >= rule. `docs/turnend-guard.md` was updated to describe the single ledger per home and the at-or-after progress rule. Verification: `bash tests/fm-turnend-guard.test.sh` passed on all 3 runs (exit 0), and `bash -n` passes. I could not run ShellCheck or `bin/fm-lint.sh` because ShellCheck is not on PATH. Under the workspace rules I did not install it
Comment thread bin/fm-turnend-guard.sh Resolved
Comment thread bin/fm-turnend-guard.sh Resolved
…ified for this round. `bash tests/fm-turnend-guard.test.sh` passes (98 ok, exit 0). I couldn't run ShellCheck or `bin/fm-lint.sh` because ShellCheck is not on PATH, and the workspace rules don't allow installing it. **ci-1: sessions sharing one ledger reset each other's budget.** The rule that must hold: one session's blocks never reset another session's retry count. Every ledger read and write goes through `$CODEX_LEDGER`, so the fix is in that one place. - I went back to one ledger per session. Each file lives in a dedicated subdirectory, `$STATE/.turnend-codex-ledgers/`, named by the cksum of `session_id`. The home-wide lock stays as it was. - Every ledger write (`codex_ledger_record_block`) now deletes ledger files there that are older than 24 hours. - The healthy pass-through (`allow_supervised_stop`) still removes this session's ledger. **ci-2: a future-dated beacon reset the budget.** The rule that must hold: a beacon counts as progress only if `last_block_time <= beacon_mtime <= now`. The check lives only in `codex_ledger_continues`, which both `codex_retry_budget_exhausted` and `codex_ledger_record_block` use. A beacon dated after now is now treated as no progress, and the retry window uses the same `now` value. **Tests** (`tests/fm-turnend-guard.test.sh`): - New helper `codex_ledger_path` gives the ledger path for a session. - New `test_hook_codex_retry_budget_is_per_session`: two sessions interleave and each reaches its own budget. - New `test_hook_codex_future_beacon_is_not_progress`. - New `test_hook_codex_ledgers_pruned_and_removed_on_healthy_stop`: a ledger older than 24 hours is deleted on the next write, and a healthy watcher removes this session's ledger. It replaces the single-ledger-per-home test. - I checked the two regression tests against the previous guard: both fail there and pass now. `docs/turnend-guard.md` now describes the per-session ledgers, the 24-hour cleanup and the future-beacon rule
Comment thread bin/fm-turnend-guard.sh Resolved
…he way you approved. `bash tests/fm-turnend-guard.test.sh` passes: 99 ok, exit 0. The new regression test fails against the old guard (exit 0 where 2 is expected) and passes with the fix. I didn't run ShellCheck or `bin/fm-lint.sh` in this round because ShellCheck isn't on PATH and I didn't install it. **What must always hold:** a stop only counts as an immediate retry inside the retry window if 0 <= now - last_block_time < window. A saved block time in the future, after a clock rollback, is treated as an expired window. That check lives only in `codex_ledger_continues` in `bin/fm-turnend-guard.sh`, and both callers go through it: `codex_retry_budget_exhausted` and `codex_ledger_record_block`. So one edit covers both. **Changes:** - **Guard:** in `codex_ledger_continues` I added `[ "$CODEX_LEDGER_TIME" -le "$now" ]` before the elapsed-time check. With a future block time, the retry no longer counts as a continuation: the exhausted budget no longer lets the stop through, the stop is checked as usual and blocked, and the count starts again at 1. When the block time is at or before now, which is the normal case, nothing changes. The comment above the ledger code now says so. - **Test:** I added one test, `test_hook_codex_future_block_time_expires_retry_window` in `tests/fm-turnend-guard.test.sh`. It blocks with budget 1, sets the ledger's `time=` an hour ahead, and then checks that the retry is blocked again with the supervision alarm. - **Docs:** I changed one sentence in `docs/turnend-guard.md`. As you asked, I added no other clock-shift safeguards
Comment on lines +589 to +591
out=$(FM_CODEX_TURNEND_BLOCK_BUDGET=1 run_codex_turn_hook "$dir" true turn-rollback); status=$?
expect_code 2 "$status" "a stop after a clock rollback must treat the retry window as expired and be checked again"
assert_contains "$out" "TURN WOULD END BLIND" "the re-armed Codex block must include the supervision alarm"

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Rollback test misses retry bound

The test confirms that a future-dated ledger causes one more block, then ends. It never checks the next immediate retry, so a regression that keeps blocking after the ledger is re-armed would pass unnoticed. With the budget set to 1, please assert that the next retry without progress is allowed.

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

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.

2 participants