Repository navigation
feat(bin): add deterministic agent lifecycle control - #1568
Merged
Merged
Conversation
Separate firstmate's data plane from its control plane. bin/fm-send.sh is the data plane: conversational text, always routing-marked for a kind=secondmate target. That marking is right for a message and wrong for a lifecycle command - a marked "/quit" arrives as ordinary chat the agent reasons about instead of executing. bin/fm-control.sh is the control plane: allowlisted interrupt, exit, and transactional relaunch verbs addressed to an exact task id, with per-harness mechanics owned by the executable bin/fm-control-lib.sh rather than improvised in agent prose, and a verified postcondition for every action. There is no arbitrary-text and no raw-key entry point. relaunch runs as a transaction with a durable journal: it resolves the profile, proves the work it must preserve is recoverable, records the required progress note, stops the old agent, then delegates the launch to its single owner, bin/fm-spawn.sh --relaunch, which adopts the recorded endpoint and worktree instead of creating either. A refusal before the stop leaves the record and instructions byte-identical; a failure after it reports the concrete state rather than claiming an agent that is not running. Teardown and discard stay separate and explicit. exit and relaunch require a backend with a recovery-grade agent-state classifier, so zellij, orca, and cmux are refused rather than reported as successful blind. A remotely placed secondmate is refused by name, because its agent runs on a host where none of these postconditions can be read.
…ng wiring fm-spawn arms per-task harness wiring on prefixes, because a task launched from a raw command records that command's basename rather than the exact adapter name. The control plane's retirement tables are keyed by the exact adapter, so a task recorded as `grok-2` had its turn-end token, private registry entry, and worktree hook pointer armed and never retired - leaving a registry entry that outlived the agent that owned it. State the prefix rule once, in the capability owner, and resolve the recorded value through it before every table lookup. bin/fm-send.sh's composer-clear lookup reads the same owner instead of keeping its own copy of which adapters need one.
kunchenguid
force-pushed
the
fm/fm-agent-lifecycle-control-r1
branch
from
August 8, 2026 08:27
7df16ef to
5a9db57
Compare
Forced secondmate teardown enumerated a home's task set, locked what it found, then re-enumerated while removing. A fresh spawn takes only its own per-task lock, so a record published inside that window was invisible to the preflight and visible to the cleanup: it was destructively processed while never lifecycle-locked. Reproduced with real agents. A record published 0.249s after teardown began was removed, its window closed, and its worktree returned to the pool - while both commands reported success. A per-task lock cannot protect a task that does not exist yet. Add a per-home task-set lock guarding WHICH tasks a home has, as opposed to the metadata lock guarding one task's record. Teardown takes it per home, parent before child, before enumerating and holds it through cleanup. A fresh spawn takes it before its own per-task locks and holds it through publication; a relaunch is exempt, because it republishes an existing task already covered by that task's control lock. Either the spawn publishes first and the teardown's preflight covers it, or the teardown owns the set and the spawn refuses. Both directions fail closed, and both are pinned by tests that hold the lock rather than racing on timing.
blazingbunny
pushed a commit
to blazingbunny/firstmate
that referenced
this pull request
Aug 9, 2026
* feat(bin): add deterministic agent lifecycle control Separate firstmate's data plane from its control plane. bin/fm-send.sh is the data plane: conversational text, always routing-marked for a kind=secondmate target. That marking is right for a message and wrong for a lifecycle command - a marked "/quit" arrives as ordinary chat the agent reasons about instead of executing. bin/fm-control.sh is the control plane: allowlisted interrupt, exit, and transactional relaunch verbs addressed to an exact task id, with per-harness mechanics owned by the executable bin/fm-control-lib.sh rather than improvised in agent prose, and a verified postcondition for every action. There is no arbitrary-text and no raw-key entry point. relaunch runs as a transaction with a durable journal: it resolves the profile, proves the work it must preserve is recoverable, records the required progress note, stops the old agent, then delegates the launch to its single owner, bin/fm-spawn.sh --relaunch, which adopts the recorded endpoint and worktree instead of creating either. A refusal before the stop leaves the record and instructions byte-identical; a failure after it reports the concrete state rather than claiming an agent that is not running. Teardown and discard stay separate and explicit. exit and relaunch require a backend with a recovery-grade agent-state classifier, so zellij, orca, and cmux are refused rather than reported as successful blind. A remotely placed secondmate is refused by name, because its agent runs on a host where none of these postconditions can be read. * fix(control): resolve a recorded harness to its adapter before retiring wiring fm-spawn arms per-task harness wiring on prefixes, because a task launched from a raw command records that command's basename rather than the exact adapter name. The control plane's retirement tables are keyed by the exact adapter, so a task recorded as `grok-2` had its turn-end token, private registry entry, and worktree hook pointer armed and never retired - leaving a registry entry that outlived the agent that owned it. State the prefix rule once, in the capability owner, and resolve the recorded value through it before every table lookup. bin/fm-send.sh's composer-clear lookup reads the same owner instead of keeping its own copy of which adapters need one. * test(control): pin muse session-binding retirement across a harness switch * no-mistakes(review): Resolve prefixed harnesses across lifecycle control verbs * no-mistakes(review): Report interrupt delivery without fabricating cancellation state * no-mistakes(review): Clear disabled relaunch trace context atomically * no-mistakes(review): Clarify control interrupts and restore legacy send state * no-mistakes(review): Refuse ambiguous relaunches and report exit delivery * no-mistakes(review): Revalidate interrupts and accept interrupt-stopped exits * no-mistakes(review): Lock descendant tasks before forced recursive teardown * no-mistakes(document): Align lifecycle adapter documentation with control plane * no-mistakes: apply CI fixes * fix(bin): serialize fresh task publication with forced teardown Forced secondmate teardown enumerated a home's task set, locked what it found, then re-enumerated while removing. A fresh spawn takes only its own per-task lock, so a record published inside that window was invisible to the preflight and visible to the cleanup: it was destructively processed while never lifecycle-locked. Reproduced with real agents. A record published 0.249s after teardown began was removed, its window closed, and its worktree returned to the pool - while both commands reported success. A per-task lock cannot protect a task that does not exist yet. Add a per-home task-set lock guarding WHICH tasks a home has, as opposed to the metadata lock guarding one task's record. Teardown takes it per home, parent before child, before enumerating and holds it through cleanup. A fresh spawn takes it before its own per-task locks and holds it through publication; a relaunch is exempt, because it republishes an existing task already covered by that task's control lock. Either the spawn publishes first and the teardown's preflight covers it, or the teardown owns the set and the spawn refuses. Both directions fail closed, and both are pinned by tests that hold the lock rather than racing on timing. * no-mistakes(review): Serialize remote secondmate publication with forced teardown * no-mistakes(review): Preserve remote spawn routing and state initialization * no-mistakes(review): Serialize teardown when descendant state is absent * no-mistakes(review): Cover symlinked descendant state refusal * no-mistakes(document): Document task-set serialization safeguards * no-mistakes(lint): Isolate task-set lock path resolution * no-mistakes: apply CI fixes
escidmore
pushed a commit
to escidmore/firstmate
that referenced
this pull request
Aug 9, 2026
* feat(bin): add deterministic agent lifecycle control Separate firstmate's data plane from its control plane. bin/fm-send.sh is the data plane: conversational text, always routing-marked for a kind=secondmate target. That marking is right for a message and wrong for a lifecycle command - a marked "/quit" arrives as ordinary chat the agent reasons about instead of executing. bin/fm-control.sh is the control plane: allowlisted interrupt, exit, and transactional relaunch verbs addressed to an exact task id, with per-harness mechanics owned by the executable bin/fm-control-lib.sh rather than improvised in agent prose, and a verified postcondition for every action. There is no arbitrary-text and no raw-key entry point. relaunch runs as a transaction with a durable journal: it resolves the profile, proves the work it must preserve is recoverable, records the required progress note, stops the old agent, then delegates the launch to its single owner, bin/fm-spawn.sh --relaunch, which adopts the recorded endpoint and worktree instead of creating either. A refusal before the stop leaves the record and instructions byte-identical; a failure after it reports the concrete state rather than claiming an agent that is not running. Teardown and discard stay separate and explicit. exit and relaunch require a backend with a recovery-grade agent-state classifier, so zellij, orca, and cmux are refused rather than reported as successful blind. A remotely placed secondmate is refused by name, because its agent runs on a host where none of these postconditions can be read. * fix(control): resolve a recorded harness to its adapter before retiring wiring fm-spawn arms per-task harness wiring on prefixes, because a task launched from a raw command records that command's basename rather than the exact adapter name. The control plane's retirement tables are keyed by the exact adapter, so a task recorded as `grok-2` had its turn-end token, private registry entry, and worktree hook pointer armed and never retired - leaving a registry entry that outlived the agent that owned it. State the prefix rule once, in the capability owner, and resolve the recorded value through it before every table lookup. bin/fm-send.sh's composer-clear lookup reads the same owner instead of keeping its own copy of which adapters need one. * test(control): pin muse session-binding retirement across a harness switch * no-mistakes(review): Resolve prefixed harnesses across lifecycle control verbs * no-mistakes(review): Report interrupt delivery without fabricating cancellation state * no-mistakes(review): Clear disabled relaunch trace context atomically * no-mistakes(review): Clarify control interrupts and restore legacy send state * no-mistakes(review): Refuse ambiguous relaunches and report exit delivery * no-mistakes(review): Revalidate interrupts and accept interrupt-stopped exits * no-mistakes(review): Lock descendant tasks before forced recursive teardown * no-mistakes(document): Align lifecycle adapter documentation with control plane * no-mistakes: apply CI fixes * fix(bin): serialize fresh task publication with forced teardown Forced secondmate teardown enumerated a home's task set, locked what it found, then re-enumerated while removing. A fresh spawn takes only its own per-task lock, so a record published inside that window was invisible to the preflight and visible to the cleanup: it was destructively processed while never lifecycle-locked. Reproduced with real agents. A record published 0.249s after teardown began was removed, its window closed, and its worktree returned to the pool - while both commands reported success. A per-task lock cannot protect a task that does not exist yet. Add a per-home task-set lock guarding WHICH tasks a home has, as opposed to the metadata lock guarding one task's record. Teardown takes it per home, parent before child, before enumerating and holds it through cleanup. A fresh spawn takes it before its own per-task locks and holds it through publication; a relaunch is exempt, because it republishes an existing task already covered by that task's control lock. Either the spawn publishes first and the teardown's preflight covers it, or the teardown owns the set and the spawn refuses. Both directions fail closed, and both are pinned by tests that hold the lock rather than racing on timing. * no-mistakes(review): Serialize remote secondmate publication with forced teardown * no-mistakes(review): Preserve remote spawn routing and state initialization * no-mistakes(review): Serialize teardown when descendant state is absent * no-mistakes(review): Cover symlinked descendant state refusal * no-mistakes(document): Document task-set serialization safeguards * no-mistakes(lint): Isolate task-set lock path resolution * no-mistakes: apply CI fixes
mackcee
added a commit
to mackcee/firstmate
that referenced
this pull request
Aug 9, 2026
* feat(bin): add deterministic agent lifecycle control (kunchenguid#1568) * feat(bin): add deterministic agent lifecycle control Separate firstmate's data plane from its control plane. bin/fm-send.sh is the data plane: conversational text, always routing-marked for a kind=secondmate target. That marking is right for a message and wrong for a lifecycle command - a marked "/quit" arrives as ordinary chat the agent reasons about instead of executing. bin/fm-control.sh is the control plane: allowlisted interrupt, exit, and transactional relaunch verbs addressed to an exact task id, with per-harness mechanics owned by the executable bin/fm-control-lib.sh rather than improvised in agent prose, and a verified postcondition for every action. There is no arbitrary-text and no raw-key entry point. relaunch runs as a transaction with a durable journal: it resolves the profile, proves the work it must preserve is recoverable, records the required progress note, stops the old agent, then delegates the launch to its single owner, bin/fm-spawn.sh --relaunch, which adopts the recorded endpoint and worktree instead of creating either. A refusal before the stop leaves the record and instructions byte-identical; a failure after it reports the concrete state rather than claiming an agent that is not running. Teardown and discard stay separate and explicit. exit and relaunch require a backend with a recovery-grade agent-state classifier, so zellij, orca, and cmux are refused rather than reported as successful blind. A remotely placed secondmate is refused by name, because its agent runs on a host where none of these postconditions can be read. * fix(control): resolve a recorded harness to its adapter before retiring wiring fm-spawn arms per-task harness wiring on prefixes, because a task launched from a raw command records that command's basename rather than the exact adapter name. The control plane's retirement tables are keyed by the exact adapter, so a task recorded as `grok-2` had its turn-end token, private registry entry, and worktree hook pointer armed and never retired - leaving a registry entry that outlived the agent that owned it. State the prefix rule once, in the capability owner, and resolve the recorded value through it before every table lookup. bin/fm-send.sh's composer-clear lookup reads the same owner instead of keeping its own copy of which adapters need one. * test(control): pin muse session-binding retirement across a harness switch * no-mistakes(review): Resolve prefixed harnesses across lifecycle control verbs * no-mistakes(review): Report interrupt delivery without fabricating cancellation state * no-mistakes(review): Clear disabled relaunch trace context atomically * no-mistakes(review): Clarify control interrupts and restore legacy send state * no-mistakes(review): Refuse ambiguous relaunches and report exit delivery * no-mistakes(review): Revalidate interrupts and accept interrupt-stopped exits * no-mistakes(review): Lock descendant tasks before forced recursive teardown * no-mistakes(document): Align lifecycle adapter documentation with control plane * no-mistakes: apply CI fixes * fix(bin): serialize fresh task publication with forced teardown Forced secondmate teardown enumerated a home's task set, locked what it found, then re-enumerated while removing. A fresh spawn takes only its own per-task lock, so a record published inside that window was invisible to the preflight and visible to the cleanup: it was destructively processed while never lifecycle-locked. Reproduced with real agents. A record published 0.249s after teardown began was removed, its window closed, and its worktree returned to the pool - while both commands reported success. A per-task lock cannot protect a task that does not exist yet. Add a per-home task-set lock guarding WHICH tasks a home has, as opposed to the metadata lock guarding one task's record. Teardown takes it per home, parent before child, before enumerating and holds it through cleanup. A fresh spawn takes it before its own per-task locks and holds it through publication; a relaunch is exempt, because it republishes an existing task already covered by that task's control lock. Either the spawn publishes first and the teardown's preflight covers it, or the teardown owns the set and the spawn refuses. Both directions fail closed, and both are pinned by tests that hold the lock rather than racing on timing. * no-mistakes(review): Serialize remote secondmate publication with forced teardown * no-mistakes(review): Preserve remote spawn routing and state initialization * no-mistakes(review): Serialize teardown when descendant state is absent * no-mistakes(review): Cover symlinked descendant state refusal * no-mistakes(document): Document task-set serialization safeguards * no-mistakes(lint): Isolate task-set lock path resolution * no-mistakes: apply CI fixes * feat(brief): have no-mistakes workers start validation themselves The generated no-mistakes definition of done told the worker to append `done: {summary}` and stop, then wait for firstmate to type /no-mistakes. That relay applied no judgement, so it only put firstmate's availability between a finished commit and the pipeline that ships it. Finished work has repeatedly idled at that gap for hours when the wake channel wedged. The scaffold now tells the worker to invoke /no-mistakes immediately after committing. The authority contract is unchanged: ask-user findings are still never the worker's to answer, `--yes` stays forbidden, and the worker still stops for firstmate's decision at every gate. Checked before changing the wording that nothing depends on firstmate seeing the commit first: - `bin/fm-spawn.sh` reads the brief's `Delivery contract: mode=` line and the registered posture only at launch, before the worker starts; no spawn-side path observes the implementation commit. - Nothing keys off a mid-flight `done:` line. `done:` is one of several generic captain-relevant wake verbs in `bin/fm-classify-lib.sh`, and the terminal `done: PR {url} checks green` report still carries it. - `bin/fm-teardown.sh` gates on git state and `no-mistakes axi status`, never on a status line. - `bin/fm-crew-state.sh` reconciles validation from the run matched to the current code, which works the same whoever started the run. Removing the relay also removes a failure mode of its own: sending `/no-mistakes` into a crew composer is the exact operation behind the slash-autocomplete submission hazards documented in `harness-adapters`. A worker loading its own skill bypasses that surface entirely. `AGENTS.md` section 7 keeps sole ownership of the flow and now points at `harness-adapters` for the restart case rather than the routine one. `bin/fm-promote.sh`'s suggested ship instructions get the same rule, since a promoted scout never receives the scaffolded definition of done. tests/fm-brief.test.sh pins both halves of the new shape: the self-start instruction is present, the stop-and-wait instruction is gone, the escalation gates survive, and neither faster mode picks up a pipeline instruction it must not have. * no-mistakes(review): make brief's no-mistakes self-start harness-neutral, guard test legs * no-mistakes(review): put validation action before done report in promote hints * no-mistakes(document): correct harness claim in fm-brief help header --------- Co-authored-by: Kun Chen <[email protected]>
sbracewell64
added a commit
to sbracewell64/firstmate
that referenced
this pull request
Aug 9, 2026
Squash-reconcile of the fork trunk (48 commits through ed376cf, fork PRs #8-#48 plus CI mirrors) rebased onto upstream main at 74230fc, resolving 72 conflicted files. The fork trunk carries: the fm-launch-lib.sh one-owner launch refactor, the slot-base/contribution-target task base contract (fm-task-base-lib.sh), the zero-budget model registry, fleet admission control stages 0/1, the wake-outcome ledger, the LoopSpec canonical representation, the research-approved-work corpus scanner, the 70% compaction doctrine, from-firstmate steer markers, the fleet launcher menu and Windows-to-WSL bridge, forge-verified merge gates, and the fleet-view per-argument cap fix. Conflict-resolution decisions a reviewer cannot see from the diff alone: - Where the fork carried an older in-flight import of upstream work (delivery contracts kunchenguid#1563, remote secondmate homes kunchenguid#1576, trace context kunchenguid#995, and every add/add remote-secondmate file), upstream's landed and further-evolved version wins outright; nothing fork-specific lived in those copies (verified blob-by-blob against upstream history). - Upstream's --relaunch lifecycle control plane and the fork's task base contract both survive: base derivation and the brief base-contract guard are gated to fresh spawns (RELAUNCH=0) because a relaunch reuses the recorded worktree and bases, and the trunk may have moved since. - Launch commands stay one-owner in bin/fm-launch-lib.sh: upstream's Muse Code adapter is ported into the library (template arm, model flag, effort mapping with max->ultra) instead of resurrecting the inline fm-spawn template, and fm-spawn's post-template FM_PI_HARNESS prefix is dropped because the library's pi templates carry the marker themselves. - Herdr presentation spaces keep upstream's 0.8.0-floor semantics (config off/on/empty, two-argument fm_backend_herdr_presentation_enabled) across spawn, config inheritance, docs, and tests. - fm-pr-check derives its per-task lock from state/<id>.meta explicitly so upstream's kunchenguid#1568 meta locking coexists with the fork's #34 landing records (fm_meta_lock_path rejects a .landing path). - tests/lib.sh keeps both the fork's identity-verified background-process reaper and upstream's fm_fake_version_tool fixture. - Merged prose follows upstream's X-mode -> Relay rename. Pre-existing on both parents, not introduced here: tests/fm-calm-pi-extension.test.sh fails under system Node 22 (ERR_UNKNOWN_FILE_EXTENSION), verified identical on the base commit. Co-Authored-By: Claude Fable 5 <[email protected]>
spirispark
added a commit
to spirispark/firstmate
that referenced
this pull request
Aug 13, 2026
* fix: preserve fleet state in truncated session-start digests (#1798)
* feat(session-start): order the startup digest for truncation safety and bound its bulk
The digest is delivered through a harness that truncates an oversized payload
from the tail, and it really has been truncated: a 70KB digest arrived as lines
1-435 of 578, cutting off eight lines before the live-task inventory. That
session took the helm without ever seeing which tasks were live or where their
endpoints were.
Three changes, one file's worth of composition:
- FLEET STATE is emitted before CONTEXT, so a truncated tail drops curated
memory - stable session to session, already governed by a captain-set budget,
recoverable with one targeted read - instead of live fleet identity. The
LOCK/BOOTSTRAP/WAKE-QUEUE safety preamble keeps its order. The read-once
contract moves out of the closing reminder into its own section ahead of both,
and now names the condition that voids it: a stage the truncation banner
reports as never emitted.
- Status-tail lines are capped per line, reusing the cut the wake digest's OPEN
DECISIONS section already applies. An observed tail line ran 865 characters
and nothing bounded it. The cut and its marker now live in one place,
bin/fm-line-cap-lib.sh, so the two digests cannot drift apart; each task's
full status log path is still printed beside its tail.
- The backlog listing is composed as a recovery input: done rows are never
listed, every in-flight, held, and blocked row is shown in full with its hold
and blocked-by metadata, and only the dispatchable-now listing is bounded -
with an exact remainder count and the command that shows the rest.
FM_SESSION_START_QUEUED_LIMIT (default 20) replaces
FM_SESSION_START_BACKLOG_LIMIT, which bounded the whole listing
indiscriminately and so could drop a held or blocked row.
Tests exercise the real digest output: section ordering with the preamble
pinned, the per-line cap and its marker, and the backlog composition including
the remainder counters on both the tasks-axi and manual paths.
* no-mistakes(document): Clarify digest source recovery comments
* feat(send): close answered decisions at answer time via --resolve-key (#1842)
A captain decision opened by a keyed needs-decision:/blocked: status line
orphaned as permanently open whenever the answer kicked off work: the
worker's next event is working [key=<workstream>] in a different key
namespace, so no resolved [key=<decision>] ever landed and the OPEN
DECISIONS fold kept listing the answered decision forever.
Remove the writer-dependency at its source: the answering firstmate
already holds the decision key when it sends the answer, so fm-send's new
--resolve-key flag (repeatable) appends the closing resolved line to this
home's own state/<id>.status after the submit is confirmed. The close is
a local ledger append for crewmates, local secondmates, and remote
secondmates alike - a remote mate's escalations reach this ledger through
the parent-replies ingest, so only the answer message crosses the
transport.
Safety: each named key must currently be open per the authoritative
status_open_decisions fold or fm-send refuses before sending; a failed or
unconfirmed send never closes a key; an append failure after a delivered
answer exits nonzero with the manual close command so the decision
re-surfaces instead of silently vanishing; a send without the flag closes
nothing, and working:/done: still never clear a captain decision.
Complementary fixes: the wake-drain OPEN DECISIONS section prints the
answer-with-close command hint at the moment of use; brief scaffolds
separate resolved's two duties (keyed-phase end vs decision closure) and
state that a done:/working: line never closes a decision even when the
answer started that work, keeping worker self-close for blockers that
clear without a firstmate reply; AGENTS.md and docs/architecture.md carry
the one-line pointers to the fm-send contract.
* fix(bin): seed remote secondmates from supplied origins (#1836)
* feat(secondmate): seed a remote home from a supplied project origin
Remote seeding required a local projects/<name> clone purely to read
`git remote get-url origin` into the provisioning manifest, so setting up
a remote second mate forced disposable clones and no-mistakes inits in the
primary home for projects that home has no reason to hold.
Firstmate now resolves the origin itself and names it as <project>=<origin-url>.
The seed validates and transports what it is given, and the receiving host
re-validates it rather than trusting the sender; bin/fm-project-origin-lib.sh
is the single owner of which URLs are accepted, refusing executable remote-helper
transports, option-shaped values, and unusable spellings at both ends. A bare
<project> still reads an already-present clone's origin, so nothing that works
today has to change. Registry consistency is unchanged: an unregistered or
local-only project is still refused.
A remote seed therefore creates nothing in the primary home beyond the route,
the charter, and its launch record.
The lifecycle test now seeds a registered project the primary has never cloned
and asserts the primary project tree is byte-identical afterwards, alongside
refusals for a missing origin, an unsafe origin, a local-only project, and an
unregistered project.
* no-mistakes(review): Clarify project origin documentation ownership
* no-mistakes(document): Document supplied-origin remote seeding contract
* feat(secondmate): accept project origins from any host or forge
Firstmate is a shared template, so a project origin must be able to name any
host: GitHub Enterprise on a private domain, GitLab hosted or self-hosted,
Bitbucket, Gitea, Codeberg, sr.ht, a bare IP, an SSH config alias, or a plain
server nobody else has heard of. The validator already decided on structure
rather than on a forge allowlist, and this makes that guarantee explicit and
closes the two gaps that a host-agnostic rule exposed:
- a bracketed IPv6 literal in the scp-like form is now accepted, so a host
reachable only by address is not excluded
- a "/../" traversal inside a local or file: origin is now refused, because
that names a path on the cloning host's own filesystem
The library is the single owner of the accepted forms, and its header says
plainly that there is no host, domain, or forge allowlist and there must never
be one. The skill keeps its distinct agent-operating lines (the agent resolves
and supplies the origin; a remote seed creates nothing in the primary home
beyond the route, the charter, and its launch record) and points at the library
for URL acceptance and at the operator doc for the rest.
The lifecycle test now drives Bitbucket, a self-hosted enterprise domain, a
self-hosted GitLab over ssh with a port, and a bare scp-like custom host through
the real seed, manifest, transport, and remote provisioning path in one seed,
asserting each URL reaches git unchanged and each clone carries its own origin's
content. The unit matrix leads with non-GitHub hosts for the same reason.
* no-mistakes(review): Validate project origin authorities safely
* no-mistakes: apply CI fixes
* no-mistakes: apply CI fixes
* fix(tests): restore reliable fm-send backend parity coverage (#1851)
* fix(tests): copy the whole bin/ tree into the old-vs-new conformance shim
main went red on tests/fm-backend.test.sh's "fm-send --key: old vs new
exit code" assertion, which reads as an fm-send fail-closed regression from
build_old_bin enumerated by hand the sibling scripts it copied into the
synthetic pre-refactor tree. #1842 made bin/fm-send.sh source
bin/fm-line-cap-lib.sh (added by #1798) and the list never learned about it,
so the pinned old fm-send.sh aborted at `. "$SCRIPT_DIR/fm-line-cap-lib.sh"`
under set -eu and exited 1 before parsing a single argument, while the
current one delivered the key and exited 0. The parity check compared a
crashed process against a working one and reported a behavior divergence
that never happened - the more so because BASE_REF collapses to HEAD on
main, where both sides run byte-identical source and a genuine divergence is
impossible. fm-send's --key exit path is unchanged and its fail-closed
contract is intact.
Copy the tree whole instead of enumerating it. An enumerated list has to be
extended by hand every time an entrypoint gains a dependency and is the only
thing that knows; it has been patched a dozen times for exactly that. A
whole-tree copy has nothing to forget. Extracting a refactored entrypoint the
baseline does not have now fails loudly instead of writing an empty file.
Only old-vs-new parity covered that exit contract, and parity is near-vacuous
on main. Pin it directly: tests/fm-send-strict.test.sh drives delivery both
ways from one stub and asserts an undelivered key exits nonzero naming the
key, so swallowing that error fails the suite.
* no-mistakes(review): Materialize historical fixture dependencies from baseline
* no-mistakes(document): Clarify fm-send key regression scope
* fix(bin): mirror remote secondmate status streams (#1846)
* fix(bin): mirror the whole remote secondmate status stream
A remote secondmate's reply channel required corr=<16hex> on every line and
failed the entire delta when one line lacked it, so the cursor could never
advance past that line and the channel wedged permanently.
The charter tells a secondmate to report its own progress phases and to raise
new decisions with no correlation token, because correlation only answers a
marked parent request. Those lines were therefore unrepresentable on the remote
channel, while a local secondmate writes them straight into the parent's status
file.
Treat the channel as what it is: a mirror of the mate's status stream. A remote
mate now presents the same status and decision model as a local one, so a newly
raised needs-decision reaches the parent's open-decision fold identically, and
correlation goes back to being a per-line property that settles a pending
request rather than a gate on the stream.
Only what crossing a machine boundary genuinely adds stays behind: cursor
continuity, confined document fetch and rewrite, at-most-once append, and
control-byte normalization that rewrites bytes without ever dropping a line.
Line framing and size bounding already belong to fm-remote-delta-read.sh. A
document the remote reader refuses is named in one escalation instead of
stalling the stream, while an unavailable transport still leaves the delta for
the existing retry.
* refactor(bin): give the remote reply stream one append owner
Every line entering the parent status stream - a mirrored line, the continuity
escalation, and the undelivered-document escalation - now goes through one
at-most-once append, so the idempotence a replayed generation depends on is
stated once instead of copied at three call sites.
* no-mistakes(review): Keep local document transfer failures retryable
* no-mistakes(review): Isolate reply headers and normalize payload bytes
* no-mistakes(review): Correct remote reply mirror contract wording
* no-mistakes(review): Update remote reply script catalog description
* no-mistakes(document): Document remote status-stream mirroring
* docs(agents): describe the digest's fleet-state-before-context order (#1826)
* fix(bin): fail closed on NUL bytes in the durable parent binding (#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.
* fix(skills): reconcile inherited secondmate plans with shipped state (#1853)
* docs(secondmate-provisioning): require record intake for an inherited domain
A new mate seeded for an existing or inherited domain previously pulled in
charter, inherited config, captain-shared preferences, project clones, and
queued backlog rows with zero instruction about the domain's shipped history,
so it assumed a greenfield domain. A live backlog keeps only the configured
recent Done entries, so an inherited queue structurally over-represents plans
and under-represents deliveries, and already-delivered work resurfaced as open.
Add a record-intake step to the creation/seed path: classify greenfield versus
existing or inherited, and for the latter reconcile every inherited plan
against origin/main plus the live deployment, take only genuinely open work
and still-live durable knowledge, never carry a plan row for shipped work, and
record what could not be reconciled. Greenfield domains are untouched.
The skill owns the procedure; the backlog handoff section carries a one-line
reinforcement at the point where plan rows actually move.
* no-mistakes(document): Clarify secondmate record-intake scope
* fix: move network checks off the session-start blocking path (#1860)
* perf(session-start): run every network check off the blocking path
The session-start digest runs on a session-open hook that blocks session
initialization, and every external-network call it made was individually
unbounded: `gh auth status`, secondmate liveness, secondmate convergence,
pending remote handoff delivery, and the fleet-sync fetch. One unreachable
remote secondmate could consume the whole FM_SESSION_START_TIMEOUT and
truncate the digest, so a slow network could cost the work queue itself.
Measured against a host hanging 25s per SSH connection, that startup took
1m18s.
The digest is now composed from local reads alone. bin/fm-startup-network.sh
runs the same checks concurrently in a bounded detached worker and the digest
harvests whatever finished, without ever waiting. Same fixture: 0.84s.
Nothing is dropped. fm-bootstrap.sh stays the single owner of every sweep and
still runs all of them, through a new FM_BOOTSTRAP_NETWORK phase split whose
`skip` and `only` halves are a partition of the unsplit run. Deferral is safe
because the sweeps are idempotent detectors, the result is durable and always
surfaces (inline, or as a `check: startup-network` wake), and the worker
re-verifies that the fleet lock still names the session that asked before it
mutates anything. While the worker is still running the digest names exactly
what is unconfirmed rather than implying it passed.
A relaunch performed by the deferred pass is now always reported, because the
digest that printed the superseded endpoint record is already out.
Also collapses the duplicate tasks-axi compatibility probe: the verdict is
computed once and handed to the bootstrap child for one process hop, then
consumed so it never reaches a spawned agent's environment. 10 tasks-axi
invocations per startup become 7.
Verified on Claude Code 2.1.222 that a worker detached by the session-open
hook survives the hook returning, the one vendor behavior this design needs
and no portable test can see.
Re-landed on current main, superseding PR #1845, which was cut from a
pre-#1842 base. The digest's section numbering in AGENTS.md section 3 now
states the emission order directly - supervision block and its read-once
contract, fleet state, network checks, then context - which keeps #1826's
fleet-state-before-context ordering. The old-bin test shim keeps main's
git-archive baseline from #1851, which already subsumes this branch's reason
for widening that shim.
* docs(verification): re-measure the deferred startup stage on the current base
Re-runs the unreachable-remote latency fixture against default-branch tip
8398d31 rather than the now-historical 345de4e, and records the sweep-result
comparison the deferral's safety argument rests on: the deferred worker's
published report is byte-identical to the three sweep lines the blocking
baseline printed, with the unreachable route preserved in both.
* no-mistakes(review): Fail deferred startup when report publication fails
* no-mistakes(document): Document deferred startup network behavior accurately
* fix(procevent): apply remote replies during capture (#1831)
* fix(procevent): apply a captured adapter result in code, not by instruction
A remote secondmate's reply was captured and announced, but never applied.
Nothing dispatched the reply adapter's `handle` on a `procevent remote-reply`
wake, and the handling instruction named only the generic acknowledgement, so
the wake was retired while everything it carried was dropped: the reply never
reached the secondmate's local status mirror, the request it answered kept
escalating as a missed report, and the relay - whose registration each capture
retires, and which only that same handling re-arms - was left dead until the
next session start armed it again.
Applying such a result carries no judgement, so it belongs in code. After
publishing, the runner now calls
`bin/fm-procevent-<adapter>.sh autohandle <source-id> <sequence> <result-file>`
and lets the adapter apply and acknowledge its own result, through the same kind
of seam that already owns the terminal verdict. It runs strictly after terminal
retirement, because a handling adapter re-arms its own next source and retiring
afterwards would drop that fresh registration. An adapter with no such command,
or one whose pass does not complete, leaves the result unacknowledged and
therefore still announced, so a handler receives it exactly as before.
Resolving the request was not enough on its own either. An escalation opens a
durable keyed decision in the parent status log, and nothing ever closed it, so
a request the remote had answered kept surfacing in every later open-decisions
fold. The pending-reply library now owns both ends of that decision: it opens
one under a per-request key rather than the shared default key, and closes it
once the record resolves, appending the closing line only while that exact
decision is still open in the fold so it can neither double-close nor clear an
unrelated decision that has since taken the same key.
The handling instruction still routes a wake to its adapter, now as the
idempotent confirmation of what the runner already did rather than as the
guarantee.
Verified end to end in a throwaway isolated home driving the real armed source,
blocking delta reader, runner, and wake queue, with the handler doing only the
generic acknowledgement and no part of the ingest stubbed: before, seven failed
observations reproducing the incident; after, none. Each half is independently
load-bearing - without the runner change the reply never reaches the mirror,
without the escalation close the settled request still surfaces as an open
decision.
* no-mistakes(review): Prevent legacy reply closure from masking decisions
* no-mistakes(review): Serialize pending reply resolution and escalation closure
* no-mistakes(review): Serialize pending reply escalation with resolution
* no-mistakes(review): Clarify guarded legacy escalation closure behavior
* no-mistakes(review): Guard legacy closure and reserve pending reply keys
* no-mistakes(review): Match pending reply escalations by construction
* no-mistakes(document): Document automatic remote reply resolution
* no-mistakes(lint): Fix unused concurrent escalation loop variable
* no-mistakes(lint): Fix unused concurrent resolution loop binding
* no-mistakes(review): Version fold cache and gate autohandle on publication
* no-mistakes(document): Clarify remote reply relay documentation
* feat(skills): port internal stow curation disciplines to the public skill (#1841)
Bring the public installer-facing stow skill up to the internal skill's
current curation behavior while keeping it fully standalone:
- Replace the total-capture thesis with the compact-operating-map framing.
- Add read-the-destination-before-writing with the inspect-then-update
triad (supersedes what, one-sentence rewrite, delete stale now).
- Add the concrete prune list together with its unique-fact guard, as an
accuracy discipline with no size-budget machinery.
- Curate every memory file the pass has open, not only the routed one.
- Add the standing-decisions sweep category.
- Add the stronger-owner pointer-over-copy test before filing.
- Add tool-agnostic task-note discipline (inspect, classify, considered
replacement body, never blind-append) and blocked-on recording.
- Give .stow-notes.md a closed set of three exits.
- Forbid storing, creating, or editing a skill as a stow destination.
- Report per-file action verbs in the completion receipt.
- Consolidate the repeated local-vs-external and .gitignore prose and fix
the second-person voice slip, so the file does not grow (11334 -> 11276
bytes).
* chore(bootstrap): raise lavish-axi version floor to 0.1.46 (#1865)
* fix(bin): keep tracked Claude hook entries inert under grok 1.0.0 (#1917)
* fix(hooks): keep tracked Claude entries inert under grok 1.0.0 hooks
Grok loads Claude-compatible settings, so the tracked `.claude/settings.json`
hook entries also fire under Grok. They were meant to be inert there, guarded
by `[ -z "${GROK_AGENT:-}" ] || exit 0`. That guard silently stopped working.
Verified from the live process environment of a wedged grok 1.0.0 Stop hook on
2026-08-07: a grok 1.0.0 HOOK process carries GROK_HOOK_EVENT, GROK_HOOK_NAME,
GROK_SESSION_ID, and GROK_WORKSPACE_ROOT, but no GROK_AGENT. The observed hook
process was labelled `GROK_HOOK_NAME=project/settings:stop[0].hooks[1]`, which
is the Claude-only auto-arm entry.
Consequence: Grok ran `bin/fm-claude-stop-autoarm.sh` synchronously. Grok has
no `asyncRewake`, so it waited on the foregrounded watcher for that entry's
declared 28800-second timeout and the Grok turn never ended - the operator saw
an infinite "Responding".
Widen the guard to `[ -z "${GROK_AGENT:-}${GROK_HOOK_EVENT:-}" ] || exit 0` on
the five entries that have a `.grok/hooks/` counterpart: both Stop entries, the
SessionStart entry, and the two PreToolUse Bash entries.
Two deliberate limits:
- The guard is NOT widened to GROK_SESSION_ID. Grok injects it into every child
process, so it can survive into a Claude session that Grok launched and would
silently disable Claude's own watcher continuity. GROK_HOOK_EVENT is
per-hook-invocation and does not leak that way.
- `bin/fm-subagent-pretool-check.sh` stays unguarded on purpose. It is the one
tracked entry with no `.grok/hooks/` counterpart, so guarding it would remove
the guard from Grok entirely rather than deduplicate it. The new test asserts
it stays unguarded so the exception cannot be closed silently, and
docs/subagent-guard.md is honest that the coverage it leaves is partial.
`bin/fm-harness.sh` corrects a comment that presented GROK_AGENT as reliably
present; it is a fast path only, and the ancestry walk is what actually
guarantees grok identification.
tests/fm-turnend-guard.test.sh adds test_tracked_claude_entries_inert_under_grok,
which runs every tracked entry under a real grok 1.0.0 hook environment, a
legacy GROK_AGENT environment, and a native Claude environment.
* no-mistakes(document): docs: sync grok hook-marker guard facts to owners
* no-mistakes(review): docs: state grok guard criterion by event coverage
* feat(startup-network): record per-step elapsed times for the deferred stage (#1918)
The deferred network stage published one aggregate started/finished pair, so
a run that took a minute could not be attributed to a phase, a host, or a
clone without re-running it by hand under manual tracing.
Add bin/fm-timing-lib.sh as the single owner of elapsed-time records, and
bracket each network owner with one: the gh auth probe, the secondmate
liveness sweep, secondmate convergence, pending handoff delivery, and the
project clone refresh, plus one record per secondmate for the remote-touching
steps (id and host) and one per project clone. Each record carries a start
offset from one shared origin, so the artifact reads as a timeline.
The stage publishes them beside its report as state/.startup-network.timings,
for a timed-out or failed run too, where the partial record is the answer.
Only the on-demand `report` command prints them: `harvest` composes the
session-start digest, so its output, the wake cadence, and every other part
of a normal session start are unchanged.
Recording is inert unless a run asks for it, so nothing else that sources
these scripts pays for it. Details are identities only - a detail carrying
whitespace is refused rather than cleaned up, which is what keeps a command
line, an environment dump, or a captured error out of the file.
Split two per-item loop bodies into their own functions so each iteration can
be timed; every `continue` became a `return 0` with the same meaning, and the
sweeps still run directly, in the same order, returning the same results.
* feat(stow): cascade the internal /stow to every registered secondmate (#1928)
* feat(stow): cascade the internal /stow to every registered secondmate
Invoked in a primary home, /stow now sweeps every registered secondmate
after the primary's own required pass, enforcing the same startup-memory
threshold in each home against that home's own allowance rather than a
fleet total.
bin/fm-stow-cascade.sh owns the mechanical inputs: it enumerates each
registered secondmate exactly once from data/secondmates.md, reports that
home's own budget accounting, and resolves how the sweep reaches it. A
live agent sweeps its own home so its uncaptured session knowledge is
captured too; a local home without one is curated in place; a remote home
without one is accounted read-only and deferred, because there is no
generic remote write path for a home's own memory files. Every host-
crossing step and each home's accounting runs under one hard bound, so a
slow or unreachable home reports an exception and the sweep continues.
Nothing changes until /stow is invoked: no new notification, digest
section, or background work. The public skills/stow skill is untouched.
* no-mistakes(review): fix(stow): extend cascade --help range to include full exit-code contract
* fix(remote-job): stop workers abandoned by a pruned code root (#1927)
29 fm-remote-job-worker.sh processes were found running at ppid 1, 1-2 days
old, each still polling and appending to a log inside a no-mistakes gate
worktree that had already been returned.
Three things combined to make that possible:
- The recorded worker.pid is the serving child, not the restart supervisor
above it, so a teardown that stops that one pid only makes the supervisor
respawn. The Linux start path also left the worker tree in the launching
command's process group, so there was no group to signal instead.
- Neither the serving loop nor the supervisor ever rechecked whether its
configured FM_ROOT still existed, so a worker launched from a worktree
outlived that worktree indefinitely.
- The supervisor restarted a failing child with a fixed 0.1s delay and no
bound, which is what grew the logs (~66MB/day measured).
The Linux start path now puts the worker tree in its own process group, and
fm_remote_job_stop_worker_tree signals that whole group - refusing any group
whose leader is not itself a worker, so a worker from an older build or from
launchd's own session is still stopped safely as a single process. The worker
stops itself once its code root stops being a Firstmate checkout, confirmed
across a grace window so an ordinary transient cannot stop a healthy worker.
The supervisor backs off and gives up rather than restarting forever.
bin/fm-remote-job-reap-orphans.sh is the belt-and-suspenders sweep for workers
already orphaned that way, wired into fm-teardown.sh. Its reap condition is
exactly "the code root named in the worker's own command line is gone", which
is why the account's healthy LaunchAgent worker and every live remote
secondmate worker are never candidates.
The two suites that leaked these in the first place now stop the worker tree
rather than the recorded pid alone.
* feat(bin): lint only the changed shard locally, full lint in CI (#1925)
* fix(bin): lint only the changed shard locally, full lint in CI
Two ships hitting fm-lint.sh at once could spike CPU to 190% and load
to 8.58 on a captain's Mac, even though each run finishes quickly.
fm-lint.sh now defaults to linting only the canonical-set files
changed since the merge-base with origin/main (including uncommitted
edits) on an ordinary local branch, using plain local git with no
network calls. It still lints the full canonical set in CI
(GITHUB_ACTIONS=true or CI=true), on the main branch, or whenever no
merge-base can be found, so CI coverage never depends on a local diff.
Explicit paths keep bypassing this selection entirely.
* no-mistakes: apply CI fixes
* feat(bin): add deterministic agent lifecycle control (#1568)
* feat(bin): add deterministic agent lifecycle control
Separate firstmate's data plane from its control plane.
bin/fm-send.sh is the data plane: conversational text, always
routing-marked for a kind=secondmate target. That marking is right for a
message and wrong for a lifecycle command - a marked "/quit" arrives as
ordinary chat the agent reasons about instead of executing.
bin/fm-control.sh is the control plane: allowlisted interrupt, exit, and
transactional relaunch verbs addressed to an exact task id, with
per-harness mechanics owned by the executable bin/fm-control-lib.sh
rather than improvised in agent prose, and a verified postcondition for
every action. There is no arbitrary-text and no raw-key entry point.
relaunch runs as a transaction with a durable journal: it resolves the
profile, proves the work it must preserve is recoverable, records the
required progress note, stops the old agent, then delegates the launch
to its single owner, bin/fm-spawn.sh --relaunch, which adopts the
recorded endpoint and worktree instead of creating either. A refusal
before the stop leaves the record and instructions byte-identical; a
failure after it reports the concrete state rather than claiming an
agent that is not running. Teardown and discard stay separate and
explicit.
exit and relaunch require a backend with a recovery-grade agent-state
classifier, so zellij, orca, and cmux are refused rather than reported
as successful blind. A remotely placed secondmate is refused by name,
because its agent runs on a host where none of these postconditions can
be read.
* fix(control): resolve a recorded harness to its adapter before retiring wiring
fm-spawn arms per-task harness wiring on prefixes, because a task
launched from a raw command records that command's basename rather than
the exact adapter name. The control plane's retirement tables are keyed
by the exact adapter, so a task recorded as `grok-2` had its turn-end
token, private registry entry, and worktree hook pointer armed and never
retired - leaving a registry entry that outlived the agent that owned
it.
State the prefix rule once, in the capability owner, and resolve the
recorded value through it before every table lookup. bin/fm-send.sh's
composer-clear lookup reads the same owner instead of keeping its own
copy of which adapters need one.
* test(control): pin muse session-binding retirement across a harness switch
* no-mistakes(review): Resolve prefixed harnesses across lifecycle control verbs
* no-mistakes(review): Report interrupt delivery without fabricating cancellation state
* no-mistakes(review): Clear disabled relaunch trace context atomically
* no-mistakes(review): Clarify control interrupts and restore legacy send state
* no-mistakes(review): Refuse ambiguous relaunches and report exit delivery
* no-mistakes(review): Revalidate interrupts and accept interrupt-stopped exits
* no-mistakes(review): Lock descendant tasks before forced recursive teardown
* no-mistakes(document): Align lifecycle adapter documentation with control plane
* no-mistakes: apply CI fixes
* fix(bin): serialize fresh task publication with forced teardown
Forced secondmate teardown enumerated a home's task set, locked what it
found, then re-enumerated while removing. A fresh spawn takes only its
own per-task lock, so a record published inside that window was
invisible to the preflight and visible to the cleanup: it was
destructively processed while never lifecycle-locked.
Reproduced with real agents. A record published 0.249s after teardown
began was removed, its window closed, and its worktree returned to the
pool - while both commands reported success. A per-task lock cannot
protect a task that does not exist yet.
Add a per-home task-set lock guarding WHICH tasks a home has, as opposed
to the metadata lock guarding one task's record. Teardown takes it per
home, parent before child, before enumerating and holds it through
cleanup. A fresh spawn takes it before its own per-task locks and holds
it through publication; a relaunch is exempt, because it republishes an
existing task already covered by that task's control lock.
Either the spawn publishes first and the teardown's preflight covers it,
or the teardown owns the set and the spawn refuses. Both directions fail
closed, and both are pinned by tests that hold the lock rather than
racing on timing.
* no-mistakes(review): Serialize remote secondmate publication with forced teardown
* no-mistakes(review): Preserve remote spawn routing and state initialization
* no-mistakes(review): Serialize teardown when descendant state is absent
* no-mistakes(review): Cover symlinked descendant state refusal
* no-mistakes(document): Document task-set serialization safeguards
* no-mistakes(lint): Isolate task-set lock path resolution
* no-mistakes: apply CI fixes
* feat(stow): add tiered decaying memory management (#1984)
* feat(stow): tiered decaying memory with captain-gated offload to local excluded skills
Implement the captain-adopted /stow redesign from the v2 tiering report as
amended by the adoption decision:
- Per-entry trailing HTML-comment markers with three tiers named for their
handling: pinned (no clock, no eviction), aging (stale after 30 days),
perishable (stale after 7 days, mandatory checkable expiry condition).
- File-scoped defaults (captain.md and captain-shared.md pinned,
learnings.md aging) with a self-describing legend line per file header.
- Reinforcement requires session evidence; re-reading memory never counts.
- Archive-not-delete: stale and budget-evicted entries move with provenance
to the never-injected data/memory-archive.md; prune always means the cold
tier, and a stale unique fact is never deleted.
- Captain-gated over-budget offload: staleness evaluated before scope, the
sweep runs only when still over budget after decay and consolidation,
proposals go through the receipt plus one durable captain-held backlog
item, migration runs through the destination's normal path, and the
memory entry leaves only once the destination is live.
- Offload destination per the adoption decision: a user-owned skill under
.agents/skills/<freeform-name>/ excluded via the local .git/info/exclude,
with the hard rule that stow never creates or writes a tracked skill.
- Five graduation moves, receipt verbs archived and proposed-offload, and
the one-time non-destructive migration of unmarked legacy entries.
The public skills/stow/SKILL.md mirrors the generic parts (markers, decay,
archive exit, user-approved on-demand offload exit, migration) with no
firstmate-specific paths.
The load-bearing assumption that a git-excluded skill is still discovered
was verified empirically against Claude Code 2.1.226 (direct
.git/info/exclude scratch-repo test plus an in-repo ignored-probe test);
the dated evidence is recorded in docs/verification/stow-memory.md.
The graduation list's deletion move is deliberately narrowed to duplicates
already preserved by a stronger owner, reconciling the v2 report's retained
'deletion of a stale entry' wording with its own prune-always-archives
rule.
* no-mistakes(review): Persist legacy migration grace across stow passes
* no-mistakes(review): Enforce archival invariants and exempt default-pinned legacy entries
* no-mistakes(review): Clarify offload scope, archive placement, and marker boundaries
* no-mistakes(review): Enforce aging fallback and verify excluded skill loading
* no-mistakes(review): Fix stow decay, pinned offload, and archival safeguards
* no-mistakes(review): Preserve pinned entries, approvals, and archive provenance
* no-mistakes(review): Restrict stow mutations to editable memory files
* no-mistakes(review): Clarify skill destinations, collision checks, and migration legends
* no-mistakes(review): Resolve exclude paths for linked worktrees
* no-mistakes(review): Secure per-home excluded skill migration
* no-mistakes(test): Require explicit tier markers on new stow entries
* no-mistakes(test): Route missing shared legends to primary owner
* no-mistakes(document): Align stow documentation with tiered memory
* fix(stow): converge the pass on an over-budget home (dogfood D1-D3)
The dogfood run against a copy of the real over-budget home showed the
pass increasing the deficit from 624 to 1,107 estimated tokens and the
relief ladder provably unable to reach budget. Three skill-text fixes:
- D1: markers become single-token spellings (<!--a:DATE-->, <!--p:DATE-->,
<!--P-->, <!--g-->), entries matching a pinned file default carry no
marker, the per-file policy legend collapses to a one-line pointer
naming the stow skill as the scheme owner, and marker/pointer bytes are
explicitly counted content - roughly 76% less metadata cost on the
dogfooded home's first installment.
- D2: the eviction rung gains a convergence precondition - total the
eligible pool first, and when archiving all of it cannot reach budget,
skip eviction entirely, archive nothing for budget reasons, and report
the exempt pinned floor as the concrete inability in the final step.
- D3: budget eviction considers only dated aging entries; <!--g-->
legacy-grace entries are ineligible until their grace cycle resolves,
so eviction cannot cancel promised grace or invert against validation.
Public skill mirrors the D1 marker/pointer changes; D2/D3 are internal
because the public skill has no budget ladder.
* no-mistakes(test): Enforce evidence-only reinforcement during stow migration
* no-mistakes(document): Clarify stow receipt marker actions
* docs: add project vision (#1997)
* docs: add firstmate vision
* no-mistakes(test): Classify VISION.md as public product documentation
* no-mistakes(document): Restore approved one-file vision diff
* no-mistakes: apply CI fixes
* fix(spawn): force regular Pi TUI for crews (#2005)
* fix(spawn): force regular Pi TUI for crews
* no-mistakes(document): Documented Pi regular TUI launch mode
* fix(cmux): classify borderless Claude composers (#2029)
* fix(cmux): classify borderless Claude composer
* no-mistakes(review): Normalize cmux NBSP prompts across locales
* no-mistakes(document): Document cmux borderless Claude composer classification
* docs(stow): generalize read-before-write in the public stow skill (#2091)
The public installer-facing stow skill scoped its classify-then-replace
discipline to TODO/BACKLOG items only, so findings routed to a memory file
had no stated rule against a blind append or a wholesale overwrite.
Step 6 now classifies every finding against the destination's current
contents as new, duplicate, superseding, or obsolete, and states the
considered replacement each classification implies. The outcomes follow the
tiered-memory contract already in the file: an obsolete entry is refreshed,
archived, or replaced in a way that preserves its fact, a duplicate folds
into the entry that already carries it, and a superseded body worth keeping
leaves through step 7's existing exits rather than a second recovery
mechanism.
* fix: resurface durable supervision work after re-arm (#2065)
* fix(watcher): resurface durable work after downtime
* no-mistakes(review): Make watcher rearm recovery durable and cursor-safe
* no-mistakes(review): Persist safe recovery markers across migration lock recovery
* no-mistakes(review): Retain stale lock when recovery marker publication fails
* no-mistakes(review): Preserve delivery-gap recovery and quarantine malformed markers
* no-mistakes(review): Serialize recovery consumption and report acknowledgment failures
* no-mistakes(review): Centralize recovery publication before clearing watcher evidence
* no-mistakes(review): Guarantee recovery evidence across queue and lock handoffs
* no-mistakes(review): Publish recovery evidence before durable wake commits
* no-mistakes(review): Replace recovery marker Perl dependency with Node
* no-mistakes(review): Keep interrupted wakes durable until handling acknowledgment
* no-mistakes(review): Add post-handling durable wake acknowledgements
* no-mistakes(review): Enforce post-handling acknowledgement across recovery and AFK return
* no-mistakes(review): Bind wake
Intent
Fix the CONFIRMED, reproduced spawn/teardown race on PR #1568's branch. This is a scoped addition to an otherwise complete and previously green PR - add ONLY this fix.
THE DEFECT (reproduced with real agents, not theoretical):
Forced secondmate teardown enumerates a home's task set, acquires per-task control and metadata locks for exactly that snapshot, and then RE-ENUMERATES the same directory while removing. A fresh (non-relaunch) fm-spawn takes only its own per-task .spawn-.lock, so a task id that did not exist at snapshot time is invisible to the preflight but visible to the cleanup. Measured: a record published 0.249s after teardown began was destructively processed - metadata removed, tmux window closed, worktree returned to the pool - while BOTH commands reported success and nothing refused. A per-task lock cannot protect a task that does not exist yet.
THE FIX (exactly the mechanism the reproduction report prescribes, nothing more):
Serialize fresh task publication and forced teardown through a shared per-home TASK-SET lock, held from enumeration through cleanup.
Either the spawn publishes first and the teardown's preflight covers it, or the teardown owns the set and the spawn refuses. Both directions fail closed.
ACQUISITION ORDER (stated in bin/fm-teardown.sh so it cannot drift): each home's task-set lock first, parent home before child home; then per-task locks in that same preorder, sorted by id within a home, each control lock before its matching metadata lock. No child lock holder reaches back for a parent lock, so acquisition cannot cycle. bin/fm-spawn.sh follows the same order.
TESTS: two behavioral tests in tests/fm-secondmate-safety.test.sh pin both directions by HOLDING the lock with a live process rather than racing on timing, so neither can go quietly vacuous: a forced teardown refuses while a task is being published (naming the contention, removing nothing, killing no window), and a fresh spawn refuses to publish while a forced teardown owns the set (publishing no record and leaving no lock behind).
SCOPE LIMITS - this PR is otherwise finished and was already green; do NOT expand:
clearverb or expand the control-plane verb allowlist.REQUIREMENTS: bin/fm-lint.sh clean; behavioral tests through the executable interface, never asserting implementation source text; deterministic and idempotent enforcement; one-owner rule for the lock path and its rationale; one sentence per line in tracked Markdown; plain dash; genuine full-matrix green CI. This is firstmate's shared tracked supervision-adjacent infrastructure, so hold the highest bar.
What Changed
interrupt,exit, and transactionalrelaunchlifecycle commands with verified harness and backend capabilities.Risk Assessment
🚨 High: The confirmed destructive spawn/teardown race remains reachable when cleanup deletes the directory containing the newly introduced lock.
Testing
After correcting an initial test-selection harness issue, focused executable-interface tests and two end-to-end contention checks confirmed both race directions fail closed, preserve existing state, avoid window teardown or task publication, and leave no unintended lock residue; reviewer-visible CLI/state evidence was captured and the worktree remained clean.
Evidence: End-to-end task-set lock contention transcript for forced teardown and fresh spawn
Pipeline
Updates from git push no-mistakes
✅ **intent** - passed
✅ No issues found.
✅ **Rebase** - passed
✅ No issues found.
bin/fm-spawn.sh:909- The required criterion says “bin/fm-spawn.sh acquires the same lock on the FRESH path only, before its own per-task locks,” but the added lock hunk is reached only afterspawn_remote_secondmateat line 619. A fresh remote-secondmate spawn acquires.spawn-<id>.lock, publishes<id>.meta, and exits without the task-set lock, so forced teardown can still snapshot first and then remove that newly published record/home while both operations succeed. Move task-set serialization to the earliest shared fresh-spawn boundary, including the remote publication path.🔧 Fix: Serialize remote secondmate publication with forced teardown
2 errors still open:
bin/fm-spawn.sh:930- Moving remote-secondmate dispatch below ordinary backend selection makes remote spawns inherit parent backend failures. For example, with FM_BACKEND/config backend set to orca or cmux, lines 643-651 reject --secondmate before spawn_remote_secondmate runs, although that path explicitly hardcodes Herdr and previously ignored ambient backend selection. Dispatch remote secondmates after acquiring the task-set lock but before ordinary backend resolution; resolve the ordinary backend only after return code 3 selects the local path.bin/fm-spawn.sh:924- A remote secondmate spawn no longer supports a missing parent state directory. The task-set acquisition requires $STATE to exist because fm_lock_abs_path must cd into it, but the existing mkdir -p "$STATE" is now inside spawn_remote_secondmate and therefore unreachable. Such a spawn falsely reports task-set contention and publishes nothing. Establish the state directory before acquiring the shared lock, retaining the function's fail-closed error handling.🔧 Fix: Preserve remote spawn routing and state initialization
1 error still open:
bin/fm-teardown.sh:1893- The required per-home serialization is skipped when<home>/stateis absent. That state is accepted by teardown validation, while a supported concurrent fresh spawn creates the directory, acquires its new lock, and publishes after this early return; forced cleanup can therefore remove the newly published task/home without ever owning the same task-set lock. This leaves the confirmed race reachable. Refuse forced teardown when a descendant home's state directory is absent, or otherwise establish a stable state-directory boundary before enumeration without violating the requirement that a refusal changes nothing.🔧 Fix: Serialize teardown when descendant state is absent
1 error still open:
tests/fm-secondmate-safety.test.sh:2447- This test does not exercise the new fail-closed branch in collect_descendant_task_locks as required. Because the regular file exists before teardown starts, validate_firstmate_home_children_removal at bin/fm-teardown.sh:2281 rejects it first via operational-directory validation; deleting lines 1897-1899 would still leave this test passing. Add an executable-interface case that reaches collection, such as an in-home state-directory symlink that passes the earlier containment validation but must be refused by the new -L check.🔧 Fix: Cover symlinked descendant state refusal
1 error still open:
bin/fm-teardown.sh:1923- The task-set lock is stored inside the home that forced cleanup later deletes (lines 2220 and 2523). Oncerm -rfortreehouse returnunlinks<home>/state/.task-set.lock, a concurrent fresh spawn can recreatestate, acquire the same textual lock path, and publish while teardown still owns its now-unreachable lock; cleanup can then delete that new record or leave an orphaned task. This violates the required invariant that teardown holds serialization through cleanup. Establish retirement/exclusion at a stable shared boundary that home removal cannot unlink, and make fresh spawn validate it before creating state or publishing.✅ **Test** - passed
✅ No issues found.
Inspected the target diff and task-set lock implementation paths inbin/fm-wake-lib.sh,bin/fm-spawn.sh, andbin/fm-teardown.sh.Ran focused functions fromtests/fm-secondmate-safety.test.sh:test_force_teardown_refuses_non_directory_descendant_state,test_force_teardown_refuses_symlinked_descendant_state,test_force_teardown_locks_descendant_with_absent_state,test_force_teardown_refuses_while_a_task_is_being_published,test_fresh_spawn_refuses_while_a_forced_teardown_owns_the_task_set, andtest_fresh_remote_secondmate_spawn_refuses_while_task_set_is_owned.Manually held the live per-home task-set lock and invokedfm-teardown.sh domain --force, verifying refusal, preserved metadata/home, zero tmux window kills, and preserved owner lock.Manually held the live per-home task-set lock and invokedfm-spawn.sh newtask <project> --scout, verifying refusal, no metadata publication, no per-task lock residue, and preserved owner lock.Checkedgit status --shortafter testing to confirm no transient working-tree artifacts remained.tests/fm-secondmate-safety.test.sh:2535- bin/fm-lint.sh fails with SC2031 at lines 2535, 2537, and 2541; executable test changes are outside this documentation phase.🔧 **Lint** - 1 issue found → auto-fixed ✅
🔧 Fix: Isolate task-set lock path resolution
✅ Re-checked - no issues remain.
✅ **Push** - passed
✅ No issues found.