Skip to content

feat: harden firstmate dispatch, teardown, and deployment flows - #618

Closed
inivosdigital wants to merge 43 commits into
kunchenguid:mainfrom
inivosdigital:fm/ship-firstmate-fmsend-verify
Closed

inivosdigital wants to merge 43 commits into
kunchenguid:mainfrom
inivosdigital:fm/ship-firstmate-fmsend-verify

Conversation

@inivosdigital

Copy link
Copy Markdown

What Changed

  • Captain-facing bootstrap, teardown, and merge flows now surface failed critical systemd services, treat no-break-space composer padding as empty, recognize local-main landed content, bound local merge pushes, and sync known live NAS deployments after landed ship tasks.
  • Dispatch and spawn gained quota-balanced selection, model/effort tiering, mechanical risk-tripwire/ultracode guardrails, Claude auto-compaction, and per-worktree Docker Compose project isolation.
  • Added docs and tests for the new bootstrap diagnostics, NAS deploy sync, dispatch guardrails, ultracode markers, composer NBSP handling, teardown landed checks, and compose isolation behavior.

Risk Assessment

⚠️ Medium: Captain, the branch is mostly well-scoped, but it adds supervisory guardrails and teardown-time automation where fail-open checks and an unbounded NAS path are worth fixing before relying on the new behavior.

Testing

Completed 1 recorded test check.

Pipeline

Updates from git push no-mistakes

⏭️ **intent** - skipped

✅ No issues found.

