Skip to content

fix: harden runtime lifecycle and turn-end supervision - #5

Merged
delaanthonio merged 100 commits into
mainfrom
fm/turnend-check-backstop-g2
Aug 23, 2026
Merged

delaanthonio merged 100 commits into
mainfrom
fm/turnend-check-backstop-g2

Conversation

@delaanthonio

@delaanthonio delaanthonio commented Jul 6, 2026 •

Copy link
Copy Markdown
Owner

Intent

Harden Firstmate's multi-backend runtime supervision so agent endpoints on tmux, Zellij, and cmux are owned, checked, and torn down safely. Turn end runs authenticated due standing checks under a shared cadence lock with durable wake queueing, backend endpoint ownership requires proven runtime identity (stable session-incarnation proof, reconstructed split-input legacy tags), and destructive teardown paths act only after confirmed backend closure - inactive pre-upgrade Zellij tabs are contained fail-closed with every lifecycle record retained. X-mode state/config overrides, home-scoped temp-root isolation and cleanup, secondmate lifecycle safety, and dispatch-profile/Droid behavior are preserved throughout, with regression coverage expanded across the touched surfaces.

What Changed

  • Runs authenticated due standing checks at turn end under a shared cadence lock, durably queues actionable or rejected-check wakes, and preserves X-mode state/config overrides.
  • Hardens Zellij and cmux ownership with home-scoped identities, stable session-incarnation proof, legacy target recovery, global cmux lookup, and retry-safe creation.
  • Requires proven endpoint ownership and confirmed backend closure before teardown mutations, while isolating and safely cleaning home-scoped task temp roots and expanding regression coverage.

Risk Assessment

⚠️ Medium: The change is extensive and touches runtime identity and destructive teardown paths, but the reviewed logic consistently fails closed and no remaining source-verifiable defect was found.

Testing

No baseline command was supplied; nine targeted behavior suites and manual history/cleanliness checks passed, directly demonstrating the standing-check backstop, runtime identity and legacy-tag handling, fail-closed teardown safety, X-mode overrides, home-scoped temp roots, secondmate lifecycle, and dispatch-profile/Droid behavior. Evidence is CLI/state-transition output because this change has no rendered UI surface.

Evidence: Standing-check behavioral transcript

Source: Standing-check behavioral transcript

FM_TEST_BEGIN 2026-08-23T10:25:54Z tests/fm-standing-checks.test.sh family=unclassified expected_gate_skip=none
ok - fm_supervision_run_due_checks: due actionable check appends wake and stamps schedule
ok - fm_supervision_run_due_checks: not-due check does not double-run
ok - fm_supervision_run_due_checks: missing and silent checks stay quiet
ok - fm_supervision_run_due_checks: erroring check fails open
ok - fm_supervision_run_due_checks: timeout fails open without wedging
ok - fm_supervision_run_due_checks: held lock prevents concurrent check execution
ok - fm_supervision_run_due_checks: unauthenticated custom checks are rejected without execution
ok - fm_supervision_run_due_checks: dangling entries do not hide valid due checks
ok - fm_supervision_run_due_checks: trailing dangling entries are reported with valid due checks
ok - fm_supervision_run_due_checks: merged PR retirement follows durable wake append
ok - fm_supervision_run_due_checks: rejected checks advance cadence after durable wake
FM_TEST_END 2026-08-23T10:25:58Z tests/fm-standing-checks.test.sh exit=0 duration_ms=4085 gate_skip=false
FM_TEST_SUMMARY total=1 failed=0 skipped_gate=0 duration_ms=4162
FM_TEST_SUMMARY_FAMILY family=unclassified count=1 duration_ms=4085 failed=0
FM_TEST_SLOWEST rank=1 script=tests/fm-standing-checks.test.sh duration_ms=4085
Evidence: Turn-end guard behavioral transcript

Source: Turn-end guard behavioral transcript

