Skip to content

fix: avoid argument-size failures in fleet contribution snapshots - #6830

Merged
kunchenguid merged 2 commits into
kunchenguid:mainfrom
kesslerio:fm/fm-fleet-snapshot-argv-overflow-55
Oct 10, 2026
Merged

kunchenguid merged 2 commits into
kunchenguid:mainfrom
kesslerio:fm/fm-fleet-snapshot-argv-overflow-55

Conversation

@kesslerio

Copy link
Copy Markdown
Contributor

Intent

Land a real fix that is already written but sitting uncommitted in the primary checkout. The captain confirmed it should be taken care of. The fix: bin/fm-fleet-snapshot.sh's contribution-input jq call passes the whole backlog JSON as one --argjson argv argument, which can exceed Linux MAX_ARG_STRLEN (128 KiB) and crash the bearings contribution path on large fleets. The staged fix routes both JSON documents through temp files with --slurpfile instead of argv. Land exactly this diff through the no-mistakes pipeline; the primary checkout returns clean afterward.

What Changed

  • Load backlog and task JSON from temporary files with jq --slurpfile, avoiding argument-size failures in contribution-input mode on large fleets while preserving the output structure.
  • Report temporary-file creation and write failures, and remove the temporary directory on exit.

Risk Assessment

✅ Low: The narrow change removes whole-document argv transport, preserves the output contract, checks staging failures, and cleans up private temporary files.

Testing

All seven live CLI scenarios passed, including baseline overflow reproductions, contribution and Bearings integration, empty input, and transport failures. Evidence was retained and disposable fixtures removed. No rendered UI changed; landing and primary-checkout cleanup remain owned by the outer executor.

  • Live validation: ✅ go - 7 of 7 scenarios driven live against the product
Scenario Result Live Evidence
Read ordinary contribution ownership with identical JSON semantics and temporary-file cleanup ✅ pass live live-results.json: small-before and small-after
Read a 400-row backlog exceeding 128 KiB and pass all owned contributions to the real consumer ✅ pass live live-results.json: large-backlog-before, large-backlog-after, large-backlog-consumer
Run Bearings on the large backlog and observe 400 owned contributions ✅ pass live large-backlog-bearings.stdout
Read task metadata exceeding 128 KiB without losing values or exceeding the argument limit ✅ pass live live-results.json: large-tasks-before and large-tasks-after
Read an empty fleet with an absent backlog and receive valid empty ownership JSON ✅ pass live live-results.json: missing-backlog
Encounter a transport write limit and receive an explicit failure, no JSON, and complete temporary-file cleanup ✅ pass live live-results.json: transport-write-failure
Use an unavailable temporary directory and receive an explicit failure without misleading output ✅ pass live live-results.json: transport-creation-failure
Evidence: Live CLI results and baseline reproductions

Source: Live CLI results and baseline reproductions

[
  {
    "command": [
      "bash",
      "~/.no-mistakes/worktrees/9f75ec418609/01M4CK3M44RTV3MR0ZCWQ01TRK/bin/.contribution-baseline.sh",
      "--contribution-input"
    ],
    "label": "small-before",
    "exit": 0,
    "stdout_bytes": 1658,
    "stderr": ""
  },
  {
    "command": [
      "bash",
      "bin/fm-fleet-snapshot.sh",
      "--contribution-input"
    ],
    "label": "small-after",
    "exit": 0,
    "stdout_bytes": 1658,
    "stderr": ""
  },
  {
    "scenario": "small ownership pair preserves exact JSON semantics and cleans transport",
    "result": "pass"
  },
  {
    "command": [
      "bash",
      "~/.no-mistakes/worktrees/9f75ec418609/01M4CK3M44RTV3MR0ZCWQ01TRK/bin/.contribution-baseline.sh",
      "--contribution-input"
    ],
    "label": "large-backlog-before",
    "exit": 0,
    "stdout_bytes": 0,
    "stderr": "~/.no-mistakes/worktrees/9f75ec418609/01M4CK3M44RTV3MR0ZCWQ01TRK/bin/.contribution-baseline.sh: line 1997: /run/current-system/sw/bin/jq: Argument list too long\n"
  },
  {
    "command": [
      "bash",
      "bin/fm-fleet-snapshot.sh",
      "--contribution-input"
    ],
    "label": "large-backlog-after",
    "exit": 0,
    "stdout_bytes": 495361,
    "stderr": ""
  },
  {
    "command": [
      "bash",
      "bin/fm-contributions.sh",
      "snapshot",
      "~/.no-mistakes/evidence/01M4CK3M44RTV3MR0ZCWQ01TRK/large-backlog-after.stdout"
    ],
    "label": "large-backlog-consumer",
    "exit": 0,
    "stdout_bytes": 330,
    "stderr": ""
  },
  {
    "scenario": "400-row backlog exceeds 128 KiB and reaches real contribution consumer",
    "result": "pass",
    "backlog_json_bytes": 363906,
    "known": 400
  },
  {
    "command": [
      "bash",
      "bin/fm-bearings-snapshot.sh",
      "--json"
    ],
    "label": "large-backlog-bearings",
    "exit": 0,
    "stdout_bytes": 5065,
    "stderr": ""
  },
  {
    "scenario": "Bearings shows contributions for a large backlog",
    "result": "pass"
  },
  {
    "command": [
      "bash",
      "~/.no-mistakes/worktrees/9f75ec418609/01M4CK3M44RTV3MR0ZCWQ01TRK/bin/.contribution-baseline.sh",
      "--contribution-input"
    ],
    "label": "large-tasks-before",
    "exit": 0,
    "stdout_bytes": 0,
    "stderr": "~/.no-mistakes/worktrees/9f75ec418609/01M4CK3M44RTV3MR0ZCWQ01TRK/bin/.contribution-baseline.sh: line 1997: /run/current-system/sw/bin/jq: Argument list too long\n"
  },
  {
    "command": [
      "bash",
      "bin/fm-fleet-snapshot.sh",
      "--contribution-input"
    ],
    "label": "large-tasks-after",
    "exit": 0,
    "stdout_bytes": 150988,
    "stderr": ""
  },
  {
    "scenario": "task document exceeds 128 KiB and preserves every metadata value",
    "result": "pass",
    "tasks_json_bytes": 150545
  },
  {
    "command": [
      "bash",
      "bin/fm-fleet-snapshot.sh",
      "--contribution-input"
    ],
    "label": "missing-backlog",
    "exit": 0,
    "stdout_bytes": 210,
    "stderr": ""
  },
  {
    "scenario": "absent backlog and empty fleet remain valid empty ownership JSON",
    "result": "pass"
  },
  {
    "command": [
      "bash",
      "bin/fm-fleet-snapshot.sh",
      "--contribution-input"
    ],
    "label": "transport-write-failure",
    "exit": 1,
    "stdout_bytes": 0,
    "stderr": "bin/fm-fleet-snapshot.sh: line 2002: printf: File too large\nbin/fm-fleet-snapshot.sh: line 2002: printf: write error: File too large\nfm-fleet-snapshot: contribution backlog write failed\n"
  },
  {
    "scenario": "failed transport write reports failure, emits no JSON, and removes temporary files",
    "result": "pass"
  },
  {
    "command": [
      "bash",
      "bin/fm-fleet-snapshot.sh",
      "--contribution-input"
    ],
    "label": "transport-creation-failure",
    "exit": 1,
    "stdout_bytes": 0,
    "stderr": "mktemp: failed to create directory via template \u2018/home/art/.no-mistakes/worktrees/9f75ec418609/01M4CK3M44RTV3MR0ZCWQ01TRK/.contribution-live-jc987gsl/does-not-exist/fm-fleet-snapshot.contrib.XXXXXX\u2019: No such file or directory\nfm-fleet-snapshot: contribution temp dir failed\n"
  },
  {
    "scenario": "unavailable temporary directory reports failure without a misleading empty result",
    "result": "pass"
  }
]
Evidence: Bearings reports 400 owned contributions

Source: Bearings reports 400 owned contributions

