Skip to content

fix(bin): ignore crew state overrides for other tasks - #5881

Merged
kunchenguid merged 2 commits into
kunchenguid:mainfrom
andrewesweet:fm/crew-state-override-guard
Oct 17, 2026
Merged

kunchenguid merged 2 commits into
kunchenguid:mainfrom
andrewesweet:fm/crew-state-override-guard

Conversation

@andrewesweet

@andrewesweet andrewesweet commented Sep 27, 2026 •

Copy link
Copy Markdown
Contributor

Intent

bin/fm-crew-state.sh honours FM_CREW_STATE_META_OVERRIDE and FM_CREW_STATE_STATUS_OVERRIDE only when the override's basename is the requested task's own .meta or .status file name, and otherwise reads the task's own records under the state directory.

A fleet snapshot sets these overrides so each state read resolves the generation it captured.
When the override leaks into a later process, for example through a Herdr server started inside a snapshot child, every later fm-crew-state.sh <id> call reads that one captured task's records instead of its own.
Upstream PR #5622 keeps the overrides out of the Herdr server launch; this change is complementary and independent of it, so a reader never trusts an override that names a different task, whatever path leaked it.
A snapshot's own override, which names the task it was captured for, is still honoured.
Regression tests cover a mismatched override being ignored and a matching one being honoured.

What Changed

  • Accept metadata and status overrides only when their basenames match the requested task’s .meta or .status filename; otherwise read that task’s state-directory records.
  • Preserve matching snapshot overrides and add regression coverage for both matching and mismatched override paths.

Risk Assessment

✅ Low: The bounded guards reject foreign-task records, preserve matching snapshots, and have behaviorally distinct regression coverage.

Testing

Focused suite and all live CLI scenarios passed. Base reproduced both leaks; metadata mutation checks confirmed regression sensitivity after correcting a temporary selector. CLI evidence captured and disposable fixtures removed. No linters or full repository suite run.

  • Live validation: ✅ go - 7 of 7 scenarios driven live against the product
Scenario Result Live Evidence
Read a task without overrides and receive its own current state ✅ pass live Live CLI transcript: No overrides: own records
Supply foreign metadata or status overrides and still receive the requested task's state ✅ pass live Live CLI transcript: Foreign metadata alone ignored; Foreign status alone ignored; Both foreign overrides ignored
Read matching captures instead of changed live records using absolute, relative, or bare filenames ✅ pass live Live CLI transcript: Matching metadata alone honoured; Matching status alone honoured; Matching captured generation overrides changed live metadata; relative and bare-path checks
Mix matching and foreign overrides and have each file selected independently ✅ pass live Live CLI transcript: Matching metadata and foreign status resolved independently; Foreign metadata and matching status resolved independently
Try misleading filenames and receive live records unless the basename matches exactly ✅ pass live Live CLI transcript: Lookalike prefix-task-a rejected; task-a-extra rejected; TASK-A rejected; Wrong file extensions rejected independently
Reuse inherited snapshot overrides across task reads without contaminating another task ✅ pass live Live CLI transcript: Inherited snapshot environment reads task-a, task-b, then task-a
Read missing records without borrowing foreign captures or silently replacing matching captures ✅ pass live Live CLI transcript: Missing own metadata never borrows foreign capture; Matching missing metadata capture remains authoritative; Matching missing status capture does not use live status
Evidence: Live CLI transcript, including base-commit reproduction

Source: Live CLI transcript, including base-commit reproduction

~/.no-mistakes/worktrees/5ac353bebe94/01M54NF7FAK33AVF9TVBAP55YG/.lv
Private tmux endpoint: records:fm-lab-task 100x30
No overrides: own records
  $ bin/fm-crew-state.sh task-a
  state: working · source: status-log · own task-a
Foreign metadata alone ignored
  $ bin/fm-crew-state.sh task-a
  state: working · source: status-log · own task-a
Foreign status alone ignored
  $ bin/fm-crew-state.sh task-a
  state: working · source: status-log · own task-a
Both foreign overrides ignored
  $ bin/fm-crew-state.sh task-a
  state: working · source: status-log · own task-a
Matching metadata alone honoured
  $ bin/fm-crew-state.sh task-a
  state: unknown · source: none · worktree gone (torn down?)
Matching status alone honoured
  $ bin/fm-crew-state.sh task-a
  state: paused · source: status-log · captured task-a
Matching captured generation overrides changed live metadata
  $ bin/fm-crew-state.sh task-a
  state: paused · source: status-log · captured task-a
Matching metadata and foreign status resolved independently
  $ bin/fm-crew-state.sh task-a
  state: working · source: status-log · own task-a
Foreign metadata and matching status resolved independently
  $ bin/fm-crew-state.sh task-a
  state: paused · source: status-log · captured task-a
Relative matching paths honoured
  $ bin/fm-crew-state.sh task-a
  state: paused · source: status-log · captured task-a
Bare matching basenames honoured
  $ bin/fm-crew-state.sh task-a
  state: paused · source: status-log · captured task-a
Lookalike prefix-task-a rejected
  $ bin/fm-crew-state.sh task-a
  state: working · source: status-log · own task-a
Lookalike task-a-extra rejected
  $ bin/fm-crew-state.sh task-a
  state: working · source: status-log · own task-a
Lookalike TASK-A rejected
  $ bin/fm-crew-state.sh task-a
  state: working · source: status-log · own task-a
Wrong file extensions rejected independently
  $ bin/fm-crew-state.sh task-a
  state: working · source: status-log · own task-a
Inherited snapshot environment reads task-a
  $ bin/fm-crew-state.sh task-a
  state: paused · source: status-log · captured task-a
Inherited snapshot environment reads task-b
  $ bin/fm-crew-state.sh task-b
  state: working · source: status-log · own task-b
Inherited snapshot environment reads task-a
  $ bin/fm-crew-state.sh task-a
  state: paused · source: status-log · captured task-a
Missing own metadata never borrows foreign capture
  $ bin/fm-crew-state.sh absent-task
  state: unknown · source: none · no metadata for absent-task
Matching missing metadata capture remains authoritative
  $ bin/fm-crew-state.sh task-a
  state: unknown · source: none · no metadata for task-a
Matching missing status capture does not use live status
  $ bin/fm-crew-state.sh task-a
  state: unknown · source: none · no current-state source available
Base reproduces foreign metadata poisoning
  $ .lv/baseline-bin/fm-crew-state.sh task-a
  state: unknown · source: none · worktree gone (torn down?)
Base reproduces foreign status poisoning
  $ .lv/baseline-bin/fm-crew-state.sh task-a
  state: blocked · source: status-log · foreign task
All exact-basename behavioral checks passed; base reproduces both reported failures.
Cleanup: private tmux stopped (exit 0); disposable home removed=True
Evidence: Expected and observed live results

Source: Expected and observed live results

