Skip to content

fix(bin): pass fleet-sized JSON to jq on stdin so large homes stop failing bearings snapshots - #30

Merged
alandomio merged 3 commits into
mainfrom
fm/fm-bearings-argmax
Sep 13, 2026
Merged

alandomio merged 3 commits into
mainfrom
fm/fm-bearings-argmax

Conversation

@alandomio

Copy link
Copy Markdown
Owner

Intent

Fix bin/fm-bearings-snapshot.sh failing on a large home: it died with 'bin/fm-fleet-snapshot.sh: line 635: /usr/bin/jq: Argument list too long' then 'fm-fleet-snapshot: main inventory summary failed', so /bearings and the bearings board produced nothing. Cause: bin/fm-fleet-snapshot.sh passed whole JSON documents to jq via --argjson (main_inventory_json with BACKLOG_JSON/TASKS_JSON, the final assembly --argjson backlog, etc.); the captain's data/backlog.md is ~72KB so the derived JSON exceeds the kernel per-argument limit MAX_ARG_STRLEN (128KB). Required: pass every potentially unbounded JSON value (backlog, tasks, secondmate summaries, anything sized by fleet data) to jq without argv - --slurpfile/--rawfile from a private temp file, or stdin; audit all --argjson/--arg sites in bin/fm-fleet-snapshot.sh and bin/fm-bearings-snapshot.sh (and direct helpers) for data-sized values; small scalars may stay. Output must be byte-identical for inputs that worked before. Add a colocated regression test that builds a backlog large enough to exceed 128KB of JSON and proves the snapshot succeeds. Temp files, if used, must be private and cleaned up on exit. Acceptance: bin/fm-bearings-snapshot.sh succeeds against the real home ~/firstmate (read-only run), existing snapshot tests pass, shellcheck clean; follow firstmate-coding-guidelines. Decisions made: chose the stdin option instead of temp files - a first temp-file version broke the existing test_perl_fallback_bounds_github_call, which deliberately runs with a minimal PATH lacking mktemp/rm, and bash process substitution stored in an arg array is closed before jq opens it. New sourced bin/fm-jq-lib.sh (one owner) provides fm_jq: with -n, any --argjson/--arg value above FM_JQ_INLINE_MAX chars (default 8192) is streamed on jq stdin (--arg strings JSON-encoded via jq -Rs .) and bound by prefixing the filter with 'input as $name |'; small values stay inline so the common case costs nothing; without -n values stay inline. The bearings projection, which used to read the snapshot on stdin, now uses fm_jq -n --argjson canonical_snapshot and starts its filter with '$canonical_snapshot |' (name chosen because $snap is already used inside the filter). Per-call '# shellcheck disable=SC2016' comments were added because shellcheck only exempts jq program quoting for a command literally named jq. Tests added in tests/fm-bearings-snapshot.test.sh: a 1500-row backlog proving >128KB backlog JSON (asserted non-vacuous) still snapshots and renders bearings (fails on the old code with the original error), and a parity test that FM_JQ_INLINE_MAX=0 (everything on stdin) yields byte-identical bearings output vs everything inline. Verified old-vs-new output byte-identical on fixtures.

What Changed

  • Added a new sourced helper, bin/fm-jq-lib.sh, which provides fm_jq. When called with -n, it sends any --argjson/--arg value longer than FM_JQ_INLINE_MAX (default 8192 chars) to jq on stdin instead of argv. It binds those values with input as $name | at the start of the filter, and --arg strings are JSON-encoded first. Smaller values stay inline, and calls without -n pass their values through inline as before. Large homes (for example a ~72KB data/backlog.md) no longer hit the kernel Argument list too long limit. That error was killing the fleet snapshot, which left /bearings and the bearings board empty.
  • bin/fm-fleet-snapshot.sh and bin/fm-bearings-snapshot.sh now call fm_jq at every jq site that can receive data-sized values: backlog/tasks inventory, secondmate summaries and records, evidence reconciliation, and PR row merging. The bearings projection no longer reads the snapshot on stdin. It now receives it through --argjson canonical_snapshot, and the filter starts with $canonical_snapshot |. Each converted call has a # shellcheck disable=SC2016 comment, and docs/scripts.md lists the new lib.
  • Added two regression tests in tests/fm-bearings-snapshot.test.sh. One builds a 1500-row backlog, checks that its JSON is over 128KB, and confirms the snapshot still renders bearings. The other checks that bearings output with FM_JQ_INLINE_MAX=0 (every value on stdin) is byte-identical to output with every value inline.