{
  "schema": "fm-bearings.v1",
  "home": "01M4CK3M44RTV3MR0ZCWQ01TRK/.contribution-live-jc987gsl",
  "generated": "2026-10-08T01:50:02Z",
  "prs": "not_requested (run: /bearings include PRs)",
  "contributions": {
    "scope": "owned contributions per home",
    "known": 400,
    "checked": 0,
    "counts": {
      "captain": 0,
      "fleet": 400,
      "maintainer": 0,
      "nobody": 0
    },
    "complete": false,
    "proven_clear": false,
    "unmeasured_homes": 0,
    "unreadable_records": 0,
    "unmeasured": 0,
    "stale_verdicts": 0,
    "missing_verdicts": 0,
    "captain_omitted": 0,
    "captain": []
  },
  "in_flight": [
    {
      "id": "sample",
      "kind": "ship",
      "state": "unknown",
      "repo": "",
      "name": "sample",
      "doing": "worktree gone (torn down?)"
    }
  ],
  "secondmates": [],
  "secondmate_reconcile": [],
  "decisions_open": [],
  "landed": [],
  "gates": [
    {
      "id": "task-0000",
      "title": "Contribution café 0",
      "blocked_by": "-",
      "reason": "-",
      "owner": "(main)",
      "filed": null
    },
    {
      "id": "task-0001",
      "title": "Contribution café 1",
      "blocked_by": "-",
      "reason": "-",
      "owner": "(main)",
      "filed": null
    },
    {
      "id": "task-0002",
      "title": "Contribution café 2",
      "blocked_by": "-",
      "reason": "-",
      "owner": "(main)",
      "filed": null
    },
    {
      "id": "task-0003",
      "title": "Contribution café 3",
      "blocked_by": "-",
      "reason": "-",
      "owner": "(main)",
      "filed": null
    },
    {
      "id": "task-0004",
      "title": "Contribution café 4",
      "blocked_by": "-",
      "reason": "-",
      "owner": "(main)",
      "filed": null
    },
    {
      "id": "task-0005",
      "title": "Contribution café 5",
      "blocked_by": "-",
      "reason": "-",
      "owner": "(main)",
      "filed": null
    },
    {
      "id": "task-0006",
      "title": "Contribution café 6",
      "blocked_by": "-",
      "reason": "-",
      "owner": "(main)",
      "filed": null
    },
    {
      "id": "task-0007",
      "title": "Contribution café 7",
      "blocked_by": "-",
      "reason": "-",
      "owner": "(main)",
      "filed": null
    },
    {
      "id": "task-0008",
      "title": "Contribution café 8",
      "blocked_by": "-",
      "reason": "-",
      "owner": "(main)",
      "filed": null
    },
    {
      "id": "task-0009",
      "title": "Contribution café 9",
      "blocked_by": "-",
      "reason": "-",
      "owner": "(main)",
      "filed": null
    },
    {
      "id": "task-0010",
      "title": "Contribution café 10",
      "blocked_by": "-",
      "reason": "-",
      "owner": "(main)",
      "filed": null
    },
    {
      "id": "task-0011",
      "title": "Contribution café 11",
      "blocked_by": "-",
      "reason": "-",
      "owner": "(main)",
      "filed": null
    },
    {
      "id": "task-0012",
      "title": "Contribution café 12",
      "blocked_by": "-",
      "reason": "-",
      "owner": "(main)",
      "filed": null
    },
    {
      "id": "task-0013",
      "title": "Contribution café 13",
      "blocked_by": "-",
      "reason": "-",
      "owner": "(main)",
      "filed": null
    },
    {
      "id": "task-0014",
      "title": "Contribution café 14",
      "blocked_by": "-",
      "reason": "-",
      "owner": "(main)",
      "filed": null
    },
    {
      "id": "task-0015",
      "title": "Contribution café 15",
      "blocked_by": "-",
      "reason": "-",
      "owner": "(main)",
      "filed": null
    },
    {
      "id": "task-0016",
      "title": "Contribution café 16",
      "blocked_by": "-",
      "reason": "-",
      "owner": "(main)",
      "filed": null
    },
    {
      "id": "task-0017",
      "title": "Contribution café 17",
      "blocked_by": "-",
      "reason": "-",
      "owner": "(main)",
      "filed": null
    },
    {
      "id": "task-0018",
      "title": "Contribution café 18",
      "blocked_by": "-",
      "reason": "-",
      "owner": "(main)",
      "filed": null
    },
    {
      "id": "task-0019",
      "title": "Contribution café 19",
      "blocked_by": "-",
      "reason": "-",
      "owner": "(main)",
      "filed": null
    }
  ],
  "reports": [],
  "recorded_prs": [
    {
      "id": "sample",
      "url": "https://github.com/example/repo/pull/1"
    }
  ],
  "omitted": [
    {
      "surface": "backlog item bodies",
      "reveal": "--fields bodies"
    },
    {
      "surface": "task paths",
      "reveal": "--fields paths"
    },
    {
      "surface": "watch/steer actions",
      "reveal": "--fields actions"
    },
    {
      "surface": "healthy endpoint detail",
      "reveal": "--fields endpoints"
    },
    {
      "surface": "full scout-report inventory",
      "reveal": "--all-reports"
    },
    {
      "surface": "gates showing 20 of 400",
      "reveal": "--all-queued"
    },
    {
      "surface": "live PR discovery + checks",
      "reveal": "--include-prs"
    }
  ]
}
Evidence: Reproducible isolated CLI driver

Source: Reproducible isolated CLI driver

import os, pathlib, subprocess, tempfile, shutil, json, resource, signal

root = pathlib.Path.cwd()
evidence = pathlib.Path('~/.no-mistakes/evidence/01M4CK3M44RTV3MR0ZCWQ01TRK')
lab = pathlib.Path(tempfile.mkdtemp(prefix='.contribution-live-', dir=root))
baseline = root / 'bin/.contribution-baseline.sh'
results = []
env = {k:v for k,v in os.environ.items() if not k.startswith('FM_') and k not in ('TASKS_AXI_FILE','TASKS_AXI_BACKEND')}
env.update(FM_HOME=str(lab), TMPDIR=str(lab/'tmp'), FM_SNAPSHOT_NOW='2026-10-07T12:00:00Z', FM_CONTRIBUTIONS_NOW='2026-10-07T12:00:00Z')
for name in ('data','state','config','projects','tmp'):
    (lab/name).mkdir()

def run(label, argv, preexec_fn=None, custom_env=None):
    p = subprocess.run(argv, cwd=root, env=custom_env or env, capture_output=True, text=True, timeout=60, preexec_fn=preexec_fn)
    (evidence/(label+'.stdout')).write_text(p.stdout)
    (evidence/(label+'.stderr')).write_text(p.stderr)
    results.append({'command': argv, 'label':label, 'exit':p.returncode, 'stdout_bytes':len(p.stdout.encode()), 'stderr':p.stderr[:1500]})
    return p

def clean_tmp():
    assert not list((lab/'tmp').iterdir()), list((lab/'tmp').iterdir())

try:
    baseline.write_bytes(subprocess.check_output(['git','show','2ce57d0067d4e860e8969fa8fa8289771b855ec5:bin/fm-fleet-snapshot.sh']))
    backlog = lab/'data/backlog.md'
    backlog.write_text('# Backlog\n\n## Queued\n- [ ] sample - Unicode café "quoted" \\ text https://github.com/example/repo/pull/1 (repo: sample) (kind: ship)\n')
    (lab/'state/sample.meta').write_text('kind=ship\npr=https://github.com/example/repo/pull/1\npr_head=abc123\n')
    a = run('small-before',['bash',str(baseline),'--contribution-input'])
    b = run('small-after',['bash','bin/fm-fleet-snapshot.sh','--contribution-input'])
    assert a.returncode == b.returncode == 0
    assert json.loads(a.stdout) == json.loads(b.stdout)
    assert len(json.loads(b.stdout)['tasks']) == 1
    clean_tmp()
    results.append({'scenario':'small ownership pair preserves exact JSON semantics and cleans transport', 'result':'pass'})

    backlog.write_text('# Backlog\n\n## Queued\n' + ''.join(f'- [ ] task-{i:04d} - Contribution café {i} https://github.com/example/repo/pull/{i+1} (repo: sample) (kind: ship)\n' for i in range(400)))
    a = run('large-backlog-before',['bash',str(baseline),'--contribution-input'])
    assert a.stdout == '' and 'Argument list too long' in a.stderr
    b = run('large-backlog-after',['bash','bin/fm-fleet-snapshot.sh','--contribution-input'])
    assert b.returncode == 0, b.stderr
    data = json.loads(b.stdout)
    assert len(data['backlog']['records']) == 400
    assert [x['id'] for x in data['backlog']['records']] == [f'task-{i:04d}' for i in range(400)]
    assert len(json.dumps(data['backlog']).encode()) > 131072
    consumer = run('large-backlog-consumer',['bash','bin/fm-contributions.sh','snapshot',str(evidence/'large-backlog-after.stdout')])
    assert consumer.returncode == 0, consumer.stderr
    c = json.loads(consumer.stdout)
    assert c['known'] >= 400, c
    clean_tmp()
    results.append({'scenario':'400-row backlog exceeds 128 KiB and reaches real contribution consumer', 'result':'pass', 'backlog_json_bytes':len(json.dumps(data['backlog']).encode()), 'known':c['known']})

    bearings = run('large-backlog-bearings',['bash','bin/fm-bearings-snapshot.sh','--json'])
    assert bearings.returncode == 0, bearings.stderr
    assert json.loads(bearings.stdout)['contributions']['known'] >= 400
    clean_tmp()
    results.append({'scenario':'Bearings shows contributions for a large backlog', 'result':'pass'})

    backlog.write_text('# Backlog\n\n## Queued\n')
    for i in range(3):
        (lab/f'state/large-{i}.meta').write_text('kind=ship\npr=https://github.com/example/repo/pull/2\npr_head='+str(i)*50000+'\n')
    a = run('large-tasks-before',['bash',str(baseline),'--contribution-input'])
    assert a.stdout == '' and 'Argument list too long' in a.stderr
    b = run('large-tasks-after',['bash','bin/fm-fleet-snapshot.sh','--contribution-input'])
    assert b.returncode == 0, b.stderr
    data = json.loads(b.stdout)
    assert len(json.dumps(data['tasks']).encode()) > 131072
    for i in range(3):
        assert next(t for t in data['tasks'] if t['id']==f'large-{i}')['pr']['head'] == str(i)*50000
    clean_tmp()
    results.append({'scenario':'task document exceeds 128 KiB and preserves every metadata value', 'result':'pass', 'tasks_json_bytes':len(json.dumps(data['tasks']).encode())})

    for meta in (lab/'state').glob('*.meta'):
        meta.unlink()
    backlog.unlink()
    p = run('missing-backlog',['bash','bin/fm-fleet-snapshot.sh','--contribution-input'])
    assert p.returncode == 0
    d = json.loads(p.stdout)
    assert d['backlog']['present'] is False and d['backlog']['records'] == [] and d['tasks'] == []
    clean_tmp()
    results.append({'scenario':'absent backlog and empty fleet remain valid empty ownership JSON', 'result':'pass'})

    backlog.write_text('# Backlog\n\n## Queued\n' + ''.join(f'- [ ] row-{i} - Entry {i}\n' for i in range(30)))
    def file_limit():
        signal.signal(signal.SIGXFSZ, signal.SIG_IGN)
        resource.setrlimit(resource.RLIMIT_FSIZE, (1024,1024))
    p = run('transport-write-failure',['bash','bin/fm-fleet-snapshot.sh','--contribution-input'],preexec_fn=file_limit)
    assert p.returncode != 0 and 'contribution backlog write failed' in p.stderr
    assert p.stdout == ''
    clean_tmp()
    results.append({'scenario':'failed transport write reports failure, emits no JSON, and removes temporary files', 'result':'pass'})

    bad_env = dict(env, TMPDIR=str(lab/'does-not-exist'))
    p = run('transport-creation-failure',['bash','bin/fm-fleet-snapshot.sh','--contribution-input'],custom_env=bad_env)
    assert p.returncode != 0 and 'contribution temp dir failed' in p.stderr and p.stdout == ''
    results.append({'scenario':'unavailable temporary directory reports failure without a misleading empty result', 'result':'pass'})