[
  {
    "name": "No overrides: own records",
    "task": "task-a",
    "meta_override": "None",
    "status_override": "None",
    "exit_code": 0,
    "expected": "state: working \u00b7 source: status-log \u00b7 own task-a",
    "observed": "state: working \u00b7 source: status-log \u00b7 own task-a",
    "stderr": "",
    "pass": true,
    "product": "target commit"
  },
  {
    "name": "Foreign metadata alone ignored",
    "task": "task-a",
    "meta_override": "~/.no-mistakes/worktrees/5ac353bebe94/01M54NF7FAK33AVF9TVBAP55YG/.lv/snapshot captures/foreign-task.meta",
    "status_override": "None",
    "exit_code": 0,
    "expected": "state: working \u00b7 source: status-log \u00b7 own task-a",
    "observed": "state: working \u00b7 source: status-log \u00b7 own task-a",
    "stderr": "",
    "pass": true,
    "product": "target commit"
  },
  {
    "name": "Foreign status alone ignored",
    "task": "task-a",
    "meta_override": "None",
    "status_override": "~/.no-mistakes/worktrees/5ac353bebe94/01M54NF7FAK33AVF9TVBAP55YG/.lv/snapshot captures/foreign-task.status",
    "exit_code": 0,
    "expected": "state: working \u00b7 source: status-log \u00b7 own task-a",
    "observed": "state: working \u00b7 source: status-log \u00b7 own task-a",
    "stderr": "",
    "pass": true,
    "product": "target commit"
  },
  {
    "name": "Both foreign overrides ignored",
    "task": "task-a",
    "meta_override": "~/.no-mistakes/worktrees/5ac353bebe94/01M54NF7FAK33AVF9TVBAP55YG/.lv/snapshot captures/foreign-task.meta",
    "status_override": "~/.no-mistakes/worktrees/5ac353bebe94/01M54NF7FAK33AVF9TVBAP55YG/.lv/snapshot captures/foreign-task.status",
    "exit_code": 0,
    "expected": "state: working \u00b7 source: status-log \u00b7 own task-a",
    "observed": "state: working \u00b7 source: status-log \u00b7 own task-a",
    "stderr": "",
    "pass": true,
    "product": "target commit"
  },
  {
    "name": "Matching metadata alone honoured",
    "task": "task-a",
    "meta_override": "~/.no-mistakes/worktrees/5ac353bebe94/01M54NF7FAK33AVF9TVBAP55YG/.lv/snapshot captures/task-a.meta",
    "status_override": "None",
    "exit_code": 0,
    "expected": "state: unknown \u00b7 source: none \u00b7 worktree gone (torn down?)",
    "observed": "state: unknown \u00b7 source: none \u00b7 worktree gone (torn down?)",
    "stderr": "",
    "pass": true,
    "product": "target commit"
  },
  {
    "name": "Matching status alone honoured",
    "task": "task-a",
    "meta_override": "None",
    "status_override": "~/.no-mistakes/worktrees/5ac353bebe94/01M54NF7FAK33AVF9TVBAP55YG/.lv/snapshot captures/task-a.status",
    "exit_code": 0,
    "expected": "state: paused \u00b7 source: status-log \u00b7 captured task-a",
    "observed": "state: paused \u00b7 source: status-log \u00b7 captured task-a",
    "stderr": "",
    "pass": true,
    "product": "target commit"
  },
  {
    "name": "Matching captured generation overrides changed live metadata",
    "task": "task-a",
    "meta_override": "~/.no-mistakes/worktrees/5ac353bebe94/01M54NF7FAK33AVF9TVBAP55YG/.lv/snapshot captures/task-a.meta",
    "status_override": "~/.no-mistakes/worktrees/5ac353bebe94/01M54NF7FAK33AVF9TVBAP55YG/.lv/snapshot captures/task-a.status",
    "exit_code": 0,
    "expected": "state: paused \u00b7 source: status-log \u00b7 captured task-a",
    "observed": "state: paused \u00b7 source: status-log \u00b7 captured task-a",
    "stderr": "",
    "pass": true,
    "product": "target commit"
  },
  {
    "name": "Matching metadata and foreign status resolved independently",
    "task": "task-a",
    "meta_override": "~/.no-mistakes/worktrees/5ac353bebe94/01M54NF7FAK33AVF9TVBAP55YG/.lv/snapshot captures/task-a.meta",
    "status_override": "~/.no-mistakes/worktrees/5ac353bebe94/01M54NF7FAK33AVF9TVBAP55YG/.lv/snapshot captures/foreign-task.status",
    "exit_code": 0,
    "expected": "state: working \u00b7 source: status-log \u00b7 own task-a",
    "observed": "state: working \u00b7 source: status-log \u00b7 own task-a",
    "stderr": "",
    "pass": true,
    "product": "target commit"
  },
  {
    "name": "Foreign metadata and matching status resolved independently",
    "task": "task-a",
    "meta_override": "~/.no-mistakes/worktrees/5ac353bebe94/01M54NF7FAK33AVF9TVBAP55YG/.lv/snapshot captures/foreign-task.meta",
    "status_override": "~/.no-mistakes/worktrees/5ac353bebe94/01M54NF7FAK33AVF9TVBAP55YG/.lv/snapshot captures/task-a.status",
    "exit_code": 0,
    "expected": "state: paused \u00b7 source: status-log \u00b7 captured task-a",
    "observed": "state: paused \u00b7 source: status-log \u00b7 captured task-a",
    "stderr": "",
    "pass": true,
    "product": "target commit"
  },
  {
    "name": "Relative matching paths honoured",
    "task": "task-a",
    "meta_override": "snapshot captures/task-a.meta",
    "status_override": "snapshot captures/task-a.status",
    "exit_code": 0,
    "expected": "state: paused \u00b7 source: status-log \u00b7 captured task-a",
    "observed": "state: paused \u00b7 source: status-log \u00b7 captured task-a",
    "stderr": "",
    "pass": true,
    "product": "target commit"
  },
  {
    "name": "Bare matching basenames honoured",
    "task": "task-a",
    "meta_override": "task-a.meta",
    "status_override": "task-a.status",
    "exit_code": 0,
    "expected": "state: paused \u00b7 source: status-log \u00b7 captured task-a",
    "observed": "state: paused \u00b7 source: status-log \u00b7 captured task-a",
    "stderr": "",
    "pass": true,
    "product": "target commit"
  },
  {
    "name": "Lookalike prefix-task-a rejected",
    "task": "task-a",
    "meta_override": "~/.no-mistakes/worktrees/5ac353bebe94/01M54NF7FAK33AVF9TVBAP55YG/.lv/snapshot captures/prefix-task-a.meta",
    "status_override": "~/.no-mistakes/worktrees/5ac353bebe94/01M54NF7FAK33AVF9TVBAP55YG/.lv/snapshot captures/prefix-task-a.status",
    "exit_code": 0,
    "expected": "state: working \u00b7 source: status-log \u00b7 own task-a",
    "observed": "state: working \u00b7 source: status-log \u00b7 own task-a",
    "stderr": "",
    "pass": true,
    "product": "target commit"
  },
  {
    "name": "Lookalike task-a-extra rejected",
    "task": "task-a",
    "meta_override": "~/.no-mistakes/worktrees/5ac353bebe94/01M54NF7FAK33AVF9TVBAP55YG/.lv/snapshot captures/task-a-extra.meta",
    "status_override": "~/.no-mistakes/worktrees/5ac353bebe94/01M54NF7FAK33AVF9TVBAP55YG/.lv/snapshot captures/task-a-extra.status",
    "exit_code": 0,
    "expected": "state: working \u00b7 source: status-log \u00b7 own task-a",
    "observed": "state: working \u00b7 source: status-log \u00b7 own task-a",
    "stderr": "",
    "pass": true,
    "product": "target commit"
  },
  {
    "name": "Lookalike TASK-A rejected",
    "task": "task-a",
    "meta_override": "~/.no-mistakes/worktrees/5ac353bebe94/01M54NF7FAK33AVF9TVBAP55YG/.lv/snapshot captures/TASK-A.meta",
    "status_override": "~/.no-mistakes/worktrees/5ac353bebe94/01M54NF7FAK33AVF9TVBAP55YG/.lv/snapshot captures/TASK-A.status",
    "exit_code": 0,
    "expected": "state: working \u00b7 source: status-log \u00b7 own task-a",
    "observed": "state: working \u00b7 source: status-log \u00b7 own task-a",
    "stderr": "",
    "pass": true,
    "product": "target commit"
  },
  {
    "name": "Wrong file extensions rejected independently",
    "task": "task-a",
    "meta_override": "~/.no-mistakes/worktrees/5ac353bebe94/01M54NF7FAK33AVF9TVBAP55YG/.lv/snapshot captures/task-a.status",
    "status_override": "~/.no-mistakes/worktrees/5ac353bebe94/01M54NF7FAK33AVF9TVBAP55YG/.lv/snapshot captures/task-a.meta",
    "exit_code": 0,
    "expected": "state: working \u00b7 source: status-log \u00b7 own task-a",
    "observed": "state: working \u00b7 source: status-log \u00b7 own task-a",
    "stderr": "",
    "pass": true,
    "product": "target commit"
  },
  {
    "name": "Inherited snapshot environment reads task-a",
    "task": "task-a",
    "meta_override": "~/.no-mistakes/worktrees/5ac353bebe94/01M54NF7FAK33AVF9TVBAP55YG/.lv/snapshot captures/task-a.meta",
    "status_override": "~/.no-mistakes/worktrees/5ac353bebe94/01M54NF7FAK33AVF9TVBAP55YG/.lv/snapshot captures/task-a.status",
    "exit_code": 0,
    "expected": "state: paused \u00b7 source: status-log \u00b7 captured task-a",
    "observed": "state: paused \u00b7 source: status-log \u00b7 captured task-a",
    "stderr": "",
    "pass": true,
    "product": "target commit"
  },
  {
    "name": "Inherited snapshot environment reads task-b",
    "task": "task-b",
    "meta_override": "~/.no-mistakes/worktrees/5ac353bebe94/01M54NF7FAK33AVF9TVBAP55YG/.lv/snapshot captures/task-a.meta",
    "status_override": "~/.no-mistakes/worktrees/5ac353bebe94/01M54NF7FAK33AVF9TVBAP55YG/.lv/snapshot captures/task-a.status",
    "exit_code": 0,
    "expected": "state: working \u00b7 source: status-log \u00b7 own task-b",
    "observed": "state: working \u00b7 source: status-log \u00b7 own task-b",
    "stderr": "",
    "pass": true,
    "product": "target commit"
  },
  {
    "name": "Inherited snapshot environment reads task-a",
    "task": "task-a",
    "meta_override": "~/.no-mistakes/worktrees/5ac353bebe94/01M54NF7FAK33AVF9TVBAP55YG/.lv/snapshot captures/task-a.meta",
    "status_override": "~/.no-mistakes/worktrees/5ac353bebe94/01M54NF7FAK33AVF9TVBAP55YG/.lv/snapshot captures/task-a.status",
    "exit_code": 0,
    "expected": "state: paused \u00b7 source: status-log \u00b7 captured task-a",
    "observed": "state: paused \u00b7 source: status-log \u00b7 captured task-a",
    "stderr": "",
    "pass": true,
    "product": "target commit"
  },
  {
    "name": "Missing own metadata never borrows foreign capture",
    "task": "absent-task",
    "meta_override": "~/.no-mistakes/worktrees/5ac353bebe94/01M54NF7FAK33AVF9TVBAP55YG/.lv/snapshot captures/task-a.meta",
    "status_override": "~/.no-mistakes/worktrees/5ac353bebe94/01M54NF7FAK33AVF9TVBAP55YG/.lv/snapshot captures/task-a.status",
    "exit_code": 0,
    "expected": "state: unknown \u00b7 source: none \u00b7 no metadata for absent-task",
    "observed": "state: unknown \u00b7 source: none \u00b7 no metadata for absent-task",
    "stderr": "",
    "pass": true,
    "product": "target commit"
  },
  {
    "name": "Matching missing metadata capture remains authoritative",
    "task": "task-a",
    "meta_override": "~/.no-mistakes/worktrees/5ac353bebe94/01M54NF7FAK33AVF9TVBAP55YG/.lv/missing/task-a.meta",
    "status_override": "None",
    "exit_code": 0,
    "expected": "state: unknown \u00b7 source: none \u00b7 no metadata for task-a",
    "observed": "state: unknown \u00b7 source: none \u00b7 no metadata for task-a",
    "stderr": "",
    "pass": true,
    "product": "target commit"
  },
  {
    "name": "Matching missing status capture does not use live status",
    "task": "task-a",
    "meta_override": "None",
    "status_override": "~/.no-mistakes/worktrees/5ac353bebe94/01M54NF7FAK33AVF9TVBAP55YG/.lv/missing/task-a.status",
    "exit_code": 0,
    "expected": "state: unknown \u00b7 source: none \u00b7 no current-state source available",
    "observed": "state: unknown \u00b7 source: none \u00b7 no current-state source available",
    "stderr": "",
    "pass": true,
    "product": "target commit"
  },
  {
    "name": "Base reproduces foreign metadata poisoning",
    "task": "task-a",
    "meta_override": "~/.no-mistakes/worktrees/5ac353bebe94/01M54NF7FAK33AVF9TVBAP55YG/.lv/snapshot captures/foreign-task.meta",
    "status_override": "None",
    "exit_code": 0,
    "expected": "state: unknown \u00b7 source: none \u00b7 worktree gone (torn down?)",
    "observed": "state: unknown \u00b7 source: none \u00b7 worktree gone (torn down?)",
    "stderr": "",
    "pass": true,
    "product": "base commit"
  },
  {
    "name": "Base reproduces foreign status poisoning",
    "task": "task-a",
    "meta_override": "None",
    "status_override": "~/.no-mistakes/worktrees/5ac353bebe94/01M54NF7FAK33AVF9TVBAP55YG/.lv/snapshot captures/foreign-task.status",
    "exit_code": 0,
    "expected": "state: blocked \u00b7 source: status-log \u00b7 foreign task",
    "observed": "state: blocked \u00b7 source: status-log \u00b7 foreign task",
    "stderr": "",
    "pass": true,
    "product": "base commit"
  }
]
Evidence: Reproducible isolated CLI driver

