Skip to content

fix(bin): harden operational safety checks - #67

Merged
dnth merged 4 commits into
mainfrom
fm/firstmate-port-clean-upstream-safety-fixes
Aug 28, 2026
Merged

dnth merged 4 commits into
mainfrom
fm/firstmate-port-clean-upstream-safety-fixes

Conversation

@dnth

@dnth dnth commented Aug 28, 2026

Copy link
Copy Markdown
Owner

Intent

Port four upstream Firstmate safety fixes confirmed to apply cleanly to this fork's HEAD as fork-native changes: kunchenguid#1847 (4cdd0bd), fail closed on NUL bytes in durable secondmate parent bindings; kunchenguid#2849 (801c083), require a real project clone root during fleet sync so git -C cannot walk upward into the Firstmate checkout; kunchenguid#2838 (86dd2f6), prevent documented global {TASK} replacement from corrupting the hard Herdr safety gate; and kunchenguid#2837 (266fdb9), use the platform-native stat form for busy-lock mtime to avoid false stale state and teardown refusal. Preserve each upstream PR's intent and add or extend a passing behavioral regression for every fix. Do not perform the large upstream merge, do not change ancestry, do not introduce bin/fm-control.sh, and adapt any non-clean hunk to the fork's equivalent code rather than forcing it. Keep the upstream remote read-only for source inspection. Follow firstmate-coding-guidelines for shared tracked material. Open the PR on dnth/firstmate only, never kunchenguid/firstmate, and complete the full No-Mistakes pipeline through green CI. The resulting branch must contain only these four safety ports and their tests, with no ancestry rewrite or control-plane addition.
Firstmate-Validation-Generation: 2e5d9dc7ce57eed6f80f40a510580599

What Changed

  • Reject NUL-bearing durable secondmate parent bindings and require fleet-sync targets to be actual clone roots.
  • Preserve the Herdr safety gate during global {TASK} replacement and use platform-native stat syntax for busy-lock expiry.
  • Add behavioral regressions covering all four safety fixes, including symlinked clones and stale GNU-stat locks.

Risk Assessment

✅ Low: The four linear, well-bounded safety ports satisfy the authoritative intent, preserve the required invariants, and include behavioral regressions without introducing material source risk.

Testing

Brief, busy-state, and public-followup suites passed, and the three new fleet-sync regressions passed in isolation with direct CLI evidence for all four safety behaviors. The complete fleet-sync file was also attempted but stopped at an earlier unrelated packed-refs fixture because this environment’s Git accepted the planted lock and fetched successfully; the changed clone-root cases were therefore exercised separately. Scope checks found exactly four intended commits, no control-plane addition, and no testing residue in the worktree.

Evidence: NUL parent-binding teardown refusal
teardown_result=a NUL-bearing durable parent record fails closed before cleanup
--- teardown refusal ---
●━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
●  WATCHER DOWN - SUPERVISION IS OFF
●  1 task(s) in flight, but no watcher has a fresh beacon (last beat: never, grace 300s).
●  Trust the emitted supervision protocol for this harness; do not use shell & for watcher repair.
●  This is a supervision warning only; the guarded operation WILL still run.
●  repair missing watcher supervision according to the session-start block for this harness; do not use shell &.
●━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
REFUSED: cannot resolve the primary home for marked secondmate mate; refusing cleanup without its durable parent binding.
child_metadata_preserved=yes
Evidence: Fleet-sync clone-root refusal and unchanged enclosing HEAD
Whole-fleet sync with a nested non-clone directory:
not-a-clone: skipped: not a clone root (git would act on /tmp/fm-fleet-sync-tests.xPy17I/enclosing-evidence/enclosing)
enclosing HEAD before=c6c1851d80a5e724b759c0c7ccf26836f3a8a83c
enclosing HEAD after =c6c1851d80a5e724b759c0c7ccf26836f3a8a83c
unchanged=yes