finally:
    baseline.unlink(missing_ok=True)
    shutil.rmtree(lab)
    (evidence/'live-results.json').write_text(json.dumps(results,indent=2)+'\n')

print(json.dumps(results,indent=2))

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 ordinary contribution ownership with identical JSON semantics and temporary-file cleanup ✅ pass live live-results.json: small-before and small-after
Read a 400-row backlog exceeding 128 KiB and pass all owned contributions to the real consumer ✅ pass live live-results.json: large-backlog-before, large-backlog-after, large-backlog-consumer
Run Bearings on the large backlog and observe 400 owned contributions ✅ pass live large-backlog-bearings.stdout
Read task metadata exceeding 128 KiB without losing values or exceeding the argument limit ✅ pass live live-results.json: large-tasks-before and large-tasks-after
Read an empty fleet with an absent backlog and receive valid empty ownership JSON ✅ pass live live-results.json: missing-backlog
Encounter a transport write limit and receive an explicit failure, no JSON, and complete temporary-file cleanup ✅ pass live live-results.json: transport-write-failure
Use an unavailable temporary directory and receive an explicit failure without misleading output ✅ pass live live-results.json: transport-creation-failure
  • python3 ~/.no-mistakes/evidence/01M4CK3M44RTV3MR0ZCWQ01TRK/drive-contribution.py
  • Executed baseline and target fm-fleet-snapshot.sh --contribution-input against isolated ordinary, oversized, and empty fleet data.
  • Executed bin/fm-contributions.sh snapshot <generated-input> and bin/fm-bearings-snapshot.sh --json.
  • Induced transport failures using RLIMIT_FSIZE and a nonexistent TMPDIR; verified errors, empty stdout, and cleanup.
  • git status --short confirmed a clean worktree after fixture teardown.
✅ **Document** - passed

✅ No issues found.

✅ **Lint** - passed

✅ No issues found.

✅ **Push** - passed

✅ No issues found.

The contribution-input branch passed the whole canonical backlog document to
jq as a single --argjson argv argument. A large fleet's backlog JSON exceeds
Linux MAX_ARG_STRLEN (128 KiB), so jq fails with E2BIG (Argument list too
long) and the contribution-input snapshot emits empty output, breaking the
bearings contribution path.

Write both the backlog and task documents to a temp directory and hand them
to jq with --slurpfile, matching how the full snapshot path already stages
the same pair. Output is unchanged for any backlog that fits in argv.
@kunchenguid

Copy link
Copy Markdown
Owner

Speaking as Kun's firstmate:

Status: waiting on CI (one shard to re-run) · contract-class: restore · head b0fe7f5a

Thanks @kesslerio. I read the diff against main 2ce57d00. fm-contributions.sh poll already depends on fm-fleet-snapshot.sh --contribution-input, and that path passes the whole backlog through --argjson. On a large backlog it fails with "Argument list too long". Staging both documents through --slurpfile matches how the main snapshot path already does it a few lines below, and the output shape is unchanged. That puts an existing default path back to what it already promised, so it's restore. One non-blocking note: the new trap … EXIT replaces the script's snapshot_cleanup trap for this mode. Nothing that trap cleans up is allocated before this branch today, so it's harmless as written.

CI: everything is green except Behavior portable serial 2, which was cancelled at the 30-minute job limit. Inside that shard, tests/fm-supervision-host.test.sh took about 28 minutes, against about 18 on main. Several PRs hit the same timeout this evening, and this PR doesn't touch supervision-host. I'll re-run that shard as soon as the run finishes. You don't need to do anything.

Next: if the re-run comes back green and the head is still mergeable, this can merge without a captain decision.

VISION.md per-rule:

  • One captain, one interface: aligns. Contributions stop silently failing on large fleets.
  • Authority explicit: aligns. No new capability.
  • Scripts/agents split: aligns.
  • Restart is a non-event: aligns.
  • Delegation with a spine: aligns. Staging failures are reported, not swallowed.
  • Outlives any vendor: aligns.
  • Scope: aligns.

@kesslerio

kesslerio commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor Author

Flagging this because it looks finished. The head is unchanged at b0fe7f5a, the merge state is CLEAN, and every check is green now - including Behavior portable serial 2, which came back success at 2026-10-08T03:13:39Z after your rerun. I have not pushed anything, and your note said a green and mergeable head here needs no captain decision, so I am just making the state visible. Happy to change anything you want changed.

@kunchenguid
kunchenguid merged commit 1a86871 into kunchenguid:main Oct 10, 2026
36 of 37 checks passed
@kunchenguid

Copy link
Copy Markdown
Owner

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