Source: Reproducible isolated CLI driver

#!/usr/bin/env python3
"""Drive the real crew-state CLI with disposable records and a private tmux.

Oracle: the author's exact-basename contract. Foreign records must not change
another task's reading; matching captures must remain authoritative. No product
commands, endpoint probes, or busy-state writers are mocked.
"""
import json
import os
from pathlib import Path
import shutil
import subprocess

ROOT = Path('~/.no-mistakes/worktrees/5ac353bebe94/01M54NF7FAK33AVF9TVBAP55YG')
EVIDENCE = Path('~/.no-mistakes/evidence/01M54NF7FAK33AVF9TVBAP55YG')
LAB = ROOT / '.lv'
assert not LAB.exists(), f'Refusing existing fixture: {LAB}'
env = {k: v for k, v in os.environ.items() if not k.startswith('FM_')}
for key in ('TMUX', 'TMUX_PANE', 'HERDR_SESSION', 'GIT_DIR', 'GIT_COMMON_DIR', 'GIT_WORK_TREE'):
    env.pop(key, None)
env.update(FM_HOME=str(LAB), TMUX_TMPDIR=str(LAB / 'tmux'), HISTFILE='/dev/null', GIT_CONFIG_GLOBAL='/dev/null', GIT_CONFIG_NOSYSTEM='1')
results = []
tmux = ['tmux', '-L', 'fm-lab']

def run(args, **kwargs):
    return subprocess.run([str(a) for a in args], cwd=ROOT, env=env, text=True,
                          capture_output=True, timeout=20, check=True, **kwargs).stdout.strip()

def meta(path, *, missing=False):
    path.parent.mkdir(parents=True, exist_ok=True)
    wt = LAB / ('missing-worktree' if missing else 'task-worktree')
    path.write_text(f'window=records:fm-lab-task\nworktree={wt}\nkind=scout\nharness=claude\nbackend=tmux\n')

def drive(name, task, expected, *, meta_override=None, status_override=None, cwd=None, baseline=False):
    child_env = env.copy()
    if meta_override is not None:
        child_env['FM_CREW_STATE_META_OVERRIDE'] = str(meta_override)
    if status_override is not None:
        child_env['FM_CREW_STATE_STATUS_OVERRIDE'] = str(status_override)
    command = LAB / 'baseline-bin/fm-crew-state.sh' if baseline else ROOT / 'bin/fm-crew-state.sh'
    proc = subprocess.run([str(command), task], cwd=cwd or ROOT, env=child_env,
                          text=True, capture_output=True, timeout=20)
    observed = proc.stdout.strip()
    row = {'name': name, 'task': task, 'meta_override': str(meta_override),
           'status_override': str(status_override), 'exit_code': proc.returncode,
           'expected': expected, 'observed': observed,
           'stderr': proc.stderr.strip(), 'pass': proc.returncode == 0 and observed == expected,
           'product': 'base commit' if baseline else 'target commit'}
    results.append(row)
    print(f'{name}\n  $ {command.relative_to(ROOT)} {task}\n  {observed}', flush=True)
    assert row['pass'], json.dumps(row, indent=2)
    return observed