Single-project sync of the same non-clone directory:
not-a-clone: skipped: not a clone root (git would act on /tmp/fm-fleet-sync-tests.xPy17I/enclosing-evidence/enclosing)
Evidence: Herdr gate after documented global task replacement
task_body_occurrences=1
remaining_placeholders=0
--- rendered Herdr safety gate ---
# Herdr lifecycle declaration - NOT ENABLED
**HARD SAFETY GATE:** this scaffold cannot inspect the task text filled in above.
If the task will start, stop, delete, restart, profile, or otherwise drive Herdr lifecycle behavior, stop and regenerate the brief with `--herdr-lab` before dispatch.
Do not add Herdr lifecycle commands to this unguarded brief by hand.
Evidence: GNU-stat stale-lock retirement state
before_retire:
task1.busy-gen
task1.busy-state
task1.busy-state.lock
retire_exit=0
after_retire:
repeat_retire_exit=0
Evidence: Isolated fleet-sync clone-root regressions
ok - a non-repo directory under projects/ never fast-forwards the enclosing repo
ok - the single-project form also refuses a directory that is not its own clone root
ok - the clone-root guard accepts a symlinked clone directory
Evidence: Brief regression suite
ok - fm-brief.sh: bash -n succeeds
/tmp/fm-brief.yoaPca/heredoc-in-substitution.sh:2
ok - fm-brief.sh: no heredoc is nested inside a command substitution (Bash 3.2 parse-safe)
ok - fm-brief.sh: --help renders the complete header
ok - fm-brief.sh: no-mistakes/direct-PR/local-only briefs generate cleanly
ok - fm-brief.sh: ship --mode is required and closed-set validated
ok - fm-brief.sh: the explicit ship mode wins over the registered posture
ok - fm-brief.sh: --yolo and scout/secondmate --mode are refused, never silently dropped
ok - fm-brief.sh: faster paths use configured authority without stacked review
ok - fm-brief.sh: no-mistakes DOD keeps its apostrophe prose, now parse-safe
ok - fm-brief.sh: ship project-memory wording carries the AGENTS.md authoring bar
ok - fm-brief.sh: --herdr-lab emits the complete hard safety contract
ok - fm-brief.sh: --herdr-lab uses its quoted Firstmate-owned helper path
ok - fm-brief.sh: ship and scout scaffolds make omitted Herdr intent fail-visible
ok - fm-brief.sh: the documented {TASK} fill cannot corrupt the Herdr safety gate
ok - fm-brief.sh: Herdr lab contract covers scouts and rejects secondmate misuse
ok - fm-brief.sh: --no-projects scaffolds a project-less charter and guards misuse
ok - fm-brief.sh: marked requests avoid generic acknowledgements and preserve material reporting
ok - fm-brief.sh: relative directory inputs ignore CDPATH, render stable absolute charter paths, or fail loudly
ok - fm-brief.sh: custom pause verb renders in every scaffold
ok - fm-brief.sh: investigation and visual-review completions load the shared decision policy
ok - fm-brief: scout and secondmate code paths still scaffold well-formed briefs
ok - fm-brief: concurrent ship scaffolds preserve one complete owner
ok - fm-brief: ship evidence publication is atomic and retryable
Evidence: Busy-state regression suite
ok - arm mints a gen sidecar and seeds busy fm-spawn at seq=1
ok - apply advances seq under the armed gen and attributes the writing source
ok - firstmate-owned interrupt and recovery events bind to the current gen
ok - apply is refused for a task whose busy contract was never armed
ok - retire waits for the writer lock and cannot remove a new incarnation
ok - retire treats only an absent sidecar as already retired
ok - the writer breaks a stale lock instead of dying on GNU stat output
ok - a late event from a previous incarnation is rejected, record unchanged
ok - a record from a stale incarnation classifies unknown, never idle
ok - a converted adapter with no record classifies unknown, never idle
ok - malformed records classify unknown malformed, never busy or idle
ok - a record with no armed gen sidecar classifies unknown
ok - a record is trusted only by the adapter whose source wrote it
ok - converted adapters never classify busy from rendered footer text
ok - the grok fallback is regex-scoped to grok and classifies only grok tasks
ok - codex classifies unknown until a semantic source passes its verification gate
ok - standalone kimi classifies unknown until the live verification gate opens
ok - endpoint death is the only process-level override and yields dead, never busy
ok - herdr's native verdict is trusted for busy only, and records outrank it
ok - record parsing never clobbers the caller's positional parameters, glob setting, or fields
ok - the boolean view reports busy only on an exact busy verdict
all fm-busy-state tests passed
Evidence: Public-followup and teardown regression suite
ok - outcome text is collapsed to one line, bounded by codepoint, and never corrupts characters
ok - restart end-to-end: typed result reconciles from disk and delivers one reply to the original thread
ok - duplicate terminal results, restart replay, and repeated delivery are all no-ops
ok - wrong source, wrong work id, stale generation, malformed, unsupported deliverable, and forged identity are all refused
ok - a relay transport failure is held as retryable with no false completion, and the retry posts once
ok - a dry-run records no public delivery and leaves the commitment retryable
ok - a late success receipt closes the exact attempt with no second post, and a mismatched attempt is refused
ok - typed terminal cleanup clears the legacy link without posting
ok - a delivery interrupted between post and receipt refuses to repost
ok - a child home reports typed results but can never become the outward-post owner
ok - typed delivery refuses to post when its cleanup registration is missing
ok - marked secondmate teardown resolves its parent and fails closed when unavailable
ok - local seeding publishes durable parent state before its identity marker
ok - a lost launch-time parent binding is recovered from the durable local record
ok - a durable local parent record does not bypass a genuinely missing parent-side registration
ok - unknown durable parent fields remain forward-compatible
ok - conflicting live and durable parent bindings fail closed
ok - unsafe durable parent records fail closed before cleanup
ok - a NUL-bearing durable parent record fails closed before cleanup
ok - relay-disabled unmarked teardown runs no public-followup work
ok - a marked child proceeds without tasks-axi when its parent relay is disabled
ok - secondmate parent resolution matches the durable registry id literally
ok - traversal-shaped registrations are rejected before path construction or posting
ok - pending keeps registrations when tasks-axi returns malformed JSON
ok - the retained private request context keeps the original thread deliverable after inbox cleanup
ok - cleanup refuses while a public reply is owed and proceeds once it has landed
ok - a relay-disabled home runs no tasks-axi call, prints nothing, and gains no artifact
ok - a relay-enabled home with no commitments makes no backlog call and stays silent
ok - a relay-exhausted follow-up binding is escalated rather than retried into the thread
ok - the relay poll stays inert without a token, silent with no commitments, and surfaces a new result once
ok - startup surfaces unresolved public commitments only in a relay home that owes one
ok - typed public-followup records carry only public-safe summaries and deliverables

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.

  • tests/fm-brief.test.sh
  • tests/fm-busy-state.test.sh
  • tests/fm-public-followup.test.sh
  • Isolated test_non_clone_dir_never_syncs_the_enclosing_repo, test_non_clone_dir_named_directly_never_syncs_the_enclosing_repo, and test_symlinked_clone_still_syncs from tests/fm-fleet-sync.test.sh
  • Generated a real brief with bin/fm-brief.sh, globally replaced {TASK}, and recorded the rendered Herdr gate plus occurrence counts
  • Invoked bin/fm-busy-event.sh arm/retire with deterministic Linux/GNU-stat shims and recorded pre/post persisted state and idempotent retry
  • Invoked bin/fm-fleet-sync.sh in whole-fleet and single-project forms against a nested non-clone, recording the refusal and identical enclosing HEAD hashes
  • Executed teardown with a NUL-bearing durable secondmate parent record, recording the explicit refusal and preserved child metadata
  • git diff --name-only 23dbd0fe36cde3a33f931d1a688b984362b385a3..53e5f6b498953b0c80a78d332cd09632e6fb6129, git rev-list --count ..., test ! -e bin/fm-control.sh, and git status --short