kunchenguid pushed a commit that referenced this pull request Oct 11, 2026
…ailures (#7036)

The large-backlog regression already proved the json and secondmate
home-summary modes stay within exec limits. It now also runs the
contribution-input mode on the same 1200-record backlog, which is the
path #6830 moved off argv. With that fix reverted the test fails with
the field error jq Argument list too long at the contribution-input call.
Authentis added a commit to Authentis/firstmate-upstream that referenced this pull request Oct 11, 2026
Resolves fm-spawn.sh (K3 env -u marker kept on upstream's __CLAUDESETTINGS__ launch line; Pi secondmate first-call hook moved to its own state/<id>.pi-first-call.ts so upstream's busy extension owns pi-ext.ts), fm-teardown.sh (cleanup lists carry both sides) and fm-fleet-snapshot.sh (fork's JSON_TRANSPORT_DIR slurpfile form kept: equivalent to kunchenguid#6830/kunchenguid#7036, avoids a second EXIT trap).
kirkins added a commit to kirkins/firstmate that referenced this pull request Oct 11, 2026
…ons, and fleet fixes (#9)

* fix: refuse a confirming Enter on the Claude background-task exit picker (#6666)

* fix: refuse a confirming Enter on the Claude exit picker

The background-task picker still classifies as pending, so a retried Enter confirms "Exit and stop tasks".
Stop after the Enter that opened it, and raise the existing stale wake with the dialog name.

A non-paused secondmate still skips that wake, so a secondmate parked on the picker still looks idle.
Model-downgrade confirmation, MCP approval, and any other Claude exit confirmation are not covered, because there is no recorded screen for them.

* no-mistakes(review): fix: anchor exit picker match and wake second mates

* fix: refuse a typed submit while the Claude exit picker is open

A pane that already shows the picker must not receive the message or a confirming Enter.
The match requires the recorded heading and footer lines, and it is skipped when no dialog name is being recorded.

* no-mistakes(review): restore watcher to main behaviour, drop dialog wake

* no-mistakes(test): test: align Herdr picker fixtures with the preflight read

* no-mistakes(document): document exit refusal on a recognised dialog

* fix: remove the dialog file when exit runs in a subshell

do_exit is invoked from a command substitution, so the parent cleanup never saw the path it is supposed to delete.

* no-mistakes(review): fix: set the dialog file path after the control lock

* no-mistakes(document): document why the dialog file path follows the lock

* no-mistakes(ci): The exit cleanup in bin/fm-control.sh now deletes the dialog file first and releases the control lock second. The changes are in the worktree and are not committed. Invariant: only the process that holds the control lock for a task may write or delete that task's dialog file ($STATE/<id>.composer-dialog, the file that carries the picker name from the composer read to the Enter checks). The old cleanup released the lock and then deleted the file, so the delete ran outside the lock. Places where this invariant must hold: control_cleanup is the only place that deletes the file, and the single assignment after CONTROL_LOCK_HELD=1 is the only place that names it. do_exit only truncates the file, and it runs while the parent holds the lock. A process that loses the lock never sets the path, so it deletes nothing (earlier fix, unchanged). No sibling site needed a change. Fix: in control_cleanup, the rm of the dialog file moved above the fm_lock_release call, with a two-line comment that gives the reason. No dialog recognition or supervision code changed. Test: added test_exit_removes_the_dialog_file_before_releasing_the_lock in tests/fm-control-relaunch.test.sh. It runs one `fm-control exit` with a recording rm on PATH. The lock release removes paths at or under the control lock with rm, so the recording rm writes whether the dialog file exists at that moment. The test asserts the last record is "absent". It starts no second command. Verification, all run locally: - Before the fix, the new test failed with "the dialog file must be gone when the control lock is released, got: present". - After the fix, tests/fm-control-relaunch.test.sh exits 0 with 75 ok lines and no "not ok" line, including the new test and the existing test that the file is gone after exit and after relaunch. - tests/fm-control.test.sh exits 0 with 44 ok lines. - shellcheck -x on both changed files exits 0 with no output. One thing I noticed and did not change: tests/fm-control-relaunch.test.sh prints 615 "rm: cannot remove ... Permission denied" lines during its temp-directory teardown. The count is the same with my change reverted, so this change does not cause it, and the suite still exits 0. I could not read the Greptile check log (the check run was not found), so I worked from the finding text and the user instructions

* fix: restore timeout watchdog compatibility with macOS Bash 3.2 (#6028)

* fix: support stock macOS Bash in timeout watchdog

* no-mistakes(ci): Fixed ci-1 in tests/fm-timeout-lib.test.sh: both startup-owner failure paths now kill the bounded command group before killing the watchdog. Fault injection reproduced both leaks before the fix and confirmed cleanup afterward. Bash 3.2 suite, syntax check, ShellCheck, and diff checks passed; GNU timeout coverage skipped because the binary is unavailable. Production code unchanged

* fix(project-management): use subshell form for Initialize command (#6699)

Wrap the cd command in a subshell to comply with the cd-guard policy
that blocks persistent top-level directory changes in the primary
firstmate checkout. The subshell form (cd projects/<name> && ...) is
accepted by the policy as documented in issue #6502.

Fixes #6502

* feat(bin): add armable daily startup growth check (#6725)

* Add daily startup growth check

* no-mistakes(review): watch printed startup memory, retain growth baselines, drop knobs

* no-mistakes(review): delegate budget verdict, report before publish, pin shim home

* no-mistakes(review): baseline first sightings silently, drop mtime, spare secondmates

* no-mistakes(review): cap the wake line, validate budget verdict fields

* no-mistakes(review): guard record schema, check appends, tighten assertions

* no-mistakes(review): drop arbitrary tracked library, make re-arm idempotent

* no-mistakes(review): correct tracked-set wording, restore shim guards, register artifacts

* no-mistakes(review): exit on signal instead of publishing partial record

* no-mistakes(document): correct startup-growth record removal cost in state registry

* no-mistakes(test): sweep orphaned empty startup-growth temp records on due evaluation

* no-mistakes(document): note watcher need for armed startup growth check

* no-mistakes(ci): Diagnosed "Behavior portable serial 5": the shard failed on tests/fm-contributions.test.sh in test_arm_plumbs_a_configured_budget_into_the_check_shim (inherited mode) with "generated check did not attempt a read" and a missing forge/calls file. Root cause: bin/fm-contributions.sh:379-382 computes DEADLINE=$(date +%s)+BUDGET and then gates each read on DEADLINE-$(date +%s) >= OBSERVATION_RESERVE (= min(BUDGET,15)). At the one-second budget this test uses, that gate demands zero elapsed whole seconds, so a wall-clock second boundary crossing between the two date calls makes the poll loop break before any forge read. The test calls wrap_forge (which installs a fake date reading $FORGE/clock only when that file exists) but never seeded forge/clock, so it ran against the real clock. The repo already documents this exact hazard at tests/fm-contributions.test.sh:675-677 and freezes the clock in every other budget-constrained test: test_budget_exhaustion_keeps_prior_record (both modes), test_genuine_failure_near_deadline_is_unavailable, test_reservation_defers_later_url_when_fifteen_seconds_do_not_remain, test_slow_read_deadline_kill_is_budget_refusal, test_budget_is_cut_down_to_the_watcher_check_bound. test_arm_plumbs was the only omission; its single loop body covers both the configured and inherited modes. The remaining wrap_forge users run the default 20-second budget (5 seconds of slack above the reserve) and are not reachable by this race. Fix (smallest, matching the sibling idiom): added the clock freeze `/bin/date +%s > "$home/forge/clock"` plus a two-line comment inside that test's loop, before the poll. Three added lines in tests/fm-contributions.test.sh; no production code and no other file touched. Verification: reproduced the exact CI failure message by running a scratch copy whose fake date advances one second per read (worst case of the unfrozen clock) - missing forge/calls, "not ok - generated check did not attempt a read". With the fix, the single test passes 10/10 standalone and the full tests/fm-contributions.test.sh passes all 46 assertions with exit 0. tests/fm-startup-growth-check.test.sh still exits 0. bash -n and shellcheck -S warning are clean on the edited file; scratch repro files were removed, leaving only the intended three-line change. Note for the author: this flake is not caused by this branch - tests/fm-contributions.test.sh is untouched by the PR and the race is pre-existing, surfacing only on a loaded runner (the shard's neighbouring assertions show 80+ second gaps). It was fixed because it is genuine nondeterminism with an established in-repo remedy and the check cannot otherwise go green. No work was done on the unselected greptile findings (ci-2..ci-5) or the cancelled "Behavior portable serial 2" check (ci-6)

* no-mistakes(ci): Diagnosed "Behavior portable serial 6": the omitted log section (fetched with gh api) shows the shard failed on tests/fm-calm-pi-extension.test.sh in test_hidden_block_geometry_e2e with "Pi Calm hidden-block geometry E2E did not complete the /reload viewport transition" (exit=1, duration_ms=23437; the family line pure-contract-unit count=3 duration_ms=51193 failed=1 matches devin-harness 3203 + calm-pi 23437 + task-delivery 24553). Root cause: tests/fm-calm-pi-extension.test.sh:2831 wait_for_geometry_transition detected the /reload by SAMPLING a single intermediate frame - it polled tmux capture-pane for Pi's transient "Reloading keybindings, extensions, skills, prompts, themes, and context files..." box and only accepted the rebuilt transcript afterwards (elif gated on saw_transient). Pi shows that box only while the reload runs and replaces it via dismissReloadBox when done, so on a loaded runner the box can live entirely between two polls; saw_transient then stays 0 forever and the 600-attempt wait times out although the reload fully succeeded. Reproduced locally under CPU oversubscription with CI's Pi 1.0.4: 1 failure in 8 runs, diagnostics proving the mechanism ("DIAG: transition timeout saw_transient=0 attempt=600") while the captured viewport already showed the completed reload status row and the intact collapsed transcript. Not a Pi-version regression: 1.0.4's handleReloadCommand and both banner strings are identical to the installed 0.85.1, and shard 6 of the previous pipeline run (job 112490351105) passed this same script on Pi 1.0.4. Invariant violated: a TUI E2E assertion must key off a durable state the UI retains, never off one intermediate frame polling may miss. Sibling enumeration: the helper was defined once and called once; grep for transient/saw_/two-stage waits across tests/, bin/ and .pi/ found no other one-shot-frame wait - every other wait in the file keys off durable text presence/absence or off continuously repeating animation frames (the working-ship motion checks) where sampling eventually connects; no doc or other test referenced the helper. Fix (smallest, one helper): renamed it wait_for_geometry_reload and made it wait for the durable status row Pi appends once the reload completed and the chat was rebuilt ("Reloaded keybindings, extensions, skills, prompts, themes, and context files", a persistent chat child via showStatus, present in both 0.85.1 and 1.0.4) together with CALM_GEOMETRY_FINAL. That marker is absent before the reload and never appears if the reload throws, so the check is strictly stronger than before (a failed reload now fails the test instead of passing on transient-then-final). One file changed: tests/fm-calm-pi-extension.test.sh, 2 hunks, no production code. Verification: deterministic before/after - with polls spaced 0.4s apart (the loaded-runner worst case) the pre-fix helper fails with exactly the CI message and the post-fix helper passes; 12/12 consecutive passes of the isolated test under load with Pi 1.0.4; full file 15/15 ok exit 0 under LANG=C.utf8 (matching the runner locale); bash -n, shellcheck -S warning and bin/fm-lint.sh clean; scratch repro files and the temp Pi 1.0.4 install removed, git status shows only the one intended modification. Notes: (1) the flake is not caused by this branch - that test file is untouched by the PR and the race is pre-existing; fixed because it is genuine nondeterminism and the check cannot otherwise go green. (2) Under far harsher load than CI applies a separate unrelated flake appeared in the same test: Pi's "Warning: tmux extended-keys is off..." row occasionally lands between the collapsed [skill] ahoy row and the final response, making assert_geometry_gap see 5 rows instead of 2. Different cause, never seen in CI, and its plausible remedies would change key delivery for the other TUI tests in the file, so it was left alone rather than growing this fix

---------

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

* fix(bin): reopen the remote-reply continuity decision on a later break (#6708)

* fix: reopen a remote-reply continuity break after repair

A later break for the same route and reason was swallowed after the
operator resolved the first one, because the status line matched for
the life of the log. The continuity ingest now appends again when the
cursor has moved or retirement has reset that episode, and an unchanged
re-read still appends nothing.

status_event_recorded is unchanged. Its other callers are the
pending-reply escalation, which already decides its own episode, the
parent-channel note append, and the remote document transfer note.

* no-mistakes(review): seed continuity episode for already recorded break line

* no-mistakes(document): document when a remote-reply continuity break reopens

* no-mistakes(ci): The adapter now stores the continuity episode record before it appends the `blocked` line, so a failed store appends nothing. The changes are uncommitted in the worktree, in `bin/fm-procevent-remote-reply.sh` and `tests/fm-remote-reply.test.sh`. **Invariant:** a continuity `blocked` line is on the parent status log only when the episode record for that break is already stored. Only the `continuity-broken` branch of `cmd_ingest` appends that line, so the fix is at that one place. **What changed in `cmd_ingest`:** - It decides first whether the break needs a line, then stores the episode record, then appends. - If storing the record fails, it stops with "cannot record continuity episode" and appends nothing. - If the line is already on the log and no episode record exists, it stores the record and does not append. **One addition you did not ask for:** if the append fails after the record is stored, the adapter puts the earlier record back (or deletes the new one when none existed). Without that, the retry would read as the unchanged repeat and append nothing, which is the issue 6701 failure again. **Deviation from your test instruction:** the test does not use `chmod` on the cursor directory. `write_continuity_episode` runs `chmod 700` on that directory before every write, so a read-only directory is made writable again. The test instead makes `mktemp` fail for the episode's temporary file in that directory, the same way the existing receipt-failure test does. **Tests added to `tests/fm-remote-reply.test.sh`:** - Store failure: the second break exits 1, appends no `blocked` line and opens no decision. One retry after storage recovers exits 3 and appends a single line. - Append failure: with the status log read-only, the third break exits 1 and appends nothing. One retry after the log is writable exits 3 and appends a single line. **Verification:** `bash tests/fm-remote-reply.test.sh` ends with "ALL TESTS PASSED" with the fix. Against the script at commit b750c828 the same test file fails at "a continuity break appended its line before its episode was stored". `shellcheck -S warning` reports only an unused loop variable at line 667 of the test file, which this change does not touch. I ran no other test files. The Greptile Review check log could not be retrieved, so I worked from the finding text alone

* fix: record a continuity break's reader position on its status line

A later break at another cursor is then a different line, so the existing
duplicate check appends it and reopens the decision. An unchanged re-read
builds the same line and appends nothing.

* fix: reopen a continuity break after an identical restore

A retirement that puts the same bytes back used to rebuild the recorded line, so the later break stayed closed. The retirement count on that line makes the later break distinct.

* no-mistakes(review): remove continuity match for full-prefix line without retirement count

* no-mistakes(document): clarify what a continuity break status line records

* fix: remove the reply cursor before recording retirement

A stop between those steps must leave the count unchanged, so an unchanged continuity break still builds the same line.

* fix(control): drop busy_gen from the task record when an incarnation is retired (#6733)

* fix(control): drop busy_gen when an incarnation is retired

A deliberate exit removed the busy sidecar and left busy_gen in the task record, so the two records disagreed about whether that incarnation was still observable.

* no-mistakes(review): drop GNU-only chmod and unreached sidecar-absent branch

* no-mistakes(review): correct lock comment to name the deadlock

* no-mistakes(ci): The test `test_exit_drops_meta_busy_gen_with_the_sidecar` in tests/fm-control.test.sh now compares the whole task record (the `state/<id>.meta` file), so the Greptile finding is fixed. Invariant: after `exit` retires an incarnation, the task record must equal the record from before `exit` with only the `busy_gen` line removed. This test is the only place in the change that asserts the record survives the rewrite, so it is the only site to fix. The other `busy_gen` tests assert that the line stays, and they do not go through the rewrite. What changed: before `exit`, the test writes the record without its `busy_gen` line to `expected.meta`. After `exit`, the test runs `diff` between that expected copy and the real record, and fails with the diff output if they differ. This one comparison replaces the two earlier checks (no `busy_gen` line left, and the `window` line present), because it covers both. I did not change bin/fm-control.sh or any other file. How I know it works: - I ran `bash tests/fm-control.test.sh`: exit code 0, 45 lines starting with `ok`, no other lines. - I temporarily changed the rewrite in bin/fm-control.sh to also drop the `harness` line. The test then failed with `not ok - exit should drop only busy_gen from the task record:` and the diff `< harness=codex`. The earlier `window`-only check would have passed that rewrite. I restored bin/fm-control.sh afterwards; `git status` shows only tests/fm-control.test.sh modified. - `bash -n` and `shellcheck` on the test file report no new warnings from the edit. The change is not committed; the working tree holds it

* test: cover PID collisions in harness ancestry detection (#6484)

* test(secondmate-harness): scope fake ps -codex label for pid 5252 to the liveness probe

Closes #6456

* no-mistakes(ci): Updated the collision test to log and assert that PID 5252 was queried before selecting 4242. Full fm-secondmate harness suite passes

---------

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

* fix: share Pi Calm's working-ship widget slot (#1854)

* fix(calm): share the standalone Pi Calm working-ship widget slot

Firstmate Calm and the user-global standalone Pi Calm both install an
animated working-ship widget during agent runs. Each claimed its own Pi
widget key, so a session loading both (the main Firstmate home) rendered
two boats. Pi replaces widgets under one key, so claiming the shared
"calm-working-ship" slot keeps dual-install sessions to a single boat
while a Firstmate-only session is unchanged.

Pins the shared slot contract in the working-ship module test so the key
cannot silently diverge again.

* test(calm): pin the shared working-ship widget key in CI, document dual-install

The key-parity assertion inside the Pi fixture only runs where the
@earendil-works/pi-coding-agent package is installed, so CI never
exercised it. Add a source-level twin that needs nothing but the
tracked file, and note in docs/calm.md that the boat shares the
standalone Pi Calm working-row widget slot.

* no-mistakes(review): Add executable dual-install widget replacement coverage

* no-mistakes(review): Guard shared widget cleanup with disposal ownership

* no-mistakes(document): Document shared Calm working-ship slot behavior

* test(calm): read the standalone Calm slot from its own module

The dual-install check registered both boats itself under the shared
slot, so it could only prove that Pi replaces a widget under one key: it
would still pass if the standalone Pi Calm extension installed its boat
under a different key, which is the two-boat regression the check exists
to prevent.

Read the standalone extension's own working-ship module when it is
installed - FM_STANDALONE_CALM_SHIP, else ~/.pi/agent/extensions/calm -
and drive the check with the key that module exports, so a rename on
either side registers two widgets and fails naming both keys. A pinned
shared-slot contract still covers a machine without the extension, and
the run reports which side it used instead of passing silently over an
absent extension.

Verified: the touched Pi Calm suite passes and reads the installed
standalone extension; with a copy of it whose key is renamed to
calm-working-ship-v2 the suite fails naming the drift.

* no-mistakes(review): Gate stock-row restoration by shared-widget ownership

* no-mistakes(review): Removed redundant widget-key source assertions

* no-mistakes(document): Document shared Calm working-ship widget ownership

* feat(bin): add opt-in --herdr-resume-lock-wait to fm-spawn (#6649)

* fix(herdr): make exact-resume presentation-lock wait instead of a bounded timeout

The exact-resume path in bin/fm-spawn.sh used the same 50-attempt-then-
give-up lock acquire as the new-task-create path, but the two paths are
not equivalent on contention: a create has no prior state to strand and
can safely fall back to a flat layout, while a resume is recovering a
specific existing identity that a concurrent recovery may legitimately
be holding the lock for. Giving up there does not degrade gracefully,
it hard-fails the resume outright. The suite's own concurrent
cross-home recoveries test already asserts both concurrent recoveries
succeed with a genuine reclaim, and the file's header comment already
(inaccurately) claimed lock contention falls back to the ordinary flat
layout for both paths alike, so the intended contract was always that
recoveries serialize and both succeed, not that either one refuses
under a short bound.

Give spawn_herdr_presentation_order_lock_acquire a wait mode that uses
this file's own established fm_lock_acquire_wait idiom (already used
for its other fleet-shared locks) instead of the bounded loop, and use
it only at the exact-resume call site. The new-task-create call site
is unchanged and keeps its bounded-then-flat-fallback behavior, which
is already covered by its own passing test. Dead-owner PID-liveness
reclaim inside fm_lock_try_acquire still bounds the wait against a
holder that crashed mid-hold.

Adds a deterministic regression test that holds the shared session
lock from an unrelated process for well past the old bound, then
asserts the resume succeeds with a genuine reclaim and took close to
the full hold duration, so a fix that merely widens the bound rather
than genuinely waiting is still caught. The existing concurrent
cross-home recovery test exercises this under real timing but does not
reliably outlast a fixed bound on its own.

Corrects the header comment's claim that create and resume share one
bounded-then-flat-fallback behavior on lock contention; they no longer
do.

* no-mistakes(document): Document Herdr recovery waiting for presentation lock

* no-mistakes(document): Update stale hard-refusal claim in verification log

* no-mistakes(ci): Fixed the Greptile finding on tests/fm-backend-herdr-presentation-e2e.test.sh:1389 by bounding the resume lock-wait regression's spawn_task call. Added an optional 4th `deadline_seconds` arg to the `spawn_task` helper (defaults to empty, so all ~20 other existing call sites are unaffected and unwrapped by `timeout`). The lock-wait test now passes `LOCK_WAIT_HOLD_SECONDS + 60` (90s) as the deadline, and a dedicated check for exit code 124 emits a clear "hung for over Xs instead of waiting out a Ys lock hold" diagnostic before falling through to the existing pass/fail assertions, which are unchanged. No product code was touched. Verified with `bash -n`, `shellcheck -x` (no warnings), a standalone reproduction of the timeout/no-timeout/success paths, the project's `bin/fm-lint.sh --fast` on the file (clean), and the full `tests/fm-lint.test.sh` suite (all 46 assertions pass)

* no-mistakes(ci): Replaced the direct `timeout "$deadline_seconds"` call in `spawn_task()` (tests/fm-backend-herdr-presentation-e2e.test.sh) with the repo's portable bounded-execution helper: sourced `bin/fm-timeout-lib.sh` at the top of the file and changed `deadline_cmd=(timeout "$deadline_seconds")` to `deadline_cmd=(fm_run_timed "$deadline_seconds")`. This removes the GNU/BSD `timeout` dependency that would fail with exit 127 on a stock macOS host without coreutils, while preserving identical semantics (exit 124 on bound-hit, command's own exit otherwise), which the existing `[ "$LOCK_WAIT_STATUS" -eq 124 ]` diagnostic check already relies on. Verified: `bash -n` syntax check, `bin/fm-lint.sh --fast` clean, full `tests/fm-lint.test.sh` suite (46/46 pass), and a standalone repro confirming `fm_run_timed` returns 124 on timeout and 0 on success identically to the prior `timeout` call. No other direct `timeout` calls exist in this file or elsewhere in the PR's diff, so no sibling sites remain

* fix(herdr): gate exact-resume lock wait behind --herdr-resume-lock-wait

Keep refuse-by-default on presentation-order lock contention for Herdr
exact resume. Callers that need concurrent recoveries to serialize must
pass --herdr-resume-lock-wait; unbounded blocking on a third-party session
lock is never the default.

Update docs and the real-Herdr e2e suite so the default path asserts the
refusal and the opt-in path asserts the wait.

* no-mistakes(test): Fix e2e test's lost exit status after if/fi with no else branch

* docs(herdr): stop advertising --herdr-resume-lock-wait on --relaunch

The relaunch path reuses the recorded endpoint and never takes the
presentation-order lock, so the flag is inert there. Drop it from the
--relaunch usage line and state where the flag applies.

* no-mistakes(review): Clarify lock-wait docs; simplify bash-3.2-safe spawn_task helper

* no-mistakes(ci): Fixed ci-1 (Greptile P2). In tests/fm-backend-herdr-presentation-e2e.test.sh, the failure cleanup `cleanup_all` stopped only `LOCK_CONTENTION_OWNER_PID`. It now also stops `LOCK_REFUSE_HOLDER_PID` and `LOCK_WAIT_HOLDER_PID`, the holders of the two new contention cases, so a `fail` before their explicit `wait` no longer leaves them running. Both new PIDs are initialised empty next to the existing one, and each is cleared right after its successful `wait` so cleanup never touches a finished PID. I changed nothing else. `bash -n` passes. The real Herdr e2e run passed both new cases ("default resumed identity refuses session lock contention" and "--herdr-resume-lock-wait waits out session lock contention instead of refusing"). The full run hit my 550s timeout in a later, unrelated case, after the new cases passed

* fix(bin): let TERM stop a watcher blocked in a pane capture on bash 3.2 (#6762)

* fix(bin): let TERM stop a watcher blocked in a pane capture on bash 3.2

Stock macOS bash 3.2 holds a HUP or TERM until a running command
substitution's child exits, and the watcher read every pane through
$(fm_backend_capture ...). A blocked backend read therefore held the
watcher's stop for as long as the read lasted, and a stopped watcher left
the hung read orphaned. tests/fm-watch-triage.test.sh
test_term_stops_a_watcher_blocked_inside_a_poll failed on /bin/bash 3.2
for this reason while passing on bash 5.

Pane captures now go through watcher_capture, which runs the read as a
waited background process group recorded like a check's, so the stop is
honored at once and watcher_cleanup stops a read still in flight along
with its per-call output file.

* no-mistakes(review): Run drain-ring idle capture in watcher shell, add regression test

* no-mistakes(document): Document watcher TERM handling for blocked checks and captures

* no-mistakes(test): Silence bash 3.2 setpgid race noise from watcher captures

* fix(bin): verify the capture group and scope the stop claim to pane reads

watcher_capture now confirms its background read leads its own process
group, as run_check_capture already does, so watcher_cleanup never relies
on a group that set -m failed to create. The comment and continuity doc
now say only fm_backend_capture pane reads go through watcher_capture;
agent-state and composer-state reads still run inside command
substitutions.

* feat: add per-home worker tool exclusions (#6750)

* feat(spawn): add per-home worker tool exclusions

Add an optional per-home config/crew-exclude-tools file listing tool names to hide from workers, one per line, with blank lines and # comments allowed.
It applies to every ship and scout launch and relaunch in that home, is never inherited by another home, and does not affect secondmate agents.
Pi and pi-signed apply it through --exclude-tools, which also covers MCP tool names.
Any other runtime, and a raw launch command, refuses the launch when the list is non-empty rather than ignoring it.
Malformed entries are refused before provisioning, and before a relaunch stops a running worker.
Exclusions that match no tool in the worker's loaded registry are reported as unverified warnings in its status record instead of refusing the worker.

Closes #6744

* no-mistakes(review): Preserve UTF-8 exclusion paths and verify Pi lifecycle behavior

* no-mistakes(document): Clarify worker tool exclusion documentation

* no-mistakes(ci): Fixed ci-1 in bin/fm-exclude-tools-lib.sh: a failed read now returns an error before printing names, so all shared launch and relaunch callers refuse rather than silently dropping exclusions. Added deterministic regression coverage for a file disappearing after readability checks across Pi/pi-signed ship and scout launches. Reproduced the original failure; verified 83 spawn checks, 77 relaunch checks, direct parser/runtime failure cases, full targeted lint, Bash syntax, and git diff --check. Relaunch tests passed with existing fixture-cleanup permission warnings. ci-2 remains unchanged per the user's decision; the outer executor owns the fresh CI run

* feat(bin): defer spawns beyond a declared per-project capacity, opt-in (#5343)

* refactor(bin): share the local Firstmate home walk from the wake library

Teardown's walk over the root home and its registered local secondmate homes
moves into bin/fm-wake-lib.sh as fm_local_firstmate_state_dirs, next to
fm_firstmate_root_home, so a second consumer can count task records across
this machine's homes without a copy. Teardown keeps its exact refusal wording
through a thin wrapper.

* feat(bin): defer spawns beyond a project's declared machine capacity

A project whose machine-local resource only serves a few workers at once had
no way to tell Firstmate so: every queued item was launched, and the surplus
workers spent full-context turns retrying the resource.

config/project-capacity in the root home now declares how many workers each
named project admits at once on this machine. bin/fm-spawn.sh counts the ship
and scout records on the same project origin across the root and its local
secondmate homes, skipping ones whose ready PR is recorded, while holding the
shared project lock through publication. A spawn with every place held exits 75
before any brief render, endpoint, worktree, record, or backlog move, so the
item stays queued; batches report it as deferred. Undeclared projects keep
today's uncapped dispatch, and an unreadable declaration refuses rather than
guessing the limit.

Refs #4237

* no-mistakes(review): Document that capacity matches the clone directory name

* no-mistakes(document): Rewrap stale fm-wake-lib root-home doc comment

* no-mistakes(review): Dedupe local state dirs by identity to avoid double-counting

* no-mistakes(document): Rewrap fm_local_firstmate_state_dirs error doc comment

* no-mistakes(ci): I fixed all four Greptile findings. All 14 tests in tests/fm-project-capacity.test.sh pass, and shellcheck at warning level is clean on the changed files. Each new test failed against the old code and passes now. - **ci-1 (spaced names):** a declaration line must give a name its capacity whenever the name is a valid clone directory name. `fm_project_capacity_lookup` now trims each line, skips blank lines and lines whose first non-blank character is `#`, and takes the last field as the capacity. Everything before that field is the name, so it may contain spaces. The old error cases still refuse: a single field is rejected, and trailing text leaves a last field that is not an integer. The library header and docs/configuration.md now say a name starting with `#` cannot be declared. New test `test_spaced_project_name_is_declared` declares `my heavy project 1` next to an indented comment line and gets a deferral. - **ci-2 (unreadable records):** the holder count must never silently leave out a holder. `fm_project_capacity_occupants` now refuses when a local home's state directory exists but cannot be read or listed, or when a `.meta` file cannot be read. The error names the path, and `fm-spawn.sh` shows it in its existing refusal message. New test `test_unreadable_holders_refuse_admission` covers an unreadable record in the root home and an unreadable state directory in a registered local secondmate home, then checks that the spawn is admitted once both are readable. The test is skipped when run as root. - **ci-3 (Orca lock):** any spawn that can become a holder for a capped project must take that project's lock. The lookup now also reports whether the declaration caps any project at all, and an Orca spawn takes the per-origin lock whenever it does. This covers every capped same-origin clone. It also covers some cases where no same-origin clone is capped, because a spawn cannot find clones under other directory names without searching for them. With no declaration file, Orca still skips the lock. The comments in the library and in the `fm-spawn.sh` header are updated. The Orca test now clones the origin as `project-2`, which has no declaration, and checks that its Orca spawn refuses while the lock is held and publishes no record. - **ci-4 (worktrees):** `assert_nothing_created` now also compares the project's `git worktree list` from before and after a deferred spawn. Both tests that call it take that snapshot first. Files changed: bin/fm-project-capacity-lib.sh, bin/fm-spawn.sh, docs/configuration.md, tests/fm-project-capacity.test.sh

* fix(bin): declare capacity for a project name that begins with #

A clone directory whose name begins with # was skipped as a comment, so that project stayed uncapped. A line is a declaration when the # is written against the rest of the name and the line ends with a capacity; a # followed by whitespace stays a comment.

* no-mistakes(document): Rewrap project-capacity library header comment

* no-mistakes(ci): Lint 2 fails because this PR's code pushes ShellCheck past its memory cap. ShellCheck ran out of memory analyzing bin/fm-teardown.sh in CI (reason=memory, rc=251, peak about 8.39 GB). On current main the same file passes at about 7.29 GB. **Cause:** the new `fm_local_firstmate_state_dirs` function in bin/fm-wake-lib.sh had a conditional `. fm-secondmate-registry-lib.sh` with a `# shellcheck source=` directive inside the function. ShellCheck followed that source again, inside a function scope, wherever fm-wake-lib.sh is sourced, and bin/fm-teardown.sh is the heaviest root that sources it. Measured locally with `shellcheck --norc --external-sources bin/fm-teardown.sh`: - current main (fd325b1b): 7.29 GB - main merged with this PR: 7.86 GB - the same merge without the in-function source: 7.27 GB **Rule this restores:** this change must not make any lint root heavier than it is on main. That function holds the only new nested source in the change. **Fix:** I removed the in-function source, which no caller needs. Both callers already load the registry library at top level before calling the function: - bin/fm-teardown.sh sources it directly. - bin/fm-spawn.sh, the only user of bin/fm-project-capacity-lib.sh, gets it through bin/fm-ff-lib.sh. I also documented the requirement in the function's comment and in the "Requires" note in bin/fm-project-capacity-lib.sh. No behaviour changes. **Verification:** - ShellCheck on head: bin/fm-teardown.sh peaks at 7.12 GB and bin/fm-spawn.sh at 6.68 GB, both with rc=0. bin/fm-wake-lib.sh and bin/fm-project-capacity-lib.sh lint clean. - tests/fm-project-capacity.test.sh, tests/fm-teardown.test.sh (102 ok) and tests/fm-teardown-endpoint-safety.test.sh all pass. Files changed: bin/fm-wake-lib.sh, bin/fm-project-capacity-lib.sh

* fix(bin): release the Herdr session lock when reclaim finishes

A concurrent resume in another home waits five seconds for that lock.
Reclaim is the last presentation change on the recovery path, so holding
the lock through the launch tail made the waiter time out. The contributions
arm check also freezes its one-second clock, the same way the budget tests
do, because an unfrozen clock can tick past before the first forge read.

* no-mistakes(review): Keep Herdr session lock through launch handoff after reclaim

* no-mistakes(review): Skip the spawning task's own record in capacity count

* no-mistakes(review): Restore release test comment above its test

* docs: scope PR-ready re-evaluation to a declared project capacity

A ready pull request frees a place only when that project declares capacity, so the always-loaded backlog contract should re-evaluate on that handoff only in that case.

* fix(bin): name the Lavish read message count by the same label as its section (#6785)

fm-procevent-lavish.sh read labels tag=message rows SESSION-ENDING MESSAGE
only when session_ended is true and CAPTAIN MESSAGE otherwise, but the
count line always said session_ending_message_count. Several composer
messages on a still-open board were therefore counted as session-ending.

The count line now follows the same session_ended switch:
session_ending_message_count once the session ended, captain_message_count
otherwise. Message rows stay out of the annotation count, per triage.

Fixes #6743

* fix(herdr): make the presentation lock namespace per OS account (#6780)

The Herdr presentation lock namespace was the fixed machine-global
/tmp/firstmate-herdr-presentation, so on a host where two OS users run
Firstmate on Herdr the first account to create it owned it and every
teardown from the other account was refused with no way to clear it.

Suffix the namespace with the account uid. The owner-uid and mode-700
checks are unchanged, so a foreign-owned or wrong-mode name at this
account's path is still refused and never adopted, chowned, or removed.

Fixes #4716.

* Fix OpenCode arm plugin to decide with the shared supervision predicate (#6809)

The OpenCode session plugin's shouldArm kept its own copy of the need
test that only looked for in-flight task records, while the turn-end
guard decides with fm_supervision_needed in bin/fm-supervision-lib.sh,
which also counts registered process-event sources and trusted custom
checks. With an empty fleet but any registered source or check, the
guard blocked every turn end while the plugin declined to arm - a loop
the guard's own repair line could not resolve because it names the
plugin as the fix.

The plugin now delegates the decision to the shared predicate through
bash, keeping the local away-record decline and the x-mode.env arm
override. OpenCode plugin test fixtures now carry the real predicate
their arming path sources, and the arm suite gains six cases asserting
the plugin's decision against the shared verdict over the same
synthetic state directories.

Co-authored-by: Mia Sun <[email protected]>

* fix(bin): resolve a pending reply only from its own task's status line (#6792)

* fix(bin): resolve a pending reply only from its own task's status line

Remote reply ingestion handed every corr= token in a mate's payload to
fm_pending_reply_try_resolve together with that mate's own status log,
so one mate echoing another mate's token resolved the other request.
Honor a status-file override only when it is the record's own
parent_status, and match the corr= token as a whole word.

Fixes #6538

* no-mistakes(document): docs: scope remote reply settlement to the asked mate

* docs(skills): index the six missing agent-only skill triggers (#6784)

agent-skill-trigger-index claims to be the complete agent-only trigger
index but omitted operational-home-layout, session-start-recovery,
validation-supervision, ship-landing, scout-completion, and
away-quiet-supervision. Add each with its own description's trigger,
placed beside the related entries.

The decision-hold-lifecycle redirect stub stays out, per triage.

Fixes #6503

* test: make agent process fixtures compatible with multicall sleep (#6814)

* test: share a rename-safe agent stand-in across liveness suites

On Ubuntu 26.04, `sleep` is the uutils multicall binary, which refuses to
run when invoked through a symlink named after another utility. The Herdr
descendant process-walk tests built their agent-named process as a `pi`
symlink to the host `sleep`, so the process exited at once, its parent shell
was gone before the walk ran, and both cases read `unknown unreadable` and
failed on that host. The suite stops at its first failure, so every later
case went unrun. The Herdr control smoke test's `claude` symlink has the
same construction.

The tmux liveness suite already solved this with a host-compiled spinner and
a survival-checked `sleep` fallback. That builder moves into tests/lib.sh as
fm_agent_standin, and the tmux suite, both Herdr descendant cases, and the
Herdr control smoke test now use it. When no stand-in can survive a foreign
name, a case skips with the reason instead of failing.

tests/fm-test-fixtures.test.sh gains a portable regression with a fake
multicall `sleep`, so it bites on hosts whose own `sleep` is single-purpose.

* no-mistakes(document): Correct Herdr verification fixture reference

* ci: retrigger cancelled shard

* fix(bin): keep the supervision host's successor watcher alive after the Stop hook's group is torn down (#6787)

* fix(bin): keep the supervision host's pass-through successor out of the hook's process group

The successor a main-only pass-through leaves for main shared the Stop hook's
process group, so the harness tearing that group down after the exit-2 rewake
stopped it. The stop published downtime and the next park's first cycle
announced an empty check: rearm-resurface, which woke main again in a loop.
Start that successor in a process group of its own, as the hook's own
handling successor already is.

* no-mistakes(review): Give the at-turn successor left for main its own group

* no-mistakes(document): Document own-group successor for turn-start hand-back too

* no-mistakes(ci): I made the change you asked for: both new teardown tests in tests/fm-supervision-host.test.sh now call the existing `stop_home_processes "$home"` just before `pass`. The tests are `test_successor_left_at_the_turn_survives_the_hook_process_group_teardown` and `test_pass_through_successor_survives_the_hook_process_group_teardown`. No production code and no other tests changed. The rule broken was that a test must not leave a home's watcher or arm processes running after it passes. These two were the only cases in the changed area that broke it. The other host+hook tests already stop their home, and `test_successor_close_during_main_turn_is_delivered_at_the_next_turn_end` leaves its watcher behind too, but it is an older test you said not to touch. The only reason anything was left over is that the successor's arm now sits in its own process group, outside the hook's teardown. `stop_home_processes` kills the watcher by the pid in its lock file, which stops it no matter which group it is in. **Checks run:** - I ran just these two tests from a scratch copy of the suite (since deleted). Both pass in about 13 seconds. - After each test, a process listing filtered to that test's home directory came back empty once the processes had about a second to exit after TERM. - `bash -n` on the test file passes. - `shellcheck` is not installed here, so I did not lint the file. - I did not run the full serial-2 suite locally. Whether it now finishes under its 30-minute limit will only show on the next CI run

* test: make tmux Claude readiness checks independent of permission footers (#6823)

* test: use idle composer readiness for Claude tmux guards

* no-mistakes(test): Fix attended supervision test expectations and isolate worker state

* no-mistakes(document): Correct live guard coverage and readiness documentation

* no-mistakes(ci): Captain, fixed SC2100 by quoting the cursor-agent assignment in tests/fm-host-mirror-live-e2e.test.sh. Reproduced the failure before editing; pinned ShellCheck lint on both PR test files, bash syntax checks, and git diff --check now pass

* test: preserve attended successor close assertions

* no-mistakes(test): Fix attended live test watcher takeover expectations

* no-mistakes(document): Correct stale attended guard documentation

* Revert "no-mistakes(document): Correct stale attended guard documentation"

This reverts commit 8e59d89e17f48afc6e5a72d6d23fdca156a0f856.

* Revert "no-mistakes(test): Fix attended live test watcher takeover expectations"

This reverts commit c0b851054917fcbe957469eb0b1bc2c2075fcc51.

* test(herdr): accept safe exit refusals and clean lab once (#6818)

* test: stabilize watcher lock race fixtures (#6887)

* test: order stale watcher-lock fixture races explicitly

* no-mistakes(review): Removed duplicate stale-steal reap call

* fix(bin): keep herdr composer probes observable-only without autostarting server (#6920)

* fix(bin): keep herdr composer probes observable-only without autostarting server

- Refuse bare pane identifiers lacking session prefix in fm_backend_herdr_parse_target
- Add fm_backend_herdr_target_observable to passively verify server liveness without autostarting
- Route visible viewport captures through fm_backend_herdr_target_observable
- Detach stdin with </dev/null on background server launch in fm_backend_herdr_server_ensure
- Add unit and regression tests in tests/fm-backend-herdr.test.sh

* fix(bin): drop parse_target colon restriction to preserve existing fixtures

Revert the fm_backend_herdr_parse_target colon check so that single-colon
session targets like sess:p1 in secondmate liveness and other fixtures parse
properly. The probe path remains observable-only via fm_backend_herdr_target_observable.

* fix(tests): clear inherited Git repository location in fixture helper (#6956)

* test: clear inherited Git repository location in fixture helper

An absolute GIT_DIR inherited from the caller (a linked-worktree hook
exports one) overrides the discovery that git -C implies, so fixture
setup moved the caller's branches and registered fixture worktrees in
it. tests/git-config-helpers.sh now unsets GIT_DIR, GIT_WORK_TREE,
GIT_INDEX_FILE and GIT_COMMON_DIR alongside the config isolation.

Fixes #6953

* no-mistakes(document): Document fixture Git location isolation in CONTRIBUTING

* fix: avoid argument-size failures in fleet contribution snapshots (#6830)

* fix(bin): stage contribution-input JSON via temp files

The contribution-input branch passed the whole canonical backlog document to
jq as a single --argjson argv argument. A large fleet's backlog JSON exceeds
Linux MAX_ARG_STRLEN (128 KiB), so jq fails with E2BIG (Argument list too
long) and the contribution-input snapshot emits empty output, breaking the
bearings contribution path.

Write both the backlog and task documents to a temp directory and hand them
to jq with --slurpfile, matching how the full snapshot path already stages
the same pair. Output is unchanged for any backlog that fits in argv.

* no-mistakes(document): Correct contribution cleanup trap comment

* fix(bin): arm the busy contract on secondmate launches (#5342)

* fix(bin): arm the busy contract on secondmate launches

A tmux-backed secondmate's active-turn gate can only see a busy verdict from the parent home's record, and those launches never armed it.

* no-mistakes(review): Reopen secondmate busy on blocked Claude Stop; drop muse guard

* no-mistakes(review): Make Claude secondmate Stop guard the sole Stop-state writer

* no-mistakes(review): Record live rewake UserPromptSubmit evidence and add regression

* docs: record Claude secondmate Stop guard as busy writer

* no-mistakes(review): Keep Stop idle hook for older secondmate guards

* no-mistakes(document): Correct stale omp secondmate -e rationale in supervision verification

* no-mistakes(document): Fix skill-relative turnend-guard link in Claude harness reference

* no-mistakes(ci): Root cause: in shard 9, the pure-contract-unit family ran two scripts, tests/fm-rovo-harness.test.sh (14712 ms) and tests/fm-omp-harness.test.sh (10335 ms). Those two durations add up exactly to the failing family's 25047 ms. The failing one was tests/fm-omp-harness.test.sh. Its test_secondmate_launch_relies_on_discovery still asserted the old contract: that an omp secondmate launch names no -e and gets no state/<id>.omp-ext.ts. This PR (issue #4268) deliberately changed that. bin/fm-spawn.sh now arms the busy contract for omp secondmates, so their launch names `-e state/<id>.omp-ext.ts` and writes that extension. The primary extensions are still left to auto-discovery. The harness reference docs were updated to match, but the test was not. The fix is test-only and touches just tests/fm-omp-harness.test.sh. The test now asserts that the secondmate launch names exactly one -e and that it points at the parent-home state/sm.omp-ext.ts. Because only one -e is allowed, the tracked .omp/extensions files are not named a second time, which would load them twice. The test also asserts that the extension file exists, and the header comment for contract 3 was updated. The posture overlay, --cwd, marker, and supervision-model assertions are unchanged. Verification: the host's load average was about 140 on 8 cores, and the full script timed out locally after 590 s having finished only its first 2 tests. So I ran the one affected test function on its own through the real fm-spawn path, and it passed (`ok - fm-spawn: a real omp secondmate launch loads only the busy -e and auto-discovers its primary extensions`). The remaining omp tests were not re-run locally. shellcheck on the file reports only existing info-level notices. The change is left uncommitted for the outer executor

* test: keep the secondmate busy stall gate visible after main's liveness probe

The merged watcher treats a window-name inventory miss as a missing endpoint and exits a later checkpoint on the previous quiet run's recovery wake. The fake pane now answers both list-windows formats, and each observation starts without a leftover downtime marker, so a busy mate still defers the stall and an idle mate still surfaces it.

* no-mistakes(review): Align fm-spawn secondmate comments with omp -e and devin refusal

* no-mistakes(document): Document secondmate busy extensions in configuration reference

* no-mistakes(test): Make live busy-contract guard clean up read-only lab dirs

* fix(bin): pass Claude secondmate busy hooks through --settings

Rewriting a persistent mate home's settings.local.json drops the captain's saved permissions. The hooks now live in a parent-state file Claude Code loads for that session only.

* no-mistakes(review): skip busy arm for raw secondmate launch commands

* no-mistakes(review): retire earlier busy arm on raw secondmate respawn

* no-mistakes(review): retire Stop pointer on relaunch, load --settings in live guard

* no-mistakes(document): Document secondmate Claude settings file and raw-launch exception

* no-mistakes(ci): The check "Behavior portable serial 9" failed because of this PR, and I fixed it with a test-only change; `tests/fm-spawn-dispatch-profile.test.sh` now passes locally in full. Cause: the one failing test was "claude secondmate launch settings JSON does not disable Claude attribution" in `tests/fm-spawn-dispatch-profile.test.sh`. This PR makes a claude secondmate launch pass `--settings` as a file path (`state/<id>.claude-settings.json`) instead of inline JSON. The test helper `claude_settings_json_arg` handed that path string to jq as if it were JSON, so jq reported a parse error. The product behavior is correct: the file does carry `feedbackDrafts` and the attribution-off policy. Invariant: a test that checks the Claude launch settings must read the settings Claude would load, whichever form `--settings` takes (inline JSON or a file path). The only place this must hold is `claude_settings_json_arg`, the single reader of the `--settings` value in the tests. Its two callers, `assert_attribution_policy` and `assert_attribution_policy_absent`, both go through it. Fix: `claude_settings_json_arg` now prints the value when it starts with `{` and prints the file contents otherwise. No product code changed. Verification: I ran `bash tests/fm-spawn-dispatch-profile.test.sh` in the worktree. It ended with "all fm-spawn-dispatch-profile tests passed", including the previously failing secondmate case and the crewmate and keep-ai-trailers cases that use the inline form. I did not run the other tests of shard 9; they passed in the CI run and this change touches only this test file. The change is uncommitted in the worktree (one file modified)

* test: guard fleet snapshot contribution input against argument-size failures (#7036)

The large-backlog regression already proved the json and secondmate
home-summary modes stay within exec limits. It now also runs the
contribution-input mode on the same 1200-record backlog, which is the
path #6830 moved off argv. With that fix reverted the test fails with
the field error jq Argument list too long at the contribution-input call.

---------

Co-authored-by: Tiago <[email protected]>
Co-authored-by: M00NLIG7 <[email protected]>
Co-authored-by: Symphony <[email protected]>
Co-authored-by: Freudator86 <[email protected]>
Co-authored-by: Quartermaster <[email protected]>
Co-authored-by: YifuGu <[email protected]>
Co-authored-by: YifuGu <[email protected]>
Co-authored-by: Thoughts-One <[email protected]>
Co-authored-by: Vytautas Stankus <[email protected]>
Co-authored-by: cloud-practitioner <[email protected]>
Co-authored-by: yairtech <[email protected]>
Co-authored-by: Asser AboElkhair <[email protected]>
Co-authored-by: dubiousenvelope <[email protected]>
Co-authored-by: Mia Sun <[email protected]>
Co-authored-by: Pedro Guimarães <[email protected]>
Co-authored-by: menidi <[email protected]>
Co-authored-by: vikash. <[email protected]>
Co-authored-by: Martin Kessler <[email protected]>
Co-authored-by: Jon Roosevelt <[email protected]>