🤖 Generated with Claude Code

Risk Assessment

✅ Low: The change is well-bounded: one new helper, fm_jq, sends large jq --arg/--argjson values through stdin, and every call site that can carry fleet-sized JSON uses it. I checked that jq accepts the input as $x | prefix (including when the filter starts with def) and that spilled and inline runs give byte-identical output, even for a string with tabs, quotes and invalid UTF-8. $SNAP is still validated before the bearings step, and the remaining plain --arg/--argjson calls pass only small values: counts, timestamps, paths, short reasons.

Testing

I ran both snapshot test files on the target and they pass, including the two new tests. I also ran the new test file against the base code, where the 1500-row backlog test fails with the original 'Argument list too long' error. Against the real home, read-only, the base commit's bearings and fleet snapshot both fail with that error, while the target renders full TOON and JSON bearings and exits 0. I couldn't compare base and target output byte-for-byte on the real home because the base produces no output there. The parity test (everything inline vs everything on stdin) and the old-vs-new fixture check reported in the intent cover that requirement. The evidence transcripts are in the evidence directory, and the worktree is clean.

Evidence: Real home: base fails with argv error, target succeeds

Source: Real home: base fails with argv error, target succeeds

$ FM_HOME=~/firstmate <base cf5bed9>/bin/fm-bearings-snapshot.sh --json
/tmp/fm-old3.yqfi/bin/fm-fleet-snapshot.sh: line 635: /usr/bin/jq: Argument list too long
fm-fleet-snapshot: main inventory summary failed
exit=

$ FM_HOME=~/firstmate <target 791a1ac>/bin/fm-bearings-snapshot.sh --json | jq '{schema, in_flight: (.in_flight|length)}'
{"schema":"fm-bearings.v1","home":"alan/firstmate","in_flight":6}
exit=
Evidence: Target bearings TOON output against ~/firstmate

Source: Target bearings TOON output against ~/firstmate

$ FM_HOME=~/firstmate bin/fm-bearings-snapshot.sh   (target 791a1ac)
schema: fm-bearings.v1
home: alan/firstmate
generated: "2026-09-13T20:24:37Z"
prs: "not_requested (run: /bearings include PRs)"
in_flight[6]{id,kind,state,doing}:
  fm-bearings-argmax,ship,working,validating (running)
  gop-stato-utenza-doc,ship,unknown,harness state unavailable (unknown missing)
  gop270-pipeline-immagine,ship,paused,MR 93 merged into its target on 2026-09-13; cleanup of this copy waits on the captain's au…
  gop274-voiceai-slots,ship,paused,MR 95 merged into test on 2026-09-10; cleanup of this copy waits on the captain's authoriz…
  gop275-port-test,ship,done,"run passed: PR merged/closed"
  ottogas-map-castel-morrone,ship,paused,MR 102 merged into test on 2026-09-12; cleanup of this copy waits on the captain's authori…
secondmates[1]{id,state,doing,provenance,freshness,age_seconds,contradiction,reason}:
  android,captain_decision,"GOP-252 MR !5: new retry path shares action=syncPosizioni with the existing push path",structured-home,fresh,0,true,"-"