try:
    print(run([ROOT / 'bin/fm-lab-home.sh', 'create', LAB]), flush=True)
    (LAB / 'tmux').mkdir()
    (LAB / 'task-worktree').mkdir()
    run([*tmux, '-f', '/dev/null', 'new-session', '-d', '-s', 'records', '-n', 'fm-lab-task',
         '-x', '100', '-y', '30', '-c', ROOT, 'bash --noprofile --norc'])
    env['TMUX'] = run([*tmux, 'display-message', '-p', '-t', 'records', '#{socket_path},#{pid},0'])
    print('Private tmux endpoint: ' + run([*tmux, 'display-message', '-p', '-t', 'records',
          '#{session_name}:#{window_name} #{pane_width}x#{pane_height}']), flush=True)
    state, snapshot = LAB / 'state', LAB / 'snapshot captures'
    snapshot.mkdir()
    for task in ('task-a', 'task-b'):
        meta(state / f'{task}.meta')
        (state / f'{task}.status').write_text(f'working: own {task}\n')
        run([ROOT / 'bin/fm-busy-event.sh', 'arm', state, task, '--state', 'idle',
             '--source', 'claude-hook', '--event', 'stop'])
    meta(snapshot / 'task-a.meta')
    (snapshot / 'task-a.status').write_text('paused: captured task-a\n')
    meta(snapshot / 'foreign-task.meta', missing=True)
    (snapshot / 'foreign-task.status').write_text('blocked: foreign task\n')
    own_a = 'state: working · source: status-log · own task-a'
    own_b = 'state: working · source: status-log · own task-b'
    captured = 'state: paused · source: status-log · captured task-a'
    gone = 'state: unknown · source: none · worktree gone (torn down?)'

    drive('No overrides: own records', 'task-a', own_a)
    drive('Foreign metadata alone ignored', 'task-a', own_a, meta_override=snapshot / 'foreign-task.meta')
    drive('Foreign status alone ignored', 'task-a', own_a, status_override=snapshot / 'foreign-task.status')
    drive('Both foreign overrides ignored', 'task-a', own_a,
          meta_override=snapshot / 'foreign-task.meta', status_override=snapshot / 'foreign-task.status')
    # Make the matching capture observably different from the current generation.
    meta(snapshot / 'task-a.meta', missing=True)
    drive('Matching metadata alone honoured', 'task-a', gone, meta_override=snapshot / 'task-a.meta')
    meta(snapshot / 'task-a.meta')
    drive('Matching status alone honoured', 'task-a', captured, status_override=snapshot / 'task-a.status')
    meta(state / 'task-a.meta', missing=True)
    drive('Matching captured generation overrides changed live metadata', 'task-a', captured,
          meta_override=snapshot / 'task-a.meta', status_override=snapshot / 'task-a.status')
    drive('Matching metadata and foreign status resolved independently', 'task-a', own_a,
          meta_override=snapshot / 'task-a.meta', status_override=snapshot / 'foreign-task.status')
    meta(state / 'task-a.meta')
    drive('Foreign metadata and matching status resolved independently', 'task-a', captured,
          meta_override=snapshot / 'foreign-task.meta', status_override=snapshot / 'task-a.status')
    drive('Relative matching paths honoured', 'task-a', captured,
          meta_override=Path('snapshot captures/task-a.meta'), status_override=Path('snapshot captures/task-a.status'), cwd=LAB)
    drive('Bare matching basenames honoured', 'task-a', captured,
          meta_override='task-a.meta', status_override='task-a.status', cwd=snapshot)
    for basename in ('prefix-task-a', 'task-a-extra', 'TASK-A'):
        meta(snapshot / f'{basename}.meta', missing=True)
        (snapshot / f'{basename}.status').write_text('blocked: lookalike foreign record\n')
        drive(f'Lookalike {basename} rejected', 'task-a', own_a,
              meta_override=snapshot / f'{basename}.meta', status_override=snapshot / f'{basename}.status')
    meta(snapshot / 'task-a.status', missing=True)
    drive('Wrong file extensions rejected independently', 'task-a', own_a,
          meta_override=snapshot / 'task-a.status', status_override=snapshot / 'task-a.meta')
    (snapshot / 'task-a.status').write_text('paused: captured task-a\n')
    # A later child inherits the same snapshot environment but requests a new id.
    for task, expected in [('task-a', captured), ('task-b', own_b), ('task-a', captured)]:
        drive(f'Inherited snapshot environment reads {task}', task, expected,
              meta_override=snapshot / 'task-a.meta', status_override=snapshot / 'task-a.status')
    drive('Missing own metadata never borrows foreign capture', 'absent-task',
          'state: unknown · source: none · no metadata for absent-task',
          meta_override=snapshot / 'task-a.meta', status_override=snapshot / 'task-a.status')
    drive('Matching missing metadata capture remains authoritative', 'task-a',
          'state: unknown · source: none · no metadata for task-a', meta_override=LAB / 'missing/task-a.meta')
    drive('Matching missing status capture does not use live status', 'task-a',
          'state: unknown · source: none · no current-state source available', status_override=LAB / 'missing/task-a.status')
    # Counterfactual: run the base CLI with unchanged libraries and identical data.
    baseline = LAB / 'baseline-bin'
    baseline.mkdir()
    for source in (ROOT / 'bin').iterdir():
        if source.name != 'fm-crew-state.sh':
            (baseline / source.name).symlink_to(source)
    source = run(['git', 'show', 'ce697402e662cd7f9d6ef5c367041dd51516eb49:bin/fm-crew-state.sh'])
    (baseline / 'fm-crew-state.sh').write_text(source + '\n')
    (baseline / 'fm-crew-state.sh').chmod(0o755)
    drive('Base reproduces foreign metadata poisoning', 'task-a', gone,
          meta_override=snapshot / 'foreign-task.meta', baseline=True)
    drive('Base reproduces foreign status poisoning', 'task-a',
          'state: blocked · source: status-log · foreign task',
          status_override=snapshot / 'foreign-task.status', baseline=True)
    print('All exact-basename behavioral checks passed; base reproduces both reported failures.', flush=True)
finally:
    stopped = subprocess.run([*tmux, 'kill-server'], env=env, capture_output=True, text=True)
    (EVIDENCE / 'crew-state-live-results.json').write_text(json.dumps(results, indent=2) + '\n')
    if LAB.exists():
        shutil.rmtree(LAB)
    print(f'Cleanup: private tmux stopped (exit {stopped.returncode}); disposable home removed={not LAB.exists()}', flush=True)
Evidence: Regression tests reject metadata-only mutations

Source: Regression tests reject metadata-only mutations

{
  "variant": "current",
  "test": "test_mismatched_state_override_is_ignored",
  "expected_exit": 0,
  "actual_exit": 0,
  "stdout": "ok - override guard: a foreign-named override is ignored and the task's own state files are read",
  "stderr": ""
}
{
  "variant": "current",
  "test": "test_matched_state_override_is_honoured",
  "expected_exit": 0,
  "actual_exit": 0,
  "stdout": "ok - override guard: a matching-name override still steers the read at the captured generation",
  "stderr": ""
}
{
  "variant": "foreign-metadata-accepted",
  "test": "test_mismatched_state_override_is_ignored",
  "expected_exit": 1,
  "actual_exit": 1,
  "stdout": "",
  "stderr": "not ok - a mismatched override must be ignored: the task's own working log line wins (missing: 'state: working')\n--- output ---\nstate: unknown \u00b7 source: none \u00b7 worktree gone (torn down?)"
}
{
  "variant": "matching-metadata-ignored",
  "test": "test_matched_state_override_is_honoured",
  "expected_exit": 1,
  "actual_exit": 1,
  "stdout": "",
  "stderr": "not ok - a matched-name override must be honoured over the live status log (missing: 'state: paused')\n--- output ---\nstate: unknown \u00b7 source: none \u00b7 worktree gone (torn down?)"
}
Disposable metadata mutations and temporary regression driver removed.

Pipeline

Updates from git push no-mistakes

✅ **Intent** - passed

✅ No issues found.

✅ **Rebase** - passed

✅ No issues found.

✅ **Review** - passed

✅ No issues found.

✅ **Test** - passed

✅ No issues found.

  • Live validation: ✅ go - 7 of 7 scenarios driven live against the product
Scenario Result Live Evidence
Read a task without overrides and receive its own current state ✅ pass live Live CLI transcript: No overrides: own records
Supply foreign metadata or status overrides and still receive the requested task's state ✅ pass live Live CLI transcript: Foreign metadata alone ignored; Foreign status alone ignored; Both foreign overrides ignored
Read matching captures instead of changed live records using absolute, relative, or bare filenames ✅ pass live Live CLI transcript: Matching metadata alone honoured; Matching status alone honoured; Matching captured generation overrides changed live metadata; relative and bare-path checks
Mix matching and foreign overrides and have each file selected independently ✅ pass live Live CLI transcript: Matching metadata and foreign status resolved independently; Foreign metadata and matching status resolved independently
Try misleading filenames and receive live records unless the basename matches exactly ✅ pass live Live CLI transcript: Lookalike prefix-task-a rejected; task-a-extra rejected; TASK-A rejected; Wrong file extensions rejected independently
Reuse inherited snapshot overrides across task reads without contaminating another task ✅ pass live Live CLI transcript: Inherited snapshot environment reads task-a, task-b, then task-a
Read missing records without borrowing foreign captures or silently replacing matching captures ✅ pass live Live CLI transcript: Missing own metadata never borrows foreign capture; Matching missing metadata capture remains authoritative; Matching missing status capture does not use live status
  • TMPDIR=&#34;$PWD/.validation-tmp&#34; timeout 240 bash tests/fm-crew-state.test.sh — passed.
  • python3 ~/.no-mistakes/evidence/01M54NF7FAK33AVF9TVBAP55YG/drive-crew-state.py — exercised the real CLI with disposable records and private tmux; reproduced both failures using the base-commit CLI.
  • python3 ~/.no-mistakes/evidence/01M54NF7FAK33AVF9TVBAP55YG/check-override-regressions.py — both regressions passed normally and rejected metadata-only mutations. Corrected an initial temporary selector timeout before the successful rerun.
  • git status --short, git diff --exit-code, and fixture-absence checks — source unchanged; disposable files and private tmux removed.
✅ **Document** - passed

✅ No issues found.

✅ **Lint** - passed

✅ No issues found.

✅ **Push** - passed

✅ No issues found.

@andrewesweet
andrewesweet force-pushed the fm/crew-state-override-guard branch from d5a90e5 to 9e90262 Compare September 27, 2026 12:30
@andrewesweet andrewesweet changed the title fix: ignore cross-task crew state overrides fix(bin): ignore fm-crew-state overrides that name another task Sep 27, 2026
bin/fm-crew-state.sh honours FM_CREW_STATE_META_OVERRIDE and FM_CREW_STATE_STATUS_OVERRIDE only when the override's basename is the requested task's own .meta or .status file name.
An override naming a different task, for example one inherited through a server started inside another task's snapshot child, falls through to the task's own records under the state directory.
A snapshot's own override, which names the task it was captured for, is still honoured.
This is complementary to kunchenguid#5622, which keeps the overrides out of the Herdr server launch: whatever path leaks an override, the reader never trusts one that names a different task.
Regression tests cover a mismatched override being ignored and a matching one being honoured.
@andrewesweet
andrewesweet force-pushed the fm/crew-state-override-guard branch from 9e90262 to 624e1ce Compare October 17, 2026 09:17
@andrewesweet andrewesweet changed the title fix(bin): ignore fm-crew-state overrides that name another task fix(bin): ignore crew state overrides for other tasks Oct 17, 2026
@kunchenguid
kunchenguid merged commit 11becbb into kunchenguid:main Oct 17, 2026
20 of 21 checks passed
@kunchenguid

Copy link
Copy Markdown
Owner

