diff --git a/.agents/skills/bootstrap-diagnostics/SKILL.md b/.agents/skills/bootstrap-diagnostics/SKILL.md index 3e6d47371..22f17db40 100644 --- a/.agents/skills/bootstrap-diagnostics/SKILL.md +++ b/.agents/skills/bootstrap-diagnostics/SKILL.md @@ -2,7 +2,7 @@ name: bootstrap-diagnostics description: >- Agent-only handling playbook for session-start bootstrap diagnostics. - Use whenever the session-start digest's bootstrap section prints any diagnostic or capability line - MISSING, MISSING_MANUAL, BACKEND_INVALID, NEEDS_GH_AUTH, TANGLE, CREW_HARNESS_OVERRIDE, CREW_DISPATCH, FLEET_SYNC, SECONDMATE_SYNC, SECONDMATE_LIVENESS, TASKS_AXI, NUDGE_SECONDMATES, or FMX - or when a standalone bin/fm-bootstrap.sh run prints one. + Use whenever the session-start digest's bootstrap section prints any diagnostic or capability line - MISSING, MISSING_MANUAL, BACKEND_INVALID, NEEDS_GH_AUTH, TANGLE, CREW_HARNESS_OVERRIDE, CREW_DISPATCH, FLEET_SYNC, SECONDMATE_SYNC, SECONDMATE_LIVENESS, TASKS_AXI, NUDGE_SECONDMATES, FMX, SERVICE_FAILED, or UPSTREAM_DRIFT - or when a standalone bin/fm-bootstrap.sh run prints one. A silent bootstrap section means all good and needs no skill load. user-invocable: false metadata: @@ -47,3 +47,12 @@ The inline rules in `AGENTS.md` section 3 still bind: detect, then consent, then A secondmate that was skipped, already current, or whose advance changed no instructions is not listed and must not be disturbed. - `FMX: X mode on ...` / `FMX: X mode off ...` - bootstrap confirmed or removed the local X-mode poll artifacts (`docs/configuration.md` "X mode (.env)"). Only when a running watcher needs the cadence transition applied immediately, restart the home-scoped watcher through the emitted harness supervision protocol; bootstrap deliberately never restarts the watcher itself. +- `SERVICE_FAILED: - failed since ` - a systemd unit named in the optional local `config/critical-services` file is in the failed state; a pure read-only detection (`systemctl is-failed`, no root), so a read-only session still surfaces it. + Report it to the captain in plain language; never restart the unit yourself - a unit that failed may be unsafe to restart without knowing why. + An absent or empty config file, a host without `systemctl`, or no failed unit all print nothing. +- `UPSTREAM_DRIFT: local main is ahead / behind upstream/main, last reconciled d ago ()` - the always-on FYI variant: firstmate's OWN repo tracking how far it has drifted from its read-only upstream template (`kunchenguid/firstmate`, the `upstream` remote after the remote swap). + It prints every session; record it silently like any capability fact and take no action while the wording stays FYI. + It only reports - the network fetch that refreshes the ref runs in the locked fleet-sync sweep, and reconciling upstream is never a bootstrap side effect. +- `UPSTREAM_DRIFT: this repo's upstream sync needs attention - ...` - the escalated variant (local main more than ~30 commits behind `upstream/main`, or the merge-base older than 10 days). + Surface it to the captain in plain outcome language and, on their go-ahead, dispatch a deliberately-reviewed firstmate-repo reconciliation ship task - fetch `upstream`, merge it into local `main`, resolve conflicts, and land local-only (`AGENTS.md` section 1) - the same shape that reconciled the divergence before. + Never automate the merge; keeping the gap small also keeps the pipeline's opportunistic upstream PR's diff clean (`AGENTS.md` section 1). diff --git a/.agents/skills/harness-adapters/SKILL.md b/.agents/skills/harness-adapters/SKILL.md index 63f378bb7..ec6bb5bc0 100644 --- a/.agents/skills/harness-adapters/SKILL.md +++ b/.agents/skills/harness-adapters/SKILL.md @@ -132,6 +132,13 @@ Its broader dark-TRUECOLOR placeholder handling and dark-theme tradeoff are docu That styled capture is internal to the boolean detector only. `fm-peek` and every other human or LLM-facing capture path stays plain `tmux capture-pane` with no escape codes. +**Auto-compaction fact (verified 2026-07-09, Claude Code 2.1.206; shipped constant raised to 300000 2026-07-11).** +`bin/fm-spawn.sh` launches every claude crewmate and secondmate with `CLAUDE_CODE_AUTO_COMPACT_WINDOW=300000`, scoped the same way as `CLAUDE_CODE_ENABLE_PROMPT_SUGGESTION=false` above, so these separately-launched processes auto-compact around 300k tokens the way the primary already does via its own `.claude/settings.local.json` (which they never inherit). +The var is read once at process startup and is capped at the model's real context window, so it can only lower the effective trigger, never raise it past the real ceiling: `min(300000, window)` is `300000` once `window` exceeds it, but a no-op (stays at `window`) below that. +This is not a universal guarantee for every possible future model choice - a differently-configured account/model capped at the plain ~200k window would see no change - but it is true for the window tier crew actually runs on today: `--model sonnet` on this account, the standard crewmate spawn, resolves to the ~1M-context beta, well above 300000. +Verified live in a tmux pane at the original 200000 value (the mechanism is unchanged, only the shipped constant moved to 300000): `claude --model sonnet` on this account resolves to a ~967k-token auto-compact window with no override (`/context` reported `Auto-compact window: 967k tokens`, i.e. the 1M-context beta, not the 200k a plain Sonnet window would imply); relaunched with `CLAUDE_CODE_AUTO_COMPACT_WINDOW=200000` set, `/context` reported `39.5k/200k tokens (20%)` and `Auto-compact window: 200k tokens` - the window pinned to the override as expected. +This is why the primary's own two-var form (`CLAUDE_CODE_AUTO_COMPACT_WINDOW=1000000` + `CLAUDE_AUTOCOMPACT_PCT_OVERRIDE=20`) is not copied here: that pair assumes a 1M window, and would silently cap a smaller-window model/account combination to a far more aggressive trigger. + **Primary-session guard fact (verified 2026-07-04, Claude Code 2.1.201; preserved 2026-07-08, Claude Code 2.1.204).** This is separate from the per-task crewmate turn-end hook above (that one just `touch`es a marker file in a task's own `.claude/settings.local.json`). The firstmate PRIMARY's own `.claude/settings.json` registers `bin/fm-turnend-guard.sh` as a Stop hook, and exiting with status 2 plus stderr reliably forces the model to continue. diff --git a/.agents/skills/updatefirstmate/SKILL.md b/.agents/skills/updatefirstmate/SKILL.md index 015bc1350..f50d50c47 100644 --- a/.agents/skills/updatefirstmate/SKILL.md +++ b/.agents/skills/updatefirstmate/SKILL.md @@ -18,6 +18,9 @@ It never forces, never creates a merge commit, never stashes, and advances a tar A tracked-files fast-forward leaves the gitignored operational dirs (data/, state/, config/, projects/, .no-mistakes/) untouched, so a secondmate's in-flight work is never disrupted. This touches only the firstmate repo and its own worktrees, never anything under `projects/`. +Post-swap, this pull follows `origin`, which is the captain's fork, so `/updatefirstmate` converges the whole fleet onto that fork and does nothing on the primary checkout, which is itself the source every fork tracks. +It deliberately never reaches for the read-only `upstream` template: folding template improvements into local `main` is a separate, reviewed reconciliation ship task, the one the `UPSTREAM_DRIFT:` bootstrap diagnostic surfaces, and it never rides in on a self-update. + ## What it does 1. **Run the updater:** diff --git a/.gitignore b/.gitignore index 5ed2da0c3..cc1d02e14 100644 --- a/.gitignore +++ b/.gitignore @@ -16,3 +16,4 @@ config/backend config/x-mode.env config/cmux-socket-password config/wedge-alarm +config/critical-services diff --git a/AGENTS.md b/AGENTS.md index 1df624bc7..44bc02a22 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -36,12 +36,19 @@ Hard rules, in priority order: 5. **Report outcomes faithfully.** If work failed, say so plainly with the evidence. -You may maintain this repo's private operational state directly. -Shared tracked material is `AGENTS.md`, `README.md`, `CONTRIBUTING.md`, `.tasks.toml`, `.github/workflows/`, `bin/`, `.agents/skills/`, and public `skills/`. -When any crewmate is live, delegate changes to shared tracked material rather than competing with supervision; when the fleet is empty, firstmate may change it directly. -This repo is a shared template, while `.env`, `data/`, `state/`, `config/`, `projects/`, and `.no-mistakes/` are captain-private and gitignored. -Ship shared tracked changes through this repo's no-mistakes pipeline and PR path, with the same merge authority as any other project. -Never add an agent name as a commit co-author. +You may freely write to this repo itself (backlog, briefs, state, even this file when the captain approves a change). +Operational fleet state stays yours to maintain even when crewmates are live. +Shared, tracked material means `AGENTS.md`, `README.md`, `CONTRIBUTING.md`, `.tasks.toml`, `.github/workflows/`, `bin/`, `.agents/skills/`, and public `skills/`. +When one or more crewmates are in flight, delegate changes to shared, tracked material to a crewmate through the normal scout or ship machinery instead of hand-editing them yourself. +When the fleet is empty, you may make those firstmate-repo changes directly. +Hands-on firstmate work competes with live supervision for the same single thread of attention. +This repo is a shared template, not the captain's personal project. +The tracking principle: shared, tracked material is tracked under git; anything personal to this captain's fleet (.env, data/, state/, config/, projects/, .no-mistakes/) is not. +Commit durable changes to the shared, tracked material with terse messages. +This repo is itself behind the no-mistakes gate: ship shared, tracked material through the pipeline - branch, commit, run the pipeline, PR - and the captain's merge rule applies here exactly as it does to projects. +This repo's own upstream (`kunchenguid/firstmate`, the `upstream` remote after the remote swap) is read-only to this fleet with no merge rights, ever, so firstmate-repo ship tasks land local-only: branch, commit, firstmate reviews the diff, the captain approves, and firstmate fast-forwards local `main`. +The pipeline still auto-opens a PR against that upstream, but it is a non-blocking, purely opportunistic contribution back - never a merge gate here and never waited on - and its diff stays clean only while the `UPSTREAM_DRIFT:` gap (section 3) is small, since a large gap makes the PR carry a lot of unrelated local-only history. +Never add an agent name as co-author. ## 2. Layout and state @@ -50,10 +57,6 @@ Never add an agent name as a commit co-author. Each secondmate has a persistent isolated `FM_HOME`, including its own state, backlog, projects, and session lock. `bin/fm-send.sh` fails closed unless `FM_HOME` is explicit, so a steer cannot silently resolve against another home. -Tracked files hold shared instructions and tooling; `data/` holds durable private fleet records; `state/` holds volatile runtime records and append-only status events; `config/` holds local operating choices; and `projects/` contains clones that are read-only to firstmate. -A `state/.status` line is a wake event, not current-state truth; `bin/fm-crew-state.sh` owns current-state reconciliation. -Treat `data/captain.md` as the canonical portable record of captain preferences and `data/learnings.md` as curated fleet-local knowledge, regardless of harness memory. - ## 3. Session start (run once at every session start) Run `bin/fm-session-start.sh` exactly once at session start. @@ -89,6 +92,12 @@ Do not add model-specific versions of that policy. Dispatch only on a backend that `fm-spawn` validates as spawn-capable. A missing dependency, authentication failure, unsupported backend, or version refusal is a blocker; never silently retry on another backend. +Before naming a specific non-default model in a dispatch rule, verify that model end-to-end on a trivial supervised task, exactly as for a new harness adapter; never copy an unverified model into a live `config/crew-dispatch.json`. + +A dispatch profile's `ultracode: true` means the matched task must get a genuinely independent second pass on its finished diff before PR-ready, launched as its own separately dispatched task rather than a sub-task the implementing crewmate spawns itself; `bin/fm-ultracode-guard.sh` tracks this mechanically (`flag` right after spawn, `check`/`reviewed` at the PR-ready gate in section 7's Validate step). +As a second, structurally independent check, run `bin/fm-risk-tripwire.sh ` before spawn and again at Validate time against the actual diff; a hit floors the model/effort to `opus`/`xhigh` with ultracode `independent-review` regardless of which rule matched, and is never silently downgraded afterward. +On a hit, also run `bin/fm-ultracode-guard.sh flag independent-review` so the independent-review requirement is tracked mechanically even when the matched rule did not set ultracode. + ## 5. Recovery After the one session-start digest, reconcile reality with durable records before taking new work. @@ -206,6 +215,15 @@ Running, fixing, or CI states remain working; parked approval or fix-review stat A worker hand-editing, committing, aborting, or restarting during an active validation run duplicates pipeline ownership; steer it back to the gate response flow. The worker reports the PR when CI first becomes green rather than waiting for merge monitoring to finish. +**Escalation triggers (mechanical, never rest on self-report alone).** +For a task assigned the trivial tier (Haiku/low), run `bin/fm-tier-guard.sh ` during Validate, or whenever a heartbeat review touches it, to check whether its diff or elapsed time has outgrown that tier's envelope; any tier also escalates once its diff crosses the script's general heavy-scale ceiling. +A report escalates the task to at least Sonnet/high in place, without losing its branch or context, mirroring `bin/fm-promote.sh`'s in-place promotion. +A crewmate's own report - it cannot find root cause, a "confirmed" fix touches a shared path, or it raised a tradeoff buried in seemingly mechanical work - is a second, non-mechanical trigger with the same effect. +Either way, escalate the model/effort in place and never silently de-escalate for the rest of that task's life. + +**Ultracode confirmation.** +Before advancing an ultracode-flagged task to PR-ready, run `bin/fm-ultracode-guard.sh check `; it refuses until a genuinely separate task - dispatched independently, never a sub-task the flagged crewmate spawned itself - has reviewed the finished diff and its findings were addressed, recorded with `bin/fm-ultracode-guard.sh reviewed `. + ### PR ready, landing, and teardown For a ready PR, use `bin/fm-pr-check.sh` to record the PR and authoritative head and to arm merge monitoring. @@ -215,6 +233,9 @@ A captain instruction to merge is explicit authority; `yolo` is the only standin Tear down a ship task only after landing is confirmed. A teardown refusal for uncommitted or unlanded work is a stop-and-investigate result, never an obstacle to bypass. Never force teardown without explicit discard authority. +`bin/fm-teardown.sh`'s header owns the full landed-work definition; a known benign case is an external-PR task whose squash merge leaves the branch commits reachable only on the contributor's fork - add the fork as a remote and fetch, then retry, never reach for `--force`. +After a successful PR-based teardown it also best-effort syncs that project's clone via `bin/fm-fleet-sync.sh`, and any non-scout, non-secondmate, non-forced teardown best-effort syncs and restarts that project's live NAS deployment, if one is recorded in `data/nas-deployments.md`, through `bin/fm-nas-deploy-sync.sh`; a project with no recorded deployment is a silent no-op. +A forced teardown (`--force`) skips this sync, since `--force` carries no landed-work guarantee. After successful teardown, record completion, retain only the configured recent Done history, and re-evaluate queued work whose blockers and time gates have cleared. A secondmate is persistent and an empty queue is healthy. @@ -347,13 +368,15 @@ The scaffold is a safety contract, not a suggestion. Firstmate's shared instruction surface reaches running homes only after it lands on the default branch and those homes fast-forward. Only `AGENTS.md`, `bin/`, and `.agents/skills/` are loaded by a running firstmate; public `skills/` is an installer-facing surface. When the captain invokes `/updatefirstmate` or asks to update firstmate, load the `/updatefirstmate` skill. -It performs guarded fast-forward updates of firstmate and registered secondmate homes, refreshes instructions, and never touches anything under `projects/`. +It performs only fast-forward self-updates of firstmate and registered secondmate homes, re-reads `AGENTS.md` when needed, nudges updated live secondmates, and never touches anything under `projects/`. +Post-swap, `origin` is the captain's fork, so `/updatefirstmate` only ever converges the fleet onto that fork and is a no-op on the primary checkout, which is itself the fleet's source of truth. +It never pulls the read-only `upstream` template; folding upstream-template improvements into local `main` is the separate reviewed reconciliation task the `UPSTREAM_DRIFT:` bootstrap line surfaces (section 3), never a self-update. ## 13. Agent-only reference skills These skills are not captain-invocable; load them only at their precise triggers. -- `bootstrap-diagnostics` - load whenever the session-start digest's bootstrap section prints any diagnostic or capability line (`MISSING:`, `MISSING_MANUAL:`, `BACKEND_INVALID:`, `NEEDS_GH_AUTH`, `TANGLE:`, `CREW_HARNESS_OVERRIDE:`, `CREW_DISPATCH:`, `FLEET_SYNC:`, `SECONDMATE_SYNC:`, `SECONDMATE_LIVENESS:`, `TASKS_AXI:`, `NUDGE_SECONDMATES:`, or `FMX:`); silence needs no load. +- `bootstrap-diagnostics` - load whenever the session-start digest's bootstrap section prints any diagnostic or capability line (`MISSING:`, `MISSING_MANUAL:`, `BACKEND_INVALID:`, `NEEDS_GH_AUTH`, `TANGLE:`, `CREW_HARNESS_OVERRIDE:`, `CREW_DISPATCH:`, `FLEET_SYNC:`, `SECONDMATE_SYNC:`, `SECONDMATE_LIVENESS:`, `TASKS_AXI:`, `NUDGE_SECONDMATES:`, `FMX:`, `SERVICE_FAILED:`, or `UPSTREAM_DRIFT:`); silence needs no load. - `diagnostic-reasoning` - load before scoping a reported bug and before acting on a diagnostic report. - `harness-adapters` - load before spawning or recovering a crewmate or secondmate, handling a trust dialog, sending a harness-specific skill invocation, interrupting or exiting an agent, resuming an exited agent, or verifying a new harness adapter. - `firstmate-orca` - load before switching to Orca, spawning or supervising Orca-backed work, smoke-testing Orca backend behavior, debugging Orca task state, or reconciling Orca-backed task metadata. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 4e7bd8154..52e790d91 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -30,6 +30,8 @@ Dependency bots are exempt so their automation keeps working, but regular contri See the [no-mistakes quick start](https://kunchenguid.github.io/no-mistakes/start-here/quick-start/) for the full first-run walkthrough. +Note: a firstmate maintainer's own working copy uses the inverted remote layout - there `origin` is the maintainer's fork and `upstream` is this parent repo - so if you are ever reading such a copy's git config rather than your own fresh clone, expect `origin` and `upstream` swapped from the step 1 layout above. + ## Repo conventions - This repo is a template for running a firstmate orchestrator agent. diff --git a/bin/backends/cmux.sh b/bin/backends/cmux.sh index 69dc0b53b..478e9ee50 100644 --- a/bin/backends/cmux.sh +++ b/bin/backends/cmux.sh @@ -398,8 +398,15 @@ fm_backend_cmux_parse_target() { # # (fm_backend_zellij_pane_exists) rather than the design sketch's original # read-screen-based suggestion. fm_backend_cmux_surface_exists() { # - local wsid=$1 sfid=$2 - fm_backend_cmux_cli list-panes --workspace "$wsid" --json --id-format uuids 2>/dev/null \ + local wsid=$1 sfid=$2 out + # Capture the list-panes call and gate on its OWN exit/output before piping to + # jq: an absent target makes list-panes fail with no output, and `jq -e` on + # empty input exits 0 on jq 1.6 (only 1.7+ reports the no-result exit 4), so + # relying on the pipe's trailing jq status alone would false-positive the + # surface as present on older jq. A failed or empty list-panes means no surface. + out=$(fm_backend_cmux_cli list-panes --workspace "$wsid" --json --id-format uuids 2>/dev/null) || return 1 + [ -n "$out" ] || return 1 + printf '%s' "$out" \ | jq -e --arg s "$sfid" '[.panes[]? | select(.surface_ids // [] | index($s))] | length > 0' >/dev/null 2>&1 } diff --git a/bin/fm-bootstrap.sh b/bin/fm-bootstrap.sh index 1f5cc5d80..605be2021 100755 --- a/bin/fm-bootstrap.sh +++ b/bin/fm-bootstrap.sh @@ -14,7 +14,10 @@ # "SECONDMATE_SYNC: secondmate : skipped: ", # "NUDGE_SECONDMATES: fm-...", # "SECONDMATE_LIVENESS: secondmate : already-live|respawned|skipped: |respawn failed: ", -# "FMX: X mode on ..." or "FMX: X mode off ...". +# "FMX: X mode on ..." or "FMX: X mode off ...", +# "SERVICE_FAILED: - failed since ", +# "UPSTREAM_DRIFT: local main ahead / behind +# upstream/main ... (needs-attention wording when far behind or stale)". # A NUDGE_SECONDMATES line lists the RUNNING secondmate task selectors # (fm-) whose worktree was fast-forwarded to firstmate's own # current default-branch commit (a purely LOCAL fast-forward, never an @@ -56,8 +59,30 @@ # X mode is OPTIONAL and inert unless FM_HOME/.env has a non-empty # FMX_PAIRING_TOKEN. When opted in, bootstrap requires curl+jq, writes # the relay poll shim and 30s cadence config, and prints an FMX line. +# A SERVICE_FAILED line means a systemd unit named in the optional local +# config/critical-services file is in the failed state; it is a pure +# read-only detection (systemctl is-failed, no root) so a read-only +# session still surfaces it. Absent config file, no systemctl, or no +# failed unit all print nothing. The timestamp clause is omitted when +# StateChangeTimestamp is unavailable. +# An UPSTREAM_DRIFT line reports, every session, how far firstmate's OWN +# local main and its read-only upstream template (upstream/main after the +# remote swap; kunchenguid/firstmate) have diverged in both directions, +# plus days since their last shared merge-base. It reads whatever +# refs/remotes/upstream/main currently holds and NEVER fetches, so it +# prints in the read-only/no-lock path too; the network fetch that +# refreshes that ref runs only in the locked mutating fleet-sync sweep +# below (bounded by FM_UPSTREAM_FETCH_TIMEOUT, default 20s). The wording +# escalates from a plain FYI to "this repo's upstream sync needs +# attention" once local main is more than 30 commits behind upstream/main +# or the merge-base is older than 10 days. It only REPORTS; reconciling +# upstream is always a deliberately dispatched, reviewed ship task, never +# automated. No-op when there is no upstream remote or no upstream/main +# ref yet. # Fleet sync fetches, fast-forwards safe default-branch states, reports -# recovered and STUCK clone drift, and prunes gone local branches; it is +# recovered and STUCK clone drift, and prunes gone local branches, and it +# also refreshes firstmate's own upstream template for the UPSTREAM_DRIFT +# report above; it is # bounded by FM_FLEET_SYNC_BOOTSTRAP_TIMEOUT when it is a non-empty # numeric override, while non-numeric values fall back to 20s. # When the override is unset or blank, the timeout is @@ -148,7 +173,94 @@ fleet_sync_relay_all_output() { done < "$tmp" } +# Upstream-drift diagnostic for firstmate's OWN repo (both halves defined here). +# firstmate's upstream template (upstream/main after the remote swap; +# kunchenguid/firstmate) is read-only to this fleet - it can never be pushed or +# merged from here - so local main and upstream/main drift apart silently over +# time, and firstmate-repo ship tasks land local-only instead (AGENTS.md prime +# directives). The report reads whatever refs/remotes/upstream/main currently +# holds WITHOUT fetching, so it is safe in the read-only/no-lock detect path; the +# fetch runs only in the locked fleet-sync sweep. It only REPORTS - reconciling +# upstream stays a deliberately dispatched, reviewed ship task, never automated. +UPSTREAM_DRIFT_BEHIND_MAX=30 +UPSTREAM_DRIFT_DAYS_MAX=10 + +# Count-and-report half: unconditional (detect section), no network. Prints one +# FYI line every session with how far local main is ahead/behind upstream/main and +# days since their merge-base, escalating the wording to "needs attention" once +# local main is more than UPSTREAM_DRIFT_BEHIND_MAX commits behind OR the +# merge-base is older than UPSTREAM_DRIFT_DAYS_MAX days. No-op without an upstream +# remote, an upstream/main ref, or a local main. +upstream_drift_report() { + local behind ahead base="" base_ct="" base_date="unknown" now="" days="?" attention=0 + git -C "$FM_ROOT" remote get-url upstream >/dev/null 2>&1 || return 0 + git -C "$FM_ROOT" rev-parse --verify --quiet refs/remotes/upstream/main >/dev/null 2>&1 || return 0 + git -C "$FM_ROOT" rev-parse --verify --quiet refs/heads/main >/dev/null 2>&1 || return 0 + behind=$(git -C "$FM_ROOT" rev-list --count main..upstream/main 2>/dev/null) || return 0 + ahead=$(git -C "$FM_ROOT" rev-list --count upstream/main..main 2>/dev/null) || return 0 + base=$(git -C "$FM_ROOT" merge-base main upstream/main 2>/dev/null || true) + if [ -n "$base" ]; then + base_date=$(git -C "$FM_ROOT" log -1 --format=%cd --date=short "$base" 2>/dev/null || echo unknown) + base_ct=$(git -C "$FM_ROOT" log -1 --format=%ct "$base" 2>/dev/null || true) + now=$(date +%s 2>/dev/null || true) + if [ -n "$base_ct" ] && [ -n "$now" ]; then + days=$(( (now - base_ct) / 86400 )) + fi + fi + case "$behind" in ''|*[!0-9]*) ;; *) [ "$behind" -gt "$UPSTREAM_DRIFT_BEHIND_MAX" ] && attention=1 ;; esac + case "$days" in ''|*[!0-9]*) ;; *) [ "$days" -gt "$UPSTREAM_DRIFT_DAYS_MAX" ] && attention=1 ;; esac + if [ "$attention" -eq 1 ]; then + echo "UPSTREAM_DRIFT: this repo's upstream sync needs attention - local main is $behind behind / $ahead ahead of upstream/main, last reconciled ${days}d ago ($base_date); dispatch a reviewed reconciliation ship task" + else + echo "UPSTREAM_DRIFT: local main is $ahead ahead / $behind behind upstream/main, last reconciled ${days}d ago ($base_date)" + fi +} + +# Fetch half: MUTATING/network, called only from fleet_sync (the locked sweep), so +# the detect-only/read-only path never fetches. Best-effort and bounded - offline, +# a transient failure, or a stalled connection just leaves the last-fetched ref in +# place, and a bound always caps a stall so session start never hangs: `timeout` +# when available, `gtimeout` on a platform that only has the Homebrew coreutils +# name for it (mirrors bin/fm-nas-deploy-sync.sh's HAVE_TIMEOUT fallback), and a +# background-then-kill fallback (mirrors fleet_sync's own pattern below) when +# neither binary is installed at all. No-op without an upstream remote. +upstream_drift_fetch() { + git -C "$FM_ROOT" remote get-url upstream >/dev/null 2>&1 || return 0 + local seconds="${FM_UPSTREAM_FETCH_TIMEOUT:-20}" pid start monitor_was_on=0 + if command -v timeout >/dev/null 2>&1; then + timeout "$seconds" git -C "$FM_ROOT" fetch --quiet upstream 2>/dev/null || true + return 0 + fi + if command -v gtimeout >/dev/null 2>&1; then + gtimeout "$seconds" git -C "$FM_ROOT" fetch --quiet upstream 2>/dev/null || true + return 0 + fi + case $- in *m*) monitor_was_on=1 ;; esac + set -m 2>/dev/null || true + git -C "$FM_ROOT" fetch --quiet upstream 2>/dev/null & + pid=$! + start=$SECONDS + while kill -0 "$pid" 2>/dev/null; do + if [ "$((SECONDS - start))" -ge "$seconds" ]; then + kill -TERM "-$pid" 2>/dev/null || kill "$pid" 2>/dev/null || true + wait "$pid" 2>/dev/null || true + [ "$monitor_was_on" -eq 1 ] || set +m 2>/dev/null || true + return 0 + fi + sleep 1 + done + wait "$pid" 2>/dev/null || true + [ "$monitor_was_on" -eq 1 ] || set +m 2>/dev/null || true +} + fleet_sync() { + # Refresh firstmate's own read-only upstream template first, independent of the + # project-clone sync below (so it runs even with no clones present). This is the + # mutating/network half of the UPSTREAM_DRIFT diagnostic; upstream_drift_report + # in the detect section never fetches, keeping that report safe in the + # read-only detect-only path. + upstream_drift_fetch + [ -x "$FM_ROOT/bin/fm-fleet-sync.sh" ] || return 0 [ -d "$PROJECTS" ] || return 0 @@ -572,6 +684,32 @@ crew_dispatch_validate() { ' "$file" } +# Detect critical systemd units in the failed state. Reads one unit name per +# line from config/critical-services (blank lines and full-line # comments +# ignored) and prints one SERVICE_FAILED line per failed unit. Pure read-only +# detection via systemctl is-failed (no root); absent config file, no systemctl, +# or no failed unit all print nothing. +critical_services_check() { + local file unit ts + file="$CONFIG/critical-services" + [ -f "$file" ] || return 0 + command -v systemctl >/dev/null 2>&1 || return 0 + while IFS= read -r unit || [ -n "$unit" ]; do + unit="${unit#"${unit%%[![:space:]]*}"}" + unit="${unit%"${unit##*[![:space:]]}"}" + [ -n "$unit" ] || continue + case "$unit" in '#'*) continue ;; esac + if systemctl is-failed --quiet "$unit" >/dev/null 2>&1; then + ts=$(systemctl show "$unit" --property=StateChangeTimestamp --value 2>/dev/null || true) + if [ -n "$ts" ]; then + echo "SERVICE_FAILED: $unit - failed since $ts" + else + echo "SERVICE_FAILED: $unit - in failed state" + fi + fi + done < "$file" +} + if [ "${1:-}" = "install" ]; then shift [ $# -gt 0 ] || { echo "usage: fm-bootstrap.sh install ..." >&2; exit 1; } @@ -631,6 +769,8 @@ crew_dispatch_validate if ! fm_backlog_backend_manual "$CONFIG" && fm_tasks_axi_compatible; then echo "TASKS_AXI: available" fi +critical_services_check +upstream_drift_report if [ "${FM_BOOTSTRAP_DETECT_ONLY:-0}" != 1 ]; then secondmate_sync secondmate_liveness_sweep diff --git a/bin/fm-brief.sh b/bin/fm-brief.sh index a1b9cb540..1e2672030 100755 --- a/bin/fm-brief.sh +++ b/bin/fm-brief.sh @@ -34,6 +34,9 @@ # local-only implement on branch, stop and report "ready in branch" (no push/PR); # captain approves, firstmate merges to local main # Ship briefs begin with a worktree-isolation assertion before the branch step. +# Both ship and scout briefs include a docker-compose isolation note telling the +# crewmate to read .treehouse-compose-project and pass it on every docker +# compose invocation (docs/configuration.md "Docker Compose project isolation"). # Scout tasks ignore mode - their deliverable is a report, not a merge. # Every scaffold's status protocol distinguishes the configured # declared-external-wait verb (FM_CLASSIFY_PAUSED_VERB, default "paused") from @@ -236,6 +239,12 @@ This is a SCOUT task: the deliverable is a written report, not a PR. The worktree is your laboratory - install, run, edit, and make scratch commits freely; all of it is discarded at teardown. The report is the only thing that survives, so anything worth keeping must be in it. +This worktree also carries a docker-compose isolation marker at \`.treehouse-compose-project\` in the worktree root. +If this task starts docker or docker-compose, read that file and pass its contents explicitly on every \`docker compose\` invocation, e.g. \`docker compose -p "\$(cat .treehouse-compose-project)" up -d\`. +Exported env vars do not reliably persist between separate tool-call invocations, so if you use \`export COMPOSE_PROJECT_NAME=\$(cat .treehouse-compose-project)\` instead, restate it at the start of every docker-related shell command rather than exporting once and assuming it sticks. +Without this, Compose's default project-naming (derived from the worktree's directory basename) collides with every other worktree of this same project, and both fight over the same container/volume/network names. +A second, related collision vector is fixed host ports: prefer not publishing a hard-coded host port and query the assigned one with \`docker compose port \`, or otherwise pick a deterministic per-worktree-derived port, since two isolated stacks can still fight over a shared host port even with different project names. + # Rules 1. Never push to any remote and never open a PR. 2. Stay inside this worktree; the only files you may write outside it are the report and the status file below. @@ -341,6 +350,12 @@ You are in a disposable git worktree of $REPO, at a detached HEAD on a clean def The path check is authoritative: \`git rev-parse --git-dir\` and \`git rev-parse --git-common-dir\` can help inspect the repo, but they do not prove you are outside the primary checkout. If the top-level path is the primary checkout or not the worktree you were launched in, STOP - do not branch or commit here - append \`blocked: launched in primary checkout, not an isolated worktree\` to the status file and stop. +This worktree also carries a docker-compose isolation marker at \`.treehouse-compose-project\` in the worktree root. +If this task starts docker or docker-compose, read that file and pass its contents explicitly on every \`docker compose\` invocation, e.g. \`docker compose -p "\$(cat .treehouse-compose-project)" up -d\`. +Exported env vars do not reliably persist between separate tool-call invocations, so if you use \`export COMPOSE_PROJECT_NAME=\$(cat .treehouse-compose-project)\` instead, restate it at the start of every docker-related shell command rather than exporting once and assuming it sticks. +Without this, Compose's default project-naming (derived from the worktree's directory basename) collides with every other worktree of this same project, and both fight over the same container/volume/network names. +A second, related collision vector is fixed host ports: prefer not publishing a hard-coded host port and query the assigned one with \`docker compose port \`, or otherwise pick a deterministic per-worktree-derived port, since two isolated stacks can still fight over a shared host port even with different project names. + 1. First action: create your branch: \`git checkout -b fm/$ID\`$SETUP2 # Rules diff --git a/bin/fm-dispatch-select.sh b/bin/fm-dispatch-select.sh index c626e9a95..dfe100379 100755 --- a/bin/fm-dispatch-select.sh +++ b/bin/fm-dispatch-select.sh @@ -115,7 +115,9 @@ first_profile() { def clean($p): {harness: $p.harness} + (if ($p.model? | type) == "string" then {model: $p.model} else {} end) - + (if ($p.effort? | type) == "string" then {effort: $p.effort} else {} end); + + (if ($p.effort? | type) == "string" then {effort: $p.effort} else {} end) + + (if ($p.ultracode? | type) == "boolean" then {ultracode: $p.ultracode} else {} end) + + (if ($p.ultracode_role? | type) == "string" then {ultracode_role: $p.ultracode_role} else {} end); clean(.[0]) ' } @@ -169,7 +171,9 @@ selection=$(printf '%s\n' "$quota_json" | jq -ec \ def clean($p): {harness: $p.harness} + (if ($p.model? | type) == "string" then {model: $p.model} else {} end) - + (if ($p.effort? | type) == "string" then {effort: $p.effort} else {} end); + + (if ($p.effort? | type) == "string" then {effort: $p.effort} else {} end) + + (if ($p.ultracode? | type) == "boolean" then {ultracode: $p.ultracode} else {} end) + + (if ($p.ultracode_role? | type) == "string" then {ultracode_role: $p.ultracode_role} else {} end); def provider_for($h): [.providers[]? | select(.provider == $h)][0]; def general_ids($h): if $h == "claude" then ["five_hour", "seven_day"] diff --git a/bin/fm-merge-local.sh b/bin/fm-merge-local.sh index fdc801148..b1eba0391 100755 --- a/bin/fm-merge-local.sh +++ b/bin/fm-merge-local.sh @@ -9,7 +9,21 @@ # auto-approves), and only as a clean fast-forward - it refuses a diverged branch # and tells you to have the crewmate rebase. See AGENTS.md prime directives, # project management, and task lifecycle. -# Usage: fm-merge-local.sh +# +# After the fast-forward, the project's origin is pushed only when the project +# IS firstmate's own repo (PROJ resolves to the same real path as FM_ROOT) - that +# is the deliberate fork-sync case (AGENTS.md prime directives; section 12's +# self-update model), where origin is the captain's own fork and keeping its +# default branch in sync is intended. A local-only PROJECT's contract is "no +# remote, no PR" (AGENTS.md section 6); auto-pushing an arbitrary local-only +# project's origin would silently break that promise, so every other project +# needs the explicit --push-origin flag to opt in. +# +# Usage: fm-merge-local.sh [--push-origin] +# --push-origin push the fast-forwarded default branch to origin even when +# PROJ is not firstmate's own repo. Only pass this on the +# captain's explicit request for that project; firstmate's own +# repo pushes automatically without it. set -eu SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" @@ -17,7 +31,12 @@ FM_ROOT="${FM_ROOT_OVERRIDE:-$(cd "$SCRIPT_DIR/.." && pwd)}" FM_HOME="${FM_HOME:-${FM_ROOT_OVERRIDE:-$FM_ROOT}}" STATE="${FM_STATE_OVERRIDE:-$FM_HOME/state}" "$FM_ROOT/bin/fm-guard.sh" || true -ID=${1:?usage: fm-merge-local.sh } +ID=${1:?usage: fm-merge-local.sh [--push-origin]} +PUSH_ORIGIN_OPT=${2:-} +case "$PUSH_ORIGIN_OPT" in + ''|--push-origin) ;; + *) echo "error: unknown argument '$PUSH_ORIGIN_OPT'; usage: fm-merge-local.sh [--push-origin]" >&2; exit 1 ;; +esac META="$STATE/$ID.meta" [ -f "$META" ] || { echo "error: no meta for task $ID at $META" >&2; exit 1; } @@ -66,3 +85,27 @@ before=$(git -C "$PROJ" rev-parse --short "$DEFAULT") git -C "$PROJ" merge --ff-only "$BRANCH" >/dev/null after=$(git -C "$PROJ" rev-parse --short "$DEFAULT") echo "merged $BRANCH into local $DEFAULT ($before -> $after) in $PROJ" + +# Keep a push-backed default branch synced with the merge that just landed, so +# the remote never silently drifts behind local main - but ONLY when PROJ is +# firstmate's own repo (the deliberate fork-sync case; see header) or the caller +# passed --push-origin explicitly. Best-effort by design when it does push: the +# local fast-forward above is the operation that matters, so a push failure +# (offline, transient network, or a non-fast-forward rejection) is reported but +# never fails the merge. A pure local-only project with no origin remote has +# nowhere to push and is skipped silently - not every local-only project is +# remote-backed. +proj_abs=$(cd "$PROJ" && pwd -P) +fm_root_abs=$(cd "$FM_ROOT" && pwd -P) +is_firstmate_repo=0 +[ "$proj_abs" = "$fm_root_abs" ] && is_firstmate_repo=1 + +if [ "$is_firstmate_repo" -eq 1 ] || [ "$PUSH_ORIGIN_OPT" = "--push-origin" ]; then + if git -C "$PROJ" remote get-url origin >/dev/null 2>&1; then + if git -C "$PROJ" push origin "$DEFAULT" >/dev/null 2>&1; then + echo "pushed $DEFAULT to origin in $PROJ" + else + echo "warning: local $DEFAULT merged, but syncing it to origin failed in $PROJ (best-effort; merge succeeded)" >&2 + fi + fi +fi diff --git a/bin/fm-nas-deploy-sync.sh b/bin/fm-nas-deploy-sync.sh new file mode 100755 index 000000000..1233dc9f7 --- /dev/null +++ b/bin/fm-nas-deploy-sync.sh @@ -0,0 +1,316 @@ +#!/usr/bin/env bash +# Best-effort, non-fatal deploy sync for a single project's live NAS checkout: a +# merged PR lands in the project's GitHub default branch, but the live app on this +# host runs from its own separate checkout under /mnt/nas/experiments//, +# managed by pm2 - that checkout does not update itself (see the 2026-07-04 entry +# in data/learnings.md). This script closes that gap after a landed ship task. +# +# Looks the project up in data/nas-deployments.md, a pipe-table with one row per +# deployed project: "| | | |" (comma- +# separated when more than one process serves the app). A project absent from +# that table - or a fresh checkout with no data/nas-deployments.md at all - has no +# known live deployment, which is not an error: prints one skip line and exits 0. +# +# When present: fetches the NAS checkout's origin and fast-forward-only merges to +# origin/, mirroring bin/fm-fleet-sync.sh's dirty/diverged safety exactly +# - never force, never discard local changes, never touch a checkout that is off +# its default branch, dirty, or diverged (reported as STUCK, left untouched). +# Restarts the recorded pm2 process(es) only when the merge actually advanced +# HEAD, then verifies each is back online via `pm2 jlist`. Always prints exactly +# one clear result line and exits 0 - this script is best-effort and must never +# fail or block its caller (see the post-teardown call in bin/fm-teardown.sh). +# +# Usage: fm-nas-deploy-sync.sh +# +# Overrides (test injection): FM_DATA_OVERRIDE points at an alternate data/ dir +# (same knob bin/fm-project-mode.sh uses); FM_NAS_DEPLOYMENTS_OVERRIDE points at +# an alternate mapping file directly. pm2 is invoked via PATH, so a fakebin shim +# ahead of it on PATH intercepts restart/list during tests - real tests must never +# reach the real /mnt/nas/experiments or a real pm2 process. +# +# Every filesystem/git touch of $NAS_PATH is wrapped in a bounded timeout +# (FM_NAS_SYNC_TIMEOUT seconds, default 15): the mount is a NAS, and an +# unreachable one is a hang risk (a stuck stat/read), not a fast failure, which +# would otherwise stall fm-teardown.sh's caller and break this script's +# non-blocking contract. +# +# $NAS_PATH is one single shared live-deployment checkout - unlike a project's +# projects/ dev clone, which is scoped to one firstmate home, two ship +# tasks for the same project landing moments apart can both reach the SAME +# NAS checkout from concurrent teardowns. That races the fetch on an orphaned +# .git/packed-refs.lock exactly like bin/fm-fleet-sync.sh's fetch had to guard +# against; fetch_with_packed_refs_lock_guard below mirrors that recovery, +# sharing the staleness proof from bin/fm-lock-lib.sh, bounded by +# FM_NAS_SYNC_PACKED_REFS_LOCK_RETRIES / _RETRY_WAIT_SECS / _AGE_SECS. +set -eu + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +FM_ROOT="${FM_ROOT_OVERRIDE:-$(cd "$SCRIPT_DIR/.." && pwd)}" +FM_HOME="${FM_HOME:-${FM_ROOT_OVERRIDE:-$FM_ROOT}}" +DATA="${FM_DATA_OVERRIDE:-$FM_HOME/data}" +MAP="${FM_NAS_DEPLOYMENTS_OVERRIDE:-$DATA/nas-deployments.md}" +NAS_SYNC_TIMEOUT="${FM_NAS_SYNC_TIMEOUT:-15}" +# shellcheck source=bin/fm-lock-lib.sh +. "$SCRIPT_DIR/fm-lock-lib.sh" +FM_LOCK_LOG_PREFIX=nas-deploy-sync + +NAS_SYNC_PACKED_REFS_LOCK_RETRIES=${FM_NAS_SYNC_PACKED_REFS_LOCK_RETRIES:-3} +NAS_SYNC_PACKED_REFS_LOCK_RETRY_WAIT_SECS=${FM_NAS_SYNC_PACKED_REFS_LOCK_RETRY_WAIT_SECS:-1} +NAS_SYNC_PACKED_REFS_LOCK_AGE_SECS=${FM_NAS_SYNC_PACKED_REFS_LOCK_AGE_SECS:-30} +case "$NAS_SYNC_PACKED_REFS_LOCK_RETRIES" in ''|*[!0-9]*) NAS_SYNC_PACKED_REFS_LOCK_RETRIES=3 ;; esac +case "$NAS_SYNC_PACKED_REFS_LOCK_AGE_SECS" in ''|*[!0-9]*) NAS_SYNC_PACKED_REFS_LOCK_AGE_SECS=30 ;; esac +if ! [[ "$NAS_SYNC_PACKED_REFS_LOCK_RETRY_WAIT_SECS" =~ ^([0-9]+([.][0-9]*)?|[.][0-9]+)$ ]]; then + echo "nas-deploy-sync: invalid packed-refs lock retry wait '$NAS_SYNC_PACKED_REFS_LOCK_RETRY_WAIT_SECS'; using 1s" >&2 + NAS_SYNC_PACKED_REFS_LOCK_RETRY_WAIT_SECS=1 +fi + +HAVE_TIMEOUT=none +if command -v timeout >/dev/null 2>&1; then + HAVE_TIMEOUT=timeout +elif command -v gtimeout >/dev/null 2>&1; then + HAVE_TIMEOUT=gtimeout +fi + +# bounded : run , killed after $NAS_SYNC_TIMEOUT seconds when +# a `timeout`/`gtimeout` binary is available, run directly otherwise. +bounded() { + case "$HAVE_TIMEOUT" in + timeout) timeout "$NAS_SYNC_TIMEOUT" "$@" ;; + gtimeout) gtimeout "$NAS_SYNC_TIMEOUT" "$@" ;; + *) "$@" ;; + esac +} + +# git_nas : git -C "$NAS_PATH" , bounded. +git_nas() { + bounded git -C "$NAS_PATH" "$@" +} + +usage() { + echo "usage: fm-nas-deploy-sync.sh " >&2 +} + +if [ "${1:-}" = "--help" ] || [ "${1:-}" = "-h" ]; then + usage + exit 0 +fi +[ $# -eq 1 ] || { usage; exit 1; } +NAME=$1 + +first_line() { + printf '%s\n' "$1" | sed -n '1s/[[:space:]]\{1,\}/ /g;1p' +} + +# True when git stderr shows the packed-refs.lock "File exists" race, mirroring +# bin/fm-fleet-sync.sh's is_packed_refs_lock_error. +is_packed_refs_lock_error() { + printf '%s\n' "$1" | grep -Eq "Unable to create ['\"].*packed-refs\\.lock['\"]: File exists" +} + +# Absolute path to $NAS_PATH's packed-refs.lock, or empty when it cannot be +# resolved. +packed_refs_lock_path() { + local lock abs + lock=$(git_nas rev-parse --git-path packed-refs.lock 2>/dev/null) || return 1 + [ -n "$lock" ] || return 1 + case "$lock" in + /*) printf '%s\n' "$lock" ;; + *) + abs=$(cd "$NAS_PATH" && pwd -P) || return 1 + printf '%s/%s\n' "$abs" "$lock" + ;; + esac +} + +# Run `git_nas fetch origin --quiet`, tolerating an orphaned packed-refs.lock +# left by a second landed-teardown racing this exact NAS checkout. Sets +# FETCH_OUTPUT and returns the fetch's exit status; mirrors bin/fm-fleet-sync.sh's +# fetch_with_packed_refs_lock_guard retry-then-provably-stale-clear contract, +# sharing the staleness proof from bin/fm-lock-lib.sh. +fetch_with_packed_refs_lock_guard() { + local rc attempt=0 lock lock_desc + FETCH_OUTPUT=$(git_nas fetch origin --quiet 2>&1); rc=$? + [ "$rc" -eq 0 ] && return 0 + is_packed_refs_lock_error "$FETCH_OUTPUT" || return "$rc" + + lock=$(packed_refs_lock_path) || lock="" + lock_desc=${lock:-packed-refs.lock} + while [ "$attempt" -lt "$NAS_SYNC_PACKED_REFS_LOCK_RETRIES" ]; do + attempt=$(( attempt + 1 )) + echo "$NAME: fetch blocked by packed-refs lock ($lock_desc) at $NAS_PATH; waiting ${NAS_SYNC_PACKED_REFS_LOCK_RETRY_WAIT_SECS}s and retrying ($attempt/${NAS_SYNC_PACKED_REFS_LOCK_RETRIES}) (owning process may be exiting)" >&2 + sleep "$NAS_SYNC_PACKED_REFS_LOCK_RETRY_WAIT_SECS" + FETCH_OUTPUT=$(git_nas fetch origin --quiet 2>&1); rc=$? + if [ "$rc" -eq 0 ]; then + echo "$NAME: fetch succeeded on retry; packed-refs lock cleared on its own" >&2 + return 0 + fi + is_packed_refs_lock_error "$FETCH_OUTPUT" || return "$rc" + done + + # Retries exhausted and still the lock signature. Clear ONLY if provably stale. + lock=$(packed_refs_lock_path) || lock="" + if [ -n "$lock" ] && [ -e "$lock" ]; then + if fm_lock_is_provably_stale "$lock" "$NAS_PATH" "$NAS_SYNC_PACKED_REFS_LOCK_AGE_SECS"; then + if ! rm -f "$lock"; then + echo "$NAME: failed to remove provably-stale packed-refs lock $lock; leaving it in place" >&2 + return "$rc" + fi + echo "$NAME: removed provably-stale packed-refs lock $lock (age >= ${NAS_SYNC_PACKED_REFS_LOCK_AGE_SECS}s, no live holder) and retrying fetch" >&2 + FETCH_OUTPUT=$(git_nas fetch origin --quiet 2>&1); rc=$? + if [ "$rc" -eq 0 ]; then + echo "$NAME: fetch succeeded after stale packed-refs lock cleanup" >&2 + return 0 + fi + return "$rc" + fi + echo "$NAME: fetch blocked by packed-refs lock $lock that persisted across ${NAS_SYNC_PACKED_REFS_LOCK_RETRIES} retries and is not provably stale (may belong to a live process); leaving it in place" >&2 + return "$rc" + fi + echo "$NAME: fetch packed-refs lock signature persisted across ${NAS_SYNC_PACKED_REFS_LOCK_RETRIES} retries even after the lock file disappeared" >&2 + return "$rc" +} + +# lookup_row: print "|" for $NAME's row in $MAP, or +# nothing when the file is absent or has no matching row. +lookup_row() { + [ -f "$MAP" ] || return 0 + # $3 ~ /^\// excludes the header ("nas_repo_path") and separator ("---") rows - + # a real NAS path is always absolute - so a project literally named "project" + # cannot collide with the header's own column label. + awk -F'|' -v n="$NAME" ' + { for (i = 1; i <= NF; i++) { gsub(/^[ \t]+|[ \t]+$/, "", $i) } } + NF >= 4 && $2 == n && $3 ~ /^\// { print $3 "|" $4; exit } + ' "$MAP" +} + +row=$(lookup_row) +if [ -z "$row" ]; then + echo "$NAME: skipped: no recorded NAS deployment" + exit 0 +fi +NAS_PATH=${row%%|*} +PROCS=${row#*|} + +if ! bounded test -d "$NAS_PATH"; then + echo "$NAME: skipped: NAS path $NAS_PATH not a directory" + exit 0 +fi +if ! git_nas rev-parse --is-inside-work-tree >/dev/null 2>&1; then + echo "$NAME: skipped: $NAS_PATH not a git repo" + exit 0 +fi +if ! git_nas remote get-url origin >/dev/null 2>&1; then + echo "$NAME: skipped: no origin remote at $NAS_PATH" + exit 0 +fi + +if ! fetch_with_packed_refs_lock_guard; then + reason="fetch failed" + [ -z "$FETCH_OUTPUT" ] || reason="$reason: $(first_line "$FETCH_OUTPUT")" + echo "$NAME: skipped: $reason" + exit 0 +fi + +default_branch() { + local ref branch + ref=$(git_nas symbolic-ref --quiet --short refs/remotes/origin/HEAD 2>/dev/null || true) + if [ -n "$ref" ]; then + echo "${ref#origin/}" + return 0 + fi + for branch in main master; do + if git_nas show-ref --verify --quiet "refs/heads/$branch"; then + echo "$branch" + return 0 + fi + done + return 1 +} + +DEFAULT=$(default_branch) || { + echo "$NAME: skipped: cannot determine default branch at $NAS_PATH" + exit 0 +} +BASE="origin/$DEFAULT" +if ! git_nas rev-parse --verify --quiet "$BASE^{commit}" >/dev/null; then + echo "$NAME: skipped: $BASE does not exist at $NAS_PATH" + exit 0 +fi + +cur=$(git_nas symbolic-ref --quiet --short HEAD 2>/dev/null || echo "") +dirty=no +[ -z "$(git_nas status --porcelain 2>/dev/null | head -1)" ] || dirty=yes + +if [ "$cur" != "$DEFAULT" ]; then + echo "$NAME: STUCK: NAS checkout at $NAS_PATH is not on $DEFAULT - needs attention" + exit 0 +fi +if [ "$dirty" = yes ]; then + echo "$NAME: STUCK: NAS checkout at $NAS_PATH has uncommitted changes - needs attention" + exit 0 +fi + +local_rev="" +if ! local_rev=$(git_nas rev-parse --verify --quiet "$DEFAULT"); then + echo "$NAME: skipped: cannot read local $DEFAULT at $NAS_PATH" + exit 0 +fi +remote_rev="" +if ! remote_rev=$(git_nas rev-parse --verify --quiet "$BASE"); then + echo "$NAME: skipped: cannot read $BASE at $NAS_PATH" + exit 0 +fi +if [ "$local_rev" = "$remote_rev" ]; then + echo "$NAME: already current" + exit 0 +fi +if ! git_nas merge-base --is-ancestor "$DEFAULT" "$BASE"; then + behind=$(git_nas rev-list --count "HEAD..$BASE" 2>/dev/null) || behind="?" + echo "$NAME: STUCK: NAS checkout at $NAS_PATH diverged from $BASE, $behind commits behind - needs attention" + exit 0 +fi + +before=$(git_nas rev-parse --short "$DEFAULT") +merge_output="" +if ! merge_output=$(git_nas merge --ff-only "$BASE" 2>&1); then + reason="fast-forward failed" + [ -z "$merge_output" ] || reason="$reason: $(first_line "$merge_output")" + echo "$NAME: skipped: $reason" + exit 0 +fi +after=$(git_nas rev-parse --short "$DEFAULT") + +# process_online : true when pm2 currently reports EVERY instance of +# as online (a clustered app can register several jlist entries under +# the same name; one lagging instance must not be masked by the others). +process_online() { + local proc=$1 status + status=$(pm2 jlist 2>/dev/null | jq -r --arg n "$proc" \ + '[.[] | select(.name == $n) | .pm2_env.status] as $s + | if ($s | length) == 0 then "missing" + elif all($s[]; . == "online") then "online" + else "not-online" + end' 2>/dev/null) || status="missing" + [ "$status" = "online" ] +} + +restart_problems="" +IFS=',' read -r -a procs <<< "$PROCS" +for proc in "${procs[@]}"; do + proc="${proc#"${proc%%[![:space:]]*}"}" + proc="${proc%"${proc##*[![:space:]]}"}" + [ -n "$proc" ] || continue + if ! pm2 restart "$proc" >/dev/null 2>&1; then + restart_problems="$restart_problems $proc(restart failed)" + continue + fi + if ! process_online "$proc"; then + restart_problems="$restart_problems $proc(not online after restart)" + fi +done + +if [ -n "$restart_problems" ]; then + echo "$NAME: synced $before..$after but restart verification failed:$restart_problems - needs attention" + exit 0 +fi +echo "$NAME: synced $before..$after, restarted $PROCS and verified online" diff --git a/bin/fm-risk-tripwire.sh b/bin/fm-risk-tripwire.sh new file mode 100755 index 000000000..e684eff57 --- /dev/null +++ b/bin/fm-risk-tripwire.sh @@ -0,0 +1,248 @@ +#!/usr/bin/env bash +# Mechanical risk trip-wire (guardrail #2): greps a task's brief text and, once +# code exists, its changed file paths for migration/auth/schema/security +# signals - a second, structurally different check from the natural-language +# "when" match a crew-dispatch rule already made, so a misclassified risky task +# cannot slip to a cheap model/effort tier on a single judgment call +# (data/research-resource-tiering-synthesis.md). +# +# Usage: fm-risk-tripwire.sh +# +# Checks whatever is available for : +# - data//brief.md, if it exists (works before spawn, right after +# bin/fm-brief.sh scaffolds it - the first checkpoint) +# - the worktree's changed file paths vs its project's default branch, if +# state/.meta records worktree=/project= (works after spawn, at +# Validate time - the second, binding checkpoint against the real diff) +# Exit codes: +# 0 no risk signal found +# 1 a RISK hit fired (one "RISK: " line per hit is printed) +# 2 could not check: a malformed invocation, neither a brief nor a usable +# worktree/project exists yet (nothing to check), or the worktree/project +# exist but their diff base could not be resolved, so the binding diff +# checkpoint could not run (warned to stderr, never a silent clean pass) +# Distinct codes matter so a caller branching on $? cannot mistake a malformed +# invocation for a real risk hit. A hit means: floor this task's model/effort to +# the safety-critical profile (opus/xhigh, ultracode independent-review) +# regardless of which rule the natural-language dispatch match picked, per +# AGENTS.md section 4's risk floor. +# +# This is a coarse, unpushed-diff-vs-default-branch name-only comparison, not +# the PR-aware exact diff bin/fm-review-diff.sh computes - good enough for a +# keyword scan, not a substitute for that script's authoritative base. +set -eu + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +FM_ROOT="${FM_ROOT_OVERRIDE:-$(cd "$SCRIPT_DIR/.." && pwd)}" +FM_HOME="${FM_HOME:-${FM_ROOT_OVERRIDE:-$FM_ROOT}}" +STATE="${FM_STATE_OVERRIDE:-$FM_HOME/state}" +DATA="${FM_DATA_OVERRIDE:-$FM_HOME/data}" + +# shellcheck source=bin/fm-tangle-lib.sh +. "$SCRIPT_DIR/fm-tangle-lib.sh" + +usage() { + echo "usage: fm-risk-tripwire.sh " >&2 +} + +if [ "${1:-}" = "-h" ] || [ "${1:-}" = "--help" ]; then + usage + exit 0 +fi + +ID=${1:-} +[ -n "$ID" ] || { usage; exit 2; } +[ $# -le 1 ] || { usage; exit 2; } + +# Case-insensitive, word-bounded match against the brief's prose, tolerating the +# inflections and affixes real task phrasing uses. Word bounding stops substring +# false positives like "auth" inside "authoritative", but three things must still +# reach the scan or a genuinely risky task slips to a cheap tier (the dangerous +# direction for a safety floor): +# - verb forms need their own stems: appending the outer (s|ed|ing|ion|...) +# suffix to a bare NOUN literal cannot reach the verb, so "migration" alone +# could only become "migrations", never "migrate"/"migrating"/"migrated", +# and the bare "auth" branch never reaches "authorize"/"authenticate". +# - the un/re/de/pre prefixes ("unauthorized"/"unauthenticated" - the most +# common access-control phrasing) glue a letter onto the stem's front, so +# the auth stems carry an explicit optional prefix. +# - a bare "auth"-anything stem is still avoided, so "authoritative"/"author" +# stay shut. +# Word bounding is done by splitting the body into whole tokens (below), NOT by +# grep's \< / \> anchors: those are a GNU extension BSD grep does not honor, so +# on macOS they would silently match nothing and let every risky brief through - +# a false negative in the dangerous direction. Whole-token matching is identical +# on GNU and BSD grep and, unlike a boundary-consuming grep -o pattern, still +# reports BOTH words of an adjacent risk pair like "session token" (a consumed +# shared delimiter would drop the second). Single-word keywords go in WORD_REGEX; +# the multi-word phrases have no lone token and are matched on the +# space-normalized stream via PHRASE_REGEX. +WORD_KEYWORDS='auth|authentication|authorization|(un|re|de|pre)?authoriz(e|ed|es|ing|ation|ations|er|ers)?|(un|re|de|pre)?authenticat(e|ed|es|ing|ion|ions|or|ors)?|session|credential|password|secret|token|payment|billing|migrat(e|ed|es|ing|ion|ions)|schema|security|encrypt|decrypt|permission' +WORD_REGEX="(${WORD_KEYWORDS})(s|es|ed|ing|ion|ions)?" +PHRASE_REGEX='(access[[:space:]]+control|data[[:space:]]+deletion|bulk[[:space:]]+mutation|public[[:space:]]+exposure|breaking[[:space:]]+change)(s|es|ed|ing|ion|ions)?' + +# Scan only the task-specific body of the brief (the # Task section up to the +# next scaffold section heading), never the fixed scaffold boilerplate +# bin/fm-brief.sh writes into every brief - that boilerplate contains benign +# words like "authoritative" and "future session" that would otherwise trip the +# wire on every task. The Herdr block bin/fm-brief.sh injects immediately after +# # Task (either the # Herdr isolation ... hard-safety contract, whose text is +# dense with "session"/"--session", or the # Herdr lifecycle declaration ... +# not-enabled stub) is scaffold boilerplate too, so its heading is a boundary as +# well; without it every --herdr-lab brief would trip on the contract's own +# "session" wording rather than the real task text. The section boundary is one +# of the scaffold's own known headings (# Herdr isolation .../# Herdr lifecycle +# declaration .../# Setup/# Rules/# Project memory/# Definition of done), not any +# column-0 "# " line: a shell/code comment embedded in the task body (e.g. +# "# then run the schema migration") must NOT end the scan, or the risk words +# after it are silently dropped - the dangerous direction for a safety floor. +# A boundary heading must also be blank-line-preceded, as every real scaffold +# heading is (bin/fm-brief.sh emits a blank line before each), so a task body +# that itself quotes a bare "# Setup" line inline does not cut the scan short. +# Lines inside a fenced code block are likewise never treated as a boundary. +# Falls back to the whole brief when there is no # Task section (a non-standard +# or hand-written brief), keeping the permissive safety bias. +brief_task_body() { + local body + body=$(awk ' + { blank = ($0 ~ /^[[:space:]]*$/) } + /^```/ { fence = !fence; prevblank = blank; next } + !fence && /^# Task[[:space:]]*$/ { intask=1; prevblank = blank; next } + intask && !fence && prevblank && /^# (Herdr isolation.*|Herdr lifecycle declaration.*|Setup|Rules|Project memory|Definition of done)[[:space:]]*$/ { intask=0 } + intask { print } + { prevblank = blank } + ' "$1") + if [ -n "$body" ]; then + printf '%s\n' "$body" + else + cat "$1" + fi +} + +# Component/token match against one changed file's path (already lowercased by +# the caller). Deliberately NOT a blanket bin/* match: firstmate's own +# supervision backbone lives under bin/ and is routed by an explicit dispatch +# rule (see docs/examples/crew-dispatch.json), so flooring every bin/ change +# here would override that rule and defeat the finer tiers. +# +# The same word-boundary discipline as the brief-text scan applies here, so a +# risk word must be a real path component or delimited token, not a bare +# substring: "strong" words (auth/migrat/schema/... families) match anywhere +# they appear as a /, -, _, or . delimited token, catching bin/auth-setup.sh, +# bin/run-migration.sh, and db/schema.sql; the weaker "session" matches only as +# a whole path component or filename base (lib/auth/session.rb, +# app/models/session.rb), never as a hyphen fragment - otherwise the +# supervision backbone bin/fm-session-start.sh would over-match. Bare-substring +# false positives like "auth" inside AUTHORS/docs/authors.md no longer trip. +# The flip side is intentional: a risk word glued into a compound component with +# NO delimiter (e.g. "authsetup.rb") is not matched, because catching it would +# require substring matching again and reopen exactly those false positives; the +# brief-text scan and the delimiter tokenization below cover the realistic cases. +PATH_STRONG_REGEX='^(auth|authn|authz|authoriz(e|ed|es|ing|ation|ations|er|ers)?|authenticat(e|ed|es|ing|ion|ions|or|ors)?|migrat(e|ed|es|ing|ion|ions)|schema|schemas|secret|secrets|credential|credentials|payment|payments|billing|security|password|passwords|token|tokens|permission|permissions|encrypt(s|ed|ing|ion|ions)?|decrypt(s|ed|ing|ion|ions)?)$' +PATH_WEAK_REGEX='^(session|sessions)$' +path_is_risky() { + local path=$1 comp base + case "$path" in + .github/workflows/*|*/.github/workflows/*) return 0 ;; + *dockerfile*|*docker-compose*) return 0 ;; + esac + while IFS= read -r comp; do + [ -n "$comp" ] || continue + base=${comp%.*} + # Whole path component or filename base equal to a strong or weak word. + if printf '%s\n%s\n' "$comp" "$base" | grep -Eiq "$PATH_STRONG_REGEX|$PATH_WEAK_REGEX"; then + return 0 + fi + # Strong words also match as a ., -, or _ delimited token inside a compound + # name (e.g. config.schema.json, run-migration.sh), the fail-safe direction. + if printf '%s\n' "$base" | tr '._-' '\n' | grep -Eiq "$PATH_STRONG_REGEX"; then + return 0 + fi + done < <(printf '%s\n' "$path" | tr '/' '\n') + return 1 +} + +FOUND=0 +CHECKED=0 +DIFF_UNRESOLVED=0 + +BRIEF="$DATA/$ID/brief.md" +if [ -f "$BRIEF" ]; then + CHECKED=1 + lc=$(brief_task_body "$BRIEF" | tr '[:upper:]' '[:lower:]') + # Split on every non-alnum char so each word is its own token (this also + # splits snake_case identifiers like run_schema_migration), then match whole + # tokens; phrases keep their inter-word gap on the space-normalized stream. + word_hits=$(printf '%s\n' "$lc" | tr -c '[:alnum:]' '\n' | grep -xE "$WORD_REGEX" || true) + phrase_hits=$(printf '%s\n' "$lc" | tr -c '[:alnum:]' ' ' | tr -s ' ' | grep -oE "$PHRASE_REGEX" || true) + hit=$(printf '%s\n%s\n' "$word_hits" "$phrase_hits" | sed '/^$/d' | sort -u | tr '\n' ',' | sed 's/,$//') + if [ -n "$hit" ]; then + echo "RISK: brief for $ID mentions risk-adjacent term(s): $hit" + FOUND=1 + fi +fi + +META="$STATE/$ID.meta" +if [ -f "$META" ]; then + WT=$(grep '^worktree=' "$META" | tail -1 | cut -d= -f2- || true) + PROJ=$(grep '^project=' "$META" | tail -1 | cut -d= -f2- || true) + if [ -n "$WT" ] && [ -n "$PROJ" ] && [ -d "$WT" ] && [ -d "$PROJ" ]; then + CHECKED=1 + diff_base_resolved=0 + # The base resolution below duplicates bin/fm-review-diff.sh's origin fetch + # and origin/ verification on purpose: this scan needs the changed + # PATH LIST, but fm-review-diff.sh only exposes --stat (a diffstat), not a + # --name-only path list, so there is nothing to reuse for a name scan. + # Adding a --name-only mode to that script is the clean fix and is left as a + # follow-up rather than expanding this task's scope into another owner. + DEFAULT=$(fm_default_branch "$PROJ" 2>/dev/null || true) + if [ -n "$DEFAULT" ]; then + BASE="$DEFAULT" + if git -C "$PROJ" remote get-url origin >/dev/null 2>&1; then + git -C "$WT" fetch origin "+refs/heads/$DEFAULT:refs/remotes/origin/$DEFAULT" --quiet 2>/dev/null || true + git -C "$WT" rev-parse --verify --quiet "refs/remotes/origin/$DEFAULT^{commit}" >/dev/null 2>&1 && BASE="origin/$DEFAULT" + fi + if git -C "$WT" rev-parse --verify --quiet "$BASE^{commit}" >/dev/null 2>&1; then + diff_base_resolved=1 + diff_paths=$(git -C "$WT" diff --name-only "$BASE...HEAD" -- 2>/dev/null || true) + risky_paths= + if [ -n "$diff_paths" ]; then + while IFS= read -r path; do + [ -n "$path" ] || continue + lower_path=$(printf '%s' "$path" | tr '[:upper:]' '[:lower:]') + if path_is_risky "$lower_path"; then + risky_paths="${risky_paths}${risky_paths:+, }$path" + fi + done <<< "$diff_paths" + fi + if [ -n "$risky_paths" ]; then + echo "RISK: diff for $ID touches risk-adjacent path(s): $risky_paths" + FOUND=1 + fi + fi + fi + # The worktree/project exist, so the binding diff checkpoint was expected to + # run - but the diff base could not be resolved (no default branch, or the + # base commit does not verify in the worktree). Do not let that read as a + # clean pass: warn loudly, like the sibling bin/fm-review-diff.sh, and mark + # the run not-checkable so a caller branching on $? floors the task rather + # than trusting a silent 0 - the safe direction for this guardrail. + if [ "$diff_base_resolved" -eq 0 ]; then + echo "warning: could not resolve a diff base for $ID (project $PROJ, default branch '${DEFAULT:-unresolved}'); the diff checkpoint did not run - reporting not-checkable (exit 2), not a clean pass" >&2 + DIFF_UNRESOLVED=1 + fi + fi +fi + +if [ "$CHECKED" -eq 0 ]; then + echo "error: neither $BRIEF nor a usable worktree/project in $META was found for $ID; nothing to check" >&2 + exit 2 +fi + +# A real risk hit (exit 1) always wins over an unresolvable diff base; only when +# nothing tripped does an unresolvable base downgrade the run to could-not-check. +if [ "$FOUND" -eq 0 ] && [ "$DIFF_UNRESOLVED" -eq 1 ]; then + exit 2 +fi + +exit "$FOUND" diff --git a/bin/fm-spawn.sh b/bin/fm-spawn.sh index a4ec0890c..5f453c379 100755 --- a/bin/fm-spawn.sh +++ b/bin/fm-spawn.sh @@ -79,6 +79,19 @@ # On success prints: spawned harness= kind= mode= yolo= window= worktree= # mode/yolo are resolved per-project from data/projects.md for ship/scout tasks; # secondmate spawns record mode=secondmate, yolo=off, home=, and projects=. +# Ship/scout spawns also derive a Docker-Compose-safe project name from the +# worktree's own pool-slot path, write it to /.treehouse-compose-project +# (excluded from git via .git/info/exclude, like the per-harness turn-end hook +# files below), and record it in meta as compose_project=, so two +# worktrees of the same project never collide on Compose's default +# project-naming (fm-brief.sh documents how a crewmate consumes it). +# claude launches (crewmate, scout, and secondmate) carry +# CLAUDE_CODE_AUTO_COMPACT_WINDOW=300000 so they auto-compact the way the primary +# interactive session already does via its own .claude/settings.local.json, which a +# separately-launched claude process never inherits; see the comment on the claude +# case in launch_template() below for why 300000 (not the primary's +# WINDOW=1000000 + PCT_OVERRIDE=20 pair) is safe to hardcode: it is capped at the +# real context window, so it is a no-op below that window and takes effect above it. set -eu SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" @@ -321,7 +334,25 @@ launch_template() { # does NOT suppress the interactive ghost text (verified empirically), so the env # var is the correct control. The dim-aware composer reader in fm-tmux-lib.sh is # the defense-in-depth backstop for any pane this flag cannot reach. - claude) printf '%s' 'CLAUDE_CODE_ENABLE_PROMPT_SUGGESTION=false claude --dangerously-skip-permissions __MODELFLAG____EFFORTFLAG__"$(cat __BRIEF__)"' ;; + # + # CLAUDE_CODE_AUTO_COMPACT_WINDOW=300000 gives claude crewmates and secondmates + # a higher auto-compaction ceiling than the plain-window default, the same way + # the primary interactive session already has via its own + # .claude/settings.local.json, which these separately-launched processes never + # inherit. The var is read once at startup and is CAPPED at the model's actual + # context window, so it can only lower the effective trigger, never raise it past + # the real ceiling: min(300000, window) is 300000 once window exceeds it, but a + # no-op (stays at window) below that. This is not a universal guarantee for every + # possible future model choice - a differently-configured account/model capped at + # the plain ~200k window would see no change - but it is true for the window tier + # crew actually runs on today: as verified for --model sonnet on this account + # (the standard crewmate spawn), the window resolves to the ~1M-context beta, + # well above 300000. + # Do not copy the primary's two-var form (WINDOW=1000000 + PCT_OVERRIDE=20): + # that pair assumes a 1M window and is not safe for a harness/account + # combination with a smaller one. See the harness-adapters skill's claude + # section for the dated /context verification. + claude) printf '%s' 'CLAUDE_CODE_ENABLE_PROMPT_SUGGESTION=false CLAUDE_CODE_AUTO_COMPACT_WINDOW=300000 claude --dangerously-skip-permissions __MODELFLAG____EFFORTFLAG__"$(cat __BRIEF__)"' ;; codex) if [ "$kind" = secondmate ]; then printf '%s' 'codex __MODELFLAG____EFFORTFLAG__--dangerously-bypass-approvals-and-sandbox "$(cat __BRIEF__)"' @@ -428,6 +459,50 @@ shell_quote() { printf "'" } +# Appends a path (relative to a worktree root) to that worktree's own +# .git/info/exclude, so a firstmate-owned pointer/marker file never blocks +# teardown's dirty-worktree check or leaks into a crewmate's commit. Shared by +# every per-harness turn-end hook file below and the docker-compose isolation +# marker. Operates on $WT, which callers must have already resolved. +exclude_path() { + local rel=$1 EXCL + EXCL=$(git -C "$WT" rev-parse --git-path info/exclude 2>/dev/null || true) + [ -n "$EXCL" ] || return 0 + mkdir -p "$(dirname "$EXCL")" + grep -qxF "$rel" "$EXCL" 2>/dev/null || echo "$rel" >> "$EXCL" +} + +# Derives a unique, Docker-Compose-safe project name from a worktree's own +# pool-slot path (AGENTS.md "Layout and state"; a treehouse pool worktree is +# .../-//), so two worktrees of the same +# project - which always share the same leaf directory basename, e.g. +# "wealthsync" - never collide on Compose's default project-naming (derived +# from cwd basename) for container/volume/network names. Stable across +# respawns into the same pool slot, so a stale stack left behind by a prior +# task in that slot is superseded rather than orphaned under a new name; +# distinct across the fleet because no two live tasks occupy the same slot at +# once. Falls back to the worktree's own leaf name, then the task id, when the +# path does not have two parent directories (e.g. a non-treehouse backend). +fm_compose_project_name() { # + local wt=$1 fallback=$2 slot pool raw name + slot=$(basename "$(dirname "$wt")" 2>/dev/null || true) + pool=$(basename "$(dirname "$(dirname "$wt")")" 2>/dev/null || true) + if [ -n "$slot" ] && [ "$slot" != / ] && [ -n "$pool" ] && [ "$pool" != / ]; then + raw="$pool-$slot" + else + raw=$(basename "$wt") + fi + name=$(printf '%s' "$raw" | tr '[:upper:]' '[:lower:]' | sed 's/[^a-z0-9-]/-/g' | tr -s '-' | sed 's/^-//; s/-$//') + if [ -z "$name" ]; then + name=$(printf '%s' "wt-$fallback" | tr '[:upper:]' '[:lower:]' | sed 's/[^a-z0-9-]/-/g' | tr -s '-' | sed 's/^-//; s/-$//') + fi + case "$name" in + [a-z0-9]*) : ;; + *) name="wt-$name" ;; + esac + printf '%s\n' "$name" +} + model_flag_for_harness() { local harness=$1 model=$2 [ -n "$model" ] && [ "$model" != default ] || return 0 @@ -861,6 +936,18 @@ if [ "$KIND" != secondmate ] && [ "$BACKEND" != orca ]; then validate_spawn_worktree "treehouse get" "$T" fi +# Docker Compose isolation marker (ship/scout only; a secondmate operates in +# its own firstmate home, not a per-task pool worktree). Two treehouse +# worktrees of the same project share a leaf directory basename, so Compose's +# default project-naming collides across them; drop a stable, worktree-scoped +# name here that the crewmate's brief (fm-brief.sh) tells it to pass on every +# docker/docker-compose invocation. +if [ "$KIND" != secondmate ]; then + COMPOSE_PROJECT=$(fm_compose_project_name "$WT" "$ID") + printf '%s\n' "$COMPOSE_PROJECT" > "$WT/.treehouse-compose-project" + exclude_path '.treehouse-compose-project' +fi + # Per-task temp root: /tmp/fm-/ with Go's build temp nested at gotmp/. Go won't # create GOTMPDIR, so mkdir before it is used; fm-teardown removes the whole root. # Nested (not a bare /tmp/fm-/gotmp) so other per-task temp can live alongside @@ -875,13 +962,6 @@ mkdir -p "$TASK_TMP/gotmp" mkdir -p "$STATE" STATE_REAL=$(cd "$STATE" && pwd -P) TURNEND="$STATE_REAL/$ID.turn-ended" -exclude_path() { - local rel=$1 EXCL - EXCL=$(git -C "$WT" rev-parse --git-path info/exclude 2>/dev/null || true) - [ -n "$EXCL" ] || return 0 - mkdir -p "$(dirname "$EXCL")" - grep -qxF "$rel" "$EXCL" 2>/dev/null || echo "$rel" >> "$EXCL" -} if [ "$KIND" != secondmate ]; then case "$HARNESS" in claude*) @@ -1001,6 +1081,7 @@ META_WINDOW=$T echo "tasktmp=$TASK_TMP" echo "model=${MODEL:-default}" echo "effort=${EFFORT:-default}" + [ "$KIND" = secondmate ] || echo "compose_project=$COMPOSE_PROJECT" # backend= is written only for a non-default (non-tmux) backend, so the # default path's meta stays byte-identical (absent backend= means tmux; # data/fm-backend-design-d7's P1 compatibility contract). diff --git a/bin/fm-teardown.sh b/bin/fm-teardown.sh index 2ee4f35d7..7846101a8 100755 --- a/bin/fm-teardown.sh +++ b/bin/fm-teardown.sh @@ -275,29 +275,51 @@ pr_is_merged() { unpushed_patches_are_in_pr_head "$head" } -# Is the branch's content already present in the up-to-date default branch? Fetches -# first, then 3-way merges the default branch with HEAD: when HEAD introduces nothing -# the default branch does not already contain (e.g. its change landed via squash) the -# merged tree equals the default branch's tree. This isolates branch-only changes, so -# unrelated commits the default branch gained past the merge-base do not count as -# "added". Returns non-zero when inconclusive (no default ref, or a merge conflict), -# so the caller refuses rather than guesses. +# Does the given ref's tree already contain everything HEAD introduces? 3-way merges +# the ref (ours) with HEAD (theirs) off their merge base into a throwaway index: when +# HEAD introduces nothing the ref does not already contain (e.g. its change landed via +# squash), the merged tree equals the ref's tree. read-tree + write-tree is used +# instead of `git merge-tree --write-tree` (git >= 2.38 only) so this stays portable to +# older git; a real merge conflict leaves unmerged index entries, write-tree fails, and +# the check stays inconclusive so the caller refuses rather than guesses. +content_matches_ref() { + local ref=$1 default_tree base merged_tree tmpdir rc + default_tree=$(git -C "$WT" rev-parse --quiet --verify "$ref^{tree}" 2>/dev/null) || return 1 + [ -n "$default_tree" ] || return 1 + base=$(git -C "$WT" merge-base "$ref" HEAD 2>/dev/null) || return 1 + tmpdir=$(mktemp -d 2>/dev/null) || return 1 + GIT_INDEX_FILE="$tmpdir/index" git -C "$WT" read-tree -im --aggressive \ + "$base^{tree}" "$ref^{tree}" "HEAD^{tree}" 2>/dev/null \ + && merged_tree=$(GIT_INDEX_FILE="$tmpdir/index" git -C "$WT" write-tree 2>/dev/null) + rc=$? + rm -rf "$tmpdir" + [ "$rc" -eq 0 ] || return 1 + [ -n "$merged_tree" ] || return 1 + [ "$merged_tree" = "$default_tree" ] +} + +# Is the branch's content already present in the up-to-date default branch? Checks +# two candidate refs, succeeding if either already contains HEAD's content: the +# fetched remote-tracking ref refs/remotes/origin/$name (the normal PR-merged case), +# and the LOCAL refs/heads/$name (a worktree and its project's primary checkout are +# linked worktrees of the same repository, so this local ref already reflects a +# firstmate-performed local fast-forward merge, even for a project whose delivery +# mode is not local-only - e.g. a PR closed unmerged upstream but the branch was +# landed into local main by hand on the captain's approval). A fetch failure only +# rules out the remote-tracking path; the local ref is still tried. Returns +# non-zero only when neither candidate ref exists or matches. content_in_default() { - local name ref default_tree merged_tree + local name name=$(default_branch) || return 1 if git -C "$WT" remote get-url origin >/dev/null 2>&1; then - git -C "$WT" fetch --quiet origin "+refs/heads/$name:refs/remotes/origin/$name" >/dev/null 2>&1 || return 1 - ref="refs/remotes/origin/$name" - elif git -C "$WT" rev-parse --quiet --verify "refs/heads/$name" >/dev/null 2>&1; then - ref="refs/heads/$name" - else - return 1 + if git -C "$WT" fetch --quiet origin "+refs/heads/$name:refs/remotes/origin/$name" >/dev/null 2>&1; then + content_matches_ref "refs/remotes/origin/$name" && return 0 + fi fi - default_tree=$(git -C "$WT" rev-parse --quiet --verify "$ref^{tree}" 2>/dev/null) || return 1 - [ -n "$default_tree" ] || return 1 - merged_tree=$(git -C "$WT" merge-tree --write-tree "$ref" HEAD 2>/dev/null) || return 1 - merged_tree=$(printf '%s\n' "$merged_tree" | head -1) - [ "$merged_tree" = "$default_tree" ] + if git -C "$WT" rev-parse --quiet --verify "refs/heads/$name" >/dev/null 2>&1; then + content_matches_ref "refs/heads/$name" && return 0 + fi + return 1 } # Has the worktree's committed work actually LANDED, though its commits are not @@ -1050,9 +1072,22 @@ fm_backend_clear_transition "$BACKEND" "$STATE" "$T" || true # Remove the per-task temp root (/tmp/fm-/, incl. its gotmp/) recorded by spawn. # Read before the state-file rm below; empty (pre-fix tasks without tasktmp=) is a no-op. [ -n "$TASK_TMP" ] && rm -rf "$TASK_TMP" -rm -f "$STATE/$ID.status" "$STATE/$ID.turn-ended" "$STATE/$ID.check.sh" "$STATE/$ID.meta" "$STATE/$ID.pi-ext.ts" "$STATE/$ID.grok-turnend-token" +rm -f "$STATE/$ID.status" "$STATE/$ID.turn-ended" "$STATE/$ID.check.sh" "$STATE/$ID.meta" "$STATE/$ID.pi-ext.ts" "$STATE/$ID.grok-turnend-token" "$STATE/$ID.ultracode" if [ "$KIND" != scout ] && [ "$KIND" != secondmate ] && [ "$MODE" != local-only ]; then "$FM_ROOT/bin/fm-fleet-sync.sh" "$PROJ" || true fi +# Best-effort, non-blocking: a landed ship task (PR merged, or a local-only merge +# to local main) may have a live NAS deployment that also needs pulling and +# restarting - see bin/fm-nas-deploy-sync.sh's header. Scouts and secondmates +# never land a project change, so they are excluded the same as the fleet-sync +# call above; unlike that call, local-only IS included here, since a local-only +# merge is just as much a landed change as a PR merge. A forced teardown carries +# no landed-work guarantee at all (--force is the explicit discard path, used +# precisely when the safety checks above were skipped), so it is excluded too - +# otherwise a discard of unlanded work would still trigger a live NAS pull and +# pm2 restart for no reason. +if [ "$KIND" != scout ] && [ "$KIND" != secondmate ] && [ "$FORCE" != "--force" ]; then + "$FM_ROOT/bin/fm-nas-deploy-sync.sh" "$(basename "$PROJ")" || true +fi echo "teardown $ID complete (window $T, worktree $WT)" backlog_refresh_reminder diff --git a/bin/fm-tier-guard.sh b/bin/fm-tier-guard.sh new file mode 100755 index 000000000..934a5bfb4 --- /dev/null +++ b/bin/fm-tier-guard.sh @@ -0,0 +1,152 @@ +#!/usr/bin/env bash +# Escalation-trigger guard for the trivial (Haiku/low) dispatch tier: mechanically +# checks whether a task's actual diff size or elapsed time has outgrown the +# resource envelope its assigned model/effort tier implies, so under-resourcing +# is never caught by the crewmate's own self-report alone (guardrail #1, +# data/research-resource-tiering-synthesis.md). Read-only: never edits meta, +# the worktree, or the branch. +# +# Usage: fm-tier-guard.sh +# +# Reads state/.meta for model=/effort=, and that file's own mtime as a +# best-effort spawn-time proxy for the age check - NOT authoritative. A later +# append to meta (bin/fm-pr-check.sh recording pr=/pr_head=, or fm-x-link +# recording X-mode fields) resets the mtime, so a long-running task can read as +# younger than it is and slip the age ceiling; the diff size/file ceilings are +# the primary signal and are unaffected by that reset. Reuses +# bin/fm-review-diff.sh --stat for the actual diff size instead of re-deriving +# the authoritative base/PR-head resolution here. +# +# Prints one "ESCALATE: " line per triggered condition. Exit codes: +# 0 within the tier's envelope (silent) +# 1 at least one escalation fired +# 2 usage or setup error (bad args, missing meta, or fm-review-diff failed) +# Distinct codes let a caller branching on $? tell a real escalation from a +# malformed invocation, matching the sibling guardrail bin/fm-risk-tripwire.sh. +# Only the trivial (Haiku/low) tier has a size/age ceiling checked here; every +# other tier is covered only by the general, tier-independent ceiling below. +# On an escalation, bump the task's model/effort in place per AGENTS.md +# section 7's Validate step; never silently de-escalate afterward. +# +# Env overrides (starting points from +# data/scout-nomistakes-tiering-t8/report.md section 3, not yet calibrated +# against this fleet's own diff-size history): +# FM_TIER_TRIVIAL_MAX_LINES default 30 +# FM_TIER_TRIVIAL_MAX_FILES default 2 +# FM_TIER_TRIVIAL_MAX_AGE_SECONDS default 1800 (30 minutes) +# FM_TIER_HEAVY_MIN_LINES default 400 +# FM_TIER_HEAVY_MIN_FILES default 8 +set -eu + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +FM_ROOT="${FM_ROOT_OVERRIDE:-$(cd "$SCRIPT_DIR/.." && pwd)}" +FM_HOME="${FM_HOME:-${FM_ROOT_OVERRIDE:-$FM_ROOT}}" +STATE="${FM_STATE_OVERRIDE:-$FM_HOME/state}" + +TRIVIAL_MAX_LINES=${FM_TIER_TRIVIAL_MAX_LINES:-30} +TRIVIAL_MAX_FILES=${FM_TIER_TRIVIAL_MAX_FILES:-2} +TRIVIAL_MAX_AGE=${FM_TIER_TRIVIAL_MAX_AGE_SECONDS:-1800} +HEAVY_MIN_LINES=${FM_TIER_HEAVY_MIN_LINES:-400} +HEAVY_MIN_FILES=${FM_TIER_HEAVY_MIN_FILES:-8} + +usage() { + echo "usage: fm-tier-guard.sh " >&2 +} + +if [ "${1:-}" = "-h" ] || [ "${1:-}" = "--help" ]; then + usage + exit 0 +fi + +ID=${1:-} +[ -n "$ID" ] || { usage; exit 2; } +[ $# -le 1 ] || { usage; exit 2; } + +META="$STATE/$ID.meta" +[ -f "$META" ] || { echo "error: no meta for task $ID at $META" >&2; exit 2; } + +MODEL=$(grep '^model=' "$META" | tail -1 | cut -d= -f2- || true) +EFFORT=$(grep '^effort=' "$META" | tail -1 | cut -d= -f2- || true) + +# Portable mtime; Linux stat lacks -f, macOS stat lacks -c (mirrors +# bin/fm-supervision-lib.sh's fm_sup_stat_mtime; not sourced from there to keep +# this script's only dependency on that library's actual contract-bearing +# function, fm_supervision_status, out of scope here). +tier_guard_stat_mtime() { + if [ "$(uname)" = Darwin ]; then + stat -f %m "$1" 2>/dev/null + else + stat -c %Y "$1" 2>/dev/null + fi +} + +is_trivial_tier() { + case "$MODEL" in + *haiku*) + if [ "$EFFORT" = low ] || [ "$EFFORT" = default ]; then + return 0 + fi + ;; + esac + return 1 +} + +STAT_ERR=$(mktemp) +STAT_OUT=$("$SCRIPT_DIR/fm-review-diff.sh" "$ID" --stat 2>"$STAT_ERR") || { + echo "error: fm-review-diff.sh failed for $ID" >&2 + rm -f "$STAT_ERR" + exit 2 +} +# fm-review-diff.sh still exits 0 but warns when it cannot resolve an open PR's +# head and falls back to the possibly-stale local branch, so the size measured +# below may under-count the real PR diff. Blanket-discarding that warning (the +# 2>/dev/null this replaces) made a degraded read indistinguishable from an +# authoritative one - the dangerous under-report direction for this guardrail. +# Detect only that specific marker (not all of fm-review-diff.sh's stderr, which +# also carries fm-guard.sh's supervision banner) and surface it below. +DIFF_MAY_LAG_PR=0 +if grep -q 'PR head unavailable' "$STAT_ERR"; then + DIFF_MAY_LAG_PR=1 +fi +rm -f "$STAT_ERR" + +FILES=0 +LINES=0 +if ! printf '%s\n' "$STAT_OUT" | grep -q '^no changes vs'; then + FILES=$(printf '%s\n' "$STAT_OUT" | grep -oE '[0-9]+ files? changed' | grep -oE '^[0-9]+' || true) + INS=$(printf '%s\n' "$STAT_OUT" | grep -oE '[0-9]+ insertions?\(\+\)' | grep -oE '^[0-9]+' || true) + DEL=$(printf '%s\n' "$STAT_OUT" | grep -oE '[0-9]+ deletions?\(-\)' | grep -oE '^[0-9]+' || true) + FILES=${FILES:-0} + INS=${INS:-0} + DEL=${DEL:-0} + LINES=$((INS + DEL)) +fi + +FOUND=0 + +if is_trivial_tier; then + if [ "$FILES" -gt "$TRIVIAL_MAX_FILES" ] || [ "$LINES" -gt "$TRIVIAL_MAX_LINES" ]; then + echo "ESCALATE: trivial (haiku/low) task $ID has grown to $FILES files / $LINES changed lines, past the trivial envelope ($TRIVIAL_MAX_FILES files / $TRIVIAL_MAX_LINES lines) - bump to at least sonnet/high" + FOUND=1 + fi + AGE_SRC=$(tier_guard_stat_mtime "$META" || true) + if [ -n "$AGE_SRC" ]; then + NOW=$(date +%s) + AGE=$((NOW - AGE_SRC)) + if [ "$AGE" -gt "$TRIVIAL_MAX_AGE" ]; then + echo "ESCALATE: trivial (haiku/low) task $ID has run ${AGE}s, past the trivial tier's ${TRIVIAL_MAX_AGE}s ceiling - bump to at least sonnet/high" + FOUND=1 + fi + fi +fi + +if [ "$FILES" -gt "$HEAVY_MIN_FILES" ] || [ "$LINES" -gt "$HEAVY_MIN_LINES" ]; then + echo "ESCALATE: task $ID's diff ($FILES files / $LINES changed lines) exceeds the heavy-scale ceiling ($HEAVY_MIN_FILES files / $HEAVY_MIN_LINES lines) regardless of its assigned tier - re-check whether it still matches its dispatched rule" + FOUND=1 +fi + +if [ "$DIFF_MAY_LAG_PR" -eq 1 ]; then + echo "warning: the diff for $ID was sized against a possibly-stale local branch because the open PR head could not be resolved; the ceilings above may under-count the real PR diff - re-check against the current PR before trusting a within-envelope result" >&2 +fi + +exit "$FOUND" diff --git a/bin/fm-ultracode-guard.sh b/bin/fm-ultracode-guard.sh new file mode 100755 index 000000000..90a79f113 --- /dev/null +++ b/bin/fm-ultracode-guard.sh @@ -0,0 +1,110 @@ +#!/usr/bin/env bash +# Ultracode enforcement (guardrail #3): mechanically confirms a genuinely +# independent second pass ran on an ultracode-flagged task's finished diff +# before it can go PR-ready - not a sub-task the same crewmate spawned itself +# (data/research-resource-tiering-synthesis.md). Tracks state via a plain +# marker file, state/.ultracode, the same convention as other +# firstmate state/ markers (state/.afk, state/.turn-ended); it never +# touches fm-spawn.sh or the task's own meta. +# +# Usage: +# fm-ultracode-guard.sh flag [] +# Records that was dispatched under a crew-dispatch rule whose +# resolved profile set ultracode=true. defaults to +# "independent-review" (the only role this fleet's rules use today; see +# docs/examples/crew-dispatch.json). Firstmate runs this right after +# spawning the task. +# fm-ultracode-guard.sh reviewed +# Records that - a distinct, separately dispatched task +# (its own state/.meta must exist) - independently +# reviewed 's finished diff and its findings were addressed. +# Refuses if equals or has no recorded meta, +# so a sub-task the same crewmate spawned itself cannot satisfy this. +# fm-ultracode-guard.sh check +# Exits 0 if was never flagged, or was flagged and reviewed. +# Exits 1 with an explanatory message if flagged but not yet reviewed - +# firstmate runs this before treating an ultracode-flagged task as +# PR-ready (AGENTS.md section 7's Validate step). +set -eu + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +FM_ROOT="${FM_ROOT_OVERRIDE:-$(cd "$SCRIPT_DIR/.." && pwd)}" +FM_HOME="${FM_HOME:-${FM_ROOT_OVERRIDE:-$FM_ROOT}}" +STATE="${FM_STATE_OVERRIDE:-$FM_HOME/state}" + +usage() { + echo "usage: fm-ultracode-guard.sh flag []" >&2 + echo " fm-ultracode-guard.sh reviewed " >&2 + echo " fm-ultracode-guard.sh check " >&2 +} + +if [ "${1:-}" = "-h" ] || [ "${1:-}" = "--help" ]; then + usage + exit 0 +fi + +CMD=${1:-} +ID=${2:-} +if [ -z "$CMD" ] || [ -z "$ID" ]; then + usage + exit 1 +fi + +MARKER="$STATE/$ID.ultracode" + +cmd_flag() { + local role=${3:-independent-review} + [ $# -le 3 ] || { usage; exit 1; } + # The marker is a line-based file (see cmd_reviewed/cmd_check), so a role + # containing a newline or other control character could inject a forged + # reviewed_by= line and bypass the independent-review requirement entirely. + case "$role" in + *[!A-Za-z0-9_-]*|'') + echo "error: role '$role' must be non-empty and contain only letters, digits, '-', or '_'" >&2 + exit 1 + ;; + esac + mkdir -p "$STATE" + # Overwrites any existing marker: re-flagging (e.g. after an escalation) + # deliberately clears a prior reviewed_by=, since that review was against an + # earlier version of the diff and the requirement starts over. + echo "role=$role" > "$MARKER" + echo "flagged $ID ultracode role=$role" +} + +cmd_reviewed() { + local reviewer=${3:-} + [ $# -eq 3 ] || { usage; exit 1; } + [ -n "$reviewer" ] || { echo "error: reviewed requires a reviewer-task-id" >&2; exit 1; } + [ -f "$MARKER" ] || { echo "error: $ID is not ultracode-flagged (no $MARKER); nothing to mark reviewed" >&2; exit 1; } + if [ "$reviewer" = "$ID" ]; then + echo "error: reviewer-task-id must be a task distinct from $ID - a task cannot independently review itself" >&2 + exit 1 + fi + if [ ! -f "$STATE/$reviewer.meta" ]; then + echo "error: $reviewer has no recorded state/$reviewer.meta - it must be a genuinely, separately dispatched task, not a made-up id or a sub-task $ID spawned itself" >&2 + exit 1 + fi + grep -qx "reviewed_by=$reviewer" "$MARKER" 2>/dev/null || echo "reviewed_by=$reviewer" >> "$MARKER" + echo "recorded $reviewer as the independent review of $ID" +} + +cmd_check() { + [ $# -eq 2 ] || { usage; exit 1; } + if [ ! -f "$MARKER" ]; then + exit 0 + fi + if grep -q '^reviewed_by=' "$MARKER" 2>/dev/null; then + exit 0 + fi + role=$(grep '^role=' "$MARKER" | tail -1 | cut -d= -f2- || true) + echo "error: $ID is ultracode-flagged (role=${role:-independent-review}) but has no recorded independent review yet - dispatch a genuinely separate task to review the finished diff, then run: fm-ultracode-guard.sh reviewed $ID " >&2 + exit 1 +} + +case "$CMD" in + flag) cmd_flag "$@" ;; + reviewed) cmd_reviewed "$@" ;; + check) cmd_check "$@" ;; + *) usage; exit 1 ;; +esac diff --git a/docs/architecture.md b/docs/architecture.md index f2c590f9c..918675427 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -95,6 +95,7 @@ Codex App support is recorded in `docs/codex-app-backend.md`; it is not selectab Crewmates never intentionally touch your project clone; [treehouse](https://github.com/kunchenguid/treehouse) pools clean worktrees for tmux, herdr, zellij, and cmux tasks, while Orca creates its own worktrees for `backend=orca`. For ship and scout work, `fm-spawn.sh` refuses to launch unless the resolved task path is a real git worktree root that is distinct from the project primary checkout. +Pooled worktrees of the same project share a leaf directory basename, which collides on Docker Compose's default project-naming; see `docs/configuration.md` "Docker Compose project isolation" for the per-worktree `compose_project=` name `fm-spawn.sh` derives to avoid it. The firstmate repo has one extra exposure because it can dispatch crewmates to work on itself. Its operating checkout (`FM_ROOT`) and the disposable crewmate worktrees are all linked git worktrees of the same repository, so the valid discriminator is branch state, not whether the checkout is linked. @@ -129,6 +130,13 @@ Secondmate launches are exempt because they resolve the secondmate harness and a Unsupported effort values are still recorded in task meta when passed to `fm-spawn.sh`, but the launch template omits any effort flag that the selected harness does not accept. That keeps spawn launch compatible across claude, codex, grok, pi, and opencode while preserving the requested profile for later audit. +A crew-dispatch profile can also carry `ultracode: true` with an optional `ultracode_role` (today only `independent-review`): a task matched to that profile must get a genuinely independent second pass on its finished diff, dispatched as its own separate task rather than a sub-task the implementing crewmate spawns, before it can go PR-ready. +Three mechanical guardrails back this tiering, each a structurally separate check from the natural-language rule match so a misclassified task cannot slip a cheaper tier on one judgment call. +`bin/fm-risk-tripwire.sh` greps a task's brief text and, once code exists, its changed file paths for migration, auth, schema, and security signals; a hit floors the task to the safety-critical profile (`opus`/`xhigh`, ultracode `independent-review`) regardless of which rule was matched. +`bin/fm-tier-guard.sh` is a read-only Validate-time check that escalates a trivial (`haiku`/`low`) task in place once its actual diff size or elapsed time outgrows that tier's envelope, plus a general heavy-scale ceiling that escalates any tier once its diff crosses it; it reuses `bin/fm-review-diff.sh --stat` for the authoritative diff size. +`bin/fm-ultracode-guard.sh` tracks the ultracode requirement through a plain `state/.ultracode` marker (`role=`, then `reviewed_by=`), the same marker convention as `state/.afk`: it flags the requirement right after spawn (also on a risk-tripwire hit), records a distinct separately-dispatched reviewer task as the independent review, and refuses to let an ultracode-flagged task go PR-ready until that review is recorded. +None of the three modify `fm-spawn.sh` or task meta. + ## Optional secondmates `data/secondmates.md` records persistent domain supervisors with natural-language scopes, project clone lists, and home paths. @@ -228,6 +236,12 @@ Fetches blocked by an orphaned `.git/packed-refs.lock` use bounded retries and r Local-only projects, clones without an origin remote, and fetch failures remain benign skips. The refresh also prunes local branches whose remote is gone and that no worktree still needs. +A landed ship task's `projects/` dev clone is not the same checkout as a live deployment of that project running elsewhere on the host. +When a project has a row in `data/nas-deployments.md`, non-scout, non-secondmate, non-forced teardown also best-effort fast-forwards that project's separate live NAS checkout and restarts its recorded pm2 process(es), verifying each comes back online (`bin/fm-nas-deploy-sync.sh`). +A forced teardown (`--force`) skips this sync, since it carries no landed-work guarantee. +It mirrors the same clean/fast-forward-only safety as the clone refresh above, including the bounded orphaned-packed-refs-lock recovery, and reports a diverged or dirty checkout as `STUCK:` rather than touching it; a project absent from the mapping is a silent no-op. +Every filesystem/git touch of the NAS checkout is time-bounded so an unreachable mount cannot hang the teardown call that triggered it. + ## Self-updates stay safe `/updatefirstmate` fast-forwards the running firstmate repo and registered secondmate homes from `origin`, then re-reads updated instructions and nudges updated secondmates without touching project clones. diff --git a/docs/cmux-backend.md b/docs/cmux-backend.md index 5859e7f2d..305a582e6 100644 --- a/docs/cmux-backend.md +++ b/docs/cmux-backend.md @@ -173,7 +173,7 @@ No session field is needed - unlike herdr/zellij there is no session layer to re | Duplicate task check | `cmux workspace list --json --id-format uuids`, match by home-scoped `.title` | cmux enforces NO title uniqueness for workspaces OR surfaces/tabs - verified live: two workspaces, and two surfaces within one workspace, all created successfully sharing one title. The adapter's own duplicate check is required, mirroring herdr/zellij, and it checks the scoped title such as `fm-firstmate-<8hex>-`. | | Create task workspace | `cmux new-workspace --name --cwd --focus false --id-format uuids` | Creates a workspace with exactly one default surface. `--focus` verified to already default to `false` for workspace/surface/pane creation - no focus-restore dance needed, unlike zellij. The caller passes `fm-`, but the adapter creates `fm--`. | | Workspace/surface id resolution | `cmux workspace list --json --id-format uuids` (find by home-scoped title), then `cmux list-panes --workspace --json --id-format uuids` (`.panes[0].selected_surface_id`) | A freshly created workspace already has exactly one surface, so no separate `new-surface` call is needed. `--id-format uuids` (or `both`) is required to get a bare `id` field in JSON; the default JSON shape returns only short `ref` strings like `"workspace:2"`. | -| Liveness / target readiness | `cmux list-panes --workspace --json --id-format uuids`, checking the surface id appears in `.panes[].surface_ids` | Structural existence check, NOT a content read - see "read-screen fails on a genuinely fresh surface" below for why `read-screen` cannot be used here. Verified reliable on a completely untouched fresh surface, unlike `read-screen`. | +| Liveness / target readiness | `cmux list-panes --workspace --json --id-format uuids`, checking the surface id appears in `.panes[].surface_ids` | Structural existence check, NOT a content read - see "read-screen fails on a genuinely fresh surface" below for why `read-screen` cannot be used here. Verified reliable on a completely untouched fresh surface, unlike `read-screen`. `fm_backend_cmux_surface_exists` captures `list-panes`' own output and checks ITS exit status before piping into `jq -e`: on jq 1.6, `jq -e` over truly empty stdin exits 0, so piping a failed/empty `list-panes` call straight into `jq` would misread a dead target as a live one. | | Send literal (unsubmitted) | `cmux send --workspace --surface -- ` | Verified live: does NOT auto-submit - text sits at the prompt, unexecuted, until a separate Enter. Matches every other backend's "literal-then-separate-Enter" contract. The `--` separator keeps option-shaped text such as `--help` literal. | | Send key | `cmux send-key --workspace --surface ` | Verified names: `enter`, `escape`, `ctrl-c` all work directly (lowercase, hyphenated). Escape is natively supported (unlike Orca); Ctrl-C correctly interrupted a running `sleep 100` in a live test. cmux's own key vocabulary is richer still (`ctrl-d`/`ctrl-z`/`ctrl-\\`, semantic aliases `sigint`/`sigtstp`/`sigquit`), but firstmate's shared vocabulary only needs these three today. | | Send + submit, composed | `send` then `send-key enter` | cmux has no single-call atomic "type and submit" primitive (unlike tmux's `send-keys ... Enter` or herdr's `pane run`); `fm_backend_cmux_send_text_line` composes the two calls, mirroring zellij's equivalent composition. | diff --git a/docs/configuration.md b/docs/configuration.md index d289c4c15..47ecf6725 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -80,6 +80,15 @@ The caller-facing label remains `fm-`, but the actual cmux workspace title i Test cleanup must use the guarded path described in [`docs/cmux-backend.md`](cmux-backend.md)'s "Test safety" section, never enumerate-and-close every workspace. The `config/backend` file is not inherited by secondmate homes. +## Docker Compose project isolation (per-worktree) + +Two treehouse worktrees of the same project always share the same leaf directory basename (e.g. `wealthsync`), so Docker Compose's default project-naming, derived from the current directory's basename, collides across them on container, volume, and network names. +For every ship/scout spawn, regardless of runtime backend, `fm-spawn.sh` derives a stable, Compose-safe project name from the worktree's own pool-slot path once it is resolved (a treehouse pool worktree is `.../-//`; the name is `-`, lowercased, with non-`[a-z0-9-]` characters replaced by `-` and repeats collapsed), falling back to the worktree's own leaf name or the task id when the path lacks that pool-slot shape (e.g. a non-treehouse backend). +The name is written to `.treehouse-compose-project` in the worktree root, excluded from git via that worktree's own `.git/info/exclude` so it never blocks teardown's dirty-worktree check or leaks into a crewmate's commit, and recorded in `state/.meta` as `compose_project=`. +It is stable across respawns into the same pool slot, not per task id, so a stale Compose stack left by a prior task in that slot is naturally superseded rather than accumulating orphaned volumes under a new name every respawn. +Secondmates never get this marker or meta field; they run in their own firstmate home, not a per-task pool worktree. +`fm-brief.sh` tells the crewmate, in both ship and scout briefs, to read `.treehouse-compose-project` and pass it explicitly on every `docker compose` invocation (e.g. `docker compose -p "$(cat .treehouse-compose-project)" up -d`), since exported env vars do not reliably persist across separate tool-call invocations; it also flags fixed host ports as a related collision vector and recommends `docker compose port ` or another deterministic per-worktree-derived port instead of a hard-coded one. + ## Away-mode supervisor backend (FM_SUPERVISOR_BACKEND / FM_SUPERVISOR_TARGET) The `/afk` sub-supervisor injects escalation digests into firstmate's own pane independently of where new task endpoints are spawned. @@ -101,6 +110,15 @@ An absent file means `auto`, i.e. default-on on macOS: the alarm exists precisel A missing or failing channel logs and falls through to the next, never crashing the daemon. See [`wedge-alarm.md`](wedge-alarm.md) for the channel reference and macOS verification evidence, and [`examples/wedge-alarm`](examples/wedge-alarm) for a copyable config. +## Critical service watch (config/critical-services) + +`config/critical-services` (local, gitignored) lists systemd unit names, one per non-empty, non-comment line, that firstmate watches for the `failed` state. +At every session start bootstrap runs `systemctl is-failed` (read-only, no root) on each listed unit and prints `SERVICE_FAILED: - failed since ` for any that are failed, dropping the `failed since` clause when the unit's `StateChangeTimestamp` is unavailable. +It exists so a silently-failed critical unit, the kind of boot-time oneshot whose failure can otherwise go unnoticed for days, surfaces the next time firstmate starts rather than never. +An absent or empty file is a no-op, and a host without `systemctl` (no systemd) silently does nothing. +The file is not inherited by secondmate homes, whose same-machine bootstrap would only re-check the same units. +See [`examples/critical-services`](examples/critical-services) for a copyable config; report a failed unit to the captain in plain language and never restart it, since a unit that failed may be unsafe to restart without knowing why. + ## Gate defaults (.no-mistakes.yaml) The tracked `.no-mistakes.yaml` keeps test evidence outside the repo and defines `commands.test` so no-mistakes runs firstmate's bash behavior suite directly. @@ -192,7 +210,7 @@ This section is the single owner of the canonical schema and its per-field seman { "when": "", "use": [ - { "harness": "", "model": "", "effort": "" } + { "harness": "", "model": "", "effort": "", "ultracode": "", "ultracode_role": "" } ], "select": "", "why": "" @@ -205,6 +223,7 @@ This section is the single owner of the canonical schema and its per-field seman Per rule, `when` and `use` are required. `use` may be a single profile object or an ordered array of profile objects; the single-object form stays fully backward-compatible, and every profile needs `harness`. `use.model`, `use.effort`, and `why` are optional. +`use.ultracode` and `use.ultracode_role` are optional; AGENTS.md section 4 owns what setting `ultracode: true` means operationally and the mechanical guard that backs it. `select` is optional and currently supports `quota-balanced`. Absent `select` means use the first array element, or the only object in the single-object form; the first array element is the deterministic tie-break and the ultimate fallback. `default` is optional. @@ -385,9 +404,20 @@ FM_CLASSIFY_PAUSED_VERB=paused # leading status verb for a declared external FM_STALE_ESCALATE_SECS=240 # idle seconds before a provably-working stale pane escalates; stale panes whose crew is not provably working surface immediately unless they declare the pause verb FM_PAUSE_RESURFACE_SECS=3600 # seconds before an idle declared external wait re-surfaces for a recheck in the watcher or away-mode daemon FM_WEDGE_DEMAND_INSPECT_COUNT=3 # consecutive provably-working stale escalations on the same unchanged pane before demand-deep-inspection is added +FM_TIER_TRIVIAL_MAX_LINES=30 # fm-tier-guard.sh: changed-line count a trivial (haiku/low) task may reach before escalation fires +FM_TIER_TRIVIAL_MAX_FILES=2 # fm-tier-guard.sh: changed-file count a trivial (haiku/low) task may reach before escalation fires +FM_TIER_TRIVIAL_MAX_AGE_SECONDS=1800 # fm-tier-guard.sh: elapsed seconds a trivial (haiku/low) task may run before escalation fires (30 min) +FM_TIER_HEAVY_MIN_LINES=400 # fm-tier-guard.sh: changed-line count that escalates any tier via the general heavy-scale ceiling +FM_TIER_HEAVY_MIN_FILES=8 # fm-tier-guard.sh: changed-file count that escalates any tier via the general heavy-scale ceiling FM_WATCH_TRIAGE_LOG_MAX_BYTES=262144 # size cap for the watcher's absorbed-wake debug log FM_FLEET_SYNC_BOOTSTRAP_TIMEOUT= # optional seconds allowed for bootstrap's best-effort clone refresh; unset/blank defaults to max(20, 5 + 3 * origin-backed-project-count) +FM_UPSTREAM_FETCH_TIMEOUT=20 # seconds allowed for the locked fleet-sync sweep's bounded `git fetch upstream` (UPSTREAM_DRIFT); bounded by timeout, gtimeout, or a background-kill fallback when neither binary is installed FM_FLEET_PRUNE=1 # set to 0 to skip pruning local branches whose upstream is gone +FM_NAS_DEPLOYMENTS_OVERRIDE= # alternate data/nas-deployments.md path for fm-nas-deploy-sync.sh, mainly for tests +FM_NAS_SYNC_TIMEOUT=15 # seconds allowed per filesystem/git touch of fm-nas-deploy-sync.sh's $NAS_PATH before it is killed, so an unreachable NAS mount cannot hang fm-teardown.sh's caller +FM_NAS_SYNC_PACKED_REFS_LOCK_RETRIES=3 # fetch retries after fm-nas-deploy-sync.sh hits the orphaned .git/packed-refs.lock signature on the shared NAS checkout (two landed teardowns for the same project can race it) +FM_NAS_SYNC_PACKED_REFS_LOCK_RETRY_WAIT_SECS=1 # seconds fm-nas-deploy-sync.sh waits before each of those retries +FM_NAS_SYNC_PACKED_REFS_LOCK_AGE_SECS=30 # min mtime age before fm-nas-deploy-sync.sh treats a leftover packed-refs.lock as provably stale FM_STALE_WORKTREE_LOCK_AGE_SECS=30 # min mtime age before fm-teardown.sh treats a leftover worktree git index.lock as provably stale FM_TREEHOUSE_RETURN_LOCK_RETRIES=3 # retries after a treehouse return fails on the transient git index.lock signature FM_TREEHOUSE_RETURN_LOCK_RETRY_WAIT_SECS=1 # seconds fm-teardown.sh waits before each retry after that signature diff --git a/docs/examples/crew-dispatch.json b/docs/examples/crew-dispatch.json index 8aec19650..8f27118e6 100644 --- a/docs/examples/crew-dispatch.json +++ b/docs/examples/crew-dispatch.json @@ -18,6 +18,21 @@ ], "select": "quota-balanced", "why": "Use a strong coding profile for broad design and implementation work." + }, + { + "when": "The task changes this firstmate repo's own supervision backbone: bin/fm-watch.sh, bin/fm-guard.sh, a harness turnend-guard hook, or other logic the always-on watcher/guard rely on for correctness.", + "use": { "harness": "claude", "model": "sonnet", "effort": "xhigh" }, + "why": "A narrow set of scripts backs every other task's supervision; a subtle regression here is silent and fleet-wide, so it earns deeper reasoning than the general firstmate-repo default even though the model tier does not need to change." + }, + { + "when": "Safety-critical, security-sensitive, or hard-to-reverse work: schema or data migrations, auth/session/credential changes, payment or billing logic, or anything touching a frozen or safety-critical spec.", + "use": { "harness": "claude", "model": "opus", "effort": "xhigh", "ultracode": true, "ultracode_role": "independent-review" }, + "why": "A model reviewing its own irreversible change has anchoring bias; an independent pass and the strongest available model are both cheap relative to the cost of a bad migration or a broken safety-flow." + }, + { + "when": "A genuine architectural or product tradeoff with long-term consequences that the crewmate must reason through and justify, not just implement.", + "use": { "harness": "claude", "model": "opus", "effort": "xhigh" }, + "why": "The deliverable's entire value is the quality of the argued judgment call; this is low-volume, high-stakes work, so the cost delta of the top model is bounded and well spent." } ], "default": { "harness": "codex", "model": "gpt-5.5", "effort": "medium" } diff --git a/docs/examples/critical-services b/docs/examples/critical-services new file mode 100644 index 000000000..5b4cf5373 --- /dev/null +++ b/docs/examples/critical-services @@ -0,0 +1,19 @@ +# config/critical-services - systemd units firstmate watches for the failed +# state (bin/fm-bootstrap.sh's critical_services_check). Copy this into a local, +# gitignored config/critical-services and replace the placeholders with your own +# unit names. One systemd unit name per non-empty, non-comment line; blank lines +# and full-line "#" comments are ignored. +# +# At every session start, firstmate runs `systemctl is-failed` (read-only, no +# root) on each listed unit and surfaces a SERVICE_FAILED line for any that are +# failed, then reports it to the captain in plain language. It never restarts a +# unit: a unit that failed may be unsafe to restart without knowing why. +# +# An ABSENT or empty config/critical-services is a no-op. On a host without +# systemd (no systemctl) the check silently does nothing. +# +# The names below are illustrative placeholders - list the units whose silent +# failure would actually matter on this machine (the oneshot that runs a +# production app at boot, a backup timer, a sync daemon, and so on). +my-app.service +nightly-backup.timer diff --git a/docs/orca-backend.md b/docs/orca-backend.md index 6be2ad58f..b10e948e3 100644 --- a/docs/orca-backend.md +++ b/docs/orca-backend.md @@ -71,7 +71,7 @@ Spawn: 1. Ensure the project repo is registered in Orca, adding it with `orca repo add --path` when needed. 2. Create an independent Orca worktree with `orca worktree create --repo id: --name fm- --no-parent --setup skip`. 3. Reuse the terminal returned by Orca worktree creation only when it appears in the verified `result.terminal.handle` shape, or create a titled terminal in that worktree when Orca returns only the worktree. -4. Install firstmate's per-harness turn-end hooks in the Orca worktree. +4. Write the docker-compose isolation marker (`.treehouse-compose-project`) and install firstmate's per-harness turn-end hooks in the Orca worktree. 5. Write metadata, then send `GOTMPDIR` export and the selected harness launch through the recorded Orca terminal. Operation routing: diff --git a/docs/scripts.md b/docs/scripts.md index 8ed71b89f..d1c7ec819 100644 --- a/docs/scripts.md +++ b/docs/scripts.md @@ -16,7 +16,7 @@ The shared no-mistakes gate refusal used by `fm-spawn.sh`, `fm-send.sh`, and `fm | `fm-update.sh` | Fast-forward-only self-update of firstmate and secondmate homes from origin | | `fm-backlog-handoff.sh` | Validate and delegate queued backlog-item moves into a secondmate home | | `fm-decision-hold.sh` | Create, verify, complete, and resolve durable captain-held decisions | -| `fm-brief.sh` | Scaffold ship, scout, secondmate-charter, and Herdr-lab briefs | +| `fm-brief.sh` | Scaffold ship, scout, secondmate-charter, and Herdr-lab briefs, including the docker-compose isolation note on ship/scout briefs | | `fm-herdr-lab.sh` | Provision and guardedly operate an isolated, never-default Herdr lab session | | `fm-ensure-agents-md.sh` | Ensure a project's real `AGENTS.md`, its `CLAUDE.md` symlink, and the canonical self-governance section | | `fm-guard.sh` | Warn on primary-checkout tangles, pending queued wakes, and stale watcher liveness | @@ -26,8 +26,11 @@ The shared no-mistakes gate refusal used by `fm-spawn.sh`, `fm-send.sh`, and `fm | `fm-arm-command-policy.mjs` | Semantic owner of the watcher-arm PreToolUse policy (docs/arm-pretool-check.md) | | `fm-supervision-instructions.sh` | Render the session-start primary-harness supervision block or the one-line repair instruction | | `fm-home-seed.sh` | Transactionally provision a secondmate home and maintain `data/secondmates.md` | -| `fm-spawn.sh` | Spawn crewmates, scouts, `id=repo` batches, and secondmates on the resolved harness and runtime backend | +| `fm-spawn.sh` | Spawn crewmates, scouts, `id=repo` batches, and secondmates on the resolved harness and runtime backend, deriving and recording a per-worktree docker-compose project name (`compose_project=`; see `docs/configuration.md` "Docker Compose project isolation") | | `fm-dispatch-select.sh` | Resolve a matched crew-dispatch rule to one concrete profile, owning `quota-balanced` selection | +| `fm-tier-guard.sh` | Mechanically check whether a dispatched task's actual diff size or elapsed time has outgrown its assigned tier's resource envelope (guardrail #1) | +| `fm-risk-tripwire.sh` | Mechanically grep a task's brief and changed files for migration/auth/schema/security signals that floor a misclassified task's dispatch tier (guardrail #2) | +| `fm-ultracode-guard.sh` | Mechanically confirm an independent second pass reviewed an ultracode-flagged task's diff before PR-ready, tracked via `state/.ultracode` (guardrail #3) | | `fm-backend.sh` | Runtime-backend selection, meta helpers, selector resolution, and operation dispatch | | `fm-backend-hometag-lib.sh` | Shared per-installation home-tag derivation for zellij tab and cmux workspace titles | | `fm-composer-lib.sh` | Single fleet-wide owner of composer-content classification for all backends | @@ -67,6 +70,7 @@ The shared no-mistakes gate refusal used by `fm-spawn.sh`, `fm-send.sh`, and `fm | `fm-pr-merge.sh` | Record PR metadata, then merge a task's PR from its full GitHub URL | | `fm-promote.sh` | Promote a scout task in place to a protected ship task | | `fm-teardown.sh` | Fail-closed teardown: return landed ship worktrees, require completed scout deliverables, retire secondmate homes | +| `fm-nas-deploy-sync.sh` | Best-effort, non-fatal fast-forward sync and pm2 restart of a project's live NAS checkout after a landed ship-task teardown, mirroring `fm-fleet-sync.sh`'s dirty/diverged safety | | `fm-harness.sh` | Detect the running harness and resolve crew or secondmate harness, model, and effort | | `fm-lock.sh` | Per-home firstmate session lock | | `fm-x-lib.sh` | Shared X-mode config, relay, and reply-threading helpers | diff --git a/tests/fm-backend-herdr.test.sh b/tests/fm-backend-herdr.test.sh index 5186cca2c..77484a693 100755 --- a/tests/fm-backend-herdr.test.sh +++ b/tests/fm-backend-herdr.test.sh @@ -34,16 +34,33 @@ set -u LOG="${FM_HERDR_LOG:?}" RESP="${FM_HERDR_RESPONSES:?}" COUNT_FILE="$RESP/.count" -next=$(( $(cat "$COUNT_FILE" 2>/dev/null || echo 0) + 1 )) { printf 'HERDR_SESSION=%s' "${HERDR_SESSION:-}" for a in "$@"; do printf '\x1f%s' "$a"; done printf '\n' } >> "$LOG" +# `herdr server` is a fire-and-forget launch: server_ensure backgrounds it and +# discards its output, so its timing relative to the immediately-following status +# poll is non-deterministic. It must NOT consume a canned-response slot, or a lost +# race with that poll would steal a status response and desync the whole sequence. +# It is still logged above, so the "did it start the server" assertion holds. +if [ "${1:-}" = server ]; then + exit 0 +fi if [ "${1:-}" = status ] && [ "${2:-}" = --json ] && [ "${FM_HERDR_SCRIPT_STATUS:-0}" != 1 ]; then printf '{"client":{"version":"0.7.1","protocol":14},"server":{"running":true}}\n' exit 0 fi +# fm_backend_herdr_server_ensure launches `herdr server` fire-and-forget +# (backgrounded) so its poll loop can proceed concurrently. No test scripts a +# canned response for it, so it must never read/write the shared call-ordinal +# COUNT_FILE below - doing so races with whichever synchronous call the poll +# loop issues at the same moment, losing an update and permanently shifting +# every later call's response number. +if [ "${1:-}" = server ]; then + exit 0 +fi +next=$(( $(cat "$COUNT_FILE" 2>/dev/null || echo 0) + 1 )) n=$next echo "$n" > "$COUNT_FILE" if [ -f "$RESP/$n.exit" ]; then @@ -291,14 +308,15 @@ test_container_ensure_starts_server_and_workspace() { printf '{"client":{"version":"0.7.1","protocol":14}}\n' > "$resp/1.out" # 2: server_ensure's status --json check -> not running printf '{"server":{"running":false}}\n' > "$resp/2.out" - # 3: `herdr server` backgrounded launch - no meaningful output - # 4: server_ensure poll -> now running - printf '{"server":{"running":true}}\n' > "$resp/4.out" - # 5: workspace list -> empty (no "firstmate" workspace yet) - printf '{"result":{"workspaces":[]}}\n' > "$resp/5.out" - # 6: workspace create -> w1, seeding default tab w1:t9 (real herdr returns + # `herdr server` is backgrounded and consumes no response slot (see the fake), + # so the very next scripted response is the server_ensure poll. + # 3: server_ensure poll -> now running + printf '{"server":{"running":true}}\n' > "$resp/3.out" + # 4: workspace list -> empty (no "firstmate" workspace yet) + printf '{"result":{"workspaces":[]}}\n' > "$resp/4.out" + # 5: workspace create -> w1, seeding default tab w1:t9 (real herdr returns # the seeded tab/pane ids in the SAME response - verified empirically). - printf '{"result":{"workspace":{"workspace_id":"w1","label":"firstmate"},"tab":{"tab_id":"w1:t9"},"root_pane":{"pane_id":"w1:p9"}}}\n' > "$resp/6.out" + printf '{"result":{"workspace":{"workspace_id":"w1","label":"firstmate"},"tab":{"tab_id":"w1:t9"},"root_pane":{"pane_id":"w1:p9"}}}\n' > "$resp/5.out" fb=$(make_herdr_fakebin "$dir") out=$( PATH="$fb:$PATH" FM_HERDR_LOG="$log" FM_HERDR_RESPONSES="$resp" FM_HERDR_SCRIPT_STATUS=1 HERDR_SESSION=fmtest \ bash -c '. "$0/bin/backends/herdr.sh"; fm_backend_herdr_container_ensure /tmp' "$ROOT" ) diff --git a/tests/fm-backend-orca.test.sh b/tests/fm-backend-orca.test.sh index 60cc0dca8..bd4aad112 100755 --- a/tests/fm-backend-orca.test.sh +++ b/tests/fm-backend-orca.test.sh @@ -502,7 +502,7 @@ test_spawn_writes_orca_metadata_and_launches_harness() { "spawn should reuse the implicit terminal returned by Orca worktree creation" assert_contains "$(cat "$log")" $'orca\x1f''terminal'$'\x1f''send'$'\x1f''--terminal'$'\x1f''term-spawn'$'\x1f''--text'$'\x1f''export GOTMPDIR=/tmp/fm-orcaspawnz1/gotmp'$'\x1f''--enter'$'\x1f''--json' \ "spawn did not export GOTMPDIR through the Orca terminal" - assert_contains "$(cat "$log")" "CLAUDE_CODE_ENABLE_PROMPT_SUGGESTION=false claude --dangerously-skip-permissions" \ + assert_contains "$(cat "$log")" "CLAUDE_CODE_ENABLE_PROMPT_SUGGESTION=false CLAUDE_CODE_AUTO_COMPACT_WINDOW=300000 claude --dangerously-skip-permissions" \ "spawn did not send the selected harness launch command through Orca" rm -rf "/tmp/fm-$id" pass "fm-spawn.sh --backend orca: reuses implicit terminal, records metadata, launches harness" diff --git a/tests/fm-backend.test.sh b/tests/fm-backend.test.sh index aba73b50a..f15370155 100755 --- a/tests/fm-backend.test.sh +++ b/tests/fm-backend.test.sh @@ -110,7 +110,7 @@ BASE_REF=$(resolve_base_ref) \ # tmux-only conformance run the tmux adapter's behavior is what is under test, # and that is unchanged by any later (e.g. non-tmux backend) addition to # fm-backend.sh's own dispatch surface. -OLD_BIN_UNCHANGED_SIBLINGS="fm-gate-refuse-lib.sh fm-guard.sh fm-lock-lib.sh fm-tangle-lib.sh fm-tmux-lib.sh fm-composer-lib.sh fm-marker-lib.sh fm-wake-lib.sh fm-classify-lib.sh fm-ff-lib.sh fm-config-inherit-lib.sh fm-tasks-axi-lib.sh fm-project-mode.sh fm-harness.sh fm-crew-state.sh fm-backend.sh" +OLD_BIN_UNCHANGED_SIBLINGS="fm-gate-refuse-lib.sh fm-guard.sh fm-lock-lib.sh fm-tangle-lib.sh fm-tmux-lib.sh fm-composer-lib.sh fm-marker-lib.sh fm-wake-lib.sh fm-classify-lib.sh fm-ff-lib.sh fm-config-inherit-lib.sh fm-tasks-axi-lib.sh fm-project-mode.sh fm-harness.sh fm-crew-state.sh fm-backend.sh fm-supervision-lib.sh fm-decision-hold.sh" OLD_BIN_REFACTORED="fm-send.sh fm-peek.sh fm-watch.sh fm-spawn.sh fm-teardown.sh" build_old_bin() { # -> echoes root dir (root/bin/