decisions_open[20]{id,key,verb,summary,owner}:
  mail-clienti-php8,mail-clienti-php8,captain-hold,"Mail ai clienti sul lavoro fatto su php8: Bozza pronta in data/mail-clienti-php8/bozza.md.…",(main)
  rag-cap-fusione,rag-cap-fusione,captain-hold,"RAG: alzare i cap di fusione/rerank e rimisurare, prima di valutare un reranker esterno: m…",(main)
  gop-metrics-jsonl-conflitti,gop-metrics-jsonl-conflitti,captain-hold,"GOPlanner: tasks/model-metrics.jsonl versionato genera conflitti su ogni ramo: va deciso s…",(main)
  goplanner-clone-su-master,goplanner-clone-su-master,captain-hold,"Allineare il clone locale di GOPlanner da master a php8: il clone della flotta e' fermo su…",(main)
  fm-mrstat-gitlab,fm-mrstat-gitlab,captain-hold,"Uno strumento che legge davvero lo stato di una merge request GitLab: va deciso se costrui…",(main)
  gop62-slots-config-data,gop62-slots-config-data,captain-hold,"GOP-62: inserire le righe calendar_slots_config per lotto su sg_italgas e sg_italgas_test:…",(main)
  gop269-injection-pattern-diffuso,gop269-injection-pattern-diffuso,captain-hold,"Stesso schema di injection su date presente 21 volte in json.php, oltre l'endpoint corrett…",(main)
  jira-triage-da-rifare,jira-triage-da-rifare,captain-hold,"Ricognizione ticket Da completare da rifare: il primo tentativo ha prodotto 5 chiusure fal…",(main)
  gop270-log-mobile-infra,gop270-log-mobile-infra,captain-hold,"GOP-270: decide mobile CloudWatch fix path (infra, not app code): Root cause is infra/depl…",(main)
  gop-jira-triage-v2-calls,gop-jira-triage-v2-calls,captain-hold,"Audit Jira GOP: 6 chiamate al capitano dalla seconda passata: Report: ~/firstmate…",(main)
  gop272-followup-allowlist-tabelle,gop272-followup-allowlist-tabelle,captain-hold,"GOP-272 seguito: la lista bianca della vista a mappa puo referenziare tabelle non unite da…",(main)
  json-admin-senza-auth,json-admin-senza-auth,captain-hold,"SICUREZZA: json_admin.php raggiunge put_intervento/put_utenza/put_misurazione senza autent…",(main)
  gop242-sim-id-test,gop242-sim-id-test,captain-hold,"GOP-242 punto 2: che fare del sentinella sim_id='test': GOP-242 chiede insieme di non romp…",(main)
  gop242-scope-put-intervento,gop242-scope-put-intervento,captain-hold,"GOP-242: decidere se estendere la MR !94 ai ~20 campi ancora iniettabili di put_intervento…",(main)
  gop275-seguito-permessi-admin,gop275-seguito-permessi-admin,captain-hold,"GOP-275 seguito: json_admin.php e ora autenticato ma non ristretto agli amministratori: De…",(main)
  pulizia-postazioni-goplanner,pulizia-postazioni-goplanner,captain-hold,Autorizzare la pulizia delle copie di lavoro GOPlanner bloccate dai due residui non versio…,(main)
  rag-mcp-lavoratori,rag-mcp-lavoratori,captain-hold,"Rendere il RAG disponibile ai lavoratori nelle loro copie isolate: Il server MCP rag_qdran…",(main)
  retrospective-pp-brain-rag,retrospective-pp-brain-rag,captain-hold,"Skill retrospective: rinominare anche li' PP Brain in RAG?: Il capitano ha chiesto l'11/09…",(main)
  gop280-worker-rollout-calls,gop280-worker-rollout-calls,captain-hold,"GOP-280: due scelte del capitano dopo la prova di compatibilita' dei worker: Prova di comp…",(main)
  ottogas-campi-misuratore,ottogas-campi-misuratore,captain-hold,"Ottogas: i campi tecnici del misuratore vanno salvati nel caricamento?: Domanda rimasta ap…",(main)