✅ **Document** - passed

✅ No issues found.

✅ **Lint** - passed

✅ No issues found.

✅ **Push** - passed

✅ No issues found.

kunchenguid and others added 4 commits August 28, 2026 10:09
…chenguid#1847)

fm_secondmate_parent_record_parse read the .fm-secondmate-parent record
with bash's read, which drops NUL bytes - and different bash generations
disagree on the result: 3.2 truncates the value at the NUL while 5.x
splices the surrounding bytes together. A NUL-bearing parent_home could
therefore resolve to a home the record's bytes never name contiguously,
and which home fm-teardown.sh's promised-public-reply resolution read
(registration, registry, relay state) - or whether that protection
engaged at all - depended on which interpreter ran the cleanup.
Reproduced end to end: the same NUL-bearing record cleaned up under bash
5.x by resolving the spliced-together registered parent, while bash 3.2
refused it as unresolved, and a literal truncated path refused under
both.

Reject any NUL byte in the record before field parsing, putting corrupt
records in the same fail-closed bucket as duplicate fields, malformed
local bindings, unsupported routes, and symlinked records. The
regression test drives the real bin/fm-teardown.sh over the proven
clean-cleanup fixture with a NUL spliced mid-path into the recorded
parent_home, so before the fix it reproduced the wrong-home cleanup and
now it must refuse with the explicit binding refusal.