Speaking as Kun's firstmate: this is merged. Thank you @andrewesweet — really appreciate you taking the time on this.

max-metaplanet added a commit to max-metaplanet/firstmate that referenced this pull request Oct 19, 2026
## Commits taken

- d20196a feat(herdr): opt-in project groups with status tags and a sorted agents view (kunchenguid#7434)
- ce69740 fix(bin): pin LC_ALL=C for remote job process identity reads (kunchenguid#7410)
- 64dddf6 fix(opencode): ignore child stdin EPIPE in guard and encoder (kunchenguid#7447)
- 11becbb fix(bin): ignore crew state overrides for other tasks (kunchenguid#5881)
- eeeeb91 fix(bin): re-anchor a Claude session's lock so /clear keeps ownership (kunchenguid#7415)
- 66c300b feat: support version URLs for watched tool updates (kunchenguid#7449)
- 3094475 fix(pi): keep a live session's extension markers when a nested Pi command loads them (kunchenguid#7287)
- f05b628 fix: reclaim orphaned Claude auto-arm claims (kunchenguid#5939)
- c4f4333 feat(bin): add Polytoken crewmate/scout worker adapter (kunchenguid#7321)
- 11990a2 Fix away branch relaunch admission (kunchenguid#7444)
- 56074d0 fix(bin): show reported checks when a pull request's base requires none (kunchenguid#7450)
- 0791268 fix: support durable per-secondmate account pins (kunchenguid#7452)
- 4e6b9f5 feat(bin): consult operator evidence guards before wedge escalation (kunchenguid#6958)
- c7b7798 fix(bin): make inbox listing succeed when the inbox is empty (kunchenguid#7460)
- 63fc5eb fix: bound remote secondmate convergence and preserve owed re-reads (kunchenguid#7394)
- 8ba34f1 fix: require positive daemon running status in crew-state (kunchenguid#7317)
- 1aa2a21 fix(tests): stabilize supervision host drain and offer fixtures (kunchenguid#7467)
- 69f9d09 fix(bin): refuse spawn into a project with an unborn HEAD (kunchenguid#6987)
- 45dd50a feat(bin): add GitLab --allow-no-pipeline merge waiver and close backlog items for GitLab MRs (kunchenguid#7462)

## Conflict decisions

- `.agents/skills/operational-home-layout/SKILL.md`: Fork seat configuration; upstream per-secondmate account configuration. Decision: Keep both configuration entries.
- `bin/backends/herdr.sh`: Fork send-failure/recovery semantics and harness variable; upstream Polytoken busy override. Decision: Keep fork send-failed and recovery handling; add Polytoken busy identity without losing the fork harness variable.
- `bin/fm-backlog-transition-lib.sh`: Fork cached library directory; upstream GitLab completion support. Decision: Keep cached source path and extend forge ownership comment to GitLab; accept GitLab completion path.
- `bin/fm-config-inherit-lib.sh`: Fork Claude/Codex seat inheritance; upstream Herdr project groups. Decision: Union the allowlist; per-secondmate account pins remain local to the primary home.
- `bin/fm-control.sh`: Fork pre-stop seat checks; upstream per-mate pins and Polytoken launch checks. Decision: Select the per-mate pin while retaining its returned account for seat conflict validation; keep all Polytoken pre-stop checks. A valid explicit pin supersedes the old recorded Claude store on relaunch.
- `bin/fm-harness.sh`: Fork in-process HARNESS_VERDICT result; upstream echo-based Polytoken detection. Decision: Add Polytoken through the fork verdict convention, retaining existing adapter detection.
- `bin/fm-lock.sh`: Fork handover reservation and runtime publication; upstream session re-anchor lease/auto-arm locks. Decision: Share the existing claim lock and release helper, add lease/auto-arm locking, then publish runtime and clear an admitted handover before releasing locks.
- `bin/fm-pr-state.sh`: Fork shared required-check evaluator from dbe11b1 and 91371c8; upstream 56074d0 adds a second gh pr checks fallback. Decision: Keep one evaluator through fm-pr-checks.sh and fm-pr-checks-lib.sh. It already checks non-advisory reported checks on unprotected bases, includes missing configured requirements, and fails closed on read errors. Adapt upstream regressions to this API; preserve the fork REQUIRED CHECK label and advisory policy.
- `bin/fm-spawn.sh`: Fork parked-session resume, seats, unclaimed-worktree guard and ticket hook; upstream Polytoken, per-mate accounts and Herdr groups. Decision: Compose both paths, retain validate_spawn_worktree_unclaimed, seat gates, profile trust and metadata, and both hooks. Extend pin/seat refusal to the selected per-mate pin while retaining the primary-home seat guard. The selected durable Claude pin owns trust and recorded store on relaunch so old seats cannot override it.
- `bin/fm-teardown.sh`: Fork merged-at/park record cleanup and isolation protections; upstream generated Polytoken wiring cleanup. Decision: Keep fork cleanup and guards; add only task-owned Polytoken files and generated untracked wiring to existing guarded teardown.
- `bin/fm-test-run.sh`: Fork timing entries and pipeline-spend suite; upstream Herdr-group and Polytoken suites. Decision: Union suite entries, preserve fork timing measurements for existing suites.
- `bin/fm-wake-lib.sh`: Fork single-read auto-arm ledger parser; upstream session-owner identity fields. Decision: Extend the single-read parser with owner_session_id and the third-line lock identity; retain orphan recovery and lease logic.
- `bin/fm-watch.sh`: Fork bounded run-activity deferral and escalation wording; upstream operator evidence guard. Decision: Keep both bounded deferrals and append operator guard evidence to both ordinary and deep-inspection escalations. Keep exact owned watcher termination semantics.
- `docs/agent-control.md`: Fork seat relaunch policy; upstream per-mate account selection. Decision: Describe both policies with account pin checked before stopping the live agent.
- `docs/configuration.md`: Fork seat sections and ticket timeout; upstream per-mate pins and remote convergence settings. Decision: Keep all sections, place per-mate pins under worker accounts before the seat sections, and retain all timeout entries.
- `tests/fm-control-relaunch.test.sh`: Fork fixture cleanup and seat regressions; upstream account and away-admission regressions. Decision: Keep fixture-scoped cleanup and all regression calls; extend the changed-pin case to check trust in the new store and recorded profile.
- `tests/fm-crew-state.test.sh`: Fork no-fork metadata parsing test; upstream override-identity tests. Decision: Keep both test bodies and calls, plus upstream positive daemon-status cases.
- `tests/fm-pr-merge.test.sh`: Fork named-case local selector; upstream GitLab waiver test definitions. Decision: Place upstream definitions before the named-case selector and retain every case.
- `tests/fm-supervision-host.test.sh`: Fork split helper/suite layout; upstream snapshot-aware offer fixture. Decision: Update the shared supervision-host-helpers.sh implementation and retain its split consumers rather than duplicate the helper in one suite.
- `tests/fm-teardown.test.sh`: Fork collision/released-claim cases; upstream Polytoken cleanup cases. Decision: Keep all regression calls.
- `tests/fm-watch-triage.test.sh`: Fork split classifier/stale/delivery suites; upstream unsplit suite with four new operator-guard cases. Decision: Keep the split and move only new guard fixtures/cases into fm-watch-triage-stale.test.sh; do not resurrect duplicated legacy test bodies.

## Additional integration and verification decisions

- Preserve fork teardown, merge, push, worktree ownership/isolation, and exact-owned watcher termination guards. GitLab no-pipeline waiver remains explicit, attended-only, GitLab-only, and only accepts an explicit null pipeline; default and existing-pipeline safety checks remain in force.
- Existing pull-request CI selects subsets and cannot prove the requested full suite. Add a manual CI workflow trigger using the existing full-suite fallback, so the feature head can run every required lane before landing; document that entry point. No local full suite or real Herdr lifecycle run is authorized.
max-metaplanet added a commit to max-metaplanet/firstmate that referenced this pull request Oct 19, 2026
* feat(herdr): opt-in project groups with status tags and a sorted agents view (kunchenguid#7434)

* feat(herdr): opt-in project groups with status tags and a sorted agents view

Add config/herdr-project-groups (absent or off: unchanged behavior). When on,
Firstmate tags each Herdr task pane, and its own projected workspace, with
display-only fm_group/fm_state/fm_task/fm_sort tokens, sets a Herdr agents
view sorted by group then status (needs-captain, problem, running, done), and
places a new projected task at the end of its own group inside the parent
block with the same single verified move as before.

The watcher reconciles tags once per poll and a spawn tags its task at once;
bin/fm-herdr-groups.sh also previews (plan), clears, and prints or appends
suggested sidebar rows with a backup. The agents view helper needs python3.
The only test-runner change is the serial weight hint for the new suite.

* docs(herdr): record the live lab check of project groups

The four hand checks for tags, the sorted agents view, placement at the
end of the group, and clear passed against a real Herdr 0.9.5 server
(protocol 22) in a guarded lab session.

* docs(herdr): align project group verification notes with the live check

* fix(bin): pin LC_ALL=C for remote job process identity reads (kunchenguid#7410)

ps -o lstart= renders in the caller's locale, so a lock or claim owner
recorded under one locale (de_DE renders "Di Okt 13 ...") failed identity
verification under another, was declared dead, and a second worker split
the queue: two serve loops reclaimed and reaped each other's live jobs,
which vanished mid-claim and failed staged jobs with exit 125 and no
output. Pin LC_ALL=C in fm_remote_job_process_start and pin the
cross-locale invariant with a regression test.

Co-authored-by: researchworldwide2026 <[email protected]>

* fix(opencode): ignore child stdin EPIPE in guard and encoder (kunchenguid#7447)

* fix(bin): ignore crew state overrides for other tasks (kunchenguid#5881)

* Guard fm-crew-state overrides by task-name basename

bin/fm-crew-state.sh honours FM_CREW_STATE_META_OVERRIDE and FM_CREW_STATE_STATUS_OVERRIDE only when the override's basename is the requested task's own .meta or .status file name.
An override naming a different task, for example one inherited through a server started inside another task's snapshot child, falls through to the task's own records under the state directory.
A snapshot's own override, which names the task it was captured for, is still honoured.
This is complementary to kunchenguid#5622, which keeps the overrides out of the Herdr server launch: whatever path leaks an override, the reader never trusts one that names a different task.
Regression tests cover a mismatched override being ignored and a matching one being honoured.

* no-mistakes(review): Make metadata override tests behaviorally distinct

* fix(bin): re-anchor a Claude session's lock so /clear keeps ownership (kunchenguid#7415)

* fix(bin): re-anchor a Claude session's lock so /clear keeps ownership

A same-session confirmation over a live lock line 1 outside the current
harness ancestry now rewrites line 1 to the session's CLAUDE_PID anchor
under the claim lock, so a later /clear re-key in the same process is
still proven by ancestry instead of being refused as a foreign owner.

Fixes kunchenguid#6820

* fix(bin): move task leases with a session-lock re-anchor

A same-session re-anchor rewrote lock line 1 off a live pid while task
leases still named that pid, so a lease held by main or the supervision
branch read as stale and the other actor could claim the task. The
re-anchor now takes the lease-command lock after the claim lock and,
in the same critical section as the line-1 write, rewrites leases
recorded against the old pid to the new anchor (fm_lease_rekey_holder).
If the lease-command lock stays busy past a short bound, the
confirmation keeps line 1 as before and a later acquisition re-anchors.

The foreign-owner reproduction now asserts the re-anchor contract: the
same trusted id from a live process outside the owner's ancestry moves
line 1 onto that process's CLAUDE_PID, and a different id is refused
against it afterwards. The ancestry membership loop is shared through
one session-lock lib helper.

The earlier commit dropped the ancestry suite's dead-front-end reclaim
phase; that coverage lives in the existing reclaim tests
(test_verified_reclaim_keeps_new_sidecar and the Stop auto-arm's
test_reclaims_stale_session_lock_before_arming).

* fix(bin): record the lock holder for a lease pinned before a re-anchor

The supervision host pins FM_LEASE_HOLDER_PID to lock line 1 at the
start of each engine turn. A same-session re-anchor inside that turn
moved line 1 to a new pid while the pinned holder stayed alive, so a
later claim or same-actor refresh in the turn recorded the old pid and
the lease read stale, letting main claim the branch's task.

A claim now records the live line 1 when the pinned holder is alive but
is no longer line 1. Another session takes the lock only from a dead
owner, so that state comes from a re-anchor; a dead pin is still
recorded as before and its lease stays stale.

* no-mistakes(review): Move auto-arm rewake session pid with lock re-anchor

* no-mistakes(review): Align startup-network downgrade test and lock-rewrite comment

* no-mistakes(review): Correct lock takeover and re-anchor signal-window comments

* no-mistakes(review): Record re-anchor rewake and pinned-claim verification evidence

* no-mistakes(document): Update network-checks diagnostic for re-anchored lock holder

* feat: support version URLs for watched tool updates (kunchenguid#7449)

* feat(bin): watch a tool's published version through version_url

A watched tool whose CLI never announces its own updates can name a version_url; the document is fetched read-only inside the probe bound, its first dotted number is the published version, and an update is reported when that is newer than the version PATH resolves. Claude Code is the shipped example entry.

* no-mistakes(review): Compare published versions against newest installed tool copy

* no-mistakes(document): Clarify watched-tool version URL documentation

* fix(pi): keep a live session's extension markers when a nested Pi command loads them (kunchenguid#7287)

* fix(pi): keep a live session's extension markers when a nested Pi command loads them

A short-lived Pi command started from inside a live session, such as the
`pi --help` capability probe, auto-loads the two primary extensions. Both
treated the session lock as owned because an ancestor holds it, so the child
rewrote `.pi-watch-extension-loaded` and `.pi-turnend-extension-loaded` with
its own pid and exited. Session start then rejected the markers and printed a
false `PI_WATCH_EXTENSION: not loaded` alarm.

Before writing, each extension now reads the marker's pid and leaves the
marker untouched when that pid is a live strict ancestor of the current
process. A missing marker, a dead pid, the current pid, or a live pid outside
the ancestry still writes as before, so a fresh start and a relaunch over a
dead session bind unchanged. Lock ownership and the reader are untouched.

Fixes kunchenguid#5202.

* fix(tests): drop apostrophes from the nested-load marker heredocs so stock Bash 3.2 parses them

* fix: reclaim orphaned Claude auto-arm claims (kunchenguid#5939)

* fix(bin): supersede an orphaned Claude auto-arm claim after a session restart

An auto-arm claim is open only while its owner still descends from the session-lock pid.
A hook whose session exited mid-cycle stays alive with no parent to receive its exit 2, so deferring to its claim left the home unsupervised until the next session turn.
The replacement session's first Stop now takes the next generation, attaches to the running watcher, and delivers the wake itself, while the orphan goes silent.
A claim with no readable numeric session lock is never open.

* no-mistakes(review): accept pid-1 ancestor and session-id-matched autoarm claims

* no-mistakes(review): pin autoarm session-id claim signal to lock holder pid

* no-mistakes(review): exercise real lock recovery in orphan supersession tests

* no-mistakes(review): record lock-holder pid-identity instead of bare pid

* no-mistakes(document): complete autoarm claim-open coverage list

* no-mistakes(ci): Greptile finding ci-1 (hidden session-lock dependency in bin/fm-wake-lib.sh) fixed. Invariant: every function fm-wake-lib.sh calls must either be defined in that file or explicitly loaded by it before the call, so a caller sourcing only the wake library cannot silently degrade. Violating sites in the changed area: fm_autoarm_claim_open's fm_session_lock_recorded_session_id call, and the sibling writer fm_autoarm_claim_next's fm_session_lock_trusted_session_id call (which would otherwise silently omit the two new ledger fields). Both fixed at one shared boundary: a new lazy loader _fm_wake_require_session_lock (bin/fm-wake-lib.sh:38), matching the file's existing _fm_wake_require_classify/_fm_wake_require_timeout idiom, invoked immediately before each call. Lazy rather than top-level source so the ~40 scripts sourcing the wake library pay no harness-identity machinery cost; no circularity (fm-session-lock-lib.sh sources only fm-cursor-lib.sh). No new behaviour, state, or fallback. Verification: sourcing only fm-wake-lib.sh, a claim with broken ancestry plus matching sidecar id and matching recorded lock-holder identity now reads OPEN and the session-lock library is loaded on demand; ordinary descent path unaffected. Suites tests/fm-claude-stop-autoarm.test.sh, tests/fm-turnend-guard.test.sh, tests/fm-wake-queue.test.sh all pass; shellcheck -S warning reports only the pre-existing SC2034 present on HEAD. tests/fm-session-lock-ancestry.test.sh fails its final case ("the pty-host was not reparented to init after the daemon ended") identically with the change reverted, so that failure is a pre-existing WSL environment behaviour, not caused by this fix

* no-mistakes(document): Clarify auto-arm claim documentation

* feat(bin): add Polytoken crewmate/scout worker adapter (kunchenguid#7321)

* wip: polytoken worker adapter (detection, launch, wiring, control, composer; tests mid-iteration)

* feat: verify the polytoken worker adapter (crewmate + scout)

Add polytoken 0.8.19 as a verified crewmate/scout adapter on the
captain-approved TUI-pane-plus-REST hybrid: the pane keeps inspection
and backend parity while the control verbs ride the session daemon's
typed REST API.

Detection is ancestry alone on the anchored polytoken comm (a tool
subprocess's parent is the session daemon, verified live), with the
launch boundary clearing every foreign ORCA_/FM_ marker plus the fixed
harness-identity set. The launch generates the per-task worker config
dir (mirrored operator config with the unattended permission posture
enforced, because a project config.yaml fully replaces the global
config), the worker role-contract facet (no model pin, delegation and
facet switching denied at the tool registry), and the worktree hook
layer binding the verified busy pair - pre_user_prompt and
pre_model_turn open, stop closes - to a no-argv generated writer. The
readiness gate binds the session id, port, and credential into task
metadata through sessions --format json and fails loudly on any
first-start dialog, because the license terms are a blocker by captain
decision and --accept-license-terms is never passed.

Interrupt is POST /turn/cancel with its typed settle (the TUI has no
interrupt chord, so no key is ever improvised), exit is /quit, and a
cancelled turn's busy close is written by the control plane because no
stop hook fires. The composer is the verified separated shape with
polytoken as its second owner, and Enter mid-turn queues, so the
busy-queued conversion applies. Crewmate and scout only: a secondmate
launch is refused, and a project's own .polytoken/hooks.json is refused
rather than clobbered.

* no-mistakes(review): Fix polytoken launch flag order, token argv, live guard

* no-mistakes(document): Correct polytoken REST doc comment and token-on-stdin invariant

* no-mistakes(lint): Silence intentional SC2016 in polytoken live guard treehouse shim

* no-mistakes(review): Retire polytoken pool wiring, drop FIFO config, test env clearing

* no-mistakes(review): Scope polytoken teardown wiring removal to untracked polytoken files

* no-mistakes(review): Refuse existing polytoken hook layer before writing any wiring

* no-mistakes(document): Note teardown as consumer of harness wiring-path table

* no-mistakes(review): Retire only firstmate-generated polytoken worktree wiring

* no-mistakes(review): Guard polytoken hook layer before relaunch cleanup arms

* no-mistakes(document): Note relaunch also skips git-tracked wiring paths

* test: stub polytoken in the refused-relaunch fixture

The refused relaunch onto polytoken resolves the polytoken binary before
its hook-layer refusal, so the case failed on CI hosts without the real
CLI installed. A no-op stub on the fixture PATH stands in; it is never
launched.

* no-mistakes(review): Guard polytoken interrupt close; refuse whitespace hook paths

* no-mistakes(review): Snapshot busy record after cancel settles before idle close

* no-mistakes(review): Guard interrupt close with pre-cancel snapshot and sync recheck

* no-mistakes(test): Clear inherited AGENT at the polytoken launch boundary

* no-mistakes(document): Document guarded polytoken interrupt close and whitespace refusal

* test: preserve Polytoken hook refusal coverage with explicit pins

* no-mistakes(review): Refuse invalid Polytoken relaunch profiles before stopping the worker

* no-mistakes(document): Document Polytoken relaunch refusals before stopping the worker

* fix: scope worker wiring cleanup to Polytoken

* fix(bin): point Polytoken workers away from tool_flow for the task directory

Polytoken 0.9.0 offers no launch-time path grant: tool_flow's file_read
refuses the Firstmate task directory while the direct file tools reach it
under the generated bypass matcher. The worker facet now says so, and the
verification record carries the live evidence.

* fix(bin): leave the pool as found when a fresh spawn fails

A fresh spawn that fails and leaves no task record now closes the endpoint
it opened before its launch was delivered, so the shell whose treehouse get
leases the slot ends and the pool gets the slot back. It also removes the
harness wiring, task temp root, and staged launch file it wrote, and drops
its slot claim under a retaken project lock after metadata publication.

* no-mistakes(review): Stop pre-launch refusals pointing at windows abort cleanup closes

* fix(bin): scope failed-spawn cleanup and the Running-for busy row to Polytoken

The failed-spawn pool cleanup and the Running-for busy row now apply only to
Polytoken, so every other harness keeps main's abort behavior, header text,
operator messages, and harness-less busy union. Tests prove the Polytoken
path cleans up and a non-Polytoken refused launch behaves as on main.

* no-mistakes(review): Scope submit-core busy reads to Polytoken pane identity

* no-mistakes(review): Stop polytoken treehouse isolation refusal pointing at closed window

* test: track the spawned window in the Polytoken harness tmux stand-in

Main now requires exact tmux window membership before sending keys
(aa9ab04), and the Polytoken harness stand-in listed no windows, so the
merged spawn could never deliver Enter. Record the created window, list
it, and forget it on kill, as tests/fixtures.sh does.

* no-mistakes(document): Scope fresh-endpoint abort comment to Polytoken spawns

* no-mistakes(ci): Lint 1 (ci-3) was caused by this PR, and I fixed it. Commit d18014e added the in_polytoken_submit_pane() subshell helper to tests/fm-polytoken-harness.test.sh. That helper sources bin/fm-tmux-lib.sh without the `# shellcheck source=/dev/null` line that every other source in the file carries (lines 55-63 and 200). With --external-sources, ShellCheck followed the library into the subshell and flagged `local pid=$!` at line 690 as SC2031. The fix is that one missing line, added above the source at line 318. After the fix, `shellcheck -x` reports nothing on the file, `bin/fm-lint.sh tests/fm-polytoken-harness.test.sh` passes with full extended analysis, and the Polytoken harness test passes. Behavior portable serial 2 (ci-1) and serial 5 (ci-2) failed in timing-sensitive tests this PR does not touch, so I made no code change for them. I reran both test files in full on this branch on macOS, and both passed (rc=0, no failures). tests/fm-supervision-host.test.sh passed, including the 'host-only transition veto changed Pi's existing offer rule' check that failed in CI. tests/fm-remote-secondmate-lifecycle-e2e.test.sh passed, including 'watch liveness: a dead remote secondmate is auto-relaunched on its own host with one wake'. Main's own recent CI runs (38950070853, 38719784765) also failed on different timing assertions in these serial shards. Together that points to runner flakes rather than a defect in this change

* no-mistakes(review): Retake per-id spawn lock before Polytoken abort deletions

* no-mistakes(document): Document per-id lock guard on Polytoken abort cleanup

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>

* Fix away branch relaunch admission (kunchenguid#7444)

* fix(bin): show reported checks when a pull request's base requires none (kunchenguid#7450)

Port the reported-check fallback and regressions from df60538. Preserve required-only reporting when required checks exist and refuse failed fallback reads.

* fix: support durable per-secondmate account pins (kunchenguid#7452)

* fix(tests): clean read-only relaunch fixtures

Use the shared fixture cleanup so generated read-only Git hook directories do not leave permission errors and temporary trees behind.

* fix(accounts): support durable per-secondmate account pins

Resolve optional primary-home secondmate account files through the worker pin parser and checks. Preserve existing defaults when no override exists and re-read the selected pin on spawn, relaunch, and recovery.

* no-mistakes(review): Name the rejected pin file in account refusals

* no-mistakes(document): Document per-secondmate account pins in relaunch and layout docs

* feat(bin): consult operator evidence guards before wedge escalation (kunchenguid#6958)

* feat(watch): consult opt-in operator guards before a wedge escalation

Add config/wedge-evidence-guards, an opt-in list of operator-owned guard
executables that the watcher's at-threshold wedge branch consults after the
wait evidence, worktree-write probe and dead-endpoint probe. A CRITICAL
answer defers one window at a time, capped by FM_WEDGE_GUARD_DEFER_MAX
consecutive deferrals recorded beside the other wedge-window records, and
the escalation that ends a capped run names the guard and its reason.
Timeouts, failures, malformed output, UNKNOWN and WARNING fail open, and an
untrusted config or guard is never run. With the config absent the ladder is
unchanged.

Refs kunchenguid#6919

* no-mistakes(document): Document wedge-evidence-guards in home layout index

* no-mistakes(document): Align jev-guards CRITICAL verdict with bounded deferral

* fix(bin): make inbox listing succeed when the inbox is empty (kunchenguid#7460)

* fix(bin): make the brief's inbox listing succeed on an empty inbox

The worker brief told crewmates to list the inbox with a bare *.msg glob.
On an empty inbox that glob fails: bash ls exits 2 and zsh aborts with
'no matches found'. Use find piped to sort -V so the listing is silent on an
empty or absent inbox and keeps numeric order past 999.

Refs kunchenguid#7244

* no-mistakes(review): Make relaunch note inbox listing safe when empty

* fix: bound remote secondmate convergence and preserve owed re-reads (kunchenguid#7394)

* fix(bin): fit remote second-mate convergence inside the startup network bound

The deferred startup network stage (120s) timed out once four second mates
were remote: the mates already converge concurrently, but each mate's
inheritance push sent its fifteen allowlisted items one SSH round trip after
another, so a single mate's convergence took 64-76s after a ~16s liveness
pass.

- fm-remote-inherit-push.sh validates and snapshots every item locally first,
  so a local refusal now sends nothing, then sends the items up to
  FM_REMOTE_INHERIT_PUSH_JOBS (default 4) at a time and replays their output in
  allowlist order. A failed item still fails the push with its own error, and
  no further item is started after it. The receiver is unchanged: each item is
  its own file and generation record, and the host's job worker still runs one
  home's commands one at a time.
- fm-bootstrap.sh gives each remote mate's convergence its own budget,
  FM_SECONDMATE_CONVERGENCE_TIMEOUT (default 75s). A mate whose sync or push
  hits it is reported as that mate's SECONDMATE_SYNC skip and keeps its retry
  marker, instead of holding the whole stage past its bound.

* fix(bin): nudge a remote second mate to re-read only when something changed

Each remote convergence attempt records its retry marker before it starts,
so a sweep cut off by the startup network bound or failing before any change
left a marker that made the next session start nudge every remote mate even
though its instructions and inherited files were unchanged. The marker now
records whether a re-read is owed, set only once an attempt actually changed
the home, and a tracked-file sync that moved nothing under AGENTS.md, bin/,
or .agents/skills/ no longer counts as a change.

* fix(bin): keep a remote mate's re-read owed when its convergence is cut short

A convergence step stopped by the per-mate budget loses its output, so a
push that had already applied an item reported nothing and left the retry
marker with no re-read owed; the next start then saw every item unchanged
and never told the mate to re-read. A step cut off by the budget now marks
the re-read owed, and so does a failed push whose output shows items it had
already pushed or removed.

The lifecycle e2e suite runs every remote leg through the real entrypoint
and job worker on the test machine, so it now gives convergence ample time;
the budget's own behavior is pinned in fm-bootstrap-network-parallel, whose
budget and failure cases are also made independent of machine load.

* no-mistakes(review): Keep re-read owed on partial or unknown completion

* no-mistakes(review): Persist owed re-read when killed mid-mutation

* no-mistakes(document): Fix stale remote re-read owed docs

* test: send inherited items one at a time in the remote lifecycle e2e fixture

Behavior portable serial 5 failed on the watcher auto-relaunch leg of
tests/fm-remote-secondmate-lifecycle-e2e.test.sh after the inheritance push
started overlapping its sends. Across 14 recent main CI runs that suite's
remote-spawn leg took 30.8-35.6s and the watcher leg 27.3-34.5s, already close
to its 30s wait; on the PR run remote spawn took 42.1s, well outside that range,
while legs that push nothing were only 5-10% slower. The watcher relaunch is a
remote spawn, and the only changed code on that path is the inheritance push.

This fixture's transport has no network latency and its job worker runs one
home's commands one at a time, so overlapping sends cannot hide any round trip
there and only add submission overhead to every remote spawn. The suite now
sends one item at a time, as it did before; the overlapped scheduler stays
covered by tests/fm-bootstrap-network-parallel.test.sh, and the production
default of four is unchanged. The watcher leg's failure now also prints the
watcher's output.

* no-mistakes(document): Clarify remote re-read obligations and consolidate documentation

* fix(bin): record a remote mate's re-read as owed before convergence can change its home

A live run against a real remote second-mate home showed the owed re-read
still lost when the startup network bound stopped the stage. That bound
stops it the way `timeout -k 1` does: TERM to the stage's process group, then
KILL one second later. Bash defers a TERM trap while the convergence worker
waits in a command substitution, and the remote call runs in its own timed
process group, so the KILL landed before the trap could record the re-read.
The remote home had already applied the change, the next start saw every item
unchanged, sent nothing, and deleted the marker, so the mate was never told
to re-read.

Bootstrap convergence and config-push now write the record owed before any
remote step can change the home, and write it back only after the attempt has
reported: removed after confirmed unchanged convergence or a successful send,
and back to owed=0 when a failed attempt's outcome proves nothing changed. A
kill at any point therefore leaves the re-read owed. The TERM/INT traps are
gone. The kill regression now sends TERM and then KILL one second later, as
the startup bound does; it fails on the previous head and passes here.

* no-mistakes(document): Clarify convergence timeout scope and consolidate reread documentation

* fix: require positive daemon running status in crew-state (kunchenguid#7317)

* fix(tests): stabilize supervision host drain and offer fixtures (kunchenguid#7467)

* fix(bin): refuse spawn into a project with an unborn HEAD (kunchenguid#6987)

* fix(bin): refuse spawn into a project with an unborn HEAD

Spawn into a repository with no commit waited 60s for treehouse and then reported that the worktree was the spawning project itself, never naming the cause. Refuse before the wait and name the unborn HEAD and the remedy. The project-management skill now states that a new local repository needs a first commit.

* docs(skills): tell the captain a new project needs a first commit

The Create a project step no longer reads as firstmate committing into the project. It states that spawn refuses an unborn HEAD and that the captain is told the project needs a first commit.

* test: give spawn fixtures a first commit for the unborn-HEAD refusal

* no-mistakes(review): Commit foreign consent fixture so spawn guard passes

* feat(bin): add GitLab --allow-no-pipeline merge waiver and close backlog items for GitLab MRs (kunchenguid#7462)

* feat(bin): add an attended GitLab --allow-no-pipeline merge waiver

A GitLab repository that deliberately runs no merge request pipeline could
never be merged through fm-pr-merge.sh: the guard requires a successful head
pipeline at the current head, and GitLab has no per-check waiver.

--allow-no-pipeline waives only the pipeline condition, and only when GitLab
reports head_pipeline as present and null. A failed, running, canceled, or
stale pipeline still refuses, every other condition (open, mergeable
detailed_merge_status, no conflicts, discussions resolved) still holds, and
the verified head is still passed to glab as --sha. The flag is attended-only
(refused while the away-posture record exists), GitLab-only, and takes no
value; without it the default refusal is unchanged.

* fix(bin): close a GitLab merge request task's backlog item with a note

tasks-axi accepts a --pr link only as a GitHub or Forgejo pull request, so
after a GitLab merge request landed, teardown could never complete the
backlog Done transition and left the close pending forever.

Extend the existing Gerrit carve-out in fm_backlog_done and
fm_backlog_retain, and the captain-hold answer replay that shares it, to
record a GitLab merge request URL as a "GitLab merge request <url>" note,
until tasks-axi accepts GitLab merge request URLs. GitHub and Forgejo pull
requests are still recorded as pr links.

* no-mistakes(document): Note GitLab --allow-no-pipeline waiver in merge-watch record

* no-mistakes(review): Order seat-pin test before footer; drop duplicate mate assignment

* no-mistakes(test): Fix herdr-groups test socket paths on macOS

* no-mistakes(document): Document account pin superseding recorded Claude profile on relaunch

* no-mistakes(ci): Fixed two failing tests in the portable serial shards, plus one doc line. The "PR must be raised via no-mistakes" check needs no code change. 1. Shard 12, `tests/fm-control-relaunch.test.sh`, "an unpinned replacement must launch exactly as before": a real merge conflict, reproduced locally. - **Cause:** when a Claude account pin applies, the fork saves the pin's directory as the task's recorded Claude profile (`claude_seat`). A relaunch without `--seat` reuses that recorded profile. So after the pin was removed, the replacement still launched under the old pin directory (`CLAUDE_CONFIG_DIR=<old pin>`). - **Rule that must hold:** a Claude profile recorded only because of a pin must not outlive the pin. - **Where it applies:** both places that read the recorded Claude profile on relaunch. - `bin/fm-spawn.sh`: the launch owner sets `RELAUNCH_SEAT`. - `bin/fm-control.sh` (`resolve_relaunch_profile`): checks the profile before the old agent is stopped. - **Fix:** both now ignore a recorded `claude_seat` that equals the task's recorded `account` (the pin's directory). - **What stays the same:** profiles chosen with `--seat` are still kept. An active pin still overrides the recorded profile, and a changed pin is still followed. - **Docs:** updated the matching line in `docs/agent-control.md`. 2. Shard 8, `tests/fm-watch-triage-delivery.test.sh`, "re-arm 4 never captured the pane": a flaky test, not caused by this change. - **Cause:** the fake `tmux` empties its tick counter file and then rewrites it. Stopping the watcher doesn't stop that child process, so the test sometimes read an empty file (`[: : integer expression expected`). - **Fix:** the fake now writes to a temp file and renames it into place, so the counter is never read empty. 3. "PR must be raised via no-mistakes": fails because the attestation records that the test step was approved over a failing test command (exit 124). The user already declined fixing that in test round 2, so no code change is warranted. It stays red until `test.allow_approve_over_failure` is set in the default-branch `.no-mistakes.yaml`, or until the PR is re-attested. **Verification:** run locally on macOS with `CLAUDE_CONFIG_DIR` unset. These files passed with no failures: `fm-control-relaunch`, `fm-watch-triage-delivery`, `fm-seat`, `fm-worker-account`, `fm-worker-account-live-e2e`. `shellcheck -x -S warning` is clean on the changed scripts. I didn't rerun the other serial shards

* no-mistakes(test): Keep recorded Claude seat separate from account pin

---------

Co-authored-by: Sebastian <[email protected]>
Co-authored-by: joergspoerl <[email protected]>
Co-authored-by: researchworldwide2026 <[email protected]>
Co-authored-by: Andrew Sweet <[email protected]>
Co-authored-by: Liam Sarsfield <[email protected]>
Co-authored-by: Tiago <[email protected]>
Co-authored-by: sjennings <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Harsha <[email protected]>
Co-authored-by: Konner Moshier <[email protected]>
Co-authored-by: Tim Kleinschmidt <[email protected]>
Co-authored-by: Arthur Cruz <[email protected]>
Co-authored-by: Robert Christensen <[email protected]>
Co-authored-by: Muhammad Syarifudin <[email protected]>
witt3rd added a commit to witt3rd/firstmate that referenced this pull request Oct 21, 2026