FM_TEST_BEGIN 2026-08-23T10:25:58Z tests/fm-turnend-guard.test.sh family=watcher-wake-lock expected_gate_skip=none
ok - fm_supervision_unhealthy: false with no state/*.meta at all
ok - fm_supervision_unhealthy: true with in-flight task and no beacon ever
ok - fm_supervision_unhealthy: true with in-flight task and a beacon far outside the grace window
ok - fm_supervision_unhealthy: false with in-flight task and a fresh beacon
ok - fm_supervision_status: FM_SUP_QUEUE_PENDING tracks state/.wake-queue
ok - fm_supervision_needed: X-mode relay poll needs supervision
ok - fm_supervision_unhealthy: source-only home needs supervision
ok - fm-turnend-guard: silent no-op with nothing in flight
ok - fm-turnend-guard: blocks when a fresh beacon has no live watcher lock
ok - fm-turnend-guard: non-Claude path blocks a source-only home
ok - fm-turnend-guard: blocks on a dead watcher lock even when the beacon is fresh
ok - fm-turnend-guard: silent no-op with a live watcher lock and fresh beacon
ok - fm-turnend-guard: healthy non-Claude harness paths ignore Claude episode contention
ok - fm-turnend-guard: blocks on a live watcher lock with an ancient beacon
ok - fm-turnend-guard: blocks with the exact required reason in the primary when unhealthy
ok - fm-turnend-guard: blocks from active FM_HOME state, not only repo-root state
ok - fm-turnend-guard: X-mode repair reason sources the cadence config
ok - fm-turnend-guard: X-mode-only supervision remains guarded in default mode
ok - fm-turnend-guard: ignores stale repo-root state when FM_HOME is set
ok - fm-turnend-guard: uses FM_STATE_OVERRIDE ahead of FM_HOME/state
ok - fm-turnend-guard: stop_hook_active=true always allows the stop (never blocks twice in one turn)
ok - fm-turnend-guard: due actionable check queues a wake and blocks only once
ok - fm-turnend-guard: secondmate primary runs the shared due-check backstop
ok - fm-turnend-guard: standing checks stay scoped out of child task worktrees
ok - fm-turnend-guard: blocks a blind turn end in a secondmate's own home (.fm-secondmate-home no longer excludes it)
ok - fm-turnend-guard: idle-by-default - silent in a secondmate home with nothing in flight
ok - fm-turnend-guard: stop_hook_active=true allows the stop in a secondmate home (never blocks twice in one turn)
ok - fm-turnend-guard: secondmate deferred-death recovery - silent while watched, forces re-arm once the watcher exits
ok - fm-turnend-guard: inert in a secondmate's own child worktree (linked git worktree) even when unhealthy
ok - fm-turnend-guard: blocks a blind turn end in a treehouse-leased LINKED secondmate home (marker force-include)
ok - fm-turnend-guard: an invalid (empty) marker cannot spoof inclusion; linked worktree stays exempt
ok - fm-turnend-guard: a non-ASCII marker cannot spoof inclusion; linked worktree stays exempt
ok - fm-turnend-guard: inert in a crewmate/scout task worktree (linked git worktree) even when unhealthy
ok - fm-turnend-guard: fails open (never blocks) when jq is missing
ok - fm-turnend-guard: silent no-op on empty stdin
ok - fm-turnend-guard: runs well under the generous timing margin (0s)
ok - fm-turnend-guard-grok: forces one explicitly marked same-session resume when the shared predicate blocks
ok - fm-turnend-guard-grok: legacy environment loop guard prevents a nested resume loop
ok - fm-turnend-guard-grok: native false delegates blocking feedback with zero resume processes
ok - fm-turnend-guard-grok: native true remains bounded and starts no resume process
ok - fm-turnend-guard-grok: both spellings are typed and camelCase has deterministic precedence
ok - fm-turnend-guard-grok: malformed, invalidly typed, and missing-prerequisite payloads start neither path
ok - fm-turnend-guard-grok: missing jq and no-supervision-needed stops stay silent and bounded
ok - tracked .claude/settings.json entries: 5 inert under grok, the documented subagent exception still armed, all live under Claude
ok - .codex/hooks.json: Stop hook uses hook process root when payload cwd is outside
ok - .codex/hooks.json: Stop hook ignores nested git root guard scripts
ok - .opencode primary plugin: guard path is anchored to worktree, not directory
ok - .pi primary extension: no-tool and multi-tool runs each inject exactly one guard follow-up
ok - .pi primary extension: delivery failure resets the logical-run latch
ok - fm-turnend-guard --claude: re-blocks a loop-guarded stop while unhealthy and unclaimed (incident regression)
ok - fm-turnend-guard --claude: X-mode-only homes re-block when auto-arm recovery is absent
ok - fm-turnend-guard --claude: a live arming epoch advances once and repeated observation is idempotent
ok - fm-turnend-guard --claude: repeated failed-to-arming races make bounded monotonic progress
ok - fm-turnend-guard --claude: terminal owner boundary excludes a concurrent start without deadlock
ok - fm-turnend-guard --claude: fresh rewake epoch prevents a duplicate continuation for the same event
ok - fm-turnend-guard --claude: fresh failed epochs preserve and advance monotonic fail-open progression
ok - fm-turnend-guard --claude: integrated fresh failures reach one bounded fail-open, stop continuation, and reset on recovery
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
FM_TEST_END 2026-08-23T10:27:00Z tests/fm-turnend-guard.test.sh exit=0 duration_ms=61608 gate_skip=false
FM_TEST_SUMMARY total=1 failed=0 skipped_gate=0 duration_ms=61696
FM_TEST_SUMMARY_FAMILY family=watcher-wake-lock count=1 duration_ms=61608 failed=0
FM_TEST_SLOWEST rank=1 script=tests/fm-turnend-guard.test.sh duration_ms=61608
Evidence: Zellij ownership and teardown transcript

Source: Zellij ownership and teardown transcript

FM_TEST_BEGIN 2026-08-23T10:27:00Z tests/fm-backend-zellij.test.sh family=zellij expected_gate_skip=optional-binary
ok - fm_backend_zellij_version_check: accepts the verified minimum (0.44.0)
ok - fm_backend_zellij_version_check: accepts a newer version (0.45.2)
ok - fm_backend_zellij_version_check: refuses an old version loudly
ok - fm_backend_zellij_version_check: refuses loudly when zellij is not installed
ok - fm_backend_zellij_session: defaults to 'firstmate' when FM_ZELLIJ_SESSION is unset
ok - fm_backend_zellij_session: honors the FM_ZELLIJ_SESSION test-isolation override
ok - fm_backend_zellij_parse_target: splits '<session>:<pane_id>' on the first colon
ok - fm_backend_zellij_normalize_key: Enter/Escape/C-c map to zellij's verified Enter/Esc/'Ctrl c'
ok - fm_backend_zellij_scoped_title: scopes a primary task title with firstmate plus home hash
ok - fm_backend_zellij_scoped_title: scopes a secondmate task title with the home marker plus home hash
ok - fm_backend_zellij_scoped_title: includes the resolved FM_HOME hash in the home label
ok - fm_backend_zellij_legacy_scoped_title: reconstructs split home-prefix and root-hash titles
ok - fm_backend_zellij_tab_matches_label: accepts an untagged legacy fm-<id> title when it is the only live tab carrying it
ok - fm_backend_zellij_tab_matches_label: refuses an untagged legacy label match when 2+ live tabs share it (migration ambiguity guard)
ok - fm_backend_zellij_tab_matches_label: preserves owned current-main root-tagged tabs
ok - fm_backend_zellij_tab_matches_label: refuses reused root-tagged ids from a later session
ok - fm_backend_zellij_tab_matches_label: refuses ambiguous legacy root-tagged tabs
ok - fm_backend_zellij_tab_matches_label: refuses reused bare ids from a later session
ok - fm_backend_zellij_legacy_ownership_proven: migrates pre-upgrade metadata from owned live-process evidence
ok - fm_backend_zellij_legacy_ownership_proven: refuses foreign reused panes without persisting proof
ok - fm_backend_zellij_legacy_ownership_proven: inactive pre-upgrade tabs fail closed with lifecycle records intact
ok - fm_backend_zellij_sidecar_fingerprint: accepts only one validated durable token
ok - zellij relaunch: retries independent metadata and sidecar fingerprint retirements
ok - fm-spawn zellij abort: retires the unpublished session-incarnation proof
ok - fm_backend_zellij_list_live: scopes to this home's own tag - excludes a different installation's tagged tab and unrelated tabs
ok - fm_backend_zellij_resolve_bare_selector: matches the home-scoped tagged title first
ok - fm_backend_zellij_resolve_bare_selector: refuses an ambiguous untagged legacy label shared by 2+ live tabs
ok - fm_backend_zellij_resolve_bare_selector: checks every session for the scoped title before legacy fallback
ok - fm_backend_zellij_resolve_bare_selector: requires untagged legacy labels to be globally unique across sessions
ok - fm_backend_zellij_session_exists: true when the session name is listed
ok - fm_backend_zellij_session_exists: false when the session name is not listed
ok - fm_backend_zellij_server_ensure: reuses an existing session without calling attach
ok - fm_backend_validate: zellij is a known backend (P3)
ok - fm_backend_busy_state: zellij (no native primitive) always reports unknown, same as tmux
ok - fm_backend_zellij_create_task: refuses a duplicate home-scoped tab title (zellij's own new-tab has no uniqueness check)
ok - fm_backend_zellij_create_task: creates a home-scoped tab and parses tab_id/pane_id from the response
ok - fm_backend_zellij_create_task: restores focus to the previously-active tab after the steal-focus new-tab call
ok - fm_backend_zellij_create_task: skips the restore call when there was no previously-active tab
ok - fm_backend_zellij_capture: small reads use viewport-only dump-screen and trim to N lines locally
ok - fm_backend_zellij_capture: reads above the watcher-size threshold request --full scrollback
ok - fm_backend_zellij_capture: fails when the specific pane is absent
ok - fm_backend_zellij_capture: fails when the target session is not listed as active (session_exists pre-check)
ok - fm_backend_zellij_send_key: normalizes the key (Escape -> Esc) and targets the explicit pane id
ok - fm_backend_zellij_send_literal: calls paste with an explicit pane id and a -- separator
ok - fm_backend_zellij_send_text_line: clears partial input when Enter fails
ok - fm_backend_zellij_send_text_line: reports unsafe input when cleanup also fails
ok - fm_backend_zellij_target_ready: expected labels allow matching fm-<id> tabs
ok - fm_backend_zellij_target_ready: fresh unpublished tabs require exact incarnation proof
ok - fm_backend_zellij_target_ready: recreated sessions cannot reuse current titles and ids
ok - fm_backend_zellij_target_ready: expected labels reject stale pane ids reused by another tab
ok - fm_backend_zellij_current_path: actively probes with marked begin/end lines and reconstructs wrapped cwd output
ok - fm_backend_zellij_current_path: never picks up a ~-prefixed banner line as the answer
ok - fm_backend_zellij_kill: resolves the owning tab id fresh and calls close-tab-by-id (never a bare close-pane)
ok - fm_backend_zellij_kill: falls back to close-pane when the owning tab cannot be resolved
ok - fm_backend_zellij_kill: closes the recorded tab id only after label verification
ok - fm_backend_zellij_kill: skips a stale recorded tab id whose label does not match
ok - fm_backend_zellij_kill: never fails when the target session no longer exists
ok - fm_backend_zellij_endpoint_confirmed_gone: refuses a live resolved pane despite stale tab metadata
ok - fm-teardown.sh: passes recorded zellij_tab_id with the expected task label
ok - fm-teardown.sh: inactive pre-upgrade zellij containment refuses before every mutation
ok - fm-teardown.sh: force cleanup reconstructs split-input legacy zellij child tags
ok - fm-teardown.sh: descendant ownership refusal preserves every child lifecycle resource
ok - fm_backend_zellij_send_text_submit: reports 'empty' once the composer classifies empty (submitted)
ok - fm_backend_zellij_send_text_submit: reports 'pending' when the composer still holds the text after retried Enters (swallowed)
ok - fm_backend_zellij_send_text_submit: an unrelated pane change is not a delivery confirmation (false-positive regression)
ok - fm_backend_zellij_send_text_submit: refuses confirmation when paste exits successfully without typing
ok - fm_backend_zellij_send_text_submit: transcript echoes outside the selected composer cannot prove typing
ok - fm_backend_zellij_send_text_submit: pre-existing text cannot prove a no-op paste landed
ok - fm_backend_zellij_send_text_submit: unrelated drafts and furniture cannot prove typing
ok - fm_backend_zellij_send_text_submit: observes wrapped text replacing a shell-prompt placeholder
ok - fm_backend_zellij_send_text_submit: observes wrapped text in a bare composer
ok - fm_backend_zellij_send_text_submit: preserves agent glyphs within wrapped content
ok - fm_backend_zellij_send_text_submit: refuses a live shell below a stale composer
ok - fm_backend_zellij_composer_state: classifies the real claude-in-zellij --ansi dump as empty
ok - fm_backend_zellij_composer_state: a dead pane (empty dumps) reads unknown, never a confirmation
ok - fm_backend_zellij_send_text_submit: reports 'send-failed' when the target session is not active
ok - fm_backend_zellij_send_text_submit: reports 'send-failed' when the target pane is absent
ok - fm-peek/fm-send: explicit metadata-matched targets use the recorded zellij backend
ok - fm-peek: fm-id zellij targets verify the owning tab label before capture
ok - fm-send: fm-id zellij targets reject pane ids whose tab label no longer matches
FM_TEST_END 2026-08-23T10:27:38Z tests/fm-backend-zellij.test.sh exit=0 duration_ms=37926 gate_skip=false
FM_TEST_SUMMARY total=1 failed=0 skipped_gate=0 duration_ms=38026
FM_TEST_SUMMARY_FAMILY family=zellij count=1 duration_ms=37926 failed=0
FM_TEST_SLOWEST rank=1 script=tests/fm-backend-zellij.test.sh duration_ms=37926
Evidence: cmux closure and teardown transcript

Source: cmux closure and teardown transcript

FM_TEST_BEGIN 2026-08-23T10:27:38Z tests/fm-backend-cmux.test.sh family=cmux expected_gate_skip=optional-binary
ok - fm_backend_cmux_version_check: accepts the verified minimum (0.64.17)
ok - fm_backend_cmux_version_check: accepts a newer version (0.70.0)
ok - fm_backend_cmux_version_check: refuses an old version loudly
ok - fm_backend_cmux_version_check: refuses loudly when cmux is not found on PATH or at the bundle path
ok - fm_backend_cmux_password: reads the first non-empty line of config/cmux-socket-password
ok - fm_backend_cmux_password: preserves spaces and tabs in config/cmux-socket-password
ok - fm_backend_cmux_password: respects FM_CONFIG_OVERRIDE
ok - fm_backend_cmux_password: empty when config/cmux-socket-password is absent
ok - fm_backend_cmux_cli: exports CMUX_SOCKET_PASSWORD when config/cmux-socket-password is set
ok - fm_backend_cmux_parse_target: splits '<workspace_uuid>:<surface_uuid>' on the first colon
ok - fm_backend_cmux_normalize_key: Enter/Escape/C-c map to cmux's verified enter/escape/ctrl-c
ok - fm_backend_cmux_scoped_title: scopes a primary task title with firstmate plus home hash
ok - fm_backend_cmux_scoped_title: scopes a secondmate task title with the home marker plus home hash
ok - fm_backend_cmux_scoped_title: normalizes the first marker line before validation
ok - fm_backend_cmux_scoped_title: includes the resolved FM_HOME hash in the home label
ok - fm_backend_validate: cmux is a known backend
ok - fm_backend_busy_state: cmux (no native primitive) always reports unknown, same as tmux/zellij/orca
ok - fm_backend_composer_state: routes cmux to the cmux composer classifier
ok - fm_backend_cmux_ping_state: reports 'ok' on PONG
ok - fm_backend_cmux_ping_state: reports 'denied' when socketControlMode=cmuxOnly rejects the connection
ok - fm_backend_cmux_ping_state: reports 'unauth' when password mode rejects a missing/wrong password
ok - fm_backend_cmux_ping_state: reports 'unauth' when password mode rejects a wrong password (Invalid password)
ok - fm_backend_cmux_ping_state: reports 'down' when the app is not running yet
ok - fm_backend_cmux_ensure_running: returns immediately when cmux is already reachable
ok - fm_backend_cmux_ensure_running: fails fast on a denied socket without attempting to launch, naming every viable mode
ok - fm_backend_cmux_ensure_running: fails fast on an unauthenticated socket, naming the password config and the Automation mode alternative
ok - fm_backend_cmux_create_task: refuses duplicate workspace titles across windows
ok - fm_backend_cmux_create_task: creates a workspace and parses workspace_id/surface_id from list responses
ok - fm_backend_cmux_create_task: durably recovers a workspace after post-create lookup failure
ok - fm_backend_cmux_create_task: recovers a workspace committed before a create error
ok - fm_backend_cmux_target_ready: fails when the workspace/surface is not found (list-panes structural check)
ok - fm_backend_cmux_target_ready: verifies the workspace title against the expected label first
ok - fm_backend_cmux_target_ready: rejects a workspace id reused under a different title
ok - fm_backend_cmux_target_ready: accepts an exact legacy root-tagged workspace
ok - fm_backend_cmux_target_ready: refuses cross-home legacy workspace adoption
ok - fm_backend_cmux_target_ready: recovers current titles across windows
ok - fm_backend_cmux_capture: fetches generously and trims to N lines locally
ok - fm_backend_cmux_capture: propagates a read-screen failure even when stdout is empty
ok - fm_backend_cmux_capture: fails when the target surface is absent
ok - fm_backend_cmux_send_key: normalizes the key (Escape -> escape) and targets the explicit workspace/surface
ok - fm_backend_cmux_send_key: recovers stale workspace/surface ids by expected label
ok - fm_backend_cmux_send_literal: calls send with an explicit workspace/surface and a -- separator
ok - fm_backend_cmux_send_text_line: clears partial input when Enter fails
ok - fm_backend_cmux_send_text_line: reports unsafe input when cleanup also fails
ok - fm_backend_cmux_current_path: actively probes with marked begin/end lines (zellij-shape frozen cwd)
ok - fm_backend_cmux_composer_state: a bare '❯' composer row reads empty
ok - fm_backend_cmux_composer_state: a borderless Claude '❯' composer row reads empty
ok - fm_backend_cmux_composer_state: a borderless Claude row outranks stale bordered scrollback
ok - fm_backend_cmux_composer_state: a borderless Claude '❯'+NBSP composer row reads empty under LC_ALL=C
ok - fm_backend_cmux_composer_state: plain-capture text after a bare glyph degrades to unknown (never false pending)
ok - fm_backend_cmux_composer_state: the ghost placeholder text reads empty, not pending
ok - fm_backend_cmux_composer_state: real composer text reads pending
ok - fm_backend_cmux_composer_state: a slash-command popup's argument-hint placeholder still reads pending (the incident fix)
ok - fm_backend_cmux_composer_state: reports unknown when the surface cannot be captured
ok - fm_backend_cmux_composer_state: reports unknown when no border-delimited composer row is found
ok - fm_backend_cmux_send_text_submit: reports 'empty' once the composer row reads empty after one Enter
ok - fm_backend_cmux_send_text_submit: reports 'pending' when the composer never clears after retried Enters (swallowed)
ok - fm_backend_cmux_send_text_submit: retries past a popup-placeholder-fill Enter and lands the real second Enter (the incident fix)
ok - fm_backend_cmux_send_text_submit: reports 'send-failed' when the target workspace/surface is absent
ok - fm_backend_cmux_window_of_workspace: walks windows and counts the membership-confirming workspace list
ok - fm_backend_cmux_window_of_workspace: echoes nothing when no window holds the workspace
ok - fm_backend_cmux_kill: closes the task workspace directly when it is not the last in its window
ok - fm_backend_cmux_kill: adds a throwaway sibling then closes the target when it is the last workspace in its window
ok - fm_backend_cmux_kill: never fails even when close-workspace fails
ok - fm_backend_cmux_kill: recovers stale workspace/surface ids by expected label
ok - fm_backend_cmux_endpoint_confirmed_gone: refuses a renamed live recorded workspace
ok - fm_backend_cmux_endpoint_confirmed_gone: confirms exact UUID and title absence
ok - fm_backend_cmux_list_live: lists only this home's scoped task workspaces using plain fm-<id> labels
ok - fm-teardown.sh: force cleanup reconstructs split-input legacy cmux child tags
ok - fm-teardown.sh: retains child lifecycle records until cmux closure is confirmed
ok - fm-spawn.sh: refuses backend=cmux for --secondmate spawns (mirrors Orca's refusal; no secondmate launch design exists yet)
FM_TEST_END 2026-08-23T10:28:01Z tests/fm-backend-cmux.test.sh exit=0 duration_ms=23276 gate_skip=false
FM_TEST_SUMMARY total=1 failed=0 skipped_gate=0 duration_ms=23408
FM_TEST_SUMMARY_FAMILY family=cmux count=1 duration_ms=23276 failed=0
FM_TEST_SLOWEST rank=1 script=tests/fm-backend-cmux.test.sh duration_ms=23276
Evidence: Home-scoped temp-root transcript

Source: Home-scoped temp-root transcript

FM_TEST_BEGIN 2026-08-23T10:28:01Z tests/fm-gotmp.test.sh family=session-bootstrap expected_gate_skip=none
ok - task temp root is home-scoped
ok - fm-teardown removes the dir pointed to by tasktmp= in meta
ok - fm-teardown treats empty FM_HOME as unset for state-override temp isolation
ok - fm-teardown skips gracefully when tasktmp= is absent (backward compat)
ok - fm-teardown skips gracefully when tasktmp= points to a nonexistent dir
ok - fm-teardown refuses unexpected tasktmp paths before cleanup
ok - fm-teardown preserves legacy task temp roots while retiring their tasks
FM_TEST_END 2026-08-23T10:28:09Z tests/fm-gotmp.test.sh exit=0 duration_ms=8053 gate_skip=false
FM_TEST_SUMMARY total=1 failed=0 skipped_gate=0 duration_ms=8133
FM_TEST_SUMMARY_FAMILY family=session-bootstrap count=1 duration_ms=8053 failed=0
FM_TEST_SLOWEST rank=1 script=tests/fm-gotmp.test.sh duration_ms=8053
Evidence: X-mode state/config override transcript

Source: X-mode state/config override transcript

FM_TEST_BEGIN 2026-08-23T10:28:10Z tests/fm-x-mode.test.sh family=pr-forge expected_gate_skip=none
ok - fm-x-poll is a hard no-op without a token (inert default)
ok - fm-x-poll treats an explicitly empty env token as configured
ok - fm-x-poll stays silent on HTTP 204 (the common case)
ok - fm-x-poll lets an explicitly empty relay env override .env
ok - fm-x-poll surfaces auth/config errors once and clears on recovery
ok - fm-x-poll diagnostic markers use private guarded publication
ok - fm-x-poll stashes the question and prints the compact marker
ok - fm-x-poll wakes once per durable request offer across inbox cleanup
ok - fm-x-poll retains offer claim diagnostics until recovery
ok - fm-x-poll preserves in_reply_to conversation context in the inbox
ok - fm-x-poll reports inbox commit failures without emitting a mention wake
ok - fm-x-poll publishes inbox records only through private guarded artifacts
ok - fm-x-poll requires a non-empty question before waking
ok - fm-x-poll rejects an unsafe request_id (path-traversal guard)
ok - fm-x-reply posts a request-bound answer and echoes only the request_id
ok - fm-x-reply accepts the reply via --text-file and stdin (safe, unexpanded)
ok - fm-x-reply exits non-zero on a non-2xx relay response
ok - fm-x-reply cleans up auth header temp files on interrupted posts
ok - fm-x-reply rejects missing arguments with a usage error
ok - fm-x-reply --help makes image support discoverable
ok - fm-x-reply rejects whitespace-only reply text
ok - fm-x-reply dry-run records the would-be reply and never posts
ok - fm-x-reply dry-run works without a token
ok - fm-x-reply honors FMX_DRY_RUN from .env
ok - fm-x-reply lets an explicitly empty dry-run env override .env
ok - fm-x-reply dry-run fails when it cannot record the preview
ok - fm-x-reply dry-run publishes outbox records only through private guarded artifacts
ok - fmx_split_thread: word-boundary, fence-aware, within-limit, numbered, lossless, capped
ok - fm-x-reply keeps a concise reply as a single unnumbered tweet
ok - fm-x-reply auto-splits a long reply into a numbered thread (texts[])
ok - fm-x-reply uses the Discord inbox platform budget instead of the X tweet budget
ok - fm-x-reply keeps numeric X requests on the X tweet budget
ok - fm-x-reply prefers an explicit relay-provided reply limit
ok - fm-x-reply rejects unsafe inbox context artifacts
ok - fm-x-reply clamps a below-floor max to 50 characters
ok - fm-x-reply posts a thread payload (texts[]) to the relay
ok - fm-x-reply --image posts an image object on answer
ok - fm-x-reply streams large image payloads outside curl argv
ok - fm-x-reply dry-run records compact image metadata for threaded replies
ok - fm-x-reply cleans image and payload temp files
ok - fm-x-reply --image rejects missing and unsupported image paths clearly
ok - fm-x-reply --followup posts to /connector/followup with the same request-bound body
ok - fm-x-reply maps a followup_unavailable follow-up 409 to exit 9
ok - fm-x-reply maps every follow-up 409 to exit 9 even without the marker
ok - fm-x-reply treats answer-endpoint 409 as a generic failure
ok - fm-x-reply --followup --image posts an image object
ok - fm-x-reply --followup is accepted in any position and leaves the answer path default
ok - fm-x-reply --followup dry-run marks the endpoint without changing the answer path
ok - fm-x-reply --followup auto-splits a long follow-up into a marked thread
ok - fm-x-reply followup dry-run keeps endpoint marker and compact image metadata
ok - fm-x-poll records the durable per-request reply context from the relay payload
ok - context registry publishes records only through private guarded artifacts
ok - context registry reads only private single-link artifacts
ok - private artifact publisher is compatible with the system bash path
ok - context registry retention is bounded to the seven-day follow-up window
ok - context registry rewrites preserve the first-seen timestamp
ok - context retention starts only when a live initial answer succeeds
ok - a delayed Discord follow-up stays one message after inbox cleanup via the durable registry
ok - an X follow-up over 280 still splits correctly after inbox cleanup
ok - every unresolved follow-up is refused before posting
ok - a partial registry platform combines with the relay's authoritative budget
ok - concurrent requests each recover their own platform/budget with no cross-overwrite
ok - fm-x-dismiss clears the durable per-request context (a dismissed mention gets no follow-up)
ok - fm-x-dismiss posts a request-bound dismiss and echoes only the request_id
ok - fm-x-dismiss dry-run records the would-be body and never posts
ok - fm-x-dismiss dry-run works without a token
ok - fm-x-dismiss dry-run publishes outbox records only through private guarded artifacts
ok - fm-x-dismiss exits non-zero on a non-2xx relay response
ok - fm-x-dismiss exits non-zero on a transport failure
ok - fm-x-dismiss rejects an unsafe request_id (path-traversal guard)
ok - fm-x-dismiss rejects missing or extra arguments with a usage error
ok - fm-x-link records and refreshes the X-request link without disturbing meta
ok - fm-x-link records Discord platform context so follow-ups keep the Discord budget
ok - fm-x-link resolves the platform by request_id so a post-cleanup link keeps the Discord budget
ok - fm-x-link warns loudly and the follow-up is held (not wrongly split) when the platform is unknown
ok - fm-x-link paired carry flags preserve a prior task's follow-up binding onto a successor
ok - fm-x-link recovery relink preserves Discord platform context after inbox drain
ok - fm-x-link rejects malformed or unpaired carry flags
ok - meta rewrites are independent of TMPDIR
ok - fm-x-link rejects unsafe ids, missing meta, and missing arguments
ok - fm-x-link keeps the plain missing-task error when no second mate is registered
ok - fm-x-link refuses a second-mate-routed task and points at the promised-final path
ok - fm-x-link points an unlocatable task at the promised-final path when second mates exist
ok - fm-x-followup --check reports postable / not-linked correctly
ok - fm-x-followup --check prunes a link past the 7-day window
ok - fm-x-followup --check prunes a link that already reached the follow-up cap
ok - fm-x-followup posts a follow-up, increments the counter, and keeps the link under the cap
ok - fm-x-followup --final clears the link after one post regardless of the remaining count
ok - fm-x-followup clears the link once the third follow-up reaches the cap
ok - fm-x-followup --image forwards the attachment through fm-x-reply --followup
ok - fm-x-followup keeps the link and counter when the post fails
ok - fm-x-followup tombstones the link when a post-success counter write fails
ok - fm-x-followup treats a relay cap/window rejection as an already-exhausted link, not a retry
ok - fm-x-followup skips silently and clears the link past the 7-day window
ok - fm-x-followup is a no-op for a task with no X link
ok - fm-x-followup dry-run records the follow-up and increments the counter, keeping the link
ok - fm-x-followup dry-run --final clears the link just as a live post would
ok - fm-x-followup rejects malformed invocations
ok - bootstrap activates X mode from an .env token, idempotently
ok - bootstrap poll shim preserves state and config overrides
ok - bootstrap ignores CDPATH when writing absolute FM_HOME into the durable X-mode poll shim
ok - bootstrap reports missing X-mode dependencies before arming
ok - bootstrap does not report X mode on when activation artifacts cannot be written
ok - bootstrap rejects linked X artifacts without touching their targets
ok - bootstrap is inert without a non-empty .env token (non-X users unaffected)
ok - bootstrap cleans up X artifacts on opt-out and is silent once off
ok - bootstrap reports failed X artifact cleanup on opt-out
FM_TEST_END 2026-08-23T10:29:29Z tests/fm-x-mode.test.sh exit=0 duration_ms=79588 gate_skip=false
FM_TEST_SUMMARY total=1 failed=0 skipped_gate=0 duration_ms=79667
FM_TEST_SUMMARY_FAMILY family=pr-forge count=1 duration_ms=79588 failed=0
FM_TEST_SLOWEST rank=1 script=tests/fm-x-mode.test.sh duration_ms=79588
- Evidence: [Harness and spawn-safety transcript](https://github.com/delaanthonio/firstmate/blob/0dee971d8e8740d1e3c72e6096843c1d205f5038/.no-mistakes/evidence/fm/turnend-check-backstop-g2/fm-kimi-harness.txt) - Evidence: [Secondmate lifecycle safety transcript](https://github.com/delaanthonio/firstmate/blob/0dee971d8e8740d1e3c72e6096843c1d205f5038/.no-mistakes/evidence/fm/turnend-check-backstop-g2/fm-secondmate-safety.txt) - Evidence: [Dispatch-profile and Droid behavior transcript](https://github.com/delaanthonio/firstmate/blob/0dee971d8e8740d1e3c72e6096843c1d205f5038/.no-mistakes/evidence/fm/turnend-check-backstop-g2/fm-spawn-dispatch-profile.txt)

Pipeline

Updates from git push no-mistakes

✅ **intent** - passed

✅ No issues found.

✅ **Rebase** - passed

✅ No issues found.

🔧 **Review** - 1 issue found → auto-fixed (4) ✅
  • 🚨 bin/fm-teardown.sh:2257 - The required criterion says “reconstruct split-input legacy tags.” Forced secondmate cleanup instead calls preflight_task_backend_ownership &#34;$home&#34; &#34;$home&#34; ..., passing the child home as both FM_HOME and FM_ROOT. A valid legacy Zellij or cmux child titled using 2ndmate-&lt;id&gt; from its home marker but hashed from the tracked code root therefore cannot pass ownership preflight, so even proven legacy work cannot be retired. Thread the actual tracked code root through this recursion and the corresponding endpoint-cleanup call while keeping FM_HOME distinct.

🔧 Fix: Thread legacy root through secondmate cleanup
2 issues (1 error, 1 warning) still open:

  • 🚨 bin/backends/zellij.sh:543 - Intent requires “require proven runtime identity” and “use stable session-incarnation ownership proof,” but an exact current home-scoped title returns success before checking the recorded fingerprint. If the Zellij session restarts and reuses the recorded tab/pane IDs with the same title, target-ready/preflight can send to or close that new endpoint. Route current-title matches through incarnation ownership proof at the shared matching boundary, including an explicit proof path for fresh pre-metadata spawns.
  • ⚠️ bin/fm-supervision-lib.sh:156 - A dangling symlink that sorts before a valid *.check.sh makes this discovery loop return immediately, so the turn-end backstop skips every valid due check and does not report the unauthenticated entry. Continue scanning/classifying matched paths and return “no check” only when the glob truly has no entries.

🔧 Fix: Require Zellij incarnation proof and scan dangling checks
1 warning still open:

  • ⚠️ bin/fm-supervision-lib.sh:224 - A leading dangling or unauthenticated check is accumulated in rejected_checks, but if a later valid check produces output, this branch immediately queues only the valid wake, stamps .last-check, and returns. A consistently actionable valid check therefore prevents the invalid entry from ever being reported, contrary to the required classify/report behavior. Before returning, durably surface both outcomes (or include the rejection in the same wake), and make the mixed-case regression assert the rejection is reported as well as the valid check executing.

🔧 Fix: Surface rejected checks with valid wake
1 warning still open:

  • ⚠️ bin/fm-supervision-lib.sh:224 - If an actionable valid check sorts before a dangling or unauthenticated check, this branch immediately queues and returns, so the later rejection is never scanned or reported and can remain hidden indefinitely. Continue scanning after preserving the first actionable result, then queue one combined wake containing every rejection; add the reverse-order mixed regression.

🔧 Fix: Report trailing rejected checks with valid wake
✅ Re-checked - no issues remain.

✅ **Test** - passed

✅ No issues found.

  • Inspected target history: git show -s --format=&#39;commit=%H%nparents=%P%nsubject=%s&#39; d2309ca and git merge-base --is-ancestor e2a79fe89e4ce11f1e17a7d148d68e90767697a8 f8fa0b3008d4a5bb1c9bde0184fe8a5ec709abcd.
  • bin/fm-test-run.sh tests/fm-standing-checks.test.sh
  • bin/fm-test-run.sh tests/fm-turnend-guard.test.sh
  • bin/fm-test-run.sh tests/fm-backend-zellij.test.sh
  • bin/fm-test-run.sh tests/fm-backend-cmux.test.sh
  • bin/fm-test-run.sh tests/fm-gotmp.test.sh
  • bin/fm-test-run.sh tests/fm-x-mode.test.sh
  • bin/fm-test-run.sh tests/fm-kimi-harness.test.sh
  • bin/fm-test-run.sh tests/fm-secondmate-safety.test.sh
  • bin/fm-test-run.sh tests/fm-spawn-dispatch-profile.test.sh
  • Verified all nine evidence transcripts ended successfully and git status --short remained empty.
✅ **Document** - passed

✅ No issues found.

🔧 **Lint** - 1 issue found → auto-fixed ✅
  • ⚠️ linter found issues (exit code 1)

🔧 Fix: Fix ShellCheck diagnostics in Zellij supervision paths
✅ Re-checked - no issues remain.

✅ **Push** - passed

✅ No issues found.

kunchenguid and others added 30 commits July 6, 2026 00:07
* fix(send): settle codex $skill popup before submit

A `$<skill>` invocation (e.g. $no-mistakes) opens codex's $-autocomplete
popup; submitting too fast lets it swallow the Enter so the invocation
never lands - biting every pipeline trigger to a codex crew/secondmate.
Mirror the existing `/` slash-popup handling: give a `$...` message the
1.2s popup-settle before the (retried) Enter, but scope it to
harness=codex (read from the target's meta) so `$`-prefixed plain text
("$5/month", "$HOME") to claude/opencode/pi keeps the 0.3s fast path. An
explicit session:window target has no meta -> harness unknown -> treated
as non-codex. The retried Enter in fm_tmux_submit_core still backs the
settle up; the `/` case, --key path, marker, and meta-resolution
contract are unchanged.

Record the codex $-popup fact in the harness-adapters skill, and add a
per-harness settle-selection test (codex $ ->1.2, claude $ ->0.3,
explicit $ ->0.3, any / ->1.2, plain ->0.3).

* no-mistakes(document): Sync fm-send popup docs
* feat(supervise): deterministic crew current-state helper

Add bin/fm-crew-state.sh, a deterministic one-line read of a crew's
CURRENT state that ends the stale-status-line friction in supervision.
The status log is an append-only wake-event log, so tail -1 reports the
last event, not the current state: after firstmate resolves a
needs-decision/blocked and the crew silently resumes, the log stays
stale. The helper takes the active no-mistakes run-step as the source of
truth (attributed to the crew's branch, via axi status then the run
list), reconciles a possibly-stale needs-decision/blocked log line
against it (flagging it superseded when the run has resumed), and falls
back to the pane busy-signature + status log when no run is active.
Handles scout/secondmate kinds and torn-down/missing crews gracefully.

Reuses fm-tmux-lib.sh busy detection and meta parsing; fully
deterministic (run-step/pane/log reads only, no heuristics, no LLM).

Wire AGENTS.md sections 7 and 8 to read current state via the helper and
to stop inferring state from a tail of the status log; the status file
stays the wake-event log. Watcher core, status-file/brief contracts, and
wake/dedup machinery are unchanged.

Add tests/fm-crew-state.test.sh covering run-step authority, superseded
stale log lines, genuine-parked, cross-branch attribution, pane and
status-log fallback, scout skip, and torn-down/missing-meta cases.

* no-mistakes(review): Fix dead-window crew state fallback

* no-mistakes(review): Harden crew state liveness checks

* no-mistakes(review): Harden crew state gate handling

* no-mistakes(review): Harden crew state gate parsing

* no-mistakes(document): Document crew state helper

* no-mistakes: apply CI fixes

* fix(crew-state): keep run-step authoritative over a closed pane

The dead-window guard ran before the no-mistakes run lookup, so a
finished crew whose agent had exited and closed its window reported
'unknown' instead of its authoritative run-step state (e.g. done) - the
normal gap between a crew completing and teardown, and a regression
against the helper's core principle of judging by the run-step, not the
shell. Move the pane-readability guard into the no-run fallback path so
it runs only after the run-step lookup: a crew with a run reports its
run-step state regardless of pane liveness, while a genuinely runless
dead window still reports unknown rather than trusting a stale log.

Replace the test that encoded the regression with two that pin the
correct behavior: a closed pane with a terminal run reports done, and a
closed pane with an active run reports working.

* no-mistakes(document): Sync crew-state docs
* feat(watch): always-on wake triage absorbs benign wakes in bash

Factor the afk daemon's classify_signal/classify_stale/heartbeat-scan into a
shared bin/fm-classify-lib.sh used by both the always-on watcher and the daemon.
fm-watch.sh now loops internally: it classifies each wake and absorbs the benign
majority (working: signals, bare turn-ended, non-terminal stale, no-change
heartbeat) by advancing the suppression marker and logging, without queuing or
exiting; it writes the durable queue and exits only on an actionable wake
(captain-relevant signal, any check, terminal stale, a non-terminal stale that
persists past FM_STALE_ESCALATE_SECS, or the heartbeat fleet-scan backstop). So
firstmate re-arms once per actionable event instead of once per wake.

Safety preserved: singleton lock + beacon (touched every poll including while
absorbing), durable queue for actionable wakes, kind=secondmate stale-skip,
per-task check polling, heartbeat backoff, bounded wedge latency. While state/.afk
exists the daemon owns triage and the watcher reverts to one-shot, so the two
never double-triage. AGENTS.md section 8 + afk skill updated; tests added.

* no-mistakes(review): Captain, repair watcher triage edge cases

* no-mistakes(document): Sync watcher triage docs

* no-mistakes: apply CI fixes
…unchenguid#87)

The firstmate side of "listen on X and reply", shipped inside the repo so every
user has it but INERT until they opt in (a non-empty FMX_PAIRING_TOKEN in .env).
Purely additive: the watcher backbone (fm-watch.sh, fm-watch-arm.sh,
fm-wake-lib.sh) and the afk daemon (fm-supervise-daemon.sh, afk skill) are
untouched.

- bin/fm-x-poll.sh: one short-poll of GET /connector/poll; hard no-op without a
  token; requires non-empty text; stashes the full mention (incl. in_reply_to
  conversation context) to state/x-inbox/<id>.json behind a path-traversal guard;
  prints "x-mention <id>" (or a rate-limited "x-mode-error ...") for the watcher.
- bin/fm-x-reply.sh: POST /connector/answer; bearer token via a 0600 header file
  (never argv); reply via --text-file/stdin so mention text is never inlined into
  a shell command. Long replies auto-split into a premium-independent numbered
  "(k/n)" thread (codepoint-aware, capped); single tweet stays unnumbered. Wire:
  {request_id, text}, plus {texts:[...]} for a thread. FMX_DRY_RUN previews to
  state/x-outbox and posts nothing.
- bin/fm-x-lib.sh: .env/env config (token, relay default, dry-run, max chars,
  thread cap; env wins over .env) and the thread splitter.
- bin/fm-bootstrap.sh: .env-presence activation - drop the check shim + 30s
  cadence config on opt-in, remove on opt-out, idempotent, silent off.
- .agents/skills/fmx-respond: public-safe answer playbook - drain inbox, judge
  follow-up worthiness (skip pure acks), conversation continuity via in_reply_to,
  concise by default, dry-run aware.
- AGENTS.md section 14 + README/CONTRIBUTING/docs; tests/fm-x-mode.test.sh
  (hermetic: fake curl, real jq).
* fix(fmx): X-mode mentions are captain instructions - act, then reply

Owner-only relay routing means every routed mention is from the firstmate's
own owner, so fmx-respond no longer frames the asker as a stranger and may
address them as captain. Enabling X mode is the standing authorization, so
replies are composed and posted autonomously with no per-reply confirmation;
dry-run stays the only non-posting path.

A mention's request is a real captain instruction to act on, not merely to
reply to: the drain loop now classifies each mention as an actionable request
(run firstmate's normal lifecycle - intake, backlog, dispatch, scout, ship -
then report the outcome), a question (answer from fleet state), or a pure
acknowledgment (skip). The public channel keeps the yolo carve-out: anything
destructive, irreversible, or security-sensitive is flagged to the captain
through the trusted channel first, never executed straight from a mention.

Public-safety (outcomes only, no secrets/internals), the untrusted-in_reply_to
caution, and the skip-acknowledgment judgment remain intact. AGENTS.md §14
reflects the owner identity, autonomous answering, and act-on-requests carve-out.

* no-mistakes(review): Captain: clarify X-mode consent safeguards

* no-mistakes(review): Captain: document X-mode action consent

* no-mistakes(document): Captain, sync X-mode docs
* fix(fleet-sync): self-heal safe detached drift, loudly flag stuck clones

A pooled clone that drifts off its default branch was silently skipped
forever by both the post-merge teardown sync and bootstrap fleet-sync,
falling further behind on every merge with only an easy-to-miss skip line.

- Auto-recover the one safe case: a clean, detached HEAD that is an
  ancestor of origin/<default> and whose <default> is free to check out
  is re-attached and fast-forwarded, reported as 'recovered:'.
- Every other off-default state (dirty, non-default named branch,
  detached with unique commits, diverged) is left untouched and reported
  as a quantified 'STUCK: ... N commits behind ... - needs attention'
  warning instead of a quiet drift. Nothing is forced, stashed, or discarded.
- Relay the new recovered:/STUCK: outcomes through bootstrap FLEET_SYNC
  lines; document both in AGENTS.md section 3.
- Add tests/fm-fleet-sync.test.sh covering recover, every stuck variant,
  ordinary fast-forward, already-current, local-only/no-origin skips, the
  whole-fleet form, and the bootstrap relay.

* no-mistakes(review): Guard detached recovery from diverged local defaults

* no-mistakes(document): Sync fleet refresh docs

* no-mistakes: apply CI fixes
* feat(x-mode): X-mention completion follow-up flow

Acknowledge an actionable X mention first, do the work, then post one
follow-up reply when it completes.

- fm-x-reply.sh: add --followup mode posting to the relay's
  /connector/followup endpoint; reuses thread-split, payload shape,
  dry-run (with a self-describing endpoint marker), and never-inline
  safety. Answer path unchanged.
- fm-x-link.sh: link a spawned task to its originating mention via
  x_request/x_request_ts in state/<id>.meta (atomic, preserves other
  lines).
- fm-x-followup.sh: --check detection plus post-and-clear on terminal
  completion; honors the 24h window (skip+prune past it), keeps the link
  on a failed post for retry.
- fm-x-lib.sh: shared meta link get/set/clear helpers.
- Docs: fmx-respond reads as one ack-first -> act -> follow-up flow;
  AGENTS.md §14 + supervision pointer document the link, completion
  follow-up, and 24h public-safe window.
- Tests: cover --followup endpoint/payload/dry-run, link, and the
  followup helper; shellcheck clean.

* no-mistakes(review): Captain, fix atomic X meta rewrites

* no-mistakes(document): Document X completion follow-ups
…id#120)

* feat(x-mode): dismiss skipped mentions at the relay

The relay now exposes POST /connector/dismiss: acknowledge a pending
mention without replying - it drops the request, posts nothing, and stops
re-offering it. Wire firstmate to use it on the skip path so a deliberately
unanswered mention no longer churns every poll and times out to the relay's
"offline" auto-reply.

- bin/fm-x-dismiss.sh: new client modeled on fm-x-reply.sh. POSTs
  {request_id} (no body) to /connector/dismiss with the bearer; echoes the
  request_id on 2xx, exits non-zero on non-2xx/transport failure. Honors
  FMX_DRY_RUN (records the would-be POST to state/x-outbox/ with an
  endpoint:"dismiss" marker, posts nothing) and rejects unsafe request_ids.
- fmx-respond skill: the skip path now calls bin/fm-x-dismiss.sh before
  clearing the inbox file; answer and follow-up paths unchanged.
- AGENTS.md section 14: documents that a skipped mention is dismissed at the
  relay, not just locally cleared.
- tests: dismiss posts {request_id} to /connector/dismiss with the bearer
  and echoes it; dry-run records and posts nothing; non-2xx and transport
  failures exit non-zero; unsafe id and bad args rejected.

* chore(no-mistakes): run the bash suite directly as the test step

The test step had no configured test command, so it delegated to an agent;
that agent-driven run crashed the no-mistakes daemon mid-step on this repo.
Configure commands.test to run the firstmate behavior suite deterministically
instead, mirroring .github/workflows/ci.yml: iterate every tests/*.test.sh,
run each, and fail the step if any exits non-zero. This removes the agent from
the test step entirely (no crash) and makes the gate's test baseline match CI.
Same pattern myfirstmate uses (commands.test: mix deps.get && mix test).

* no-mistakes(review): Fix X dismiss docs and gate preflight

* no-mistakes(document): Document X dismiss and gate tests
…unchenguid#126)

* feat(watcher): absorb wakes only when the crew is provably working

The no-verb triage path (a bare turn-end, a working: note, a non-terminal
stale) used to be benign by default and surfaced only on a captain-relevant
status verb. A crew that finished but reported through interactive pane menus
(no done: status) had its final turn-end absorbed, so firstmate was never
woken and the finish was missed.

Invert the rule: absorb a no-verb turn-end or non-terminal stale ONLY when the
crew shows positive evidence it is still working - its no-mistakes run for its
branch is in an actively-running step, or its pane shows the harness busy
signature. Otherwise surface it so firstmate peeks (done, waiting, or wedged).

- fm-classify-lib.sh: add crew_is_provably_working (reuses fm-crew-state.sh,
  no run-step duplication) and signal_crew_provably_working; FM_CREW_STATE_BIN
  override for tests.
- fm-watch.sh: signal path surfaces a no-verb wake whose crew is not provably
  working (costly check runs only on the no-verb, non-afk path); non-terminal
  stale surfaces immediately when not provably working, else absorbs with the
  wedge timer (run-step read only on first sight of a stale hash).
- afk path unchanged: the watcher stays one-shot and skips the provably-working
  read; the daemon keeps its bounded-latency stale backstop.
- tests: cover every required semantic (mid-pipeline absorb, finished/parked
  surface, no-running-pipeline idle surface, busy absorb, captain-verb surface)
  as classifier unit tests and behavioral watcher runs; queue-safety test for
  the new immediate-surface stale path.
- AGENTS.md section 8: document absorb-only-when-provably-working.

* no-mistakes(document): Sync watcher documentation
* feat(harness): add grok (Grok Build) as a verified crewmate adapter

Empirically verified against grok 0.2.73 and encoded across the machinery:

- fm-harness.sh: detect grok via GROK_AGENT=1 env marker (grok does not set
  CLAUDECODE) and `grok` command-name ancestry.
- fm-spawn.sh: grok launch template (`grok --always-approve "$(cat BRIEF)"`,
  fully autonomous, no permission gate) and a turn-end Stop hook. grok only
  loads project hooks after a manual folder-trust grant, so the hook is a
  single firstmate-owned global hook (~/.grok/hooks/fm-turn-end.json, always
  trusted) that is a guarded no-op unless the workspace holds a per-task
  .fm-grok-turnend pointer; fm-spawn drops that gitignored pointer naming
  state/<id>.turn-ended. Hook stays outside the worktree, needs no trust grant.
- fm-watch.sh + fm-tmux-lib.sh: grok busy signature `Ctrl+c:cancel` (the
  mid-turn cancel hint; ASCII, present iff a turn runs).
- harness-adapters skill: grok facts section (busy, exit=Ctrl+Q x2,
  interrupt=Ctrl+C, skill invocation /<skill>, resume) and /no-mistakes form.

Gating question confirmed: grok invokes /no-mistakes and drives a real
no-mistakes axi run, so grok is usable for no-mistakes-mode tasks. End-to-end
verified through fm-spawn: autonomous launch past the dir picker into the
worktree, brief processed, busy->idle and turn-end signal detected, fm-send
steer lands, clean Ctrl+Q exit and teardown. config/crew-harness is left
unchanged; this only makes grok available as a verified option.

* no-mistakes(review): Captain, harden Grok hook lifecycle

* no-mistakes(review): Captain, make Grok harness test executable

* no-mistakes(review): Captain, bound Grok pointer reads

* no-mistakes(test): Captain, harden crew-state and watcher-lock timing

* no-mistakes(document): Document Grok harness support
* feat(harness): split secondmate harness and inherit primary config into secondmate homes

Add config/secondmate-harness so secondmates can run on a different adapter
than crewmates. fm-harness.sh gains a `secondmate` mode resolving the chain
config/secondmate-harness -> config/crew-harness -> own; `crew` mode is
unchanged. fm-spawn resolves a --secondmate launch through that mode (durable:
every respawn re-resolves), while an explicit per-spawn harness arg still wins
and the unverified-adapter guard still holds.

Add a generic, extensible inheritable-config mechanism (fm-config-inherit-lib.sh)
that pushes the primary's declared LOCAL config into each secondmate home's
config/ at secondmate spawn and on the bootstrap secondmate sweep. Exactly one
item is wired today: config/crew-harness, so a secondmate's own crewmates use
the primary's setting. Primary-authoritative (re-pushed every convergence,
mirrors absence); config/secondmate-harness is deliberately not inherited since
secondmates never spawn secondmates. config/ is gitignored, so this is a copy
separate from the tracked-files fast-forward.

Update AGENTS.md (layout, bootstrap, harness, spawn), the harness-adapters
skill, docs/scripts.md, and .gitignore. New tests cover secondmate resolution
and fallback, spawn/respawn honoring config/secondmate-harness, config
propagation on spawn and sweep, the unverified-adapter guard, and backward
compatibility.

* no-mistakes(review): Surface inherited config propagation failures

* no-mistakes(review): Harden inherited config propagation

* no-mistakes(review): Document literal harness inheritance requirement

* no-mistakes(document): Document secondmate harness config
* feat(backlog): default to tasks-axi backend

* no-mistakes(document): Sync backlog backend docs
… /tmp (kunchenguid#36)

* fix(spawn): set per-task GOTMPDIR so interrupted Go builds don't leak /tmp

Go's GOTMPDIR is unset, so every go build/test creates numbered /tmp/go-build*
dirs. Go cleans them on a clean exit but LEAVES THEM when interrupted (signal,
timeout, OOM, full disk), accumulating and filling the disk over time.

Give each task its own temp root at /tmp/fm-<id>/ with Go's build temp nested at
gotmp/. fm-spawn creates the dir (Go won't mkdir GOTMPDIR), exports GOTMPDIR into
the crewmate pane so the agent and child processes inherit it, and records
tasktmp= in meta. fm-teardown reads tasktmp= and removes the whole root on
cleanup, deterministically.

GOTMPDIR (not TMPDIR) is the targeted knob: TMPDIR is too broad (affects every
program's temp). The nested root is extensible: other per-task temp can live
under /tmp/fm-<id>/ later.

Backward compat: tasks spawned before this change have no tasktmp= in meta;
teardown tolerates the empty value as a no-op. The daily fm-disk-cleanup.sh cron
remains a safety net for any pre-fix stray dirs.

* fix(tests): silence SC2016 for literal grep -F patterns in fm-gotmp test

The structural grep -F assertions deliberately match literal $TASK_TMP in the
fm-spawn source; add per-line shellcheck disable=SC2016 (the codebase's existing
pattern, e.g. bin/fm-spawn.sh) so CI lint passes.

* no-mistakes(document): docs: document tasktmp= meta field for per-task GOTMPDIR

---------

Co-authored-by: e-jung <[email protected]>
* fix(teardown): accept landed squash-merge PR heads

* no-mistakes(document): Document teardown landing behavior

* no-mistakes: apply CI fixes

* fix(test): pass explicit teardown git identity
* feat(dispatch): add dynamic crew profiles

* no-mistakes(review): Captain, document dispatch profile inheritance

* no-mistakes(review): Captain, guard stale dispatch inheritance

* no-mistakes(document): Sync dispatch profile docs

* no-mistakes: apply CI fixes
* Harden crew dispatch profile enforcement

* no-mistakes(document): Captain, synced crew dispatch docs
* feat(config): add live secondmate config push

* no-mistakes(document): Document config push behavior

* no-mistakes(lint): Clean changed shell lint

* no-mistakes: apply CI fixes
* feat(x): add image attachments to reply helpers

* no-mistakes(review): Stream X image replies safely

* no-mistakes(review): Captain, clean X reply temp tracking

* no-mistakes(document): Document X reply image support
* fix(teardown): make landed-check robust when no pr= was ever recorded

fm-teardown.sh's squash-merge landed-check already falls back to
discovering a merged PR by branch name when state/<id>.meta has no
recorded pr=, but nothing guaranteed pr=/pr_head= actually got
recorded on a yolo-authorized merge - the "checks green" trigger that
normally runs fm-pr-check.sh never fires on repos with no PR CI, so a
merge done via a bare `gh-axi pr merge` silently skips it.

Add bin/fm-pr-merge.sh as the one path for merging a task's PR: it
always runs fm-pr-check.sh first, so pr=/pr_head= land in meta as part
of the merge itself regardless of any CI signal. Document both the
existing branch-name discovery fallback and the new merge path in
AGENTS.md, and add regression coverage for the no-pr=-recorded landed
scenario and for fm-pr-merge.sh's record-then-merge behavior.

* no-mistakes(review): Guard PR merges on task metadata

* no-mistakes(document): Document PR merge wrapper

* no-mistakes: apply CI fixes
* Fix fm-pr-merge.sh to parse PR URLs for gh-axi

gh-axi pr merge expects a PR number and --repo, not a full GitHub URL.
Parse the URL, default to --squash when no merge method is passed, and
fail fast on malformed URLs. Tests cover parsing, defaults, and refusal.

* no-mistakes(review): Harden PR merge validation

* no-mistakes(review): Harden PR merge URL guards

* no-mistakes(document): Document PR merge URL handling

* no-mistakes(lint): Clean shell lint
* feat: pin secondmate model/effort in config/secondmate-harness

Extend config/secondmate-harness's format to an optional
"<harness> [<model>] [<effort>]" line so a secondmate can be durably
locked to a concrete model/effort in the same file, without adding a
new config file. A bare harness-only file behaves exactly as before.

fm-harness.sh gains secondmate-model/secondmate-effort accessors;
fm-spawn.sh populates MODEL/EFFORT from them on every secondmate spawn
(including respawns) unless the caller passed an explicit --model/--effort.

* no-mistakes(review): Fix secondmate override pin precedence

* no-mistakes(document): Document secondmate harness pins
* feat(bin): extract tmux runtime behind a backend interface (P1)

Add bin/fm-backend.sh (selection, meta helpers, selector resolution,
dispatch) and bin/backends/tmux.sh (the tmux adapter), then route
fm-send.sh, fm-peek.sh, fm-watch.sh, fm-spawn.sh, and fm-teardown.sh
through them. Every default tmux command sequence, meta shape, and
printed output stays byte-identical: missing backend= still means
tmux, and a default spawn never writes backend=tmux.

Adds a --backend flag (tmux-only for now) and FM_BACKEND/config/backend
selection, refusing any unimplemented backend loudly. Names the
watcher's poll loop as the default event-source implementation over the
backend's pull primitives, per the herdr-addendum's events-as-the-core-
abstraction direction, without changing its behavior.

Verification: fake-tmux/treehouse old-vs-new command-log conformance
tests for send/peek/spawn/teardown, a real-tmux smoke test for the
adapter, and the full existing suite passing unmodified (bar two
fixture-only additions in fm-gotmp.test.sh for the new sibling
scripts).

* no-mistakes(review): Captain, harden backend baseline resolution

* no-mistakes(review): Captain, ignore and document backend config

* no-mistakes(review): Captain, make backend tests executable

* no-mistakes(document): Sync runtime backend documentation
* feat(bin): add experimental herdr runtime backend (P2)

Implements bin/backends/herdr.sh (session-provider adapter, D3: treehouse
stays the worktree provider) wired through fm-backend.sh's dispatch, with
--backend herdr / FM_BACKEND=herdr / config/backend selection, a
version/protocol gate at spawn, semantic busy-state detection via herdr's
agent.get (fm-watch.sh and fm-crew-state.sh consult it before falling back to
the existing tmux pane-regex path), and label-based recovery discovery.

Container shape (D4) decided empirically: tab-per-task in one "firstmate"
workspace, mirroring tmux's one-session-many-windows model.

Found and fixed two real herdr v0.7.1 bugs during verification: `pane read
--lines N` returns empty for small N (worked around by over-fetching and
trimming locally), and `pane get`'s cwd field is frozen at pane-creation time
(fixed to read foreground_cwd instead, needed for fm-spawn's worktree-
discovery poll after `treehouse get`). Also fixed a pre-existing bug in
tests/fm-backend.test.sh's old-vs-new fixture that was silently missing
fm-backend.sh/bin/backends/ from the old bin/ shim.

Full empirical verification, the D4 decision evidence, and a real end-to-end
run (spawn/steer/peek/done/merge-local/teardown, including confirming
teardown refuses before the merge) are recorded in docs/herdr-backend.md.
The entire existing tmux conformance suite stays green.

* no-mistakes(review): Fix Herdr supervision recovery gaps

* no-mistakes(review): Captain, fix Herdr stale recovery gaps

* no-mistakes(review): Document Herdr composer primitive candidate

* no-mistakes(review): Captain, harden Herdr stale recovery and tests

* no-mistakes(document): Sync herdr backend docs

* no-mistakes: apply CI fixes
* feat(bin): auto-detect runtime backend from HERDR_ENV/TMUX markers

fm_backend_name now falls through to runtime auto-detection between
config/backend and the hard tmux default: a firstmate running natively
inside herdr (HERDR_ENV=1) now spawns crewmates into herdr by default,
mirroring how harness detection already works in fm-harness.sh. Nesting
resolves innermost-first (tmux wins over a nested herdr pane). Explicit
--backend/FM_BACKEND/config/backend settings always win over detection.
Selecting herdr via auto-detect prints a loud stderr notice; auto-detecting
tmux stays silent so the unconfigured default path is unchanged.

* no-mistakes(review): Captain, pin tmux tests and backend docs

* no-mistakes(document): Sync backend autodetect docs

* no-mistakes: apply CI fixes
* feat(stow): add operational-memory learnings convention and /stow skill

Add data/learnings.md as the fleet-local operational-learnings home,
a knowledge-routing table in AGENTS.md, and a user-invocable /stow
skill that sweeps a session for uncaptured durable knowledge and
files it to the right disk home before a reset.

* no-mistakes(review): Fix stow backlog note command

* no-mistakes(document): Document stow memory routing
…nguid#199)

* fix(tests): stop real-herdr smoke tests from ever killing the default session

Both fm-backend-herdr-smoke.test.sh and fm-backend-autodetect-smoke.test.sh
tore down their isolated throwaway HERDR_SESSION via a bare/inline-prefixed
`herdr server stop`, which is unscoped and resolves ambiently. On this herdr
client, that ambient resolution silently falls back to whatever server is
already running instead of the requested session - it killed the captain's
live default herdr server twice in production (2026-07-02), once from each
smoke test's cleanup trap.

Add tests/herdr-test-safety.sh with herdr_safe_stop_and_delete: it uses the
explicit-by-name `herdr session stop/delete <name>` form (never the ambient
`server stop`) and, before that, a read-only hard guard
(herdr_refuse_if_default) that re-queries `herdr session list --json` and
refuses outright if the target is literally "default", not found, or flagged
default:true. Fails closed on any ambiguity. Verified empirically against a
real isolated session: refuses on default/nonexistent/empty names without
ever calling stop, and correctly tears down a genuine isolated session while
leaving the default session's workspace state byte-identical before and
after.

* no-mistakes(review): guard herdr delete with fresh check

* no-mistakes(document): Document herdr smoke cleanup safety
…uid#200)

* feat(bin): give each secondmate its own labeled herdr workspace

Give each secondmate its own labeled herdr workspace, and land crewmates
spawned from a secondmate home in that secondmate's own space, instead of
every firstmate home (primary and all secondmates) sharing one "firstmate"
workspace.

bin/backends/herdr.sh: replace the constant FM_BACKEND_HERDR_WORKSPACE_LABEL
with fm_backend_herdr_workspace_label(), resolved fresh from FM_HOME on every
call. The primary (no .fm-secondmate-home marker) still resolves to
"firstmate" - byte-identical to every pre-existing task's recorded label, no
forced migration. A secondmate home resolves to "firstmate-<secondmate-id>".
Every workspace-scoped path (find/ensure, tab create + duplicate check,
list-live recovery, pane-for-tab) uses this same resolution, so recovery and
duplicate checks stay scoped to each home's own space. Workspace and tab
create now pass --no-focus unconditionally (verified: neither focuses by
default once a workspace exists; --no-focus is defense in depth against the
one bootstrap edge case where the very first workspace in a session auto-
focuses).

Also fixes a session-targeting bug found while verifying this empirically:
HERDR_SESSION (env var, exported or inline-prefixed) is not reliably honored
by herdr 0.7.1 CLI subcommands once another herdr server is already running -
it silently falls back to whatever server IS running. fm_backend_herdr_cli
wraps every herdr invocation with both HERDR_SESSION and a trailing
--session <name> flag (verified to route correctly in every case tried),
fixing this for the whole adapter, not just the new label-scoped calls.

bin/fm-spawn.sh: a --secondmate spawn is launched BY the primary's own
process, whose FM_HOME still names the primary at that point. The herdr case
arm now shadows FM_HOME to the secondmate's own home (PROJ_ABS) for just the
two calls that resolve/create the workspace and tab, restored automatically
afterward (bash's temporary-assignment-before-a-command form works for shell
functions too). A crewmate/scout spawned FROM a secondmate's own fm-spawn.sh
process needs no such glue - its own FM_HOME already names it.

Tests: extended tests/fm-backend-herdr.test.sh (per-home label resolution,
--no-focus, --session flag, workspace-find/list-live scoping) and
tests/fm-backend-herdr-smoke.test.sh (a secondmate-shaped home's workspace
label, list-live scoping, restart stability in the multi-workspace shape).
Added tests/fm-backend-herdr-workspace-per-home-e2e.test.sh: the mandatory
isolated E2E, driving real bin/fm-spawn.sh/fm-teardown.sh - a primary-shaped
home into "firstmate", a --secondmate spawn into its own labeled space, a
crewmate spawned FROM that secondmate-shaped home landing in the same space
(this exact path had never run before), teardown closing only the right tab,
and list-live recovery seeing only each home's own tabs. All ten assertions
passed on the real binary; the default herdr session's own workspace state
was confirmed byte-identical before and after every real-herdr test run in
this change.

docs/herdr-backend.md: rewrote "Task container shape" for the workspace-per-
home design (label derivation, the --secondmate FM_HOME-shadow wrinkle, focus
behavior, label-collision/adopt-don't-duplicate semantics, no-forced-
migration), added "Session targeting: the --session flag, not HERDR_SESSION
alone", extended "ID stability" to the multi-workspace shape, and documented
the new E2E test.

* no-mistakes(review): Clarify herdr focus docs

* no-mistakes(review): Captain, clarify herdr server session docs

* no-mistakes(document): Document herdr per-home spaces
)

* Rename herdr secondmate workspace prefix to 2ndmate-

The primary home keeps the firstmate label; secondmate homes now
resolve to 2ndmate-<id> so the herdr spaces sidebar is unambiguous.
Tests and docs updated; pre-rename workspaces can be aligned with
herdr workspace rename.

* no-mistakes(review): Clarify herdr workspace migration behavior

* no-mistakes(document): Herdr docs label alignment
* feat(bin): collapse session start into one command

Add bin/fm-session-start.sh, composing fm-lock.sh, fm-bootstrap.sh, and
fm-wake-drain.sh into one ordered digest (lock, bootstrap diagnostics,
wake queue, context files, fleet state) instead of six-plus separate
turns. Lock now runs before bootstrap's mutating sweeps, closing a race
where a second concurrent session could mutate shared state before
discovering the lock was held. A lock refusal prints a loud read-only
banner, skips every mutating step via a new opt-in
FM_BOOTSTRAP_DETECT_ONLY flag on fm-bootstrap.sh, and still completes
the read-only-safe digest.

Add fm_backend_target_exists to fm-backend.sh as a shared, read-only,
never-side-effecting per-task endpoint-liveness primitive for both the
tmux and herdr backends.

Rewrite AGENTS.md sections 3 and 5 around the single command and add
tests/fm-session-start.test.sh.

* no-mistakes(review): Harden session-start read-only guidance

* no-mistakes(review): Suppress read-only tangle repair guidance

* no-mistakes(review): Include orphan status logs

* no-mistakes(review): Captain: make session-start test executable

* no-mistakes(review): Captain: clarify status tail guidance

* no-mistakes(document): Sync session-start docs

* no-mistakes(lint): Shell lint clean

* fix(tests): avoid shellcheck boolean chain
* fix(bin): corroborate herdr idle agent_status with the pane's own text

crew_pane_is_busy trusted a bare `idle` verdict from herdr's agent.get
outright, skipping the tail-regex corroboration unknown already gets.
agent.get reports generation state only (working while the model streams
a turn), so it reads idle for a crew blocked on its own long foreground
no-mistakes run - even though the pane still shows the busy banner the
whole time. Combined with the no-mistakes CLI's 10-run attribution cap,
this made a genuinely working herdr crew read as not provably working,
triggering an immediate stale wake instead of absorb-then-escalate.

* no-mistakes(document): Align herdr busy-state docs
@delaanthonio delaanthonio changed the title feat: add multi-backend runtime supervision fix: harden runtime lifecycle and turn-end supervision Aug 23, 2026
@delaanthonio
delaanthonio merged commit 578379e into main Aug 23, 2026
15 checks passed
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.

5 participants