(cherry picked from commit 4cdd0bd)
…2849)

* fix(bin): require a clone root before fleet-sync touches a project

Git repository discovery walks upward, so `git -C projects/<dir>` on a plain
directory nested under projects/ resolves to the enclosing repository - in a
firstmate home, the firstmate checkout itself. fm-fleet-sync.sh guarded its
candidates with `rev-parse --is-inside-work-tree`, which such a directory
passes, so every later git call read, pruned and fast-forwarded firstmate's own
default branch and reported it under the project directory's label. A running
session's AGENTS.md changed underneath it, and the report named a project that
had nothing to do with the change.

Require each candidate to be the root of its own work tree before any other git
command: compare `rev-parse --show-toplevel` against the directory's own
physical path. Both sides are physical, so a symlinked clone still compares
equal. Anything else is skipped by name, naming the repository that would have
been touched, and bootstrap relays that as a FLEET_SYNC line.

Regression coverage reproduces the wrong-repo fast-forward against a home nested
inside another repository, in both the whole-fleet and single-project forms, and
pins that a symlinked clone dir still syncs.

* no-mistakes(review): Keep enclosing fixture clean during clone-root regression

(cherry picked from commit 801c083)
… gate (kunchenguid#2838)

The unguarded Herdr declaration quoted `{TASK}` in its own prose while the
scaffold instructs firstmate to replace every `{TASK}` placeholder. The
documented global replace therefore spliced the whole task body into the
middle of the safety gate's sentence, silently destroying the one contract
that exists precisely because the scaffold cannot inspect the task text.

Reword the gate to refer to the task text filled in above, leaving the
placeholder only at its genuine fill site. Rewording rather than renaming the
token keeps the unfilled-charter guards in fm-home-seed.sh and
fm-remote-home-seed.sh working unchanged.

Add a regression test that performs the documented global fill on ship and
scout scaffolds and asserts the body lands once and the gate survives.

(cherry picked from commit 86dd2f6)
…tat form (kunchenguid#2837)

The writer lock's stale-lock branch read the lock's mtime with
`stat -f %m ... || stat -c %Y ...`. On GNU coreutils `-f` is filesystem
stat, so it consumed the format string as a path, complained on stderr,
printed a partial filesystem dump ("  File: ...") on stdout, and still
exited 0. The GNU form in the fallback therefore never ran, and the
following arithmetic evaluated the word `File`, aborting the writer under
`set -u` with "File: unbound variable".

fm-teardown.sh died there after returning the worktree, leaving
state/<id>.meta, .status, .busy-gen, .busy-state, .busy-state.lock/ and
.turn-ended behind. The surviving metadata kept the watcher monitoring an
endpoint whose agent was gone, so a finished task produced stale wakes
forever, and every re-run died identically because the abandoned lock was
never broken.

Detect the platform once and pick the right stat form, the pattern
bin/fm-watch.sh already documents, and treat any non-numeric result as
"just created" so a future portability surprise degrades to a lock-timeout
refusal rather than killing teardown mid-way.

(cherry picked from commit 266fdb9)
@dnth
dnth merged commit e90715c into main Aug 28, 2026
15 checks passed
@dnth
dnth deleted the fm/firstmate-port-clean-upstream-safety-fixes branch August 28, 2026 07:21
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.

3 participants