Repository navigation
fix(bin): parse punctuated secondmate registry entries safely - #1452
Merged
Merged
Conversation
quinnbot-ai
pushed a commit
to quinnbot-ai/firstmate
that referenced
this pull request
Aug 1, 2026
…nguid#1452) * fix: centralize secondmate registry parsing * no-mistakes(review): Centralize secondmate registry binding validation * no-mistakes(review): Harden registry EOF and symlink validation * no-mistakes(review): Reject unreadable registries before parsing * no-mistakes(document): Document punctuation-safe secondmate registry validation * no-mistakes: apply CI fixes
quinnbot-ai
added a commit
to quinnbot-ai/firstmate
that referenced
this pull request
Aug 1, 2026
) * test: stabilize tmux teardown conformance baseline (kunchenguid#1209) * fix(test): pin teardown tmux baseline to historical kill selectors merge-base HEAD main collapses to HEAD after the exact-selector change lands on the default branch, so the old teardown fixture was accidentally exercising current exact targets. Resolve a content-historical permissive tmux adapter from first-parent history and force that post-squash topology inside the conformance case so main and feature branches keep the same old-vs-new contract. * no-mistakes(lint): Suppress intentional literal-pattern ShellCheck warnings * fix(bin): normalize relative durable paths (kunchenguid#1256) * fix(bin): handle dash-leading harness process names (#2) * fix: handle dash-leading harness process names * no-mistakes(review): Make dash-leading harness regression hermetic * fix: preserve secondmate reply routes across relative homes Resolve relative home, data, and state inputs before durable charter generation, and fail when caller-relative directories cannot be resolved. Use absolute paths at the related spawn, AFK daemon, and X-mode cross-process handoffs so later processes cannot reinterpret them from another working directory. * no-mistakes(review): Preserve absolute overrides and normalize relative durable paths * no-mistakes(review): Normalize relative home before deriving durable paths * no-mistakes(document): Document relative durable-path normalization * no-mistakes(review): Captain: Ignore inherited CDPATH during relative path normalization * no-mistakes(lint): Fix empty CDPATH assignments for ShellCheck * refactor(skills): make Bearings chat-only by default (kunchenguid#1136) * Add internal status skill * no-mistakes(document): register /status skill in documentation-audiences inventory * no-mistakes(lint): replace grep|wc -l with grep -c in status skill test * test: silence literal status skill patterns * Refactor bearings default to chat-only --------- Co-authored-by: Kun Chen <[email protected]> * test: replace source assertions with behavioral coverage (kunchenguid#1282) * test: remove source-content assertions * no-mistakes(review): Replace source assertions with runtime behavior coverage * no-mistakes(review): Isolate Kimi task temp runtime coverage * no-mistakes(document): Refresh test cleanup documentation * no-mistakes: apply CI fixes * fix(gitignore): ignore config/ as a directory, not by exact filename (kunchenguid#1261) A name-by-name list of config/ entries silently stops ignoring any new or home-local file placed there, which makes the working tree read as dirty and blocks guarded sync paths that refuse to touch a dirty home. AGENTS.md already documents config/ as captain-private and gitignored as a category; this makes .gitignore match that contract. * fix(tests): replace source-content .gitignore assertion with behavioral coverage (kunchenguid#1304) The second assertion in fm-gitignore-config.test.sh (added by kunchenguid#1261) greps .gitignore for a specific spelling of the config/ ignore pattern. It fails on a semantically equivalent pattern like config/** and does not prove Git actually ignores anything, per the completed source-content-test audit. Replace it with a real git check-ignore control test on a generated unrelated path, and strengthen the existing directory-coverage test with generated unpredictable direct and nested config/ paths. * feat: bound and consolidate startup memory during stow (kunchenguid#1303) * Add bounded startup memory curation * no-mistakes(review): Record reproducible stow verification evidence * no-mistakes(review): Validate inherited secondmate stow evidence * no-mistakes(document): Document editable startup-memory budget propagation * fix(herdr): place workers in the launching workspace (kunchenguid#1328) * fix(herdr): place workers in the launching agent's exact workspace Herdr enforces no workspace-label uniqueness, and spawn resolved its container by taking the FIRST workspace whose label matched the home label. With two workspaces both labeled "firstmate", a worker launched from the second one was created in the first, so it appeared in a different space than the Firstmate the captain was watching. Reproduced end to end on Herdr 0.7.5 protocol 17 by running the real bin/fm-spawn.sh inside a launcher pane in the second "firstmate" workspace: the worker landed in w1 while its launcher was in w2, with an unrelated third workspace focused throughout, which also rules out any dependence on the focused workspace. Placement now binds to the launching process's own Herdr identity. Herdr injects HERDR_PANE_ID, HERDR_SESSION, and HERDR_SOCKET_PATH into every process it manages a pane for, and fm_backend_herdr_launcher_identity resolves that pane's current owning tab and workspace live from Herdr, cross-checking the pane against its tab and confirming the workspace exists exactly once in the session. The injected HERDR_TAB_ID and HERDR_WORKSPACE_ID are creation-time snapshots and are deliberately not read as current identity. Labels are no longer placement authority. A claimed parent identity that is unreadable, contradictory, stale, or from another named session or Herdr server stops the spawn before any worker endpoint exists, rather than degrading to a label search. A launcher with no Herdr ancestry has no workspace to inherit and keeps the per-home labeled container, which must now resolve to exactly one workspace; two same-labeled candidates refuse instead of adopting either. A --secondmate launch keeps standing up that home's own workspace by design. With presentation spaces enabled, the projected child is created and bound under that same exact parent and anchors its ordering on it, so a duplicated home label no longer makes the layout ambiguous. Projection, focus restoration, restart binding, and quarantine rules are unchanged, and children are never collapsed into the parent. tmux, Zellij, cmux, Orca, and the away-mode daemon terminal were each inspected and are not affected: none resolves a container by searching mutable labels. tests/fm-backend-herdr-launcher-workspace-e2e.test.sh drives the real spawn and teardown against an isolated Herdr lab, with its headline case running fm-spawn.sh inside a real Herdr pane so the identity comes from Herdr's own injection. The refusal matrix and the ordering anchor are covered deterministically in tests/fm-backend-herdr.test.sh. Eight existing real-Herdr suites inherited the developer terminal's own Herdr pane into their isolated lab sessions, which the new cross-session check correctly refuses. tests/herdr-test-safety.sh now owns herdr_forget_inherited_pane and those suites call it, so what they assert no longer depends on where they were launched from. Two unrelated fixes found along the way. tests/fm-secondmate-harness.test.sh had the same class of environment leak through CLAUDECODE, which outranks PI_CODING_AGENT in bin/fm-harness.sh and made its pi-signed ancestry case resolve "claude" whenever the suite ran inside Claude Code. And fm-spawn.sh's usage() printed a fixed line range that had already been truncating its own help mid-sentence. * no-mistakes(review): Enforce exact Herdr launcher and projection identity * no-mistakes(document): Document exact Herdr launcher workspace placement * fix(calm): refine Calm working boat animation (kunchenguid#1339) * feat(calm): replace Pi's working row with an animated ship while Calm is on While Calm is active and one logical agent run is under way, Calm now hides Pi's built-in working row and renders a small two-row SSHHIP-derived boat in its place. When Calm is off, Pi's stock working row is left untouched. The presentation uses only public Pi extension API: setWorkingVisible(false) plus a temporary setWidget() component whose render(width) owns the responsive geometry and whose timer requests a TUI render. Visibility follows agent_start through agent_settled, so the boat does not flicker between tool calls, automatic continuations, retries, or compaction inside the same run, and settle, abort, and failure all reach the same cleanup. fm-calm.ts stays the sole owner of the presentation choice and the only caller of setWorkingVisible(); the new lib owns the sprite geometry and widget. * no-mistakes(review): Guarded Calm-off lifecycle visibility writes; focused tests pass * no-mistakes(test): Fixed Calm E2E wait to include tmux scrollback * no-mistakes(document): Document Calm working boat behavior * no-mistakes: apply CI fixes * feat(calm): slow the Calm boat, animate blue water, and make the sail directional The boat now moves one column every 880ms while a bounded fixed-cell water phase advances every 220ms, so the water ripples several times between boat steps and the presentation reads as calm. One scheduler drives both clocks and disposing the widget stops them together; ticks rather than wall-clock timestamps drive every state change, so tests seek animation time exactly. Colors are standard ANSI foreground codes instead of theme lookups: blue for every water cell and yellow for the complete boat, each run closed with a default-foreground reset so nothing bleeds into padding or later frames. ANSI bytes never enter geometry, so visible width stays exact. The mainsail is directional and trails aft of the mast: <| travelling right and |> travelling left. Direction reverses the moment the boat lands on an endpoint, so the endpoint frame already shows the new heading and no frame at or after a bounce shows the previous sail. * test(calm): wait for the Ctrl+O expansion redraw this block asserts * docs(calm): record the revised working-presentation verification evidence * no-mistakes(document): Fix Calm feasibility document EOF whitespace * fix(dispatch): preflight candidate auth before quota escalation (kunchenguid#1349) * fix(dispatch): scope candidate authentication to its own surface A locally expired timestamp in one credential store was reported to the captain as a sign-out, including for dispatch candidates that never read that store. A `harness=pi, model=xai/grok-*` candidate authenticates through Pi's own xAI credential, but the only Grok quota reading available was gated on the standalone Grok CLI's separate token, whose expiry clock drifts independently. The always-loaded intake rule then turned that unreadable quota into a mandatory captain escalation. Add `bin/fm-auth-preflight.sh` as the deterministic owner of the parts that must not depend on agent memory: it resolves a tuple's authentication surface from quota-axi's own emitted auth sources rather than from a harness or model name, so another harness's CLI can never gate a candidate that does not use it. A vendor CLI is launched only when the tuple's own harness owns the credential store under test and a non-destructive discovery command is registered for it, which today is `grok models` alone. That probe runs at most once with stdin closed and a hard timeout, reads its verdict from the first stdout line because the command exits 0 either way, treats unrecognized output as indeterminate, and never invokes login, logout, or the interactive TUI. Quota is read at most twice, and unknown headroom never makes a candidate ineligible on its own. Update the dispatch procedure to match: usable authentication with unmeasurable headroom stays eligible at lower preference with the unknown disclosed, and stop-and-report is reserved for unresolved authentication, an unresolved relationship, or malformed configuration. Record that Grok's `credits.remaining` is a prepaid balance rather than window headroom. Gate quota-axi at 0.1.16 in bootstrap, the first build reporting per-credential auth sources. A stale install previously passed the presence check silently, which is why a fix published two days earlier was still not in effect. Replace the orphaned quota-array-dispatch fixtures, which encoded a `provider: "xai"` shape the tool never emits and had no consumer, with fixtures shaped like real 0.1.16 output that the new suite drives the script against. The suite asserts the verdict and, separately, which vendor CLIs were launched, so a Pi/xAI candidate reaching the Grok CLI fails. Map `tests/fixtures/<dir>` to its consuming suite so a fixture change selects the right tests instead of refusing. * refactor(bootstrap): give the quota-axi floor one owner The floor was stated twice - once in bootstrap's gate and once inline in the auth preflight - so bumping it needed two edits that could drift. Move it to bin/fm-quota-axi-lib.sh alongside its rationale, matching the existing tasks-axi library, and derive the comparison from the constant so the number appears exactly once. Bootstrap turns a failing check into the operator diagnostic; the preflight refuses to emit an unscoped verdict. Map the new library to both consuming suites so a bump re-runs them, and record that any usable source means the surface authenticates. * no-mistakes(review): Captain: bound quota checks and removed Python dependency * no-mistakes(review): Captain: enforce conservative headroom and exact preflight retry * no-mistakes(review): Captain: preserve OpenCode eligibility without auth-surface guessing * no-mistakes(review): Captain: reject malformed OpenCode model relationships * no-mistakes(review): Captain: exempt verified unmodeled tuples from intake escalation * no-mistakes(document): Updated dispatch authentication documentation * no-mistakes: apply CI fixes * feat(x-mode): reconcile promised public replies deterministically (kunchenguid#1350) * feat(x-mode): reconcile promised public replies deterministically A promised final reply in an X or Discord thread was only kept while the primary remembered it. Compaction or restart erased that memory, so a typed public-followup obligation could sit at pending-work after its PR merged and the original thread never got its reply. Make the promise durable state instead: - bin/fm-public-followup-emit.sh reports a typed terminal work result (source home, work id, generation, outcome, safe deliverables, bounded public-safe text) into the owning home's private inbox. The event id is derived from that identity tuple, so duplicate reports and restart replay converge with no coordination, and nothing ever parses a free-form done: sentence. - bin/fm-public-followup.sh registers a commitment, reconciles events through tasks-axi public-followup, and runs the idempotent delivery sequence (begin-delivery with the payload hash, post, record the posted receipt or a typed error) against the stored platform and opaque thread binding. A delivery interrupted between post and receipt refuses rather than risk a second public reply. - Session start surfaces unresolved commitments from disk, the existing relay poll surfaces a new terminal-result set once
Intent
Fix the shared secondmate-registry parsing contract so valid natural-language punctuation cannot break guarded operations.
Before editing, reproduce the landed child-cleanup failure through end-user public interfaces using an isolated fixture with an earlier parenthetical in a valid registered secondmate summary and parentheses plus semicolons in natural-language scope before the explicit structured suffix ends. Exercise guarded fm-teardown.sh child cleanup while a durable parent public-followup binding requires resolving the main home data/secondmates.md record. Show the old parser returns no home and cleanup refuses despite matching registered home and task metadata. Separate the punctuation trigger, the simple parser-compatible registry line that masks it, and the visible cleanup refusal. Confirm fm-home-seed.sh validate accepted the same operationally unparseable record. Do not mutate a real home, public reply, or existing task during reproduction.
Fix parsing so generated structured fields resolve from their explicit suffix rather than the first parenthesis or first incidental semicolon. Audit every duplicated secondmate-registry parser in fm-home-seed.sh, fm-spawn.sh, fm-teardown.sh, and shared helpers. Use one authoritative parser owner where appropriate under the one-owner rule, with callers sharing validation and refusal behavior. Make validation reject every record operational consumers cannot parse. Preserve refusal without mutation for malformed, duplicate, ambiguous, unsafe, or identity-mismatched records. Do not weaken cleanup, public-followup, home identity, symlink, force, discard, or unlanded-work safeguards.
Inspect divergent parsing paths and relevant history, test the punctuation counterfactual against the simple line, and seek disconfirming evidence before settling on the cause. Add executable regressions through public interfaces for home and project resolution, secondmate spawn or validation where relevant, and the exact guarded child-cleanup path that failed. Use isolated fixtures and never assert implementation source bytes.
Run focused and full relevant tests, bin/fm-lint.sh, bin/fm-doc-audience-check.sh where maintained prose changes, and the complete configured no-mistakes pipeline. Preserve this complete task-specific contract and all accepted follow-ups in this intent, excluding generic scaffold boilerplate.
This task is independent of the intent-handoff change and PR 1446. Do not change, synchronize, recover, resume, validate, or merge either unrelated task, either PR 1446 validation run, or any preserved PR 1446 head.
What Changed
Risk Assessment
✅ Low: The shared parser now snapshots only a successfully and fully read regular registry, handles unterminated final records, rejects symlinks and ambiguous bindings, and validates identity before spawn or teardown mutation with matching public-interface regressions.
Testing
Inspected the parser consolidation and history, ran five focused relevant suites covering public-followup cleanup, secondmate safety, project handoff, registry-backed updates, and fleet snapshots, then manually exercised the punctuation-bearing guarded child-cleanup path. All checks passed, and the CLI evidence shows correct parent resolution, refusal for the owed reply, and preservation without mutation.
Evidence: Punctuated registry guarded-cleanup transcript
Punctuation-bearing registry validation: accepted. Guarded teardown: refused because work-child still owes public commitment pf-teardown-valid. Child metadata and identity marker preserved; parent registry unchanged; no endpoint kill requested.Pipeline
Updates from git push no-mistakes
✅ **intent** - passed
✅ No issues found.
✅ **Rebase** - passed
✅ No issues found.
🔧 **Review** - 2 issues found → auto-fixed (3) ✅
bin/fm-teardown.sh:899- Intent requires: “Preserve refusal without mutation for malformed, duplicate, ambiguous, unsafe, or identity-mismatched records.” This loop rejects malformed syntax but never proves a unique ID-to-home binding. Registries containingA -> HplusB -> H, orA -> HplusA -> H2, pass teardown preflight when H2 is unrelated. Teardown can then delete H and either leave B pointing at a deleted home or remove both A records. Move whole-registry uniqueness validation and the expected ID/home match to a shared pre-removal boundary.bin/fm-spawn.sh:569- Intent requires callers to share refusal behavior for duplicate, ambiguous, and identity-mismatched records. The shared lookup now returns failure for malformed or duplicate matching records, but secondmate spawn bypasses home lookup when an explicit or metadata home exists, and its projects lookup failure is swallowed. Consequentlyfm-spawn <id> <home> ... --secondmatecan create an endpoint and metadata despite a duplicate registry ID or a registry home that disagrees with the supplied home. Resolve one unique registry record and compare its canonical home before any spawn mutation.🔧 Fix: Centralize secondmate registry binding validation
2 errors still open:
bin/fm-secondmate-registry-lib.sh:99- Intent requires refusal for every malformed or duplicate record. The new authoritative loop drops a final record when the file lacks a trailing newline becausereadassigns the text but returns nonzero before executing the body. A validA -> Hline followed by an unterminated duplicateA -> H2is therefore accepted, allowing spawn or teardown mutation under the same ambiguity this boundary is meant to reject. Process the final nonempty read withwhile read ... || [ -n "$line" ].bin/fm-home-seed.sh:230- Intent says: “Do not weaken ... symlink ... safeguards.” The new wrapper treats any path failing-fas an absent registry, so a brokendata/secondmates.mdsymlink bypasses the shared validator even though that validator explicitly rejects symlinks.fm-home-seed.sh validatereports success, and a seed can later replace the unsafe symlink after other provisioning mutations. Distinguish a genuinely absent path from[ -L "$REG" ]and refuse the symlink before mutation.🔧 Fix: Harden registry EOF and symlink validation
1 error still open:
bin/fm-secondmate-registry-lib.sh:91- Intent requires: “Make validation reject every record operational consumers cannot parse.” This boundary checks only file type and symlink status. If a regular registry cannot be opened for reading, the redirected loop processes zero records and an expected-ID-freefm-home-seed.sh validatereaches success with an empty temporary table. Explicitly open the registry before validation and convert any open/read failure intoSECONDMATE_REGISTRY_ERROR.🔧 Fix: Reject unreadable registries before parsing
✅ Re-checked - no issues remain.
✅ **Test** - passed
✅ No issues found.
Inspectedgit diffand relevant history from68641a33c25e220ab3cab6cafe84eff971008714throughcb222b3a4d93c35d68e2477b11d3dfc7f7511751.tests/fm-public-followup.test.shtests/fm-secondmate-safety.test.shtests/fm-backlog-handoff.test.shtests/fm-update.test.shtests/fm-bearings-snapshot.test.shRan the isolatedtest_secondmate_teardown_requires_parent_bindingfixture and recorded validation, teardown refusal, preserved durable state, and absence of endpoint mutation.✅ **Document** - passed
✅ No issues found.
✅ **Lint** - passed
✅ No issues found.
✅ **Push** - passed
✅ No issues found.