landed[6]{id,what,artifact,owner}:
  gop279-endpoint-non-autenticati,"GOP-279 SICUREZZA: json_timbratori.php e api.php senza autenticazione,…","-",(main)
  android-rebase-release-line,"Rebase the release line (gestione-avvisi, 14 commits ahead, versionCod…","-",android
  ener-mms-photo-loss,Investigate whether photos can be lost on Android app after a DNS/netw…,data/ener-mms-photo-loss/report.md,android
  android-mr4-mr5-conflict-resolve,Rebase fm/gop251-android-gps-tracking-restart (MR4) onto the current m…,"-",android
  android-diagnostics-metrics,Investigate app-side diagnostic signals for a new ticket on incident-d…,data/android-diagnostics-metrics/report.md,android
  android-changelog-versioning,Automate changelog and semantic version bump for goplanner-android (An…,"-",android
gates[20]{id,title,blocked_by,reason,owner}:
  (main-inventory),in-flight backlog item has no child metadata,"-",main inventory,(main)
  chatbot-chiavi-swarm,"Indagine: perche' il chatbot su Swarm ha perso le chiavi; so…","-","Ripristino chatbot su Swarm: due guasti …",(main)
  agy,Ottimizzazione della pipeline RAG a partire dal notebook Not…,"-",Indagine completata,(main)
  in2-credenziali-ssm,"IN-2: inventario delle credenziali in chiaro e disegno del p…","-",Inventario IN-2 completo in data/in2-cre…,(main)
  gop238-pagina-esportazione,"GOP-238: pagina File > Esportazione secondo il mockup Indust…","-","MR 69 aperta e in attesa del merge: pagi…",(main)
  gop234-overlay-avviso,"GOP-234: overlay foto lato server con data avviso arretrata …","-",Superata dalla MR 64 su master. La MR ht…,(main)
  gop226-php-target,"GOP-226: Chiarire versione PHP target fra AGENTS.md e contai…","-",Consegna completata e rilievo bloccante …,(main)
  gop218-toolbar-filters,"GOP-218: Ricerca Avanzata, addToolbarFilters non si attiva m…","-","Revisione indipendente: APPROVE WITH NIT…",(main)
  gop219-advfilters-sqli,"GOP-219: SICUREZZA: adv_filters accetta nomi di campo dal cl…","-","Revisione indipendente: APPROVE",(main)
  gop233-doc-regole-stile,Documentare le regole di stile trasversali del tema Industry,"-",Correzione del rilievo bloccante gia' sp…,(main)
  gop230-ruoloservice-perf,"GOP-230: RuoloService::salva() O(n^2) sui permessi, ~150s pe…","-",In attesa del via al merge dal capitano.…,(main)
  gop227-lotti-entity,"GOP-227: gestione lotti come entita' reale (Flexigrid+modale…","-",In attesa della decisione del capitano s…,(main)
  gop228-user-modal-redesign,"GOP-228: redesign modale Dati utente - ruoli per tenant, ten…",gop227-lotti-entity,"-",(main)
  gop-ritiro-users-tipo,Ritiro progressivo di users.tipo a favore di RBAC,"-","-",(main)
  secondmate-android-charter,Proporre al capitano la lettera di incarico per un secondo u…,"android-kb-skill,android-emulator-test-scout","-",(main)
  jsoncontroller-users-sqli,"SICUREZZA: json.php?action=users permette a un admin di qual…","-","-",(main)
  infra-ticket-audit,Verificare quali dei dieci ticket di infrastruttura siano gi…,"-","-",(main)
  gop-ticket-cleanup-audit,"Verificare GOP-203, 215, 223 e 225 prima di chiuderli","-","-",(main)
  rag-parametri-rifiutati,Il RAG rifiuta le query con 'Invalid request parameters' anc…,"-","-",(main)
  gop244-campi-iniettabili,"GOP-244: ripulire q, uid, matr, gcm, coordinate mappautenti,…","-","-",(main)
reports: []
recorded_prs[5]{id,url}:
  gop-stato-utenza-doc,"https://gitlab.com/alandomio/GOPlannerWeb/-/merge_requests/83"
  gop270-pipeline-immagine,"https://gitlab.com/alandomio/GOPlannerWeb/-/merge_requests/93"
  gop274-voiceai-slots,"https://gitlab.com/alandomio/GOPlannerWeb/-/merge_requests/95"
  gop275-port-test,"https://gitlab.com/alandomio/GOPlannerWeb/-/merge_requests/98"
  ottogas-map-castel-morrone,"https://gitlab.com/alandomio/GOPlannerWeb/-/merge_requests/102"
omitted[13]{surface,reveal}:
  backlog item bodies,"--fields bodies"
  task paths,"--fields paths"
  watch/steer actions,"--fields actions"
  healthy endpoint detail,"--fields endpoints"
  full scout-report inventory,"--all-reports"
  superseded or prose-deferred queued items,"--all-queued"
  landed showing 6 of 7 (incl. 1 secondmate home(s)),"--all-landed"
  landed per-home capped at 6 for 1 home(s),"--all-landed"
  secondmate home Done capped at the snapshot layer for 1 home(s),"--all-landed"
  "main in-flight backlog item(s) have no child metadata: 2",inspect main data/backlog.md In flight vs state/*.meta
  decisions_open showing 20 of 23,"--all-decisions"
  gates showing 20 of 39,"--all-queued"
  live PR discovery + checks,"--include-prs"
exit=0
Evidence: New regression test fails on base code (reproduces original bug)

Source: New regression test fails on base code (reproduces original bug)

# new regression test run against BASE bin/ (cf5bed9)
/tmp/fm-old.8XuD/bin/fm-fleet-snapshot.sh: line 635: /usr/bin/jq: Argument list too long
fm-fleet-snapshot: main inventory summary failed
not ok - fleet snapshot failed on a backlog beyond the argv string limit
exit=
Evidence: fm-bearings-snapshot test run on target

Source: fm-bearings-snapshot test run on target

ok - a backlog deriving more than 128KB of JSON still snapshots and renders bearings
ok - values moved off argv produce byte-identical bearings output
ok - Domain Alpha structured state overrides a stale parent Phase 7 event
ok - GNU stat file reads select -c without BSD filesystem-report pollution
ok - parent activity evidence is bounded and disclosed
ok - Bearings excludes a status-only child decision
ok - a structured child captain hold reaches Captain's Call
ok - missing, invalid, unreadable, malformed, and timed-out homes stay explicit unknowns
ok - an oversized secondmate summary retains the strict empty unknown fallback
ok - secondmate and per-home child counts are bounded, disclosed, and explicitly expandable
ok - parent decisions remain untrusted contradiction evidence
ok - parent evidence reconciliation distinguishes matching holds, blocks, and decisions
ok - nonprogressing child states are explicit and inconsistent terminal rows invalidate
ok - registry unavailability and bounded truncation remain explicit
ok - repeated snapshots keep the same current landed baseline and ignore prior reports
ok - default output is bounded, local-only, and marks omitted surfaces
ok - TOON and JSON are parity representations of the same model
ok - landed includes secondmate-managed merges alongside main-home merges
ok - default landed selection balances one dominant home with sparse homes
ok - landed selection refills capacity after sparse homes exhaust
ok - landed selection uses deterministic home order when homes exceed the cap
ok - landed selection preserves deterministic home and internal tie ordering
ok - landed selection handles no landed items
ok - --all-landed keeps the complete global landed output
ok - landed stays bounded with per-home + overall caps and omitted[] disclosure
ok - Bearings keeps a live blocker in structured live state and never converts it to Charted Next queue work
ok - action-free items (working/done/queued/landed) do not leak into Captain's Call
ok - main orphan in-flight stays out of Underway and is disclosed in omitted/gates
ok - main unstructured current is disclosed while structured siblings still project
ok - counterfactual meta clears main inventory warning and projects the live task
ok - mixed secondmate roles, partial state, and captain readiness project independently
ok - main and secondmate captain actionability use the same blocker readiness
ok - a completed scout with decision-like report prose is a pointer, not pending
ok - an authoritative captain hold surfaces end-to-end
ok - current report pointers surface
ok - superseded queued items are dropped by default and restored with --all-queued
ok - --include-prs is the only path that fetches, and it enriches correctly
ok - a partial GitHub failure degrades gracefully
ok - Perl fallback bounds stalled GitHub calls without coreutils timeout
ok - all fleet-sized sections are capped with counted opt-in expansion
ok - captain-held tasks of any kind reach Captain's Call, deferral is honored, and landed excludes answered calls
ok - live PR enrichment caps repositories with counted expansion
ok - per-repository open-PR caps are disclosed with an expansion knob
ok - projection and TOON rendering failures exit nonzero with diagnostics
bash tests/fm-bearings-snapshot.test.sh  49,86s user 36,85s system 116% cpu 1:14,44 total
Evidence: fm-fleet-snapshot-view test run on target

Source: fm-fleet-snapshot-view test run on target

ok - empty fleet snapshot and view use explicit absence markers
ok - fixture snapshot covers task rows, backlog rows, pointers, and stable ordering
ok - main_inventory discloses orphan/unstructured and clears when inventory is consistent
ok - backlog normalization preserves strict roles and resolves every blocker compatibly
ok - snapshot event hints follow reconciled current state
ok - durable fold keeps an open decision past a later unrelated event
ok - a live secondmate endpoint preserves unrelated open decisions
ok - durable captain-held transfer closes the duplicate live status decision
ok - durable fold clears a decision only on a keyed resolution
ok - a completed scout's stale decision surfaces as a report pointer, not pending
ok - a scout still parked at a decision stays pending (terminal clear does not over-fire)
ok - snapshot includes durable scout reports after teardown
ok - snapshot parses tasks-axi rows and respects operational overrides
ok - fleet view renders the snapshot without secondmate peek guidance
ok - fleet view renders secondmate agent liveness

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.

  • bash tests/fm-bearings-snapshot.test.sh (all tests pass, including new test_backlog_beyond_argv_string_limit and test_stdin_spill_is_byte_identical)
  • bash tests/fm-fleet-snapshot-view.test.sh (all pass)
  • New test file run against base cf5bed9 bin/ (via git archive into /tmp): fails with fm-fleet-snapshot.sh: line 635: /usr/bin/jq: Argument list too long / main inventory summary failed
  • FM_HOME=~/firstmate bin/fm-bearings-snapshot.sh (TOON) and --json on the target: exit 0, full bearings rendered; real home's git status was the same before and after (read-only)
  • Base cf5bed9 fm-bearings-snapshot.sh and fm-fleet-snapshot.sh --json against the real home: both fail with the original argv error, so the bug reproduces on real data
  • FM_HOME=~/firstmate bin/fm-fleet-snapshot.sh --json | jq -c .backlog | wc -c: about 125KB of backlog JSON; the full snapshot is about 222KB
✅ **Document** - passed

✅ No issues found.

✅ **Lint** - passed

✅ No issues found.

✅ **Push** - passed

✅ No issues found.

Alan Domio added 3 commits September 13, 2026 22:20
A home with a ~72KB backlog.md derives more than 128KB of backlog JSON,
past the kernel's per-argument limit, so fm-fleet-snapshot.sh died with
"Argument list too long" and /bearings produced nothing.

Add bin/fm-jq-lib.sh with fm_jq: any --argjson/--arg value above
FM_JQ_INLINE_MAX (8192 chars) travels on jq's stdin and is bound with
`input as $name`, so no temp files or extra tools are needed and output
stays byte-identical. Route every data-sized jq call in
fm-fleet-snapshot.sh and fm-bearings-snapshot.sh through it.

Claude-Session: https://claude.ai/code/session_011RUQ7zuDDvfQLVcGh8Sh7b
@alandomio
alandomio merged commit c0974ec into main Sep 13, 2026
13 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant