Repository navigation
fix(bin): route remaining large snapshot JSON through files instead of argv - #4008
mihneamanolache wants to merge 5 commits into
Conversation
…sed named envelopes
…act in script header
Confidence Score: 4/5The PR appears safe to merge, with only a non-blocking temporary-file cleanup gap on signal termination. The file-backed transport and fail-closed collection paths preserve the snapshot contract, but interrupted PR enrichment can leave its newly introduced temporary file behind. Files Needing Attention: bin/fm-bearings-snapshot.sh Reviews (1): Last reviewed commit: "no-mistakes(document): document snapshot..." | Re-trigger Greptile |
| cleanup_candidate_prs() { | ||
| rm -f -- "$CANDIDATE_PRS_FILE" | ||
| } | ||
| trap cleanup_candidate_prs EXIT |
There was a problem hiding this comment.
Signal exits leak transport files
When the script receives SIGINT, SIGTERM, or SIGHUP during PR collection, the EXIT-only cleanup does not run, leaving an fm-bearings-prs.* transport file in the temporary directory. Register signal handlers so interrupted invocations exit through the existing cleanup path.
| trap cleanup_candidate_prs EXIT | |
| trap cleanup_candidate_prs EXIT | |
| trap 'exit 130' INT | |
| trap 'exit 143' HUP TERM |
Intent
Filed 2026-09-01 and reproduced then. Priority 1, and it has sat queued a week because the fleet
kept having louder problems - which is itself the argument for fixing it now.
Bearings is completely blocked.
/bearingsin every mode - plain, file, and lavish - failsbefore any field projection:
Passing a reduced
--fieldslist does not help, because the failure is upstream of projection.Cause, already diagnosed:
main_inventory_json()passes the entire backlog JSON and the entiretasks JSON to jq as COMMAND-LINE arguments, via
--argjson "$1"/--argjson "$2". Those blobsland in argv, so once they exceed the kernel argument limit the exec simply fails.
data/backlog.mdis now 129,785 bytes and this home carries 73 open captain holds, several withlong multi-sentence reasons. That is what crossed the threshold.
Why it matters more than one broken command. This is the single deterministic fleet-state
source the bearings skill mandates, and that skill explicitly forbids substituting a second reader.
So the failure removes the fleet's entire catch-up surface at exactly the moment the backlog is
large enough to need one. It is a threshold failure rather than a gradual one: it worked earlier
that day and now fails on every invocation until the backlog shrinks, and it will recur in any home
whose backlog grows.
There is an interim workaround - read
state/*.meta,bin/fm-crew-state.shper task, and thebacklog directly - but the skill deliberately prohibits that substitute and it must not become the
norm.
What Changed
fm-bearings-snapshot.shnow accumulates candidate open-PR rows in amktempJSONL file (cleaned up via anEXITtrap) and hands them to the modeljqwith--slurpfile, replacing the--argjsonaccumulator that put the whole PR inventory in argv.fm-fleet-snapshot.shgains ajson_envelope_filehelper plus a sharedJQ_ENVELOPE_PRELUDE(envelope/member) so per-task components, parent-evidence bundles, and the unbounded status-log note travel tojqas named-key files (--slurpfile/--rawfile) rather than--argjsonarguments; the prelude errors out on a transport that is not a single JSON object or that is missing a key instead of folding it tonull.task_json_linesandscout_report_linesnow build rows into a file instead of a pipedjq -sloop, so a failed record composition returns non-zero and aborts the snapshot instead of publishing a silently truncatedtasks[]/scout_reports[]; parent evidence reconciliation and contradiction reads fail closed with per-task diagnostics, and the header documents that records are omitted only through disclosed bounds. Four tests cover large PR/decision inventories exceeding the per-argument limit and mid-inventory task and scout-report composition failures.Risk Assessment
✅ Low: The change is a well-bounded argv-to-file transport migration whose durable fix I reproduced end to end (base commit both overflows
jqargv and fail-opens with a task silently missing; HEAD renders the same 146 KB component correctly), every remaining--arg/--argjsonin both scripts carries a bounded per-item scalar, the new envelope guard provably fails closed on empty or multi-value components, and the only findings are three informational polish/attribution items.Testing
Built real FM_HOME fixtures matching the report (131,485-byte backlog, 73 long-reason captain holds, live crewmate metas/status logs, one registered secondmate home) and drove /bearings the way each mode does, on both the base and target commits. Base reproduces the reported failure on the argv transports this change removes: the PR-enrichment path exits 1 with
jq: Argument list too longand no fleet state, and an oversized per-task component makes the snapshot exit 0 while silently omitting a live task from Underway and from the fleet-state inventory the bearings skill mandates. Target projects all of it completely with clean stderr (620 PR rows, 401-decision secondmate present, parked crewmate visible in Underway). I also ran the full owning suite tests/fm-bearings-snapshot.test.sh and the downstream tests/fm-fleet-snapshot-view.test.sh at target (all ok), and ran each of the 4 new tests against base scripts where all 4 fail, confirming they are real regressions. No visual artifact applies: the change is shell/JSON transport with no rendered surface, and the lavish board is composed downstream from the same --json step I exercised and is untouched by the diff. Worktree left clean; transient fixture scaffolding removed and only transcripts plus reproduction scripts kept in the evidence directory.Evidence: Before/after CLI transcript: three argv-overflow scenarios plus base-vs-target verdicts for the 4 new tests
Source: Before/after CLI transcript: three argv-overflow scenarios plus base-vs-target verdicts for the 4 new tests
Evidence: /bearings on the reproduced reported home at the target commit - plain, reduced --fields, --json, --include-prs
Source: /bearings on the reproduced reported home at the target commit - plain, reduced --fields, --json, --include-prs
Evidence: Same mode sweep at the base commit (honest context: that home's plain path already survives on base after #3677)
Source: Same mode sweep at the base commit (honest context: that home's plain path already survives on base after #3677)
Evidence: Captain-facing digest difference (excerpt)
Pipeline
Updates from git push no-mistakes
✅ **intent** - passed
✅ No issues found.
✅ **Rebase** - passed
✅ No issues found.
bin/fm-fleet-snapshot.sh:1994-scout_report_linesstill uses the exact fail-open piped-loop shape that commit ab116ce removed fromtask_json_lines:find … | sort | while … jq -n … done | jq -s 'sort_by(.id)'. The script does not setpipefail, so the function's exit status is the finaljq -s, which succeeds on whatever prefix reached it. Concrete path: make one task directory under$DATAunreadable (mode 000).findprints its readable entries, writes 'Permission denied' to stderr and exits 1;jq -sexits 0 on the partial stream;scout_report_lines > "$SCOUT_REPORTS_JSON_FILE" || { … exit 1; }never fires, and the snapshot publishesscout_reportswith records silently missing - so a completed scout report never reaches the captain and/bearingsshows an inventory it believes is complete. The same holds if the innerjq -nfails for any single report. This is the identical violated invariant ('composition failures must fail this function rather than … leave a sorted truncated prefix as the published inventory') at the immediately adjacent sibling collector, and the fix is the same one already applied at line 939: accumulate into a file with|| return 1per record, thenjq -s 'sort_by(.id)' < "$file".bin/fm-fleet-snapshot.sh:1853-reconciliation=$(parent_evidence_reconciliation_json "$summary_file" "$evidence_file")discards the return status, and the new envelope guard gives that call a real new failure mode (a malformedtask/activity_scancomponent now makes iterror()out). When it fails,$reconciliationis empty,contradiction=$(printf '' | jq -r '.contradiction')yields the empty string, and the run only fails later because--argjson contradiction ""is rejected as invalid JSON by the record-composing jq. It does fail closed, but via a downstream accident and with an opaque 'Invalid JSON text passed to --argjson' message rather than the named diagnostic the rest of this branch establishes. Add|| return 1to the call so the failure is attributed where it happens.bin/fm-fleet-snapshot.sh:1855- Theterminal_contradictionjq now loads the whole parent-evidence envelope via--slurpfileplus the prelude solely to re-derive$notefrom$task.paths.status_log.last_event.note, when the identical value is already in the shell as$event_note(line 1762) and is passed as a plain argument toterminal_evidence_jsonon the next line.$event_noteis a single bounded status-log note, not an unbounded blob, so it does not need file transport. Replacing the--slurpfile/prelude with--arg note "$event_note"removes a redundant file read and one of the two places this field is derived.bin/fm-fleet-snapshot.sh:739- Each failure path intask_json_lines(lines 739, 783, 831, 850, 931) callssnapshot_task_cleanupbeforereturn 1, buttrap snapshot_cleanup EXITalready runssnapshot_task_cleanup, and the sole caller (TASKS_JSON=$(task_json_lines) || … exit 1) exits immediately. Because the caller is a command substitution, these in-function calls also tear down the observation directory that the parent shell'sSNAPSHOT_TASK_DIRstill names, which would break any future non-fatal handling of atask_json_linesfailure. Dropping the fivesnapshot_task_cleanupcalls and keeping barereturn 1leaves behavior identical and removes the duplicated teardown.tests/fm-bearings-snapshot.test.sh:1582-test_large_task_decision_inventory_avoids_argument_transportasserts that the whole canonical snapshot exceeds 131072 bytes, but the bug it guards is a single argument (--argjson open_decisions) exceeding MAX_ARG_STRLEN. Those are different quantities: the snapshot already carries the backlog, task rows and secondmate records, so a later fixture trim (fewer decisions, or a shorter suffix) could keep the total above 131072 whileopen_decisionsitself drops under 128 KiB, and the test would then pass against the pre-fix code. Assert on the component instead, e.g.[.tasks[] | select(.id == "mate")][0].hints.open_decisions | tojson | length > 131072, so the guard pins the argument that actually overflowed. (The sibling candidate-PR test at line 1554 is tight enough, since candidate_prs dominates that model.)🔧 Fix: fail closed on scout report and reconciliation failures
3 infos still open:
bin/fm-fleet-snapshot.sh:1992-scout_report_lineswrites find output topaths_file, sorts it intosorted_file, then loops oversorted_file- but the function's finaljq -s 'sort_by(.id)'(line 1999) re-orders every record by.id, and.idisbasename(dirname(report)), which is unique per record. The pre-sort therefore cannot affect the published order: it is one extra file plus one extra process per snapshot for no observable difference. Read the loop directly frompaths_fileand dropsorted_file(and theLC_ALL=C sortline). Verified: the emittedscout_reportsarray is identical either way becausesort_by(.id)is total over unique ids.bin/fm-fleet-snapshot.sh:1858-terminal=$(terminal_evidence_json "$task" "$event_note" true)(and the sibling at line 1908) discards the return status, two lines below theparent_evidence_reconciliation_jsoncall this fix round deliberately hardened with|| { echo ...; return 1; }.terminal_evidence_jsoncan exit non-zero: its finaljq -n --argjson bytes "$bytes" --argjson lines "$lines"rejects an emptybytes/lines, which happens if thewc -c/wc -lpipeline fails. On that path$terminalis empty,json_envelope_file(line 1863) emits"terminal":}, and the run dies at the record-composing jq with a bareInvalid JSON textparse error against a temp file path rather than the named per-task diagnostic the surrounding code now establishes. It does fail closed, so this is attribution only - add the same|| { echo "fm-fleet-snapshot: terminal evidence capture failed for $id" >&2; return 1; }guard to both call sites.bin/fm-fleet-snapshot.sh:1990- Noting a verified behavior change for visibility, not as a defect:find ... > "$paths_file" || return 1now propagates any non-zerofindexit, so a single unreadable directory under$DATAaborts the entire snapshot. Verified directly - withchmod 000 $DATA/locked, base b84e0e3 exits 0 and publishes the readable reports, HEAD exits 1 withfm-fleet-snapshot: scout report snapshot failedand emits nothing, taking down the whole/bearingscatch-up surface the intent calls the fleet's only deterministic fleet-state source. This is precisely the fail-closed behavior round 1 requested (its repro was a mode-000 task directory) and is the right trade against silently omitting a finished scout report, so no change is recommended. Nothing in the repo creates a$DATA/<id>directory with restricted permissions or removes one (fm-brief.sh:186onlymkdir -ps them), so there is no reachable transient-race path that would make this fire in normal operation. If a degraded-but-published surface is ever wanted here, the script already has the idiom for it (available:false/reasonsinbounded_parent_activities_json).✅ **Test** - passed
✅ No issues found.
bash tests/fm-bearings-snapshot.test.shat target commit - full owning suite, every case ok including the 4 new argv/fail-closed casesbash tests/fm-fleet-snapshot-view.test.shat target commit - downstream consumer of the changed snapshot producer, all okONLY_TEST=<test> bash tests/fm-bearings-snapshot.test.shfor each of the 4 new tests against a base-commit tree: all reportnot ok(fail-before / pass-after proven)Manual scenario A:bin/fm-bearings-snapshot.sh --include-prs --all-pr-repos --jsonon a 31-repo home with 20 open PRs per repo and default caps - base vs targetManual scenario C:bin/fm-bearings-snapshot.sh --fields home,in_flight,decisions_openon a home whose parked crewmate carries 520 keyed open decisions (124,334-byte status log, 136,761-byte component) - base vs targetManual scenario B:bin/fm-fleet-snapshot.sh --jsonon a home whose persistent secondmate stream carries 401 keyed open decisions (122 KB status log) - base vs target, comparing tasks[] inventory and hints.open_decisionsManual mode sweep on the reproduced reported home:bin/fm-bearings-snapshot.sh,--fields home,decisions_open,in_flight,--json,--include-prs --jsonEdge checks at target: fresh empty FM_HOME still snapshots (exit 0, empty inventories) and no/tmp/fm-bearings-prs.*transport files leak after a run.agents/skills/bearings/SKILL.md:37- .agents/skills/bearings/SKILL.md step 1 mandates bin/fm-bearings-snapshot.sh --json as the single fleet-state source and forbids a second reader, but gives no guidance for a non-zero exit - which this change makes a reachable outcome for a composition failure, not just a missing home. Left unchanged deliberately: the failure mode is pre-existing (the command could always exit non-zero on a backlog or observation failure), and restating the exit contract in the skill would duplicate the script header that the skill already names as authoritative. Worth a follow-up only if the captain wants an explicit "report the failure, do not fall back to reading state/*.meta" instruction in the skill.✅ **Lint** - passed
✅ No issues found.
✅ **Push** - passed
✅ No issues found.