⚠️ **Rebase** - 1 warning
  • ⚠️ .agents/skills/afk/SKILL.md - branch carries 38 commit(s) that exist on your local main branch but were never pushed to origin/main; rebasing would bundle this unrelated work (61 file(s)) into the PR:
  • 50d6f04 clarify /updatefirstmate converges to the fork, not the upstream template
  • 74d5779 keep firstmate repo in sync with upstream template
  • cfa760f Merge origin/main into local main; reconcile bidirectional divergence
  • b039383 feat: surface failed critical systemd services at bootstrap
  • bff4c82 no-mistakes(document): Synced AGENTS.md and docs/architecture.md/cmux-backend.md with the NAS auto-deploy-sync feature and cmux liveness fix.
  • 3ccc84a no-mistakes(test): placeholder - awaiting background test run completion
  • 6e52da2 no-mistakes(review): Guard NAS sync fetch race, document timeout knob, add tests
  • 87235f8 no-mistakes(review): Bound NAS deploy sync git/fs calls with a timeout
  • 72908a5 no-mistakes(review): Aggregate pm2 cluster status and stub NAS sync in gotmp tests
  • b76a52b no-mistakes(review): Sandbox teardown tests' NAS deploy sync lookup file
  • b4db9dc no-mistakes(review): docs: document fm-nas-deploy-sync.sh script and override var
  • 54664f6 feat: auto-sync live NAS deployments after a landed ship task
  • 7e96f50 fix(teardown): check both origin and local ref for landed content
  • a2358d5 no-mistakes: apply CI fixes
  • ed77f25 no-mistakes(test): skip handoff tests on incompatible tasks-axi; fix herdr server-race
  • 966e3ca no-mistakes(review): pass ultracode through dispatch, tighten tiering guardrail coverage
  • ea46f0b no-mistakes(review): stop tiering guardrails passing silently when diff uncheckable
  • f58cccd no-mistakes(review): clean up orphan .ultracode state marker on teardown
  • f668c1f no-mistakes(review): exclude herdr-lab brief block from risk-tripwire scan
  • 3f6f5db no-mistakes(document): sync docs with new resource-tiering guardrail scripts
  • 8373d2a no-mistakes(test): fix jq/git-version and test-env portability in failing tests
  • 526bb7b no-mistakes(review): set exec bit on new tests, fix ultracode marker doc
  • 5574d89 no-mistakes(review): make risk-tripwire grep portable, give tier-guard distinct exit codes
  • d875150 no-mistakes(review): harden risk-tripwire scans and mechanically wire ultracode floor
  • 20bac0a no-mistakes(review): scope risk-tripwire brief scan, narrow bin path, distinct exit codes
  • 8aefd99 feat(dispatch): add model/effort tiers and mechanical quality guardrails
  • 78889ac feat: add quota-balanced crew dispatch selection (feat: add quota-balanced crew dispatch selection #327)
  • 6ee7399 test(teardown): drop stale git-2.38 skip gate for content-in-default tests
  • db71662 fix(teardown): recognize work fast-forwarded into local main as landed
  • 3e45217 feat(spawn): raise claude auto-compact window to 300000
  • 6590039 no-mistakes(test): fix environment-fragile test failures (jq, git, harness detection)
  • eb16757 feat(spawn): auto-compact claude crewmates around 200k tokens
  • e3d3c15 no-mistakes(lint): Fix unused $out variable flagged by shellcheck in compose isolation test
  • 067e5e7 no-mistakes(document): docs already fully synced; added missing docker-compose note to fm-brief.sh header comment
  • 7eef86e no-mistakes(document): docs: document per-worktree docker-compose project isolation
  • 7232821 no-mistakes(test): fix(tests): make herdr fake CLI counter race-safe against backgrounded server call
  • 04f34fc no-mistakes(test): waiting for background test run to complete
  • 31bce30 fix(spawn): isolate docker-compose project names per worktree

Push main to origin, or rebase your branch onto origin/main, before gating.

⚠️ **Review** - 3 warnings
  • ⚠️ bin/fm-risk-tripwire.sh:207 - git diff --name-only "$BASE...HEAD" is allowed to fail open because the || true converts any diff failure into an empty path list after diff_base_resolved=1. If the refs exist but there is no merge base, or another diff-time error occurs, the binding risk checkpoint exits clean instead of exit 2, so risky auth/migration/schema paths can be missed. Capture the diff status and mark DIFF_UNRESOLVED=1 unless the diff command succeeds.
  • ⚠️ bin/fm-nas-deploy-sync.sh:153 - This stale-lock path calls fm_lock_is_provably_stale with the NAS checkout as its companion dir, but that helper runs [ -e ], lsof, and stat without the script's bounded timeout wrapper. On the exact degraded NAS case this script is meant to contain, teardown can still hang indefinitely while checking or removing a packed-refs lock. Keep the stale-lock probe/removal bounded too, or skip stale cleanup when it cannot be checked under the timeout.
  • ⚠️ bin/fm-dispatch-select.sh:119 - ultracode is silently dropped unless it is a JSON boolean, while bootstrap validation does not reject malformed values. A hand-edited safety-critical rule with "ultracode": "true" would still appear active but would not require the independent review guard. Extend dispatch config validation to reject non-boolean ultracode and non-string ultracode_role values instead of stripping them here.
✅ **Test** - passed

✅ No issues found.

  • command -v tmux >/dev/null || { echo "tmux is required for e2e tests" >&2; exit 1; }; tmux -V; rc=0; for t in tests/*.test.sh; do echo "== $t =="; bash "$t" || rc=1; done; exit "$rc"
✅ **Document** - passed

✅ No issues found.

✅ **Lint** - passed

✅ No issues found.

✅ **Push** - passed

✅ No issues found.

@inivosdigital
inivosdigital force-pushed the fm/ship-firstmate-fmsend-verify branch from 7e667bc to b2cbeb0 Compare July 16, 2026 00:01
@kunchenguid

Copy link
Copy Markdown
Owner

Automated reminder: thanks for the PR! This branch currently has a merge conflict with the base branch.

When you get a chance, please rebase onto (or merge) the latest base branch, resolve the conflict, and push. After that, checks will re-run and the PR will get looked at again.

Noted for firstmate#618 at b2cbeb08.

Michael added 28 commits July 15, 2026 20:11
Two treehouse worktrees of the same project share a leaf directory
basename, so Compose's default project-naming collides across them on
container/volume/network names. fm-spawn.sh now derives a stable name
from the worktree's own pool-slot path and drops it at
.treehouse-compose-project (git-excluded, like the other turn-end
pointer files), recorded in meta as compose_project=. fm-brief.sh tells
ship/scout crewmates to consume it on every docker compose invocation
and to avoid fixed host ports as a second collision vector.
…r-compose note to fm-brief.sh header comment
Claude crewmates and secondmates are separate claude processes launched
by fm-spawn.sh; they never inherit the primary's .claude/settings.local.json,
so they only compact at the hard context wall instead of proactively.

Add CLAUDE_CODE_AUTO_COMPACT_WINDOW=200000 to the claude launch template.
The var is capped at the model's real context window, so a fixed 200000
lands auto-compaction around 200k regardless of whether the spawned model's
window is 200k or (as verified live for --model sonnet on this account,
which carries the 1M-context beta) ~1M. The primary's own two-var form
(WINDOW=1000000 + PCT_OVERRIDE=20) assumes a 1M window and is not safe to
copy blindly for a smaller-window model/account combination.

grok, codex, opencode, and pi launches are left untouched: grok's binary
is not verified to honor Claude Code env vars, and the other three ignore
them harmlessly but should not carry a var meant for a harness they aren't.
Bump CLAUDE_CODE_AUTO_COMPACT_WINDOW from 200000 to 300000 for claude
crewmates and secondmates, matching the primary session's own updated
target.

The override is capped at the model's real context window, so it is a
no-op below 300000 and only takes effect above it; today's standard
--model sonnet crewmate spawn resolves to the ~1M-context beta, well
above the new threshold. Updated the fm-spawn.sh header comment,
launch_template() comment, and the harness-adapters SKILL.md fact to
describe this conditional behavior instead of the "regardless of
window" framing that only held at the old 200000 value.
content_in_default() only ever diffed a branch against the fetched
refs/remotes/origin/$name, so a no-mistakes-mode task whose branch was
merged into the LOCAL default branch by hand (e.g. after its upstream
PR was closed unmerged) was never recognized as landed and teardown
refused it. It now also checks the local refs/heads/$name ref.
…tests

content_in_default()'s diff-based comparison (from local main's own prior
rewrite) no longer depends on git merge-tree --write-tree, so the two
tests that used to skip themselves on older git now run and pass here.
Extends config/crew-dispatch.json's schema with model/effort/ultracode
axes per the resource-tiering design: docs/examples/crew-dispatch.json
gains rules for the firstmate-repo supervision-backbone carve-out,
safety-critical/security/migration work (opus/xhigh, ultracode-flagged),
and architectural/product tradeoffs (opus/xhigh).

Adds the four hardened guardrails as mechanical checks rather than prose
aspirations:
- bin/fm-tier-guard.sh: firstmate-observable escalation triggers (diff
  size and elapsed time vs. the trivial tier's envelope, plus a general
  heavy-scale ceiling for any tier).
- bin/fm-risk-tripwire.sh: a keyword/path trip-wire against a task's
  brief and diff, independent of the natural-language dispatch match.
- bin/fm-ultracode-guard.sh: flag/reviewed/check subcommands that
  mechanically confirm a genuinely independent second pass ran before an
  ultracode-flagged task reaches PR-ready.
- A documented model-verification gate in AGENTS.md section 4, extending
  the existing unverified-harness discipline to model names.

Verification tiering (light/standard/heavy no-mistakes runs) is
deliberately out of scope here and left for a follow-up change.
The read-tree portability rewrite restructured content_in_default() into
an if/elif that checks exactly one candidate ref: the fetched origin ref
when a remote exists, falling back to the local ref only when there is no
remote at all. That silently dropped the case a no-mistakes-mode project
with a closed, unmerged PR but work fast-forwarded into local main by
hand - the fetched origin ref exists but does not contain the work, so
the local ref is never even checked. Restore checking both candidates in
sequence via a shared content_matches_ref helper, matching the pre-rewrite
behavior tests/fm-teardown.test.sh's local-land regression test expects.
A merged PR does not, by itself, reach the live site: deployed apps run from a
separate checkout under /mnt/nas/experiments/<name>/, managed by pm2,
independent from the projects/<name> clone used for development. This gap
required a manual pull+restart to notice and fix.

bin/fm-nas-deploy-sync.sh fast-forwards a project's live NAS checkout and
restarts its pm2 process(es), looked up from a captain-private
data/nas-deployments.md mapping (best-effort, non-fatal, mirrors
fm-fleet-sync.sh's dirty/diverged safety exactly). bin/fm-teardown.sh now
calls it automatically after a landed ship task, including local-only merges.
Michael and others added 15 commits July 15, 2026 20:25
…-backend.md with the NAS auto-deploy-sync feature and cmux liveness fix.
Add config/critical-services (local, gitignored): one systemd unit name
per line, blank lines and full-line "#" comments ignored. bin/fm-bootstrap.sh
reads it in the detect-only diagnostics and prints one read-only
SERVICE_FAILED line per failed unit via systemctl is-failed (no root), with
a "failed since" timestamp when available. An absent or empty file, or a host
without systemctl, is a no-op; nothing is ever auto-restarted.

Wire it into AGENTS.md's config list and section 3's diagnostic-handling
list, docs/configuration.md, a copyable docs/examples/critical-services,
and tests.
Swap remotes on this working copy so origin is the captain's fork and
upstream is the read-only parent template, and keep the fork alive:

- fm-merge-local.sh: after a local fast-forward, best-effort push the
  default branch to origin when it exists, so a push-backed local-only
  default branch never silently drifts behind local main. Skipped
  silently for no-remote local-only projects.
- fm-bootstrap.sh: always-on UPSTREAM_DRIFT diagnostic reporting how far
  local main diverges from upstream/main in both directions plus
  days-since-merge-base, escalating wording past 30 commits behind or a
  10-day-old merge-base. The upstream fetch lives only in the locked
  mutating fleet-sync sweep; the count-and-report runs unconditionally
  from the already-present upstream ref, never fetching in the
  detect-only path.
- Document the local-only landing pattern and the opportunistic,
  non-blocking upstream PR in AGENTS.md, the UPSTREAM_DRIFT trigger in
  the bootstrap-diagnostics skill, and the inverted remote layout in
  CONTRIBUTING.md.
…late

Post-swap origin is the captain's fork, so /updatefirstmate only
converges the fleet onto that fork (a no-op on the primary source of
truth) and never pulls the read-only upstream template. Folding
upstream-template improvements into local main is the separate reviewed
reconciliation task surfaced by the UPSTREAM_DRIFT bootstrap line, not a
self-update. Note it inline in AGENTS.md section 12 and in the
updatefirstmate skill.
The turn-end guard blocked essentially every turn during a legitimate
watcher re-arm, not just a genuine supervision gap. fm_watcher_healthy
requires a live, identity-matched watcher lock with zero grace, but a
backgrounded re-arm needs a brief moment, roughly 0.25-0.3s measured,
more under load, to fork the new watcher and register its lock after
the old one released it. The Stop hook fired inside that gap on
essentially every re-arm, so it blocked with no real supervision lapse.

The pull-based warning banner tolerates this same gap because it checks
only beacon freshness with a 300s grace. The turn-end guard's sharper
live-lock check had no equivalent tolerance.

Replace the single fm_watcher_healthy check with a bounded poll: retry
every 0.2s, mirroring the watcher-arm script's own confirm loop, and
block only once a deadline passes still unhealthy. The deadline
defaults to FM_ARM_CONFIRM_TIMEOUT (10s), the same budget the arm gives
itself to confirm, and is independently overridable via
FM_TURNEND_ARM_WAIT.

A watcher that is genuinely missing, dead, or identity-mismatched for
the whole window still blocks; it now takes up to that deadline instead
of blocking on the first check. This intentionally slows the
truly-blind path (no arm in flight at all), which is the documented
tradeoff.

Update docs/turnend-guard.md's Shared Predicate section, the contract's
one authoritative statement, to describe the bounded poll instead of an
immediate block.

Testing: tests/fm-turnend-guard.test.sh's test_hook_runs_fast now pins
the bounded-poll latency instead of asserting a near-instant return, and
a new test_hook_allows_watcher_that_registers_mid_poll confirms a lock
that registers partway through the window is let through rather than
blocked. Other block-path tests default to a short override so the
suite stays fast; ran the lint gate and the full behavior suite (41
tests, all passing).
Claude draws its cleared composer prompt as the glyph "❯" followed by a
non-breaking space (U+00A0), not an ASCII space. Under a glibc UTF-8
locale, [[:space:]] does not classify U+00A0 as whitespace, so the
composer classifier's ASCII-only trimming left the U+00A0 behind as
phantom content and read an otherwise-empty composer as pending.
fm-send's submit-verify loop then exhausted its retries and returned the
false "Enter swallowed" / exit 1 the caller saw against genuinely
submitted steers to a claude target.

Normalize U+00A0 and its narrow sibling U+202F to an ASCII space before
classifying, so a composer empty but for no-break padding reads empty on
every backend while real typed text separated by a no-break space still
classifies pending. Add tests/fm-composer-nbsp.test.sh pinning the fix
at four layers: the shared classifier, the tmux composer reader on the
real captured bytes, the submit loop, and the full fm-send exit code.
@inivosdigital
inivosdigital force-pushed the fm/ship-firstmate-fmsend-verify branch from b2cbeb0 to 36b5617 Compare July 16, 2026 00:46
@kunchenguid

kunchenguid commented Jul 16, 2026 •

Copy link
Copy Markdown
Owner

Automated reminder: thanks for the PR! This branch currently has a merge conflict with the base branch.

When you get a chance, please rebase onto (or merge) the latest base branch, resolve the conflict, and push. After that, checks will re-run and the PR will get looked at again.

Noted for firstmate#618 at 36b56172.

@inivosdigital

Copy link
Copy Markdown
Author

Closing: this is an automated, non-blocking PR opened opportunistically by our own tooling against this upstream template. We treat this repo as read-only and don't merge back here, so this branch isn't being tracked or rebased for review. Closing to stop the conflict-reminder notifications; no action needed on your end. Apologies for the noise.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants