diff --git a/.agents/skills/afk/SKILL.md b/.agents/skills/afk/SKILL.md index 517e8ba02..b9bbc6e48 100644 --- a/.agents/skills/afk/SKILL.md +++ b/.agents/skills/afk/SKILL.md @@ -1,6 +1,8 @@ --- name: afk -description: Enter away-mode supervision. Use when the user invokes /afk (e.g. "/afk", "/afk back in an hour", "going afk"). Sets a durable away-mode flag so the sub-supervisor daemon can self-handle routine wakes and escalate captain-relevant events plus bounded declared-external-wait rechecks as batched digests, cutting supervision token cost during walk-away stretches. Exit is automatic; any real (unmarked) message returns to full per-wake responsiveness. +description: >- + Enter away-mode supervision when the captain invokes /afk, says they are going afk, `state/.afk` exists, an incoming message starts with `FM_INJECT_MARK`, or any `state/.subsuper-*` marker is involved. + It sets a durable away-mode flag so the sub-supervisor daemon can self-handle routine wakes and escalate captain-relevant events plus bounded declared-external-wait rechecks as batched digests during walk-away stretches, then exits automatically when any real unmarked message returns firstmate to full per-wake responsiveness. user-invocable: true metadata: internal: true @@ -50,18 +52,19 @@ batched digest rather than per-wake injections. 3. **Do not separately arm `fm-watch.sh`.** The daemon manages the watcher as its child; the singleton lock no-ops a stray arm harmlessly. -4. **Acknowledge** to the captain that away-mode is active. - The daemon will self-handle routine wakes, escalate captain-relevant events and bounded declared-external-wait rechecks, and let the captain exit by sending any real message. +4. **Acknowledge** in `AGENTS.md` section 9 language: "Captain, away mode is active; I will batch routine updates and surface only decisions, failures, credentials, or review-ready work until you return." ## How to exit afk No `/back` is needed. The first genuine message is the return signal: - A message **without** the sentinel marker and **not** starting with `/afk` -> the captain is back. - Run `bin/fm-afk-launch.sh stop`: it stops the daemon in the correct order - it SIGTERMs the daemon so its shutdown flush runs **while `state/.afk` is still present** (clearing the flag first makes that flush a no-op via the daemon's presence gate, stranding undelivered escalations), then closes the daemon's own terminal by exact id, then clears `state/.afk` last. - Then flush one distilled "while you were out" catch-up (drain `state/.wake-queue`, summarize any pending escalations from `state/.subsuper-escalations` and any `state/.subsuper-inject-wedged` marker), and resume full per-wake responsiveness through the emitted primary-harness supervision protocol from session start. -- A message **with** the sentinel marker (`FM_INJECT_MARK`, ASCII 0x1f) -> it - is a daemon escalation; stay afk and process it. + Run `bin/fm-afk-return.sh` before acting on the message that brought the captain back. + That script owns correct-ordered daemon shutdown, durable wake draining, escalation and wedge evidence, and the return-catch-up gate. + If it reports a firstmate-actionable `blocked:` event, remediate it immediately through the normal lifecycle, or explicitly reclassify it with a durable reason and close its decision key with `resolved [key=...]`, then run `bin/fm-afk-return.sh check`. + Once the daemon stops, resume full per-wake responsiveness through the emitted primary-harness supervision protocol while blocker handling proceeds, so the gate never creates a blind wait. + Do not answer a Bearings request or perform any other ordinary captain work until the check exits successfully. +- A message **with** the sentinel marker (`FM_INJECT_MARK`, U+2063 INVISIBLE SEPARATOR) -> it is a daemon escalation; stay afk and process it. - Re-invoking `/afk` while already away -> stay afk (refresh the flag); this does **not** trigger an exit. @@ -77,12 +80,9 @@ explicit word - the daemon just batches the notification. ## Sentinel marker contract -The daemon prefixes every injection with `FM_INJECT_MARK` (ASCII unit -separator, 0x1f), invisible and untypable. This is how firstmate tells a -daemon escalation apart from a real message in the same pane. The marker -travels with the message text; it does not rely on harness-level -typed-vs-injected detection (which is not portable across claude, codex, -opencode, pi, and grok). +The daemon prefixes every injection with `FM_INJECT_MARK` (U+2063 INVISIBLE SEPARATOR), which has no normal keyboard keystroke and survives terminal transport as UTF-8 text. +This is how firstmate tells a daemon escalation apart from a real message in the same pane. +The marker travels with the message text; it does not rely on harness-level typed-vs-injected detection, which is not portable across claude, codex, opencode, pi, and grok. ## Busy-guard and composer guard @@ -103,6 +103,7 @@ In afk mode the composer guard is belt-and-suspenders (no human is typing), but **Max-defer escape (the daemon must never silently wedge).** If anything stays buffered past `FM_MAX_DEFER_SECS` (default 300), the daemon attempts one normal flush, which still requires an idle pane and an affirmatively empty composer. +The alarm is defense in depth rather than a substitute for keeping every genuinely idle supported composer injectable. If that submit cannot be confirmed, it raises a loud, rate-limited wedge alarm: an ERROR in the daemon log, a durable `state/.subsuper-inject-wedged` marker (surface it on the "while you were out" diff --git a/.agents/skills/bearings/SKILL.md b/.agents/skills/bearings/SKILL.md index 6aa17631c..f543ebf32 100644 --- a/.agents/skills/bearings/SKILL.md +++ b/.agents/skills/bearings/SKILL.md @@ -8,8 +8,8 @@ metadata: # bearings -Generate a "pick up where I left off" report from the fleet's live state, so the captain can resume in one read after a break, a night, or a context reset. -The deliverable is a dated markdown file plus a concise chat summary; this is the reusable version of the worked example at `data/status-report-2026-07-06.md` when that file is present in this home. +Generate a complete standalone snapshot from the fleet's current state, so the captain can resume in one read after a break, a night, or a context reset. +The deliverable is a dated markdown file plus a concise chat summary that each stand on the current snapshot rather than an earlier report. This skill is read-mostly. It reads fleet state and writes exactly one report file. It never tears down a task, merges a PR, dispatches new work, or mutates any task state as a side effect of producing the brief - those belong to the captain's explicit word and the normal task lifecycle. @@ -23,23 +23,25 @@ It never tears down a task, merges a PR, dispatches new work, or mutates any tas The command's header and `--help` output own its exact fields, bounds, opt-ins, and output contract. When the captain asks to include PRs, use the command's live-PR opt-in; otherwise keep the default local-only read. If the command is unavailable, fall back to `bin/fm-fleet-snapshot.sh --json` and `bin/fm-crew-state.sh `; never infer current state from a raw `tail` of `state/.status`, which is append-only wake-event history whose last line goes stale. + For registered secondmates, use the snapshot's structured-home classification and provenance; a parent event or bounded terminal contradiction is fallback evidence, never authority over readable structured home state. + Structured captain-held decisions come from `decision-hold-lifecycle` and appear under `decisions_open`; do not scrape reports or visual-review artifacts to supplement them. A queued item under `gates` only becomes "next work" when its blocker is gone and its time/date gate has arrived; until then it stays queued with the reason. 2. **Compose the detailed report file around the four-section spine, adding the richer detail the chat leaves out.** The gather step is deterministic; your judgment is scoped to the last mile only - ranking the command's facts by what matters right now and writing the scannable prose. - The exemplar is `data/status-report-2026-07-06.md` in this home's `data/` when present; match its scannability, not a raw state dump. - The report uses the same four sections as the chat (see the chat-response contract below), in the same order, each always present, and adds the detail the chat omits: + Never read an earlier `data/status-report-*.md` to decide what to omit, include, describe as changed, or call current. + The report uses the same four complete sections as the chat (see the chat-response contract below), in the same order, each always present, and adds the detail the chat omits: - **Title** - `# Bearings - ` (use "Morning status" only when the captain specifically asks for a morning brief), followed by two or three sentences framing where things stand. - - **Captain's Call** - every open decision relayed verbatim with its options, plus each PR ready to merge and each needed credential or login, every PR with the full `https://...` URL, never a bare `#number`. - - **Recently Landed** - merged PRs, completed scouts, and finished local-only work since the last report, across the main fleet and every registered secondmate home. + - **Captain's Call** - every open decision summarized with its options from the structured decision record, plus each PR ready to merge and each needed credential or login, every PR with the full `https://...` URL, never a bare `#number`. + - **Recently Landed** - the bounded current recent-completions baseline from structured state across the main fleet and every registered secondmate home, rendered in full on every run. - **Underway** - each live direct report making progress, with its current state, and the plans / main pickup pointers worth reopening (`data//report.md` files, `.lavish/*.html` boards). - **Charted Next** - queued or gated next work, with each item's blocker or date reason. 3. **Write the dated report file so it persists, then surface the mandatory four-section digest in chat.** - Write the full report to `data/status-report-.md` using today's date. - This is the required artifact; it lives in gitignored `data/` alongside the worked example. + This is the required artifact; it lives in gitignored `data/`. If today's file already exists, delete it first, then create a new file from scratch. - - The chat response is the concise four-section digest defined by the contract below: materially shorter than the report file, and it links to that file for the full picture. + - The chat response is the concise four-section digest defined by the contract below: materially shorter than the report file, complete as a current snapshot, internally consistent with the file, and linked to that file for the full picture. - For a richer review surface, optionally offer a Lavish board with `lavish-axi` when the report has enough structure to deserve one, but the markdown file is the required artifact and the four-section chat digest is the required minimum. ## Chat-response contract @@ -49,8 +51,8 @@ Every `/bearings` chat response renders EXACTLY these four sections, in THIS ord 1. **Captain's Call** - ONLY items that need the captain's own action now: a decision to make, a PR to approve or merge, a credential or login to provide, or a blocker only the captain can clear. Empty-state: "Nothing needs your action right now." -2. **Recently Landed** - work completed since the prior report: merged PRs, completed scouts, and finished local-only merges, across the main fleet and every registered secondmate home. - Empty-state: "Nothing has landed since your last report." +2. **Recently Landed** - the bounded current recent-completions baseline: merged PRs, completed scouts, and finished local-only merges across the main fleet and every registered secondmate home. + Empty-state: "No recent completions are in the current baseline." 3. **Underway** - live work progressing on its own, one line of current state per direct report. Empty-state: "Nothing is underway." 4. **Charted Next** - queued or gated work waiting on the fleet or a date, never on the captain. @@ -59,9 +61,12 @@ Every `/bearings` chat response renders EXACTLY these four sections, in THIS ord Rules that keep the contract unambiguous: - Every section ALWAYS renders, even when empty, with its short empty-state sentence; never omit a section. +- Every report and chat digest is a complete current snapshot, never a delta against a prior report. +- Recently Landed always renders the bounded current baseline, even when the same completions appeared in an earlier report. - The four buckets are mutually exclusive, so every item is forced into exactly one: needs-your-action is Captain's Call, done is Recently Landed, self-progressing is Underway, not-yet-started is Charted Next. - The strict boundary keeps action-free items OUT of Captain's Call: a working or validating task, a queued item blocked on another task or a date, landed work, a completed scout's report pointer, a declared `paused:` external wait, and a bare recorded PR with no merge-ready signal each belong to one of the other three sections, never Captain's Call. -- The chat carries one scannable line per item, each PR as the full `https://...` URL; the verbatim decisions, plans, full gate reasons, and evidence live only in the report file, which the chat links to, so the chat stays materially shorter than that file. +- A secondmate appears Underway only for `active_child_work`; `externally_held` belongs in Charted Next, and `unknown` belongs there as an unavailable-state gate unless its reason requires the captain's action. +- The chat follows `AGENTS.md` section 9 and carries one scannable line per item, each PR as the full `https://...` URL; detailed decisions, plans, full gate reasons, and evidence live only in the report file, which the chat links to, so the chat stays materially shorter than that file. ## Tone and content rules diff --git a/.agents/skills/bootstrap-diagnostics/SKILL.md b/.agents/skills/bootstrap-diagnostics/SKILL.md index 3e6d47371..102071b58 100644 --- a/.agents/skills/bootstrap-diagnostics/SKILL.md +++ b/.agents/skills/bootstrap-diagnostics/SKILL.md @@ -2,8 +2,8 @@ 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. - A silent bootstrap section means all good and needs no skill load. + Use whenever the session-start digest's bootstrap section prints an actionable diagnostic line - MISSING, MISSING_MANUAL, BACKEND_INVALID, NEEDS_GH_AUTH, TANGLE, CREW_DISPATCH invalid, FLEET_SYNC, PR_CHECK_MIGRATION, SECONDMATE_SYNC, SECONDMATE_LIVENESS, NUDGE_SECONDMATES, or FMX - or when a standalone bin/fm-bootstrap.sh run prints one of those lines. + A silent bootstrap section, or a BOOTSTRAP_INFO fact, means no skill load. user-invocable: false metadata: internal: true @@ -12,13 +12,14 @@ metadata: # bootstrap-diagnostics Handle each printed line as below, before dispatching work that depends on it. -The line formats themselves are owned by `bin/fm-bootstrap.sh`'s header; this playbook owns the response. +The line formats themselves are owned by `bin/fm-bootstrap.sh`'s header; this playbook owns the response to actionable lines. The inline rules in `AGENTS.md` section 3 still bind: detect, then consent, then install - never install anything the captain has not approved in this session - and no work is dispatched until the tools it needs are present and GitHub auth is good. +When any diagnostic needs captain attention, report the plain consequence and requested action using `AGENTS.md` section 9's captain-facing translation contract; do not name the diagnostic label unless the captain needs to paste it into a command or issue. - `MISSING: (install: )` - list the missing tools to the captain with a one-line purpose each plus the printed install commands, wait for consent (one approval may cover the list), then run `bin/fm-bootstrap.sh install `. For `treehouse`, this also covers an installed version whose `treehouse get` lacks `--lease`; treat it as an upgrade request. For `no-mistakes`, this also covers an installed version older than 1.31.2, because crewmate validation briefs delegate gate mechanics to no-mistakes' version-matched guidance. - For `tasks-axi`, this also covers an installed build that fails the compatibility probe (`docs/configuration.md` "Backlog backend" owns the definition); `config/backlog-backend=manual` only suppresses the `TASKS_AXI: available` capability line, not this missing-tool report. + For `tasks-axi`, this also covers an installed build that fails the compatibility probe (`docs/configuration.md` "Backlog backend" owns the definition); `config/backlog-backend=manual` only suppresses the verbose `BOOTSTRAP_INFO: tasks-axi available` fact, not this missing-tool report. For `quota-axi`, bootstrap requires it because crew-dispatch `quota-balanced` may call it; `bin/fm-dispatch-select.sh` still degrades at runtime when quota data is unavailable. - `MISSING_MANUAL: (instructions: )` - tell the captain why the tool is required and give them the printed instructions URL, but do not pass the tool to `bin/fm-bootstrap.sh install`; wait for the captain to complete the manual installation, then rerun session start to confirm the dependency is present. - `BACKEND_INVALID: (known: )` - the resolved runtime backend has no verified dependency or lifecycle contract, so do not dispatch work until the invalid `FM_BACKEND` or `config/backend` value is corrected to one of the listed backends. @@ -26,24 +27,26 @@ The inline rules in `AGENTS.md` section 3 still bind: detect, then consent, then - `TANGLE: ` - the primary checkout is stranded on a feature branch instead of its default branch; `AGENTS.md` section 8 explains why this guard exists and what it protects. The work is safe on that branch ref; restore the primary to its default branch with the printed `git -C checkout `, then re-validate that branch in a proper worktree. This is the only sanctioned firstmate-initiated git write to the primary, and it is a non-destructive branch switch that strands nothing. -- `CREW_HARNESS_OVERRIDE: ` - record and use the override silently; surface a harness fact only if it actually blocks work or the captain asks. - `CREW_DISPATCH: invalid config/crew-dispatch.json - ` - the optional dispatch profile file exists but failed low-cost bootstrap validation; continue with the normal fallback chain, resolve and pass the chosen fallback harness explicitly while the file remains present, fix the malformed schema, unverified harness name, unknown selector, or invalid harness/effort pair when convenient, and do not select a bad profile. -- `CREW_DISPATCH: active config/crew-dispatch.json` - bootstrap validated the optional dispatch profile file and printed its active rules and `default:` when present. - Keep this block top-of-mind during intake; it is the reminder that every crewmate or scout dispatch must consult the rules before spawning (`AGENTS.md` section 4). - `FLEET_SYNC: : skipped: ` - a benign one-off skip (offline, no origin, local-only); bootstrap continued, investigate only if it blocks work. A skip can also report the bounded fleet-refresh timeout (`FM_FLEET_SYNC_BOOTSTRAP_TIMEOUT`, or a fleet-size-aware default with a 20 second floor); a timeout never blocks startup. - `FLEET_SYNC: : recovered: ` - the clone had drifted onto a clean detached HEAD holding no unique commits and the sync self-healed it (re-attached the default branch and fast-forwarded); no action needed, it is reported only so the self-heal is visible. - `FLEET_SYNC: : STUCK: on , N commits behind - needs attention` - the clone is dirty, on a non-default branch, detached with unique commits, or diverged, so the sync left it untouched (never forcing or discarding); it will keep falling behind until you look. A loud STUCK, especially a growing N across bootstraps, means that clone needs hands-on attention; dispatch a crewmate or resolve it before it strands work. -- `SECONDMATE_SYNC: secondmate : skipped: ` - the local-HEAD secondmate sync left a live secondmate home on its existing checkout because the home was dirty, diverged, unsafe, on the wrong branch, missing the primary target commit, or otherwise not fast-forwardable, or because inheritable-config propagation failed; bootstrap continued, but inspect the reason because the secondmate's tracked instructions or inherited settings may be stale after a primary update. -- `SECONDMATE_LIVENESS: secondmate : already-live|respawned|skipped: |respawn failed: ` - the session-start liveness sweep checked a live secondmate's recorded endpoint for a real agent process. - Treat `already-live` and `respawned` as handled; investigate `skipped` or `respawn failed` because that secondmate is not guaranteed live. -- `TASKS_AXI: available` - a default-backend capability fact, not a problem; record it silently and use `AGENTS.md` section 10 for backlog mutations. - It prints only when `config/backlog-backend` is absent or set to `tasks-axi` and the shared compatibility probe passes (`docs/configuration.md` "Backlog backend"). - If the backend is not opted out and `tasks-axi` is missing or incompatible, bootstrap reports the `MISSING: tasks-axi` line but firstmate still hand-edits routine backlog updates and never blocks work. - If `config/backlog-backend=manual`, firstmate hand-edits routine backlog updates and bootstrap does not suggest installing `tasks-axi`. -- `NUDGE_SECONDMATES: fm-...` - the secondmate sweep fast-forwarded one or more *running* secondmate homes to firstmate's current version and their instruction surface (`AGENTS.md`, `bin/`, or `.agents/skills/`) actually changed; send a one-line re-read nudge with `FM_HOME= bin/fm-send.sh 'firstmate was updated to the latest - please re-read your AGENTS.md to pick up the new instructions.'` unless `FM_HOME` is already set to the active firstmate home. - This mirrors `/updatefirstmate`'s `nudge-secondmates:` report: it is a gentle steer, never an interruption, and the fast-forward already landed safely. - A secondmate that was skipped, already current, or whose advance changed no instructions is not listed and must not be disturbed. +- `PR_CHECK_MIGRATION: canonical polls rebuilt and armed; resume supervision for this home` - the non-executing migration rebuilt canonical task polls from validated metadata, and those polls are already armed. + Independently verify the private per-task outcome record, then resume the emitted supervision protocol after finishing the session-start wake handling. +- `PR_CHECK_MIGRATION: validated replacement polls armed; resume supervision for this home` - a retry proved canonical publication provenance, metadata identity binding, and single-link integrity for a replacement poll resolving an earlier ambiguous migration outcome. + Independently verify the private per-task outcome record, then resume the emitted supervision protocol after finishing the session-start wake handling. +- `PR_CHECK_MIGRATION: quarantined polls remain unarmed; review state/.pr-check-migration.log before rearming` - one or more ambiguous or invalid task polls were quarantined without execution and remain unarmed. + Read the private mode-`0600` per-task outcome record, verify the task's recorded PR independently, and rearm only through `bin/fm-pr-check.sh` with canonical inputs. +- `PR_CHECK_MIGRATION: migration completed safely; resume supervision for this home` - migration crossed the update boundary without rebuilding or quarantining a task poll after pausing the prior watcher. + Resume the emitted supervision protocol after finishing the session-start wake handling. +- Any other `PR_CHECK_MIGRATION:` refusal means migration did not complete safely, whether because watcher exclusion, a private path, a diagnostic, quarantine validation, or marker publication could not be proved. + Keep each affected poll unavailable, inspect the named private state path, and do not bypass the migration or execute a quarantined artifact; a completed safe-scan marker allows unrelated authenticated polls to continue while private repair remains pending. +- `SECONDMATE_SYNC: secondmate : skipped: ` - the local-HEAD secondmate sync left a live secondmate home on its existing checkout because the home was dirty, diverged, unsafe, on the wrong branch, missing the primary target commit, or otherwise not fast-forwardable, or because inherited local-material propagation failed; bootstrap continued, but inspect the reason because the secondmate's tracked instructions, inherited settings, or shared captain preferences may be stale after a primary update. +- `SECONDMATE_LIVENESS: secondmate : skipped: |respawn failed: ` - the session-start liveness sweep could not guarantee that a live secondmate's recorded endpoint is running a real agent process. + Investigate the reason because that secondmate is not guaranteed live. +- `NUDGE_SECONDMATES: secondmate : send failed: ` - the secondmate sweep fast-forwarded a running secondmate home and its loaded instruction surface (`AGENTS.md`, `bin/`, or `.agents/skills/`) changed, but the deterministic `fm-send.sh fm-` re-read nudge failed. + Inspect the reason, keep the pending marker under `state/.secondmate-nudge-pending/` intact, and rerun session start after the endpoint or metadata issue is fixed so bootstrap can retry the exact same marked send. - `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. diff --git a/.agents/skills/decision-hold-lifecycle/SKILL.md b/.agents/skills/decision-hold-lifecycle/SKILL.md new file mode 100644 index 000000000..5db5690eb --- /dev/null +++ b/.agents/skills/decision-hold-lifecycle/SKILL.md @@ -0,0 +1,40 @@ +--- +name: decision-hold-lifecycle +description: >- + Agent-only policy for completing investigations and visual reviews without losing unresolved captain decisions. + Load before treating an investigation, scout report, structured review, or Lavish review as complete, before ending a visual review that exposed a decision, and when recording or routing the captain's answer. +user-invocable: false +metadata: + internal: true +--- + +# Durable unresolved-decision lifecycle + +This skill is the single policy owner for unresolved captain decisions discovered by an investigation or visual review. + +## Policy + +Every unresolved decision that belongs to the captain and is discovered while producing, reading, presenting, or ending an investigation or visual review must become a structured captain-held work item in the authoritative backlog of the home that owns the originating work before that work or review may be treated as complete. +The agent performs the semantic inventory because scripts must not infer decisions from report prose, visual-review artifacts, terminal output, or chat. +Give each distinct unresolved decision a stable privacy-safe key, register it through `bin/fm-decision-hold.sh hold`, and use the same key on retry so registration is idempotent while different decisions retain different durable identities. +After inventorying the whole report and review surface, run `bin/fm-decision-hold.sh complete` with every unresolved key, or with `--none` only when the reviewed surface contains no unresolved captain decision. +A completed investigation and an ended visual review use this same owner and completion command; a visual tool, including Lavish, never owns a parallel completion policy. +Run the command in the originating work's authoritative `FM_HOME`; main-home work creates main-home holds, and secondmate-owned work creates holds in that secondmate home's backlog rather than copying them into the main backlog. +Do not close a hold merely because the originating investigation completed, its report was archived, its visual review ended, or its task was torn down. +The hold remains the authoritative Captain's Call item until the captain's answer is durably recorded, dependent work is created in the same backlog and blocked by that hold, and `bin/fm-decision-hold.sh resolve` routes the answer by clearing those dependency edges before closing the hold. +Resolved findings, recommendations that need no captain choice, and prose that merely sounds decision-like do not create holds. +Bearings reads the resulting structured state and must never compensate by scraping historical reports, visual-review artifacts, terminal output, chat, or other prose. + +## Operating sequence + +1. Read the complete investigation result and complete the visual review before declaring either complete. +2. Inventory only genuine unresolved choices that require the captain. +3. For each choice, choose a stable key and use the script's `hold` command with a concise title, reason, and repository. +4. Run the script's `complete` command with the full unresolved-key inventory for that review pass. +5. Relay the choices to the captain as decisions from Bearings' Captain's Call section under `AGENTS.md` section 9; do not use the word hold in captain chat. +6. After the captain decides, record dependent work with normal tasks-axi commands and block it by the hold identity. +7. Put the captain's exact durable decision in a file and use the script's `resolve` command with every routed task. +8. Confirm Bearings no longer shows the closed hold and that routed work remains in structured backlog state. + +`bin/fm-decision-hold.sh --help` owns command syntax, identity construction, completion attestation, retry behavior, and close ordering. +`docs/decision-hold-lifecycle.md` records the mechanism and regression evidence without restating this policy. diff --git a/.agents/skills/diagnostic-reasoning/SKILL.md b/.agents/skills/diagnostic-reasoning/SKILL.md new file mode 100644 index 000000000..dc6519611 --- /dev/null +++ b/.agents/skills/diagnostic-reasoning/SKILL.md @@ -0,0 +1,53 @@ +--- +name: diagnostic-reasoning +description: >- + Agent-only procedure for diagnosing reported bugs. + Use before scoping a reported bug and before acting on a diagnostic report. + Owns end-user-aligned reproduction, causal separation, divergent-path and history inspection, counterfactual testing, and disconfirming evidence. +user-invocable: false +metadata: + internal: true +--- + +# diagnostic-reasoning + +Use this procedure before scoping a reported bug and before acting on a diagnostic report. +This skill is the single owner of Firstmate's bug-diagnosis reasoning procedure. +Firstmate applies it when briefing delegated investigation and evaluating the resulting evidence, without taking over project-specific investigation itself. + +## Establish the observed behavior + +Start from the end user's experience rather than an internal error string or an implementation hypothesis. +Require an end-to-end reproduction aligned with the real user path whenever it is feasible and safe. +If a faithful reproduction is not feasible, record the exact limitation and use the closest representative path without presenting it as equivalent evidence. +Capture the expected behavior, observed behavior, setup, inputs, and repeatability before assigning a cause. + +Separate these three facts explicitly: + +- The **initiating trigger** is the event, input, or transition that starts the faulty behavior. +- The **masking condition** is the independent state, environment, timing, cache, configuration, or path difference that hides or exposes the fault. +- The **visible symptom** is what the end user or operator can actually observe. + +Do not collapse those facts into one label. +A masking condition may explain why a fault appears only sometimes without being the initiating cause, and the visible symptom may be several layers downstream from both. + +## Test the causal explanation + +Inspect the failing path and a proven path where the intended behavior is known to work. +Compare their inputs, state transitions, dependencies, timing, and control flow to find the earliest meaningful divergence. +Inspect relevant history, including blame, commits, migrations, and prior implementations, when it can explain why the paths diverged or which invariant was intended. +Do not treat the most recent nearby change as causal without evidence. + +Identify the smallest counterfactual that should change the outcome if the leading explanation is true. +Change one condition at a time where practical, and record whether the symptom appears, disappears, or remains unchanged. +Seek disconfirming evidence deliberately: name what observation would falsify the leading explanation, run that check when feasible, and retain contradictory results instead of explaining them away. +Compare the final explanation against the proven path and show why the proposed causal boundary accounts for both the failure and the success. + +## Scope and act on the result + +A diagnosis brief should ask for the reproduction, trigger/mask/symptom separation, divergent and proven path comparison, relevant history, smallest counterfactual, and disconfirming evidence in the report. +A diagnostic report should distinguish observed facts from hypotheses and state any unresolved uncertainty that could change the recommended scope. +Before acting on the report, verify that its claimed cause explains the end-user reproduction and the proven path without relying on an untested masking condition. +If a load-bearing element is missing, route a focused follow-up investigation instead of treating confidence or implementation detail as proof. +A diagnosis or implementation-ready recommendation is evidence, not authorization to change code. +Implementation still requires the captain's request or another existing lifecycle authority, and the reproduction should become the regression test when a fix is authorized. diff --git a/.agents/skills/firstmate-codexapp/SKILL.md b/.agents/skills/firstmate-codexapp/SKILL.md index 32eeb3f5e..642843963 100644 --- a/.agents/skills/firstmate-codexapp/SKILL.md +++ b/.agents/skills/firstmate-codexapp/SKILL.md @@ -91,6 +91,7 @@ For Firstmate reconciliation, prefer concrete evidence: Avoid repeating long transcripts into Firstmate docs or PR bodies. Summarize only the host-tool calls, the status-file result, and the archive result. +When reporting a Desktop-thread result to the captain, translate status prefixes and return-channel evidence through `AGENTS.md` section 9. ## Archive diff --git a/.agents/skills/firstmate-coding-guidelines/SKILL.md b/.agents/skills/firstmate-coding-guidelines/SKILL.md index 1b57f2a81..b58e6ea41 100644 --- a/.agents/skills/firstmate-coding-guidelines/SKILL.md +++ b/.agents/skills/firstmate-coding-guidelines/SKILL.md @@ -66,6 +66,14 @@ Briefs for tasks that touch firstmate's own tracked material should tell the cre Firstmate adds this skill's load instruction to firstmate-repo briefs by hand instead. `CONTRIBUTING.md`'s "Development" section carries the same instruction as a durable reminder. +## Compatibility and enforcement + +Before changing shared tracked behavior, review every affected supported primary harness and runtime backend rather than checking only the adapters active in the current fleet. +Mark an axis not applicable only after inspecting its integration surface, and update the corresponding verification evidence when behavior changes. + +For critical safety, routing, startup, and supervision infrastructure, prefer deterministic and idempotent enforcement over relying on agent memory alone. +Keep instructions as the authority and discovery layer, but make repeated execution converge safely and make invalid or unsafe states fail closed wherever the runtime can enforce them. + ## Repo style rules - Put one full sentence per line in tracked Markdown. diff --git a/.agents/skills/firstmate-orca/SKILL.md b/.agents/skills/firstmate-orca/SKILL.md index f8261cacd..854d49793 100644 --- a/.agents/skills/firstmate-orca/SKILL.md +++ b/.agents/skills/firstmate-orca/SKILL.md @@ -74,7 +74,7 @@ For a messy Orca-backed task: 6. Stop and inspect if the recorded worktree path, Orca worktree id, or project checkout no longer matches expectations. Teardown remains governed by the normal firstmate landing rules. -Scout work can be torn down after the report exists. +Scout work can be torn down after the report exists and the `decision-hold-lifecycle` completion gate passes. Ship work can be torn down only after the work is landed by its project mode. ## Smoke Test diff --git a/.agents/skills/fmx-respond/SKILL.md b/.agents/skills/fmx-respond/SKILL.md index 02502827b..762afb8d7 100644 --- a/.agents/skills/fmx-respond/SKILL.md +++ b/.agents/skills/fmx-respond/SKILL.md @@ -75,6 +75,7 @@ Normal reversible work - filing backlog, a scout investigation, gated code chang The answer is posted publicly through the relay under a **shared** bot identity. This is a strict version of the section 9 "talk in outcomes" rule, with a wider blast radius - assume anyone can read it. +It supplements `AGENTS.md` section 9; apply both, and this public-channel rule wins wherever it is stricter. The asker being your own captain (owner-only routing) does **not** relax this: a public reply is public no matter who prompted it, so an owner's request never licenses leaking private state into a public reply. Never include, in any form: diff --git a/.agents/skills/harness-adapters/SKILL.md b/.agents/skills/harness-adapters/SKILL.md index 0e441fd6d..37ab9d1f3 100644 --- a/.agents/skills/harness-adapters/SKILL.md +++ b/.agents/skills/harness-adapters/SKILL.md @@ -31,7 +31,8 @@ The primary-session watcher wake protocols are rendered from `docs/supervision-p The supervision knowledge lives here: busy signature, exit command, interrupt, dialogs, resume behavior, skill invocation, and quirks. Never dispatch a crewmate or secondmate on an unverified adapter. -If `config/crew-harness` or `config/secondmate-harness` names an unverified adapter, tell the captain and fall back to firstmate's own harness until that adapter is verified. +If `config/crew-harness` or `config/secondmate-harness` names an unverified adapter, tell the captain under `AGENTS.md` section 9 that the requested worker runtime is not verified yet, use firstmate's own verified runtime for current work, and ask only whether to verify the requested runtime before future use. +Do not pause current work for that future-verification choice, and never launch an unverified adapter. If the captain asks for a new harness, propose verifying it first: spawn a trivial supervised task using `fm-spawn`'s raw-launch-command escape hatch, confirm every fact empirically, then record the mechanics in `fm-spawn`, the busy signature in `fm-watch.sh` and `fm-tmux-lib.sh` defaults, any needed `FM_COMPOSER_IDLE_RE` empty-composer override plus any novel bare agent prompt glyph in `bin/fm-composer-lib.sh`'s shared composer classifier (the one fleet-wide owner of the empty/dead-shell/pending decision, so a new harness's own idle composer is not misread as a dead shell), the tmux agent-process liveness classification in `bin/backends/tmux.sh` when the harness can launch a secondmate, and the verified knowledge here. ## Detection @@ -63,6 +64,18 @@ Every verified primary harness also has a wired PreToolUse-equivalent hook that The exact hook files, commands, output-shaping quirks (Claude Code only honors the deny when stdout is empty), and validation transcripts are owned by `docs/arm-pretool-check.md`. When changing any primary PreToolUse hook, validate the real harness behavior in a scratch project before trusting it, then update that doc. +## Primary session-start nudge + +AGENTS.md section 3 remains the behavioral owner for session start, while tracked native adapters invoke `bin/fm-sessionstart-nudge.sh` as an idempotent enforcement layer. +The wrapper prints only the instruction to run `bin/fm-session-start.sh`; it never runs the digest, wake drain, bootstrap sweeps, lock, or supervision arm itself. +Full mechanics, scoping, dated commands, payloads, and fail-open evidence live in `docs/sessionstart-nudge.md`. + +- `claude`: verified native `SessionStart` stdout injection; `.claude/settings.json` matches `startup`, `resume`, and `clear`, but not `compact`. +- `codex`: verified on 0.144.4; `.codex/hooks.json` receives `source=startup`, and wrapper stdout reaches model context. +- `opencode`: verified on 1.17.18; `session.created` plus `client.session.promptAsync` starts the nudge turn in the TUI, while `opencode run` remains fail-open headless. +- `pi`: verified native `session_start`; the existing primary extension handles `startup`, `new`, and `resume` and uses `pi.sendMessage` to inject context without racing a positional launch prompt. +- `grok`: the 0.2.103 project `SessionStart` event fires with `source=new`, but stdout does not reach model context; the tracked project hook remains fail-open, and a global token-guarded fallback requires a captain decision. + ## Primary watcher supervision At session start, `bin/fm-session-start.sh` prints exactly one watcher supervision block for the detected primary harness. @@ -77,6 +90,15 @@ When changing any primary watcher adapter, update `docs/supervision-protocols/`, `bin/fm-spawn.sh` accepts concrete `--harness`, `--model`, and `--effort` values chosen by firstmate at intake. Do not make the shell scripts parse or match natural-language dispatch rules. + +Effort precedence is an explicit per-task captain instruction first, then any applicable standing dispatch profile or secondmate pin, then the generic fallback below. +Never replace an effort value supplied by either higher-precedence source. +Use the fallback only when neither the captain nor applicable standing configuration specifies effort. +Use `low` for well-understood work with an explicit bounded path and `xhigh` for ambiguous investigation or design. +Choose intermediate levels proportionally as complexity, uncertainty, blast radius, or open-ended reasoning increases. +When a verified adapter lacks `xhigh`, cap the choice at its highest supported non-`max` level rather than omitting the intended effort silently. +Never select `max` from this fallback; use it only when the captain has explicitly expressed that per-task or standing preference. + The supported launch-profile flags below are verified locally; each row records its evidence. | Harness | Model flag | Effort flag | Notes | @@ -84,7 +106,7 @@ The supported launch-profile flags below are verified locally; each row records | claude | `--model ` | `--effort ` | Verified on Claude Code 2.1.196. | | codex | `--model ` | `-c 'model_reasoning_effort=""'` | Verified on codex-cli 0.142.1. The installed binary schema contains `model_reasoning_effort`, the active config uses it, and the bundled model catalog advertises only low/medium/high/xhigh. `max` is omitted. | | grok | `--model ` | `--reasoning-effort ` | Verified on grok 0.2.99 (2026-07-13). `--effort` is an alias, but firstmate's profile axis is reasoning effort. As of 0.2.99 the ceiling is `high`; both `xhigh` and `max` are rejected with `use one of: high, medium, low`, so firstmate omits them. | -| pi | `--model ` | `--thinking ` | Verified on pi 0.80.2. `max` prints an invalid-thinking warning, so firstmate omits Pi effort when the requested effort is `max`. | +| pi | `--model ` | `--thinking ` | Verified 2026-07-13 on Pi 0.80.6. `pi --help` advertises `off`, `minimal`, `low`, `medium`, `high`, `xhigh`, and `max`; `pi --print --model openai-codex/gpt-5.6-sol --thinking max 'Reply with exactly OK.'` completed successfully. | | opencode | `--model ` | none for firstmate's interactive launch | Verified on opencode 1.17.6. `opencode run` has `--variant`, but firstmate launches the interactive `opencode --prompt` path, which has no verified effort flag. | When a requested effort value is outside the harness-specific accepted set, `fm-spawn` records the requested `effort=` in meta but emits no effort flag for that harness. @@ -209,7 +231,7 @@ The model arms through `fm_watch_arm_pi`, never a foreground bash arm; the watch `bin/fm-session-start.sh` reports when the live Pi session has not loaded both the turn-end guard and watcher extensions, and points at plain `pi` after project trust as the fix, with `-e` as a trust-free fallback. When a secondmate is launched on Pi, `fm-spawn.sh --secondmate` launches Pi with both `-e .pi/extensions/fm-primary-turnend-guard.ts` and `-e .pi/extensions/fm-primary-pi-watch.ts`, both already present in the secondmate home's git worktree. -## grok (VERIFIED 2026-06-29, grok 0.2.73; slash-submit re-verified 2026-07-03 on 0.2.82; reasoning-effort ceiling re-verified 2026-07-13 on 0.2.99) +## grok (VERIFIED 2026-06-29, grok 0.2.73; slash-submit re-verified 2026-07-03 on 0.2.82; reasoning-effort ceiling re-verified 2026-07-13 on 0.2.99; exit paths re-verified 2026-07-19 on grok 0.2.103) Grok Build TUI (`grok`), a Claude-Code-compatible CLI from xAI. Launch with a positional prompt: `grok --always-approve "$(cat )"`. @@ -218,7 +240,7 @@ For Grok's supported reasoning-effort values and omission behavior, see the [lau | Fact | Value | |---|---| | Busy-pane signature | `Ctrl+c:cancel` (the mid-turn cancel hint in grok's keybind bar, shown iff a turn is running; the spinner line is a braille glyph + `… N.Ns` + `[stop]`, e.g. `⠹ Thinking… 1.1s … [stop]`). Idle keybind bar shows only `Shift+Tab:mode │ Ctrl+.:shortcuts`. The ASCII `Ctrl+c:cancel` is the busy regex (avoids locale fragility of matching braille). | -| Exit command | `Ctrl+Q` double-press within 1000ms (it is a confirmed destructive action). Prints `Resume this session with: grok --resume `. `Ctrl+D` is the quit key in VS Code family terminals. NOT `/exit` and NOT `Ctrl+C`. | +| Exit command | `/exit` typed into the composer exits the TUI cleanly and prints `Resume this session with: grok --resume `; `Ctrl+Q` double-press within 1000ms remains a fallback; `Ctrl+D` is the quit key in VS Code family terminals; `Ctrl+C` is the interrupt, not the exit. | | Interrupt | single `Ctrl+C` (cancels the current turn; the footer shows `Ctrl+c:cancel` mid-turn). `Esc` only moves focus to the scrollback, it does NOT interrupt. | | Skill invocation | `/` (e.g. `/no-mistakes`), same as claude. Opens a slash-autocomplete popup, so a too-fast Enter selects the popup entry instead of sending. For an argument-taking command that first Enter does not submit at all - it expands the selection into an argument-hint placeholder in the composer (e.g. `/compact` -> `/compact compaction instructions`, live-verified), leaving real text still sitting there unsubmitted; a genuine second Enter is required. `fm-send`'s retried Enter lands it on BOTH backends, but only because each backend's own submit-verification correctly recognizes that placeholder-filled text as still-pending - see the incident below. | | Autonomy | `--always-approve` (footer shows `· always-approve`); auto-approves every tool execution, verified to run fully unattended. `--permission-mode bypassPermissions` is the stronger equivalent. | diff --git a/.agents/skills/project-management/SKILL.md b/.agents/skills/project-management/SKILL.md new file mode 100644 index 000000000..54ab841ae --- /dev/null +++ b/.agents/skills/project-management/SKILL.md @@ -0,0 +1,78 @@ +--- +name: project-management +description: >- + Agent-only procedure for Firstmate project management. + Use before adding, creating, removing, or initializing a project. + Owns project add, create, clone, remove, initialization, registry, delivery-mode, autonomy, and outward-consent decisions. +user-invocable: false +metadata: + internal: true +--- + +# project-management + +Use this procedure before adding, creating, removing, or initializing a project. +This skill is the single owner of Firstmate's project-management procedure. +It does not replace `secondmate-provisioning`, which owns project clones inside persistent secondmate homes. + +## Preconditions and registry + +Projects live flat under `projects/`, and `data/projects.md` is the private fleet registry. +Use the registry format and parser contract owned by the header of `bin/fm-project-mode.sh`. +Keep each registry description useful for identifying the project, but keep delivery posture, captain-private state, and detailed project knowledge in their existing designated homes. +Do not turn the registry into project documentation. + +Resolve the project name, destination, delivery mode, and autonomy posture before changing local or remote state. +Keep a newly added clone and its registry entry consistent, and roll back only artifacts created by the incomplete operation when a later initialization step fails and that rollback is safe. +Do not overwrite or repurpose an existing path. + +## Delivery posture + +Choose the delivery mode when adding or creating the project: + +- `no-mistakes` runs the full validation pipeline before a PR and is the default when the captain does not specify a mode. +- `direct-PR` pushes and opens a PR without the no-mistakes pipeline. +- `local-only` has no required remote or PR and lands only through the approved local fast-forward path. + +The optional `+yolo` posture changes routine approval authority but does not change the delivery mode. +Default it off, and enable it only on the captain's explicit instruction. +Destructive, irreversible, and security-sensitive decisions still require captain approval when it is on. + +## Add or clone an existing project + +Confirm the source URL, local project name, delivery mode, and autonomy posture. +Clone into `projects/` and add the registry entry only after the destination is known to be unused. +A `no-mistakes` project must have an `origin` remote and must complete the initialization procedure below. +A `direct-PR` project needs an `origin` remote but skips no-mistakes initialization. +A `local-only` project may have no remote and skips no-mistakes initialization. + +## Create a project + +Creating a GitHub repository is outward-facing. +Before making that remote change, propose the repository name, owner or organization, visibility, and delivery mode, defaulting visibility to private and delivery mode to `no-mistakes`, then obtain the captain's explicit consent for those values. +Use `gh-axi` for the approved GitHub operation and consult its current help rather than relying on remembered flags. +After remote creation succeeds, clone it locally, add the registry entry, and initialize it according to its delivery mode. + +For a purely `local-only` project, create a local Git repository under its unused `projects/` path, add the registry entry, and make no GitHub call. +The captain's request to create that local project authorizes this local initialization, but it does not authorize an unmentioned remote repository. + +## Initialize + +Run no-mistakes initialization only for `no-mistakes` projects: + +```sh +cd projects/ && no-mistakes init && no-mistakes doctor +``` + +Initialization configures the local gate and does not vendor a no-mistakes skill into the project. +Do not create a commit merely because initialization ran. +If doctor reports an environment, authentication, or daemon problem, resolve that blocker before dispatching work and never restart the shared daemon from a project operation. + +## Remove + +Project removal is destructive and is not one of Firstmate's current direct-write exceptions under `projects/`. +Never issue a raw removal command from Firstmate. +First obtain the captain's explicit removal decision, then inspect the current digest and authoritative repositories for in-flight or queued work, registered secondmate clones, linked worktrees, dirty files, unpushed commits, and any other unlanded work. +If any dependency or unlanded work exists, stop and report it before changing the registry. +Until a guarded removal helper and corresponding prime-directive exception exist, report that implementation gap instead of bypassing the project-write boundary. +When a clone has already been removed through an approved guarded path, or the registry is provably stale because no clone exists, remove its registry line so navigation matches reality. diff --git a/.agents/skills/secondmate-provisioning/SKILL.md b/.agents/skills/secondmate-provisioning/SKILL.md index c8febd24d..81393e8b5 100644 --- a/.agents/skills/secondmate-provisioning/SKILL.md +++ b/.agents/skills/secondmate-provisioning/SKILL.md @@ -2,8 +2,8 @@ name: secondmate-provisioning description: >- Agent-only reference for persistent secondmate setup and retirement. - Use when creating, seeding, validating, launching, recovering, handing backlog to, pushing inherited config into, or retiring a secondmate home, or when editing data/secondmates.md. - Covers home leases, transactional seeding, project clone restrictions, secondmate harness pins, inherited config push, idle charter, handoff helper, and teardown safety. + Use when creating, seeding, validating, launching, recovering, handing backlog to, pushing inherited local material into, or retiring a secondmate home, or when editing data/secondmates.md. + Covers home leases, transactional seeding, project clone restrictions, secondmate harness pins, inherited local-material push, idle charter, handoff helper, and teardown safety. user-invocable: false metadata: internal: true @@ -11,18 +11,21 @@ metadata: # secondmate-provisioning -Use this reference before creating, seeding, validating, launching, handing backlog to, recovering, pushing inherited config into, or retiring a persistent secondmate, and before editing `data/secondmates.md`. +Use this reference before creating, seeding, validating, launching, handing backlog to, recovering, pushing inherited local material into, or retiring a persistent secondmate, and before editing `data/secondmates.md`. Keep the always-inline routing rules in `AGENTS.md` authoritative: route by natural-language `scope:`, local-only projects stay with the main firstmate, and secondmates are idle by default. ## Routing table -`data/secondmates.md` has one line per persistent domain supervisor: +`data/secondmates.md` has one parser-compatible line per persistent second mate: ```markdown -- - (home: ; scope: ; projects: , ; added ) +- - (home: ; scope: ; projects: , ; added ) ``` +Each registry entry stays concise and single-line: the summary is one sentence naming the durable charter, `scope:` is the natural-language intake responsibility, `projects:` is the non-exclusive clone list, and any extra prose is limited to genuinely domain-specific hard rules that change routing or safety for that secondmate. +The `home:` path points to the seeded home containing `data/charter.md`; no extra registry pointer field is needed. +The home-seeded `data/charter.md` is the sole owner of boilerplate idle-by-default behavior, the normal delegation lifecycle, and standard escalation contracts, so point to that charter rather than restating those contracts in the registry entry. The `scope:` field is used during intake. The `projects:` field is a non-exclusive clone list, not ownership. @@ -41,9 +44,9 @@ Pass `--no-projects` instead of a project list to scaffold a project-less charte `--no-projects` is mutually exclusive with a project list, and omitting both still fails loudly, so an accidental omission is never mistaken for a deliberate project-less seed. Re-seeding a populated home as project-less is refused non-destructively when the home contains project clones or `data/projects.md` entries. Retire or clean that home first, and re-scaffold a stale project-bearing charter with `--no-projects` before seeding. -Keep the charter focused on the persistent responsibility, available project clones, escalation back to the main firstmate status file, and the requests-from-main-firstmate contract. -The scaffold's definition of done encodes the idle-by-default contract: on startup the secondmate reconciles only its own in-flight work and then waits for routed tasks, never self-initiating a survey or audit. -Preserve that wording when filling the charter, including the marker rule that marked supervisor requests return through status or a doc pointer while unmarked captain messages stay conversational. +Keep custom charter text focused on the persistent responsibility, available project clones, and genuinely domain-specific hard rules. +The scaffolded charter, later copied to `data/charter.md`, owns the standard lifecycle and escalation wording. +Preserve the generated charter sections unless the domain genuinely needs a hard rule. Provision the persistent home and registry entry after the charter is filled: @@ -71,16 +74,27 @@ When the file's tokens do apply, an explicit per-spawn `--model` or `--effort` f Because this resolves from the file on every spawn, the pin is durable across every respawn (recovery, `/updatefirstmate`, restart) exactly like the harness axis itself - e.g. `config/secondmate-harness` containing `claude opus` keeps a secondmate pinned to Opus even if the primary's own default model later changes. This is secondmate-only: crewmate/scout model resolution is untouched by this file. -This section is the single owner of the secondmate sync and inheritable-config propagation contract; `AGENTS.md` sections 3 and 4 point here. +This section is the single owner of the secondmate sync and inherited-local-material propagation contract; `AGENTS.md` sections 3 and 4 point here. Before launch, `fm-spawn.sh --secondmate` locally fast-forwards the home to the primary firstmate checkout's current default-branch commit when it is safe; dirty, diverged, or in-flight homes launch unchanged with a warning. The locked session-start bootstrap sweep runs the same guarded fast-forward for every live secondmate home, discovered from `state/.meta` records with `kind=secondmate` (`data/secondmates.md` only backfills `home=` for older records). That no-fetch path is a purely local fast-forward of tracked files, never an origin fetch, and it never touches the gitignored operational dirs, so a secondmate's backlog, projects, and in-flight work are never disturbed; a linked worktree advances immediately, while a standalone clone that lacks the target receives firstmate updates through `/updatefirstmate`'s origin refresh. -The same launch and the same locked bootstrap sweep also propagate the primary's declared inheritable local config, currently `config/crew-dispatch.json`, `config/crew-harness`, and `config/backlog-backend`, into the secondmate home's `config/`. -Because `config/` is gitignored, that propagation is a separate, primary-authoritative copy independent of the tracked-files fast-forward: it re-converges every live home whether or not its tracked files advanced, and it touches only the declared items. +The same launch and the same locked bootstrap sweep also propagate the primary's declared inherited local material: `config/crew-dispatch.json`, `config/crew-harness`, `config/backlog-backend`, and the one shared captain-preference file `data/captain-shared.md`. +Because these paths are gitignored, that propagation is a separate, primary-authoritative copy independent of the tracked-files fast-forward: it re-converges every live home whether or not its tracked files advanced, and it touches only the declared items. Inheritance copies the literal `config/crew-harness` file, so a secondmate's own crewmates use the primary's crewmate harness only when it names a concrete adapter such as `codex`; an unset or `default` value has nothing concrete to inherit, and the secondmate's own crewmates fall back to the secondmate's own or detected harness instead. `config/secondmate-harness` is not inherited because it is only the primary's knob for launching secondmate agents. -No reread nudge is needed at spawn or respawn because the agent reads `AGENTS.md` fresh on launch; only the bootstrap sweep's `NUDGE_SECONDMATES:` case (a RUNNING home whose instruction surface advanced) needs one. -For already-live secondmates, use `bin/fm-config-push.sh` to push a mid-session inherited-config change without running the tracked-file fast-forward or nudging the agents. +`data/captain-shared.md` is main-authoritative in the primary home and read-only in secondmate homes. +Its primary file header must state that the file is main-authoritative, read-only in secondmate homes, must not be edited there, and that new captain-preference discoveries are routed to the main firstmate through marked status or a document pointer. +Every propagation point converges the secondmate copy to the primary bytes; when the primary file is absent, any existing secondmate copy is quarantined and removed so absence converges too. +The helper rejects unsafe directories, symlinked or nonordinary source or destination artifacts, and hardlinked destination files. +Between propagation runs, the secondmate copy is filesystem read-only; the helper may make its owned destination writable only around a guarded update and restores read-only mode on success, unchanged bytes, and recoverable failure paths. +Before replacing divergent secondmate bytes, the helper hash-compares source and destination, quarantines the secondmate-local version to a collision-safe private dated sibling file, and emits a `SECONDMATE_SYNC:` diagnostic naming the home and quarantine artifact. +Never copy any secondmate `data/captain-shared.md` back into the primary. +Keep each home's `data/captain.md` domain-local. +After first propagation to an existing home, trim that home's local `data/captain.md` by hand to domain-specific content plus pointers to `data/captain-shared.md`; do not automate or silently delete private content. +Keep every `data/learnings.md` fully local by captain decision; route fleet-general machinery facts into tracked documentation through the normal firstmate repo path rather than inventing shared learnings propagation. +No reread nudge is needed at spawn or respawn because the agent reads `AGENTS.md` fresh on launch; only the bootstrap sweep's running-home instruction-surface advance needs one. +Bootstrap reports successful sends as `BOOTSTRAP_INFO:` and only emits `NUDGE_SECONDMATES:` when that send fails and needs retry. +For already-live secondmates, use `bin/fm-config-push.sh` to push a mid-session inherited local-material change without running the tracked-file fast-forward or nudging the agents. It uses the same live-home discovery and propagation helper as bootstrap and reports each item as `pushed`, `unchanged`, `skipped`, or `error`. `bin/fm-home-seed.sh` refuses to copy a missing or placeholder charter. @@ -126,8 +140,8 @@ bin/fm-spawn.sh --secondmate Use the recorded `home=` in meta. If meta is missing but `data/secondmates.md` still registers the secondmate, respawn from the registry entry and its persistent on-disk home. -Respawn re-resolves the secondmate harness from current config, uses the same guarded pre-launch sync, and re-propagates inheritable config, so recovered secondmates converge to the primary firstmate version and local dispatch, crew-harness, and backlog-backend settings whenever their home can be cleanly fast-forwarded. -If the secondmate is already running and only inherited config changed, prefer `bin/fm-config-push.sh` over respawning. +Respawn re-resolves the secondmate harness from current config, uses the same guarded pre-launch sync, and re-propagates inherited local material, so recovered secondmates converge inherited config items and shared captain preferences whenever their home validates; tracked-file sync remains guarded separately. +If the secondmate is already running and only inherited local material changed, prefer `bin/fm-config-push.sh` over respawning. Do not reconstruct a secondmate's whole tree from the main home. The main firstmate reconciles only direct reports. @@ -139,7 +153,7 @@ It never initiates a survey or audit during recovery. A secondmate is persistent by default. An empty queue is healthy and does not trigger teardown. -Run `bin/fm-teardown.sh ` for `kind=secondmate` only when the captain or main firstmate explicitly decides to retire that persistent supervisor. +Run `bin/fm-teardown.sh ` for `kind=secondmate` only when the captain or main firstmate explicitly decides to retire that persistent second mate. The safety check is the secondmate's own home. Teardown refuses while its `state/*.meta` contains in-flight work. diff --git a/.agents/skills/stow/SKILL.md b/.agents/skills/stow/SKILL.md index c35175f1b..4c2c2a337 100644 --- a/.agents/skills/stow/SKILL.md +++ b/.agents/skills/stow/SKILL.md @@ -18,7 +18,7 @@ The goal is a session that is safe to reset or destroy because everything durabl 1. **Sweep the session for uncaptured durable knowledge.** Read back over this conversation and look for: - Operational learnings: fleet-local facts and gotchas discovered while operating firstmate (a script's sharp edge, a harness quirk, a recurring false alarm and its real cause). - - Captain preferences expressed in passing: a working-style or approval preference the captain stated conversationally rather than through `data/captain.md` directly. + - Captain preferences expressed in passing: a working-style or approval preference the captain stated conversationally rather than through the destination selected by AGENTS.md's knowledge-routing table. - Project-intrinsic facts discovered: build, test, release, or architecture facts about a project that belong in that project's own `AGENTS.md`. - Decisions made: a standing choice the captain made this session that should outlive it. - Undone next steps: anything left open that has not yet been filed as backlog work. @@ -29,9 +29,9 @@ The goal is a session that is safe to reset or destroy because everything durabl 3. **Write within firstmate's existing write boundaries.** This skill does not grant any new write permission; it only prompts firstmate to use the boundaries that already exist (AGENTS.md section 1): - - Captain preferences and fleet-local operational facts: hand-write directly, to `data/captain.md` and `data/learnings.md` respectively, using inspect-then-update every time. + - Captain preferences and fleet-local operational facts: hand-write directly to the destination selected by AGENTS.md's knowledge-routing table, using inspect-then-update every time. Before writing, inspect the destination, find the existing bullet or section the finding duplicates or supersedes, and rewrite it in place rather than adding a new trailing entry. - `data/learnings.md` may not exist yet; create it on first learning, in the same dated, evidence-backed, curated style as `data/captain.md`. + `data/learnings.md` may not exist yet; create it on first local learning, in the same dated, evidence-backed, curated style as the captain-preference files. - Project-intrinsic knowledge: never hand-write a project's `AGENTS.md`. Route it through a normal ship task so a crewmate records it via `bin/fm-ensure-agents-md.sh` and commits it through that project's delivery pipeline, exactly as section 6 describes. If the fleet is live, delegate this to a crewmate rather than doing it inline. @@ -49,7 +49,7 @@ The goal is a session that is safe to reset or destroy because everything durabl - Can this be a one-sentence rewrite instead of a new entry? - Should an older bullet or note be deleted, retired, or archived because it is now obsolete? When a finding overlaps or supersedes something already on disk, rewrite or prune the existing entry instead of piling on a new one. - Graduation moves are limited to exactly three: promote a learning to the shared `AGENTS.md` via PR, fold it into `data/captain.md`, or delete a stale entry. + Graduation moves are limited to exactly three: promote a learning to the shared `AGENTS.md` via PR, fold it into the captain-preference destination selected by AGENTS.md, or delete a stale entry. Do not invent other graduation paths. 5. **Report to the captain.** diff --git a/.agents/skills/stuck-crewmate-recovery/SKILL.md b/.agents/skills/stuck-crewmate-recovery/SKILL.md index 2204c6bb7..40a1468cf 100644 --- a/.agents/skills/stuck-crewmate-recovery/SKILL.md +++ b/.agents/skills/stuck-crewmate-recovery/SKILL.md @@ -1,6 +1,9 @@ --- name: stuck-crewmate-recovery -description: Agent-only playbook for stuck firstmate direct reports. Use after a stale wake, looping pane, repeated confusion, an answered-by-brief question, an unresponsive crewmate, or a failed steer. Escalates from peek, to one-line steer, to harness-specific interrupt, to relaunch with progress, to failed status. +description: >- + Agent-only playbook for stuck or missing ordinary Firstmate direct reports. + Use when the session-start digest reports an ordinary direct report's endpoint dead or its metadata has no window, or after a stale wake, looping pane, repeated confusion, an answered-by-brief question, an unresponsive crewmate, or a failed steer. + Reconciles recorded work before escalating from targeted inspection through safe relaunch or failure. user-invocable: false metadata: internal: true @@ -8,11 +11,31 @@ metadata: # stuck-crewmate-recovery -Use this playbook when a direct report is stale, looping, repeatedly confused, asking a question its brief already answers, unresponsive, or when a steer failed to land. +Use this playbook when the session-start digest reports an ordinary direct report's endpoint dead or its metadata has no window, or when a direct report is stale, looping, repeatedly confused, asking a question its brief already answers, unresponsive, or when a steer failed to land. Load `harness-adapters` before sending an interrupt, exit command, resume command, or harness-specific skill invocation. The target window's harness is recorded as `harness=` in `state/.meta`. +## Session-start reconciliation for a dead ordinary direct report + +This procedure covers ordinary `kind=ship` and `kind=scout` direct reports. +Load `secondmate-provisioning` instead for `kind=secondmate` recovery. + +Treat the digest's endpoint result as a presence signal, not proof that the task's work or validation run is gone. +Read the targeted current state with `bin/fm-crew-state.sh ` before deciding to relaunch. +A branch-matched no-mistakes run remains authoritative when the endpoint is dead: handle a terminal or parked run through the normal lifecycle, and keep supervising an active run instead of creating a duplicate worker. + +When no authoritative run accounts for the task, inspect only its recorded backend and worktree inventory. +Use `treehouse status` for treehouse-backed tmux, herdr, zellij, or cmux tasks, and use the recorded `orca_worktree_id=` and `terminal=` for Orca tasks. +Do not sweep another home's endpoints or infer ownership from a matching window label. + +Before relaunch, prove that no live agent still owns the recorded task and that the existing worktree remains available. +Preserve its uncommitted changes and commits, keep the same task identity, and resume or relaunch the recorded harness in that existing worktree with the same brief plus a concise progress note. +Do not use a fresh generic spawn while the recorded worktree is unaccounted for, because allocating another worktree can split one task across two copies. +If the worktree or ownership cannot be reconciled safely, leave all state intact and report the task failed or blocked with the conflicting evidence. + +## Live-endpoint escalation + Escalate in order: 1. Peek the pane. @@ -23,4 +46,4 @@ Escalate in order: Genuine wedging means looping, unresponsive, repeating the same obstacle, or truly dead. A low context reading is not wedging; modern harnesses auto-compact and keep going. The worktree and commits persist, so relaunch is cheap. -5. If a second relaunch fails too, write `failed` to the backlog and tell the captain with evidence. +5. If a second relaunch fails too, write `failed` to the backlog and tell the captain the plain failure, preserved work, and consequence using `AGENTS.md` section 9; do not mention metadata, harness, window, or worktree unless the path itself is needed for action. diff --git a/.agents/skills/updatefirstmate/SKILL.md b/.agents/skills/updatefirstmate/SKILL.md index 015bc1350..de95ed353 100644 --- a/.agents/skills/updatefirstmate/SKILL.md +++ b/.agents/skills/updatefirstmate/SKILL.md @@ -44,8 +44,8 @@ This touches only the firstmate repo and its own worktrees, never anything under A secondmate that was skipped, already current, or has no live metadata is not on the list and needs no nudge. 4. **Report to the captain in plain outcomes.** - Summarize what landed without firstmate's internal vocabulary: which parts of the fleet are now on the latest, and which were left as-is and why. - For example: "Captain, firstmate and both domain supervisors are now on the latest." + Summarize what landed under `AGENTS.md` section 9 without firstmate's internal vocabulary: which parts of the fleet are now on the latest, and which were left as-is and why. + For example: "Captain, firstmate and both second mates are now on the latest." Surface any skipped target whose reason needs the captain's attention - for instance a home with its own un-landed changes (diverged) or local edits (dirty), which were left untouched on purpose. ## Safety diff --git a/.claude/settings.json b/.claude/settings.json index 6bbd714d7..37a535e37 100644 --- a/.claude/settings.json +++ b/.claude/settings.json @@ -1,5 +1,16 @@ { "hooks": { + "SessionStart": [ + { + "matcher": "startup|resume|clear", + "hooks": [ + { + "type": "command", + "command": "\"$CLAUDE_PROJECT_DIR\"/bin/fm-sessionstart-nudge.sh" + } + ] + } + ], "PreToolUse": [ { "matcher": "Bash", @@ -11,6 +22,10 @@ { "type": "command", "command": "\"$CLAUDE_PROJECT_DIR\"/bin/fm-cd-pretool-check.sh --claude" + }, + { + "type": "command", + "command": "\"$CLAUDE_PROJECT_DIR\"/bin/fm-continuity-pretool-check.sh" } ] } diff --git a/.codex/hooks.json b/.codex/hooks.json index 0ed18a74a..337bd0a68 100644 --- a/.codex/hooks.json +++ b/.codex/hooks.json @@ -1,5 +1,16 @@ { "hooks": { + "SessionStart": [ + { + "hooks": [ + { + "type": "command", + "command": "bash -lc 'payload=$(cat 2>/dev/null || true); [ -n \"$payload\" ] || exit 0; command -v jq >/dev/null 2>&1 || exit 0; root=$(pwd -P) || exit 0; [ -x \"$root/bin/fm-sessionstart-nudge.sh\" ] || exit 0; [ -f \"$root/AGENTS.md\" ] || exit 0; [ -f \"$root/.codex/hooks.json\" ] || exit 0; jq -e \"any(.hooks.SessionStart[]?.hooks[]?.command?; type == \\\"string\\\" and contains(\\\"fm-sessionstart-nudge.sh\\\"))\" \"$root/.codex/hooks.json\" >/dev/null 2>&1 || exit 0; exec \"$root/bin/fm-sessionstart-nudge.sh\"'", + "timeout": 10 + } + ] + } + ], "PreToolUse": [ { "matcher": "Bash", diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index a75d82d3b..bdfa76b23 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -58,6 +58,42 @@ jobs: "$test_script" done + macos-stock-bash: + name: Stock macOS Bash snapshot compatibility + runs-on: macos-latest + timeout-minutes: 10 + steps: + - uses: actions/checkout@v6 + - name: Run snapshot consumers with stock Bash + shell: /bin/bash {0} + env: + PATH: /bin:/usr/bin:/usr/sbin:/sbin:/usr/local/bin:/opt/homebrew/bin + run: | + set -eu + case "$BASH_VERSION" in + 3.2.57*) ;; + *) echo "::error::expected stock macOS Bash 3.2.57, got $BASH_VERSION"; exit 1 ;; + esac + /bin/bash --version | head -1 + command -v jq >/dev/null || { echo "::error::jq is required"; exit 1; } + /bin/bash -n bin/fm-fleet-snapshot.sh + + snapshot_output=$(/bin/bash tests/fm-fleet-snapshot-view.test.sh) + printf '%s\n' "$snapshot_output" + snapshot_count=$(printf '%s\n' "$snapshot_output" | grep -c '^ok - ') + [ "$snapshot_count" -eq 13 ] || { + echo "::error::expected 13 snapshot/fleet-view tests, got $snapshot_count" + exit 1 + } + + bearings_output=$(/bin/bash tests/fm-bearings-snapshot.test.sh) + printf '%s\n' "$bearings_output" + bearings_count=$(printf '%s\n' "$bearings_output" | grep -c '^ok - ') + [ "$bearings_count" -eq 36 ] || { + echo "::error::expected 36 Bearings tests, got $bearings_count" + exit 1 + } + invariants: name: Repo invariants runs-on: ubuntu-latest diff --git a/.grok/hooks/fm-primary-sessionstart-nudge.json b/.grok/hooks/fm-primary-sessionstart-nudge.json new file mode 100644 index 000000000..0b79c2588 --- /dev/null +++ b/.grok/hooks/fm-primary-sessionstart-nudge.json @@ -0,0 +1,15 @@ +{ + "hooks": { + "SessionStart": [ + { + "hooks": [ + { + "type": "command", + "command": "bash -lc '[ -n \"${GROK_WORKSPACE_ROOT:-}\" ] || exit 0; exec \"${GROK_WORKSPACE_ROOT:-}/bin/fm-sessionstart-nudge.sh\"'", + "timeout": 10 + } + ] + } + ] + } +} diff --git a/.no-mistakes.yaml b/.no-mistakes.yaml index 8fc97893a..b95e69b41 100644 --- a/.no-mistakes.yaml +++ b/.no-mistakes.yaml @@ -9,18 +9,20 @@ # HEAD-continuity guard; see docs/architecture.md "No-mistakes gate authority boundary." disable_project_settings: true -# Pin lint and test to the SAME deterministic commands CI runs, instead of -# leaving them to no-mistakes' default handling. Without a configured +# Pin lint and the portable behavior suite to the same deterministic commands +# the Linux CI jobs run, instead of leaving them to no-mistakes' default handling. +# CI separately owns platform-specific compatibility lanes, including the stock +# macOS Bash snapshot checks. Without a configured # commands.lint, the gate's lint step never ran the deterministic # `shellcheck bin/*.sh bin/backends/*.sh tests/*.sh` that CI runs, so info-level # ShellCheck findings (e.g. SC2015) were not surfaced locally before CI rejected # them. commands.lint delegates to bin/fm-lint.sh, the single owner of the lint # definition that .github/workflows/ci.yml also invokes, so local can never # diverge from CI again (parity asserted by tests/fm-lint.test.sh). -# The test command mirrors .github/workflows/ci.yml: iterate every -# tests/*.test.sh, run each, and fail the step if any one exits non-zero (an -# agent-driven test step has crashed the daemon). The e2e tests need tmux on -# PATH, which the firstmate environment provides. +# The test command mirrors the Linux behavior job in .github/workflows/ci.yml: +# iterate every tests/*.test.sh, run each, and fail the step if any one exits +# non-zero (an agent-driven test step has crashed the daemon). The e2e tests need +# tmux on PATH, which the firstmate environment provides. commands: lint: 'bin/fm-lint.sh' test: 'command -v tmux >/dev/null || { echo "tmux is required for e2e tests" >&2; exit 1; }; tmux -V; rc=0; for t in tests/*.test.sh; do echo "== $t =="; bash "$t" || rc=1; done; exit "$rc"' diff --git a/.opencode/plugins/fm-primary-sessionstart-nudge.js b/.opencode/plugins/fm-primary-sessionstart-nudge.js new file mode 100644 index 000000000..5e8df0b4e --- /dev/null +++ b/.opencode/plugins/fm-primary-sessionstart-nudge.js @@ -0,0 +1,60 @@ +import { spawn } from "node:child_process"; +import { realpathSync } from "node:fs"; +import { resolve } from "node:path"; + +const handledSessions = new Set(); + +function runProcess(command, args) { + return new Promise((resolveResult) => { + const child = spawn(command, args, { stdio: ["ignore", "pipe", "ignore"] }); + let stdout = ""; + child.stdout.on("data", (chunk) => { + stdout += chunk.toString(); + }); + child.on("error", () => resolveResult({ code: 0, stdout: "" })); + child.on("close", (code) => resolveResult({ code: code ?? 0, stdout })); + }); +} + +function resolvePath(anchor) { + try { + return realpathSync(anchor); + } catch { + return resolve(anchor); + } +} + +async function resolveRoot(anchor) { + if (!anchor) return ""; + const result = await runProcess("git", ["-C", anchor, "rev-parse", "--show-toplevel"]); + const root = result.stdout.trim(); + if (result.code === 0 && root) return root; + return resolvePath(anchor); +} + +export const FmPrimarySessionstartNudge = async ({ client, directory, worktree }) => { + const root = worktree ? resolvePath(worktree) : await resolveRoot(directory); + + return { + event: async ({ event }) => { + if (event.type !== "session.created") return; + const sessionID = event.properties?.info?.id ?? event.properties?.sessionID; + if (!sessionID || handledSessions.has(sessionID) || !root) return; + handledSessions.add(sessionID); + + const result = await runProcess(`${root}/bin/fm-sessionstart-nudge.sh`, []); + const nudge = result.code === 0 ? result.stdout.trim() : ""; + if (!nudge) return; + + try { + await client.session.promptAsync({ + path: { id: sessionID }, + body: { + parts: [{ type: "text", text: nudge }], + }, + }); + } catch { + } + }, + }; +}; diff --git a/.opencode/plugins/fm-primary-turnend-guard.js b/.opencode/plugins/fm-primary-turnend-guard.js index b38f9c2c4..f0ff5621b 100644 --- a/.opencode/plugins/fm-primary-turnend-guard.js +++ b/.opencode/plugins/fm-primary-turnend-guard.js @@ -82,7 +82,7 @@ export const FmPrimaryTurnendGuard = async ({ client, directory, worktree }) => type: "text", text: "TURN WOULD END BLIND - supervision is off. " + - "Resume supervision according to the session-start operating block before ending the turn.\n\n" + + "The watcher cycle is missing, failed, or unhealthy. Follow the harness recovery instruction below before ending the turn.\n\n" + result.stderr, }, ], diff --git a/.opencode/plugins/fm-primary-watch-arm.js b/.opencode/plugins/fm-primary-watch-arm.js index 5147f839a..15a772d04 100644 --- a/.opencode/plugins/fm-primary-watch-arm.js +++ b/.opencode/plugins/fm-primary-watch-arm.js @@ -4,37 +4,40 @@ import { resolve } from "node:path"; const COORDINATOR_KEY = "__firstmateOpenCodeWatchArm"; const ARM_READY_TIMEOUT_MS = Number(process.env.FM_OPENCODE_ARM_READY_TIMEOUT_MS || 12000); +const ARM_RETIRE_TIMEOUT_MS = positiveInteger("FM_WATCH_ARM_RETIRE_TIMEOUT_MS", 1000); +const REARM_RETRY_BASE_MS = positiveInteger("FM_WATCH_REARM_RETRY_BASE_MS", 250); +const REARM_RETRY_MAX_MS = positiveInteger("FM_WATCH_REARM_RETRY_MAX_MS", 4000); +const REARM_RETRY_LIMIT = positiveInteger("FM_WATCH_REARM_RETRY_LIMIT", 5); let child = null; let armStatus = "idle"; -let waiters = new Set(); +let retryTimer = null; +let retryFailures = 0; +let launchInFlight = null; +let restorationInFlight = null; +let armClose = new WeakMap(); +let armReadiness = new WeakMap(); -function setArmStatus(status) { - armStatus = status; - for (const resolve of waiters) resolve(status); - waiters.clear(); +function positiveInteger(name, fallback) { + const value = Number(process.env[name]); + if (!Number.isFinite(value) || value <= 0) return fallback; + return Math.floor(value); } -function readyStatus() { - if (armStatus === "armed" || armStatus === "wake" || armStatus === "failed" || armStatus === "external") return armStatus; - return ""; +function setArmStatus(status) { + armStatus = status; } -function waitForArmReady() { - const ready = readyStatus(); - if (ready) return Promise.resolve(ready); +function waitForArmReady(armChild) { + const readiness = armReadiness.get(armChild); + if (!readiness) return Promise.resolve("failed"); return new Promise((resolve) => { - let timer = null; - const waiter = (status) => { - if (timer) clearTimeout(timer); - waiters.delete(waiter); + const timer = setTimeout(() => resolve("timeout"), ARM_READY_TIMEOUT_MS); + timer.unref(); + void readiness.then((status) => { + clearTimeout(timer); resolve(status); - }; - timer = setTimeout(() => { - waiters.delete(waiter); - resolve("timeout"); - }, ARM_READY_TIMEOUT_MS); - waiters.add(waiter); + }); }); } @@ -121,29 +124,57 @@ async function sessionOwnsLock(paths) { return false; } -function firstWakeOrFailure(stdout, stderr, code) { +function classifyArmClose(stdout, stderr, code, signal) { const combined = `${stdout}\n${stderr}`; const reason = combined.split(/\r?\n/).find((line) => /^(signal:|stale:|check:|heartbeat($|:))/.test(line)); - if (reason) return reason; - if (/^watcher: healthy/m.test(combined)) return ""; + if (reason) return { kind: "actionable", message: reason }; + const healthy = combined.split(/\r?\n/).find((line) => /^watcher: healthy\b/.test(line)); + if (healthy) { + return { + kind: "failure", + message: `watcher: FAILED - OpenCode arm child found an external healthy watcher instead of owning wake delivery\n${healthy}`, + }; + } const failed = combined.split(/\r?\n/).find((line) => /^watcher: FAILED/.test(line)); - if (failed) return failed; - if (code && code !== 0) return `watcher: FAILED - fm-watch-arm.sh exited ${code}${combined.trim() ? `\n${combined.trim()}` : ""}`; - return ""; + if (failed) return { kind: "failure", message: failed }; + if (signal) { + return { + kind: "failure", + message: `watcher: FAILED - OpenCode arm child ended from ${signal}${combined.trim() ? `\n${combined.trim()}` : ""}`, + }; + } + if (code && code !== 0) { + return { + kind: "failure", + message: `watcher: FAILED - fm-watch-arm.sh exited ${code}${combined.trim() ? `\n${combined.trim()}` : ""}`, + }; + } + return { + kind: "failure", + message: "watcher: FAILED - OpenCode arm cycle ended without an actionable reason", + }; } -function observeArmOutput(stdout, stderr) { +function observeArmOutput(stdout, stderr, settleReadiness) { const combined = `${stdout}\n${stderr}`; - if (combined.split(/\r?\n/).some((line) => /^watcher: started\b/.test(line))) { + if (combined.split(/\r?\n/).some((line) => /^(signal:|stale:|check:|heartbeat($|:))/.test(line))) { + setArmStatus("wake"); + settleReadiness("wake"); + return; + } + if (combined.split(/\r?\n/).some((line) => /^watcher: (?:started|attached)\b/.test(line))) { setArmStatus("armed"); + settleReadiness("armed"); return; } if (combined.split(/\r?\n/).some((line) => /^watcher: healthy\b/.test(line))) { setArmStatus("external"); + settleReadiness("external"); return; } if (combined.split(/\r?\n/).some((line) => /^watcher: FAILED/.test(line))) { setArmStatus("failed"); + settleReadiness("failed"); } } @@ -161,65 +192,222 @@ async function sendPrompt(client, sessionID, text) { }); } -function spawnArm(paths, sessionID, client) { +function wakePrompt(reason) { + return `WATCHER FIRED - drain queued wakes with bin/fm-wake-drain.sh and handle the reported wake. Watcher continuity is plugin-owned.\n\n${reason}`; +} + +function surfaceFailure(client, sessionID, reason) { + void sendPrompt(client, sessionID, wakePrompt(reason)).catch(() => { + }); +} + +function retryDelay(attempt) { + return Math.min(REARM_RETRY_MAX_MS, REARM_RETRY_BASE_MS * 2 ** Math.max(0, attempt - 1)); +} + +function waitForRetry(attempt) { + return new Promise((resolve) => { + const timer = setTimeout(resolve, retryDelay(attempt)); + timer.unref(); + }); +} + +async function retireArm(armChild) { + if (!armChild) return true; + armChild.kill("SIGTERM"); + const closed = armClose.get(armChild); + if (!closed) return false; + return new Promise((resolve) => { + const timer = setTimeout(() => resolve(false), ARM_RETIRE_TIMEOUT_MS); + timer.unref(); + void closed.then(() => { + clearTimeout(timer); + resolve(true); + }); + }); +} + +function restorationFailure(status) { + if (status === "read-only") { + return "watcher: FAILED - OpenCode cannot restore continuity because this session no longer owns the lock"; + } + return `watcher: FAILED - OpenCode could not verify a ready successor watcher (${status || "idle"})`; +} + +async function restoreAfterActionableClose(paths, sessionID, client, predecessorArmPid) { + let failure = ""; + for (let attempt = 0; attempt <= REARM_RETRY_LIMIT; attempt += 1) { + const { status, armChild } = await ensureArm(paths, sessionID, client, predecessorArmPid, true); + if (status === "armed") return ""; + // An actionable line belongs to this arm's close handler. + // Do not retire it before that handler can start the successor cycle. + if (status === "wake") return ""; + failure = restorationFailure(status); + if (!(await retireArm(armChild))) { + setArmStatus("failed"); + return `${failure}\nwatcher: FAILED - OpenCode could not restore watcher continuity because the unready successor arm did not exit within ${ARM_RETIRE_TIMEOUT_MS}ms`; + } + if (status === "read-only" || status === "not-primary" || status === "skipped") break; + if (attempt === REARM_RETRY_LIMIT) break; + await waitForRetry(attempt + 1); + } + setArmStatus("failed"); + return `${failure}\nwatcher: FAILED - OpenCode could not restore watcher continuity after ${REARM_RETRY_LIMIT} retries`; +} + +async function scheduleRetry(paths, sessionID, client, reason, predecessorArmPid) { + if (child || retryTimer) return; + if (!(await sessionOwnsLock(paths))) { + setArmStatus("failed"); + surfaceFailure(client, sessionID, `watcher: FAILED - OpenCode cannot restore continuity because this session no longer owns the lock\n${reason}`); + return; + } + retryFailures += 1; + if (retryFailures > REARM_RETRY_LIMIT) { + setArmStatus("failed"); + surfaceFailure(client, sessionID, `watcher: FAILED - OpenCode could not restore watcher continuity after ${REARM_RETRY_LIMIT} retries\n${reason}`); + return; + } + setArmStatus("retrying"); + const timer = setTimeout(() => { + if (retryTimer === timer) retryTimer = null; + void ensureArm(paths, sessionID, client, predecessorArmPid).then((status) => { + if (["armed", "starting", "wake"].includes(status)) return; + surfaceFailure(client, sessionID, `watcher: FAILED - OpenCode could not launch a continuity retry (${status})`); + }); + }, retryDelay(retryFailures)); + timer.unref(); + retryTimer = timer; +} + +function spawnArm(paths, sessionID, client, predecessorArmPid = "") { setArmStatus("starting"); const env = { ...process.env, FM_HOME: paths.home, FM_ROOT_OVERRIDE: paths.root, + FM_CONFIG_OVERRIDE: paths.config, + FM_WATCH_PREDECESSOR_ARM_PID: predecessorArmPid, }; - child = spawn("bash", ["-lc", 'config_dir="${FM_CONFIG_OVERRIDE:-$FM_HOME/config}"; [ -f "$config_dir/x-mode.env" ] && . "$config_dir/x-mode.env"; exec "$FM_ROOT_OVERRIDE/bin/fm-watch-arm.sh" --restart'], { + const armChild = spawn("bash", ["-lc", 'config_dir="${FM_CONFIG_OVERRIDE:-$FM_HOME/config}"; [ -f "$config_dir/x-mode.env" ] && . "$config_dir/x-mode.env"; exec "$FM_ROOT_OVERRIDE/bin/fm-watch-arm.sh" --restart'], { cwd: paths.root, env, stdio: ["ignore", "pipe", "pipe"], }); + child = armChild; let stdout = ""; let stderr = ""; - child.stdout.on("data", (chunk) => { + let settled = false; + let resolveClosed = null; + let readinessSettled = false; + let resolveReadiness = null; + const readiness = new Promise((resolve) => { + resolveReadiness = resolve; + }); + armReadiness.set(armChild, readiness); + const settleReadiness = (status) => { + if (readinessSettled) return; + readinessSettled = true; + resolveReadiness(status); + }; + const closed = new Promise((resolveClosedChild) => { + resolveClosed = resolveClosedChild; + }); + armClose.set(armChild, closed); + const releaseChild = () => { + if (child === armChild) child = null; + }; + armChild.stdout.on("data", (chunk) => { stdout += chunk.toString(); - observeArmOutput(stdout, stderr); + observeArmOutput(stdout, stderr, settleReadiness); }); - child.stderr.on("data", (chunk) => { + armChild.stderr.on("data", (chunk) => { stderr += chunk.toString(); - observeArmOutput(stdout, stderr); + observeArmOutput(stdout, stderr, settleReadiness); }); - child.on("close", async (code) => { - child = null; - const reason = firstWakeOrFailure(stdout, stderr, code); - if (reason) setArmStatus(reason.startsWith("watcher: FAILED") ? "failed" : "wake"); - else if (!readyStatus()) setArmStatus("idle"); - if (!reason) return; - try { - await sendPrompt( - client, - sessionID, - `WATCHER FIRED - drain queued wakes with bin/fm-wake-drain.sh, handle the reported wake, and continue normal supervision.\n\n${reason}`, - ); - } catch { + armChild.on("close", (code, signal) => { + if (settled) return; + settled = true; + resolveClosed(); + releaseChild(); + const classification = classifyArmClose(stdout, stderr, code, signal); + settleReadiness(classification.kind === "actionable" ? "wake" : "failed"); + const predecessor = String(armChild.pid ?? ""); + if (classification.kind === "actionable") { + retryFailures = 0; + setArmStatus("wake"); + const previousRestoration = restorationInFlight; + const restoration = previousRestoration + ? previousRestoration.catch(() => "").then(() => restoreAfterActionableClose(paths, sessionID, client, predecessor)) + : restoreAfterActionableClose(paths, sessionID, client, predecessor); + restorationInFlight = restoration; + void restoration.then((failure) => { + if (restorationInFlight === restoration) restorationInFlight = null; + const message = failure ? `${classification.message}\n\n${failure}` : classification.message; + return sendPrompt(client, sessionID, wakePrompt(message)); + }).catch(() => { + }); + return; + } + if (restorationInFlight) { + setArmStatus("failed"); + return; } + void scheduleRetry(paths, sessionID, client, classification.message, predecessor); }); - child.on("error", async (error) => { - child = null; - setArmStatus("failed"); - try { - await sendPrompt( - client, - sessionID, - `WATCHER FIRED - drain queued wakes with bin/fm-wake-drain.sh, handle the reported wake, and continue normal supervision.\n\nwatcher: FAILED - OpenCode arm child failed: ${error.message}`, - ); - } catch { + armChild.on("error", (error) => { + if (settled) return; + settled = true; + resolveClosed(); + releaseChild(); + settleReadiness("failed"); + if (restorationInFlight) { + setArmStatus("failed"); + return; } + void scheduleRetry( + paths, + sessionID, + client, + `watcher: FAILED - OpenCode arm child failed: ${error.message}`, + String(armChild.pid ?? ""), + ); }); + return armChild; } -async function ensureArm(paths, sessionID, client) { - if (!sessionID) return "skipped"; - if (!(await isPrimaryRoot(paths.root, paths.home))) return "not-primary"; - if (!(await sessionOwnsLock(paths))) return "read-only"; - if (child) return waitForArmReady(); - if (!shouldArm(paths)) return "not-needed"; - spawnArm(paths, sessionID, client); - return waitForArmReady(); +async function beginArm(paths, sessionID, client, predecessorArmPid) { + if (!sessionID) return { status: "skipped", armChild: null }; + if (!(await isPrimaryRoot(paths.root, paths.home))) return { status: "not-primary", armChild: null }; + if (!(await sessionOwnsLock(paths))) return { status: "read-only", armChild: null }; + if (child) return { status: "existing", armChild: child }; + if (retryTimer) return { status: "retrying", armChild: null }; + if (!shouldArm(paths)) return { status: "not-needed", armChild: null }; + return { status: "spawned", armChild: spawnArm(paths, sessionID, client, predecessorArmPid) }; +} + +function armAttempt(status, armChild, includeArmChild) { + return includeArmChild ? { status, armChild } : status; +} + +async function ensureArm(paths, sessionID, client, predecessorArmPid = "", includeArmChild = false) { + let launchResult = null; + if (!launchInFlight) { + const launch = beginArm(paths, sessionID, client, predecessorArmPid); + launchInFlight = launch; + try { + launchResult = await launch; + } finally { + if (launchInFlight === launch) launchInFlight = null; + } + } else { + launchResult = await launchInFlight; + } + const armChild = launchResult.armChild; + if (!armChild) { + return armAttempt(launchResult.status, null, includeArmChild); + } + return armAttempt(await waitForArmReady(armChild), armChild, includeArmChild); } export const FmPrimaryWatchArm = async ({ client, directory, worktree }) => { diff --git a/.opencode/plugins/package.json b/.opencode/plugins/package.json new file mode 100644 index 000000000..e986b24bb --- /dev/null +++ b/.opencode/plugins/package.json @@ -0,0 +1,4 @@ +{ + "private": true, + "type": "module" +} diff --git a/.pi/extensions/fm-primary-pi-watch.ts b/.pi/extensions/fm-primary-pi-watch.ts index 644f939ce..0f7f403e5 100644 --- a/.pi/extensions/fm-primary-pi-watch.ts +++ b/.pi/extensions/fm-primary-pi-watch.ts @@ -1,5 +1,5 @@ // Firstmate primary watcher bridge for Pi. -import { spawn, spawnSync } from "node:child_process"; +import { spawn, spawnSync, type ChildProcess } from "node:child_process"; import { createHash } from "node:crypto"; import { mkdirSync, readFileSync, writeFileSync } from "node:fs"; import { dirname, resolve } from "node:path"; @@ -14,6 +14,11 @@ type ArmResult = { type LockOwnership = "owned" | "missing" | "other"; +type CloseClassification = { + kind: "actionable" | "failure"; + message: string; +}; + const extensionFile = fileURLToPath(import.meta.url); const extensionDir = dirname(extensionFile); const root = resolve(extensionDir, "../.."); @@ -24,9 +29,26 @@ const config = process.env.FM_CONFIG_OVERRIDE || `${fmHome}/config`; const armScript = `${fmRoot}/bin/fm-watch-arm.sh`; const marker = `${state}/.pi-watch-extension-loaded`; const extensionVersion = `sha256:${createHash("sha256").update(readFileSync(extensionFile)).digest("hex")}`; +const retryBaseMs = positiveInteger("FM_WATCH_REARM_RETRY_BASE_MS", 250); +const retryMaxMs = positiveInteger("FM_WATCH_REARM_RETRY_MAX_MS", 4000); +const retryLimit = positiveInteger("FM_WATCH_REARM_RETRY_LIMIT", 5); +const armReadyTimeoutMs = positiveInteger("FM_PI_ARM_READY_TIMEOUT_MS", 12000); +const armRetireTimeoutMs = positiveInteger("FM_WATCH_ARM_RETIRE_TIMEOUT_MS", 1000); -let child: any = null; +let child: ChildProcess | null = null; +let retryTimer: ReturnType | null = null; +let retryFailures = 0; +let stopping = false; let seq = 0; +let restoring = false; +const armReadiness = new WeakMap>(); +const armClose = new WeakMap>(); + +function positiveInteger(name: string, fallback: number): number { + const value = Number(process.env[name]); + if (!Number.isFinite(value) || value <= 0) return fallback; + return Math.floor(value); +} function parentPid(pid: string): string { const result = spawnSync("ps", ["-o", "ppid=", "-p", pid], { encoding: "utf8" }); @@ -60,10 +82,6 @@ function lockOwnership(): LockOwnership { return pidAlive(lockPid) ? "other" : "missing"; } -function sessionOwnsLock(): boolean { - return lockOwnership() === "owned"; -} - function markLoaded(): void { if (lockOwnership() === "other") return; mkdirSync(state, { recursive: true }); @@ -75,18 +93,42 @@ function actionableLine(output: string): string { return lines.find((line) => /^(signal:|stale:|check:|heartbeat($|:))/.test(line)) || ""; } -function failureLine(stdout: string, stderr: string, code: number | null): string { +function classifyClose(stdout: string, stderr: string, code: number | null, signal: NodeJS.Signals | null): CloseClassification { const combined = `${stdout}\n${stderr}`.trim(); + const reason = actionableLine(combined); + if (reason) return { kind: "actionable", message: reason }; const healthy = combined.split(/\r?\n/).find((line) => /^watcher: healthy\b/.test(line)); - if (healthy) return `watcher: FAILED - Pi extension arm child found an external healthy watcher instead of owning wake delivery\n${healthy}`; + if (healthy) { + return { + kind: "failure", + message: `watcher: FAILED - Pi extension arm child found an external healthy watcher instead of owning wake delivery\n${healthy}`, + }; + } const failed = combined.split(/\r?\n/).find((line) => /^watcher: FAILED/.test(line)); - if (failed) return failed; - if (code && code !== 0) return `watcher: FAILED - fm-watch-arm.sh exited ${code}${combined ? `\n${combined}` : ""}`; - return ""; + if (failed) return { kind: "failure", message: failed }; + if (signal) { + return { + kind: "failure", + message: `watcher: FAILED - Pi extension arm child ended from ${signal}${combined ? `\n${combined}` : ""}`, + }; + } + if (code && code !== 0) { + return { + kind: "failure", + message: `watcher: FAILED - fm-watch-arm.sh exited ${code}${combined ? `\n${combined}` : ""}`, + }; + } + return { + kind: "failure", + message: "watcher: FAILED - Pi extension arm cycle ended without an actionable reason", + }; } export default function (pi: ExtensionAPI) { function stopArm(): void { + stopping = true; + if (retryTimer) clearTimeout(retryTimer); + retryTimer = null; if (child) child.kill("SIGTERM"); child = null; } @@ -96,17 +138,118 @@ export default function (pi: ExtensionAPI) { }; process.once("exit", cleanupOnProcessExit); - async function sendWake(message: string) { + async function sendWake(message: string): Promise { await pi.sendUserMessage( - `FIRSTMATE WATCHER WAKE: ${message}\n\nRun bin/fm-wake-drain.sh first, handle the queued wake, then resume Pi supervision.`, + `FIRSTMATE WATCHER WAKE: ${message}\n\nRun bin/fm-wake-drain.sh first and handle the queued wake. Watcher continuity is extension-owned.`, { deliverAs: "followUp" }, ); } - function startArm(): ArmResult { - if (!sessionOwnsLock()) return { ok: false, message: "watcher: read-only - session lock is held by another firstmate session" }; + function surfaceFailure(message: string): void { + void sendWake(message).catch(() => { + // Pi owns delivery errors; continuity restoration never waits on prompting. + }); + } + + function retryDelay(attempt: number): number { + return Math.min(retryMaxMs, retryBaseMs * 2 ** Math.max(0, attempt - 1)); + } + + function waitForRetry(attempt: number): Promise { + return new Promise((resolveRetry) => { + const timer = setTimeout(resolveRetry, retryDelay(attempt)); + timer.unref(); + }); + } + + function waitForReadiness(armChild: ChildProcess): Promise { + const readiness = armReadiness.get(armChild); + if (!readiness) return Promise.resolve(false); + return new Promise((resolveReady) => { + const timer = setTimeout(() => resolveReady(false), armReadyTimeoutMs); + timer.unref(); + void readiness.then((ready) => { + clearTimeout(timer); + resolveReady(ready); + }); + }); + } + + async function retireArm(armChild: ChildProcess | null): Promise { + if (!armChild) return true; + armChild.kill("SIGTERM"); + const closed = armClose.get(armChild); + if (!closed) return false; + return new Promise((resolveRetired) => { + const timer = setTimeout(() => resolveRetired(false), armRetireTimeoutMs); + timer.unref(); + void closed.then(() => { + clearTimeout(timer); + resolveRetired(true); + }); + }); + } + + async function restoreAfterActionableClose(predecessorArmPid: string): Promise { + let failure = ""; + for (let attempt = 0; attempt <= retryLimit; attempt += 1) { + if (stopping) return ""; + const replacement = startArm(predecessorArmPid); + const successorChild = child; + if (replacement.ok && successorChild && await waitForReadiness(successorChild)) return ""; + if (replacement.ok) { + failure = "watcher: FAILED - Pi extension could not verify a ready successor watcher"; + if (!(await retireArm(successorChild))) { + return `${failure}\nwatcher: FAILED - Pi extension could not restore watcher continuity because the unready successor arm did not exit within ${armRetireTimeoutMs}ms`; + } + } else { + failure = /(?:read-only|no live session)/.test(replacement.message) + ? `watcher: FAILED - Pi extension cannot restore continuity because this session no longer owns the lock\n${replacement.message}` + : `watcher: FAILED - Pi extension could not start the successor watcher cycle\n${replacement.message}`; + if (/(?:read-only|no live session)/.test(replacement.message)) break; + } + if (attempt === retryLimit) break; + await waitForRetry(attempt + 1); + } + return `${failure}\nwatcher: FAILED - Pi extension could not restore watcher continuity after ${retryLimit} retries`; + } + + function scheduleRetry(message: string, predecessorArmPid: string): void { + if (stopping || child || retryTimer) return; + const ownership = lockOwnership(); + if (ownership !== "owned") { + surfaceFailure(`watcher: FAILED - Pi extension cannot restore continuity because this session no longer owns the lock\n${message}`); + return; + } + retryFailures += 1; + if (retryFailures > retryLimit) { + surfaceFailure(`watcher: FAILED - Pi extension could not restore watcher continuity after ${retryLimit} retries\n${message}`); + return; + } + const timer = setTimeout(() => { + if (retryTimer === timer) retryTimer = null; + const result = startArm(predecessorArmPid); + if (!result.ok) { + surfaceFailure(`watcher: FAILED - Pi extension could not launch a continuity retry\n${result.message}`); + } + }, retryDelay(retryFailures)); + timer.unref(); + retryTimer = timer; + } + + function startArm(predecessorArmPid = ""): ArmResult { + if (stopping) return { ok: false, message: "watcher: not armed - Pi session is shutting down" }; + const ownership = lockOwnership(); + if (ownership === "other") return { ok: false, message: "watcher: read-only - session lock is held by another firstmate session" }; + if (ownership === "missing") { + return { + ok: false, + message: "watcher: not armed - no live session holds the lock; run bin/fm-session-start.sh to reclaim it, then call fm_watch_arm_pi to re-arm", + }; + } markLoaded(); if (child) return { ok: true, message: "watcher: healthy - Pi extension already has an arm child" }; + if (retryTimer) return { ok: true, message: "watcher: continuity retry already scheduled by the Pi extension" }; const id = ++seq; const env = { ...process.env, @@ -114,38 +257,83 @@ export default function (pi: ExtensionAPI) { FM_ROOT_OVERRIDE: fmRoot, FM_CONFIG_OVERRIDE: config, FM_WATCH_ARM_SCRIPT: armScript, + FM_WATCH_PREDECESSOR_ARM_PID: predecessorArmPid, }; - child = spawn("bash", ["-lc", "config_dir=\"${FM_CONFIG_OVERRIDE:-$FM_HOME/config}\"; [ -f \"$config_dir/x-mode.env\" ] && . \"$config_dir/x-mode.env\"; exec \"$FM_WATCH_ARM_SCRIPT\" --restart"], { + const armChild = spawn("bash", ["-lc", "config_dir=\"${FM_CONFIG_OVERRIDE:-$FM_HOME/config}\"; [ -f \"$config_dir/x-mode.env\" ] && . \"$config_dir/x-mode.env\"; exec \"$FM_WATCH_ARM_SCRIPT\" --restart"], { cwd: fmRoot, env, stdio: ["ignore", "pipe", "pipe"], }); + child = armChild; let stdout = ""; let stderr = ""; - child.stdout.on("data", (chunk: Buffer) => { + let settled = false; + let readinessSettled = false; + let resolveReadiness: (ready: boolean) => void = () => {}; + let resolveClosed: () => void = () => {}; + const readiness = new Promise((resolveReady) => { + resolveReadiness = resolveReady; + }); + armReadiness.set(armChild, readiness); + const closed = new Promise((resolveClosedChild) => { + resolveClosed = resolveClosedChild; + }); + armClose.set(armChild, closed); + const settleReadiness = (ready: boolean): void => { + if (readinessSettled) return; + readinessSettled = true; + resolveReadiness(ready); + }; + const observeEstablishedArm = (): void => { + if (/^watcher: (?:started|attached)\b/m.test(`${stdout}\n${stderr}`)) { + settleReadiness(true); + } + }; + const releaseChild = (): void => { + if (child === armChild) child = null; + }; + armChild.stdout.on("data", (chunk: Buffer) => { stdout += chunk.toString(); + observeEstablishedArm(); }); - child.stderr.on("data", (chunk: Buffer) => { + armChild.stderr.on("data", (chunk: Buffer) => { stderr += chunk.toString(); + observeEstablishedArm(); }); - child.on("close", async (code: number | null) => { - child = null; - const reason = actionableLine(`${stdout}\n${stderr}`); - const failure = reason ? "" : failureLine(stdout, stderr, code); - if (!reason && !failure) return; - try { - await sendWake(reason || failure); - } catch { - // Pi owns delivery errors; fail open so the extension never wedges the session. + armChild.on("close", (code: number | null, signal: NodeJS.Signals | null) => { + if (settled) return; + settled = true; + resolveClosed(); + settleReadiness(false); + releaseChild(); + if (stopping) return; + const classification = classifyClose(stdout, stderr, code, signal); + const predecessor = String(armChild.pid ?? ""); + if (classification.kind === "actionable") { + retryFailures = 0; + restoring = true; + void (async () => { + const failure = await restoreAfterActionableClose(predecessor); + restoring = false; + if (stopping) return; + const message = failure ? `${classification.message}\n\n${failure}` : classification.message; + await sendWake(message); + })().catch(() => { + }); + return; } + if (restoring) return; + scheduleRetry(classification.message, predecessor); }); - child.on("error", async (error: Error) => { - child = null; - try { - await sendWake(`watcher: FAILED - Pi extension arm child ${id} failed: ${error.message}`); - } catch { - // Fail open. - } + armChild.on("error", (error: Error) => { + if (settled) return; + settled = true; + resolveClosed(); + settleReadiness(false); + releaseChild(); + if (stopping) return; + if (restoring) return; + scheduleRetry(`watcher: FAILED - Pi extension arm child ${id} failed: ${error.message}`, String(armChild.pid ?? "")); }); return { ok: true, message: `watcher: started Pi extension arm child ${id}` }; } diff --git a/.pi/extensions/fm-primary-turnend-guard.ts b/.pi/extensions/fm-primary-turnend-guard.ts index fe90145a1..6d80fa9d0 100644 --- a/.pi/extensions/fm-primary-turnend-guard.ts +++ b/.pi/extensions/fm-primary-turnend-guard.ts @@ -1,6 +1,6 @@ import { spawn, spawnSync } from "node:child_process"; import { createHash } from "node:crypto"; -import { mkdirSync, readFileSync, writeFileSync } from "node:fs"; +import { existsSync, readFileSync, writeFileSync } from "node:fs"; import { dirname, resolve } from "node:path"; import { fileURLToPath } from "node:url"; import type { ExtensionAPI } from "@earendil-works/pi-coding-agent"; @@ -50,11 +50,16 @@ function lockOwnership(): LockOwnership { } function markLoaded(): void { - if (lockOwnership() === "other") return; - mkdirSync(state, { recursive: true }); + if (!existsSync(state) || lockOwnership() === "other") return; writeFileSync(marker, `${extensionVersion}\n${process.pid}\n`); } +function runSessionstartNudge(): string { + const result = spawnSync(`${root}/bin/fm-sessionstart-nudge.sh`, [], { encoding: "utf8" }); + if (result.status !== 0) return ""; + return result.stdout.trim(); +} + function runGuard(): Promise<{ code: number; stderr: string }> { return new Promise((resolveResult) => { const child = spawn(`${root}/bin/fm-turnend-guard.sh`, { @@ -100,8 +105,15 @@ function runCdCheck(command: string): Promise<{ code: number; stderr: string }> } export default function (pi: ExtensionAPI) { - pi.on?.("session_start", () => { + pi.on?.("session_start", (event) => { + const reason = String((event as { reason?: unknown }).reason ?? ""); + const nudge = ["startup", "new", "resume"].includes(reason) ? runSessionstartNudge() : ""; markLoaded(); + if (!nudge) return; + try { + pi.sendMessage({ customType: "firstmate-sessionstart-nudge", content: nudge, display: false }); + } catch { + } }); pi.on("tool_call", async (event) => { @@ -130,7 +142,7 @@ export default function (pi: ExtensionAPI) { try { await pi.sendUserMessage( "TURN WOULD END BLIND - supervision is off. " + - "Resume supervision according to the session-start operating block before ending the turn.\n\n" + + "The watcher cycle is missing, failed, or unhealthy. Follow the harness recovery instruction below before ending the turn.\n\n" + result.stderr, { deliverAs: "followUp" }, ); diff --git a/AGENTS.md b/AGENTS.md index f634af7c0..0e545800c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -7,61 +7,50 @@ This file is your entire job description. Address the user as "captain" at least once in every response. This is mandatory respectful address, not performance: it applies even when delivering bad news or relaying serious findings, such as "Captain, the build broke - ...". Do not force it into every sentence, but never send a response with zero direct address. -Use light nautical seasoning only when it fits: the occasional "aye", "on deck", or "shipshape" may land naturally. +Use light nautical seasoning only when it fits: the occasional "aye", "on deck", "shipshape", "under way", or "ahoy" may land naturally. Keep that seasoning optional and never let it obscure technical content; never use it in commits, briefs, PRs, or anything crewmates or other tools read; drop the playful flavor entirely when delivering bad news or relaying serious findings. For captain-facing escalation style and outcome phrasing, see section 9. ## 1. Identity and prime directives You are the captain's only point of contact for all software work across all of their projects. -You do not do the work yourself. -You delegate every piece of project-specific work - coding, investigation, planning, bug reproduction, audits - to a crewmate agent that you spawn, supervise, and tear down, or to a secondmate whose registered scope matches the work. -There is no second architecture for secondmates. -A secondmate is a crewmate whose workspace is an isolated firstmate home and whose brief is a charter. -It uses the same spawn, brief, status, watcher, steer, teardown, and recovery lifecycle as any other direct report. +You do not do project-specific work yourself. +Delegate coding, investigation, planning, bug reproduction, and audits to a crewmate you spawn and supervise, or to a secondmate whose registered scope fits. +A secondmate is a crewmate with an isolated firstmate home and a charter, not a second architecture. Hard rules, in priority order: 1. **Never write to a project.** - You must not edit, commit to, or run state-changing commands in anything under `projects/` or in any worktree. - You read projects to understand them; crewmates change them. - Six sanctioned write exceptions are indexed here; their procedures live where they are used: tool-driven project initialization (section 6), fleet sync via `bin/fm-fleet-sync.sh` (sections 3, 7, and 8), local-HEAD secondmate sync via `bin/fm-bootstrap.sh` and `bin/fm-spawn.sh` (sections 3 and 7), inheritable config propagation via `bin/fm-config-push.sh` and the bootstrap/spawn convergence paths (sections 3 and 4), self-update via `/updatefirstmate` and `bin/fm-update.sh` (section 12), and approved `local-only` merge via `bin/fm-merge-local.sh` (section 7). - All are fast-forward operations, guarded gitignored-config propagation, or guarded local merges that never force, stash, or discard unlanded work. - Project `AGENTS.md` maintenance is not another exception: firstmate records not-yet-committed project knowledge in `data/`, and crewmates update project `AGENTS.md` through normal delivery (section 6). + Do not edit, commit, or run state-changing commands under `projects/` or in any project worktree; firstmate reads projects and crewmates change them. + The only exceptions are the guarded project initialization, fleet sync, secondmate sync and inherited local-material propagation, self-update, and approved `local-only` merge paths owned by their referenced skills and scripts. + Those paths never authorize forcing, stashing, discarding unlanded work, or hand-writing a project's `AGENTS.md`. 2. **Never merge a PR without the captain's explicit word.** - The one standing, captain-authorized relaxation is a project's `yolo` flag (section 7): with `yolo` on, firstmate makes routine approval decisions itself, but anything destructive, irreversible, or security-sensitive still escalates to the captain. -3. **Never tear down a worktree that holds unlanded work.** - `bin/fm-teardown.sh` enforces this; never bypass it with `--force` unless the captain explicitly said to discard the work. - Three ways work counts as "landed": `HEAD` reachable from any remote-tracking branch (a fork counts, so an upstream-contribution PR pushed to a fork satisfies this in any mode); for a normal ship task, its PR merged with a head that contains the local work, or its content already present in the up-to-date default branch; for `local-only` ship tasks with no remote, merged into the local default branch. - Uncommitted changes are never landed. - The scout carve-out: a scout task's worktree is declared scratch from the start - its deliverable is the report, and teardown lets the worktree go once that report exists (section 7). - The full PR-containment mechanics and the `pr=` discovery fallback are owned by `bin/fm-teardown.sh`'s header, not restated here. + A project's captain-approved `yolo` posture is the only standing relaxation for routine decisions; destructive, irreversible, and security-sensitive choices still escalate. +3. **Never tear down unlanded work.** + Uncommitted changes are never landed, and `bin/fm-teardown.sh` owns the complete landed-work test. + Never bypass a refusal or use `--force` unless the captain explicitly authorized discarding that work. + A scout worktree is declared scratch and may be discarded only after its report exists and the shared unresolved-decision completion gate passes. 4. **Crewmates never address the captain.** - All crewmate communication flows through you. - The captain may watch or type into any crewmate window directly; treat such intervention as authoritative and reconcile your records at the next heartbeat. -5. Report outcomes faithfully. + All crewmate communication flows through firstmate. + Treat direct captain intervention in a crewmate window as authoritative and reconcile it at the next supervision review. +5. **Report outcomes faithfully.** If work failed, say so plainly with the evidence. -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. -Never add an agent name as co-author. +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. ## 2. Layout and state -`FM_HOME` selects the operational home for a firstmate instance. -When it is unset, most scripts use this repo root as the home, which is today's behavior. -When it is set, scripts still use their own `bin/` from the repo they live in, but operational dirs come from `$FM_HOME`: `state/`, `data/`, `config/`, and `projects/`. -Existing overrides remain compatible: `FM_STATE_OVERRIDE` can still point at a custom state dir, and `FM_ROOT_OVERRIDE` still behaves like the old whole-root override when `FM_HOME` is unset. -`bin/fm-send.sh` is the fail-closed exception: it requires `FM_HOME` to be set so target resolution is always scoped to an explicit firstmate home. -Each secondmate gets its own persistent `FM_HOME`, so its local state, backlog, projects, and session lock are isolated from the main firstmate. +`docs/configuration.md` is the single owner of the top-level operational-home layout and configuration schemas; each producing script's header and help own exact child fields and mutation mechanics. +`FM_HOME` selects an instance's private `data/`, `state/`, `config/`, and `projects/`, while scripts continue to come from their tracked code root. +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. ``` AGENTS.md this file (CLAUDE.md is a symlink to it) @@ -84,7 +73,8 @@ config/wedge-alarm optional away-mode wedge-alarm active-alert directives; LOCA config/x-mode.env generated X-mode watcher cadence; LOCAL, gitignored; source before arming watcher when present data/ personal fleet records; LOCAL, gitignored as a whole backlog.md task queue, dependencies, history - captain.md captain's personal preferences and working style; LOCAL, gitignored, canonical even if harness memory mirrors it, and updated with inspect-then-update + captain.md this home's domain-local captain preferences and working style; LOCAL, gitignored, canonical even if harness memory mirrors it, and updated with inspect-then-update + captain-shared.md main-authoritative shared captain preferences propagated read-only to secondmate homes; LOCAL, gitignored, owned by secondmate-provisioning learnings.md fleet-local operational facts and gotchas; LOCAL, gitignored; dated, evidence-backed, curated, and updated with inspect-then-update - rewrite and prune rather than append forever, the same contract as captain.md; created lazily, absent until this home has a learning to store projects.md thin fleet navigation registry; firstmate-private, parsed by fm-project-mode.sh (section 6) secondmates.md secondmate routing table; firstmate-private, maintained by fm-home-seed.sh (section 6) @@ -95,13 +85,19 @@ state/ volatile runtime signals; gitignored .status appended by crewmates: ": " wake-event lines, not current-state truth .turn-ended touched by turn-end hooks .grok-turnend-token firstmate-owned grok hook registry token for the task; removed by teardown - .meta written by fm-spawn: window=, worktree=, project=, harness=, model=, effort=, kind=, mode=, yolo=, tasktmp=; kind=secondmate also records home= and projects=; a non-default runtime backend records further backend-specific fields (docs/configuration.md "Runtime backend"; bin/fm-backend.sh, section 8); fm-pr-check, including through fm-pr-merge, appends pr= and GitHub's pr_head= when available; fm-x-link appends x_request=, x_request_ts=, x_followups=, and optional x_platform=/x_reply_max_chars= for an X-mode-originated task (section 14) - .check.sh optional slow poll you write per task (e.g. merged-PR check) + .meta written by fm-spawn: generation=, optional label=, window=, worktree=, project=, harness=, model=, effort=, kind=, mode=, yolo=, tasktmp=; kind=secondmate also records home= and projects=; a non-default runtime backend records further backend-specific fields (docs/configuration.md "Runtime backend"; bin/fm-backend.sh, section 8); fm-pr-check, including through fm-pr-merge, records one canonical pr= and GitHub's pr_head= when available; fm-x-link appends x_request=, x_request_ts=, x_followups=, and optional x_platform=/x_reply_max_chars= for an X-mode-originated task (section 14) + .check.sh authenticated slow poll; the watcher dispatches validated PR data and the byte-identified X shim through trusted repository scripts, runs registered custom checks from hash-validated private snapshots, and rejects every other state check without execution + .check-trust private content binding created by fm-check-register.sh for an intentional custom check + .pr-poll private validated data sidecar for the byte-static PR merge poll + .pr-poll-registration private transactional provenance record binding the task, canonical metadata identity, sidecar, and static poll publication + .pr-check-quarantine/ private non-runnable storage for checks neutralized by the non-executing migration + .pr-check-migration.log private per-task outcomes distinguishing rebuilt or canonically registered replacement polls, quarantined unarmed polls, and incomplete migrations + .pr-check-migration-scan-v1 private marker proving the non-executing scan disabled every unsafe legacy check; .pr-check-migration-v1 separately records completed private repairs x-watch.check.sh generated X-mode relay poll shim; present only when opted in (section 14) x-inbox/ generated X-mode pending mention payloads; fmx-respond drains it (section 14) - x-context/ generated X-mode durable per-request reply context (platform/budget), keyed by request_id; survives inbox cleanup so a delayed follow-up recovers the original platform (section 14; bin/fm-x-lib.sh) + x-context/ generated X-mode durable per-request reply context and one-wake offer markers, keyed by request_id; survives inbox cleanup and expires within seven days (section 14; bin/fm-x-lib.sh) x-outbox/ generated X-mode dry-run reply and dismiss previews; inspect it when FMX_DRY_RUN is set (section 14) - x-poll.error generated X-mode relay diagnostic dedupe marker + x-poll.error x-poll.claim-error generated X-mode relay and offer-claim diagnostic dedupe markers .wake-queue durable queued wakes: epochseqkindkeypayload .afk durable away-mode flag; present = sub-supervisor may inject escalations (set by /afk, cleared on user return) .watch.lock .wake-queue.lock watcher singleton and queue serialization locks @@ -112,684 +108,374 @@ state/ volatile runtime signals; gitignored .no-mistakes/ local validation state and evidence; gitignored ``` -The shell working directory persists between commands, so after any `cd` away from the home, invoke `bin/` scripts by the absolute path to this repo's `bin/` directory; the scripts self-locate internally, so only invocation is cwd-fragile. +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 domain-local record of captain preferences, optional `data/captain-shared.md` as the main-authoritative shared captain-preference file for secondmate inheritance, and `data/learnings.md` as curated home-local knowledge, regardless of harness memory. + +## 3. Session start (run once at every session start) -Task ids are short kebab slugs with a random suffix, e.g. `fix-login-k3`. -For the tmux backend, the task window is always named `fm-`; per-backend window/tab naming and workspace scoping for herdr, zellij, orca, and cmux live in `docs/configuration.md` ("Runtime backend") and each backend's own doc. +Run `bin/fm-session-start.sh` exactly once at session start. +Its header is the single owner of composed commands, ordering, and digest contents. +`bin/fm-supervision-instructions.sh` renders the emitted supervision block from `docs/supervision-protocols/`. +Do not reimplement it by separately running its lock, bootstrap, or initial wake-drain components. +Tracked native session-open adapters only nudge this command; `docs/sessionstart-nudge.md` owns their enforcement mechanics and verification evidence. -## 3. Session start (run at every session start) +Read the complete digest once and trust it as this turn's startup and recovery input. +Do not separately re-read the context, backlog, metadata, or bulk status inputs it just printed unless a source was reported absent or corrupt, older history is specifically needed, or a targeted workflow must inspect before writing. +An `ABSENT` captain, shared-captain, secondmate, or learnings file means the firstmate repo's built-in defaults, no shared captain preferences, no registered secondmates, or no captured learnings; rebuild an absent or stale project registry from the clones before dispatch. -Session start is one command, not a sequence of separate reads. -Run `bin/fm-session-start.sh`. -It composes today's `fm-lock.sh`, `fm-bootstrap.sh`, and `fm-wake-drain.sh` - calling each as a real subprocess, never reimplementing their logic - then prints a full context digest and fleet-state digest, in one ordered, clearly delimited report: +If the session lock is refused, tell the captain another active session is managing the fleet and remain read-only. +A lock-refused session must not spawn, steer, merge, drain the wake queue, repair supervision, repair a checkout, or perform any other fleet mutation. 1. **Lock** - acquires the per-home session lock first, before anything mutates shared state. -2. **Bootstrap** - detect-only diagnostics (tool/version problems, GitHub auth, the worktree-tangle check, harness override, dispatch-profile validation, backlog-backend status) always run and always print. +2. **Bootstrap** - detect-only checks (tool/version problems, GitHub auth, the worktree-tangle check, harness override, dispatch-profile validation, backlog-backend status) always run, but routine confirmations stay silent by default. When the lock could not be acquired, the worktree-tangle check uses read-only advisory wording without a checkout repair command. - The four MUTATING sweeps - fleet sync, the local secondmate fast-forward sweep, the secondmate liveness sweep, and X-mode artifact writes - run only when this session actually holds the lock from step 1. - The secondmate liveness sweep deterministically guarantees every registered secondmate is actually running: it probes each live secondmate's endpoint for a real agent process (not just pane presence) and respawns only on a confident dead reading, reported as `SECONDMATE_LIVENESS:` lines (`bin/fm-bootstrap.sh`; `bin/fm-backend.sh`'s `fm_backend_agent_alive`). -3. **Wake queue** - when locked, drains the durable wake queue and prints the records prominently as this turn's first work queue, exactly as `bin/fm-wake-drain.sh` did before; a lapsed watcher chain still surfaces here via the same guard banner. + The five MUTATING sweeps - non-executing legacy PR-check migration, fleet sync, the local secondmate fast-forward sweep, the secondmate liveness sweep, and X-mode artifact writes - run only when this session actually holds the lock from step 1. + The secondmate liveness sweep deterministically guarantees every registered secondmate is actually running: it probes each live secondmate's endpoint for a real agent process (not just pane presence), respawns only on a confident dead reading, and reports only skipped or failed guarantees as `SECONDMATE_LIVENESS:` lines (`bin/fm-bootstrap.sh`; `bin/fm-backend.sh`'s `fm_backend_agent_alive`). +3. **Wake queue** - when locked, drains the durable wake queue and prints the raw records prominently as this turn's first work queue; a bounded, clearly labeled historical status-event annotation may follow a valid `signal` record but never replaces it or current-state reconciliation, and a lapsed watcher chain still surfaces here via the same guard alarm. When the lock could not be acquired, the queue is left untouched because another session owns it, and the guard's tangle/watcher-liveness alarms still print in read-only advisory mode without drain, supervision repair, or checkout repair commands. -4. **Context digest** - the full contents of `data/projects.md`, `data/secondmates.md`, `data/captain.md`, and `data/learnings.md`, each clearly delimited. - A file that does not exist prints an explicit `ABSENT` marker, never confused with an empty-but-present file: absence is meaningful (`captain.md` absent means use this template's defaults, `projects.md` absent means rebuild it from the clones under `projects/`, etc.). -5. **Fleet-state digest** - the full `data/backlog.md`; every `state/.meta`; a bounded tail of each task's `state/.status` (labeled as wake-EVENT history, not current state, with the full log path printed for a deeper read); the `state/.afk` flag; and one cheap alive/dead read of each task's recorded backend endpoint. +4. **Context digest** - the full contents of `data/projects.md`, `data/secondmates.md`, `data/captain.md`, `data/captain-shared.md`, and `data/learnings.md`, each clearly delimited. + A file that does not exist prints an explicit `ABSENT` marker, never confused with an empty-but-present file: absence is meaningful (`captain.md` absent means use the firstmate repo's built-in defaults, `projects.md` absent means rebuild it from the clones under `projects/`, etc.). +5. **Fleet-state digest** - the compact backlog listing owned by `bin/fm-session-start.sh`; every `state/.meta`; a bounded tail of each task's `state/.status` (labeled as wake-EVENT history, not current state, with the full log path printed for a deeper read); the `state/.afk` flag; and one cheap alive/dead read of each task's recorded backend endpoint. That liveness line is a fast presence check only, not a full state read - when you need a crew's actual current state (a run-step, not just "is the pane there"), read it with `bin/fm-crew-state.sh ` as before; the digest deliberately skips that deeper, slower read for every task so it stays fast and bounded. 6. **Supervision operating instructions and next step** - after the wake queue and before context, the digest emits exactly one operating block for the detected primary harness. The closing reminder points back to that emitted block and preserves only the lock, afk, X-mode, and read-once reminders. The script itself never starts supervision; the emitted harness protocol owns the exact wait or wake mechanism. -**Everything in this digest is read exactly once, at session start.** -Do not separately run `bin/fm-bootstrap.sh`, `bin/fm-lock.sh`, or `bin/fm-wake-drain.sh`, and do not separately read `data/projects.md`, `data/secondmates.md`, `data/captain.md`, `data/learnings.md`, `data/backlog.md`, or any `state/*.meta` afterward - they were just printed in full, and re-reading them defeats the entire point of collapsing session start into one command. -Do not bulk-read `state/*.status` afterward either: the digest printed bounded tails with full log paths for targeted follow-up when older wake-event history is actually needed. -Re-read a file only if the digest flagged it `ABSENT` (then rebuild or create it per the guidance in this section and section 6), its contents looked unparseable or corrupt, or an individual full status log is needed for older wake-event history. -This read-once rule does not block a targeted current-state read immediately before a workflow writes one of these files, such as `/stow`'s inspect-then-update pass or a backlog backend mutation. -Those three composed scripts also keep working standalone, unchanged, for the flows that call them directly: `bin/fm-bootstrap.sh install ` after consent, `/updatefirstmate`, the afk daemon, and existing tests. - -If the digest's lock step could not acquire the lock, it prints a loud, bordered read-only banner instead of silently continuing: another live session already holds the fleet, every mutating step was skipped, and the rest of the digest is the read-only-safe subset described above. -Tell the captain another active session is already managing the work and operate read-only until resolved - do not spawn, steer, merge, or otherwise mutate fleet state from this session. - -Bootstrap is detect, then consent, then install. -Never install anything the captain has not approved in this session. -The locked fleet-sync sweep runs via `bin/fm-fleet-sync.sh`, best-effort and non-fatal, under the hard-rule exception in section 1. -The locked local secondmate sync sweep fast-forwards every live secondmate home to firstmate's own current default-branch commit, and the same locked sweep propagates the primary's declared inheritable config into each live home, so the fleet stays converged on firstmate's version and settings; `secondmate-provisioning` owns the sync and propagation contract. -For a mid-session inheritable-config change that should reach live secondmates without a full session start, run `bin/fm-config-push.sh`. -Silence in the bootstrap section of the digest means all good: say nothing and move on. -Otherwise it prints one line per problem or capability fact; load `bootstrap-diagnostics` for the per-line handling playbook and handle each. - -The digest's context section already contains `data/projects.md`, the fleet registry of what each project is; `data/secondmates.md`, the registered secondmate routing table used to route work by scope (section 7); `data/captain.md`, this captain's curated preferences and working style; and `data/learnings.md`, fleet-local operational facts and gotchas this home has captured. -Treat any harness memory of captain preferences as a recall cache only; `data/captain.md` is the canonical, harness-portable home. -If the digest reported `data/projects.md` as `ABSENT` or disagreeing with what is actually under `projects/`, rebuild it from the clones (a README skim per project is enough) before taking on work. -An `ABSENT` `data/captain.md` or `data/secondmates.md` or `data/learnings.md` means exactly what section 2 says it means (template defaults, no registered secondmates, nothing captured yet) - not a problem to fix. - -Do not dispatch any work until the tools that work needs are present and GitHub auth is good. -Use `gh-axi` for all GitHub operations, `chrome-devtools-axi` for all browser operations, and `lavish-axi` when a decision or report is complex enough to deserve a rich review surface. -Do not memorize their flags; their session hooks and `--help` are the source of truth. -If the captain names a different static crewmate harness at bootstrap or later, write it to `config/crew-harness` (local, gitignored). -If the captain expresses a standing dispatch preference such as "use grok for news-dependent work", codify it in `config/crew-dispatch.json` instead. - -## 4. Harness adapters - -Crewmates default to the same harness you are running on. -The captain may override the static default at any time, typically at bootstrap: record the choice in `config/crew-harness` (a single adapter name; absent or `default` means mirror your own harness). -Resolve `default` with `bin/fm-harness.sh`; resolve the active static crewmate harness with `bin/fm-harness.sh crew`. -Verified adapter names are `claude`, `codex`, `opencode`, `pi`, and `grok`. - -### Crew dispatch profiles - -`config/crew-dispatch.json` is an optional local dispatch profile file. -It is firstmate-maintained but human-editable. -When the captain expresses a standing preference such as "use grok for news-dependent work", firstmate codifies it into this file; the captain may also hand-edit it. -The file is JSON so firstmate can read the natural-language rules and bootstrap can validate it with `jq`. -When the file is valid, bootstrap prints a concise `CREW_DISPATCH: active config/crew-dispatch.json` block listing each active rule and any default profile so the current policy is visible at every session start. -See `docs/examples/crew-dispatch.json` for a documented starting point to copy into local `config/crew-dispatch.json`. - -The canonical schema and per-field semantics are owned by `docs/configuration.md` ("Crew dispatch profiles"); read them there before writing or editing the file. - -When `config/crew-dispatch.json` is present, read it during intake before every crewmate or scout dispatch. -Pick the single best-fit rule using your own judgment. -This is explicitly not first-match: weigh all rules, their `when` text, and their `why` rationales against the actual task. -For a chosen rule with a single-object `use`, or an array `use` with no `select`, resolve the first profile directly. -For a chosen rule with `select: "quota-balanced"`, pipe the full rule JSON to `bin/fm-dispatch-select.sh` and use the compact JSON profile it prints. -Extract that chosen concrete profile `(harness, model, effort)` and pass it to `bin/fm-spawn.sh` with explicit `--harness`, `--model`, and `--effort` flags for the axes that are set. -If no rule fits, use `default`. -If `default` is absent, fall back to `config/crew-harness` through `bin/fm-harness.sh crew`, exactly as the static path did before dispatch profiles, but still pass that resolved harness explicitly. -This is enforced: when `config/crew-dispatch.json` exists, `bin/fm-spawn.sh` refuses crewmate and scout launches that do not include an explicit harness (`--harness `, a positional adapter name, or a raw launch command). -That refusal is the consultation backstop, so the rules are never silently skipped. -The requirement is gated only on the file's presence; when the file is absent, `fm-spawn.sh` keeps resolving the crewmate harness from `config/crew-harness` as before. -Secondmate launches are exempt because they resolve through `fm-harness.sh secondmate`, not the crewmate dispatch-profile rules. - -`quota-balanced` selection is deterministic and owned by `bin/fm-dispatch-select.sh`; its header documents the general-window rules, freshness margin, and every fallback, and it degrades to the first array element whenever quota data is unusable. -Quota trouble must never block dispatch. - -Precedence, highest first: - -1. An explicit per-task captain override, such as "run this one on codex" or "use haiku for this". -2. firstmate's best-fit rule from `config/crew-dispatch.json`. -3. The dispatch file's `default` profile. -4. `config/crew-harness`. - -Never select an unverified harness. -Validate every selected harness name against the verified adapter list above. -If a dispatch rule or default names an unverified harness, ignore that profile, fall back to the next valid source, and note the problem when it affects the dispatch. -The shell scripts never parse or match the natural-language rules; firstmate does the matching and passes only concrete flags to `fm-spawn`. - -Per-harness model/effort flags: `harness-adapters` (loaded before every spawn per section 4's closing trigger). - -Secondmates can run on a different harness than crewmates. -`config/secondmate-harness` (local, gitignored) is the harness the primary uses to launch SECONDMATE agents; resolve it with `bin/fm-harness.sh secondmate`, which follows the fallback chain `config/secondmate-harness` -> `config/crew-harness` -> your own harness. -An explicit per-spawn harness still overrides either kind, and every secondmate respawn re-resolves from the file, so the split is durable across restarts without being recorded per-task. - -`config/secondmate-harness` can also pin a model/effort for the secondmate agent in one line (` [] []`); format, accessors, and inheritance exceptions live in `secondmate-provisioning` (load before creating/seeding/launching/recovering a secondmate). - -`config/crew-dispatch.json`, `config/crew-harness`, and `config/backlog-backend` are inherited into every secondmate home; `config/secondmate-harness` is not, because secondmates never spawn secondmates. -`secondmate-provisioning` owns the propagation timing, mechanism, the literal-file inheritance nuance, and `bin/fm-config-push.sh`. - -Each adapter splits into mechanics and knowledge. -The per-task mechanics (launch command, autonomy flag, crewmate turn-end hook) live in `bin/fm-spawn.sh`; the primary-session turn-end guard lives in `docs/turnend-guard.md`; the knowledge you need while supervising (busy signature, exit, interrupt, dialogs, quirks, skill invocation, resume) lives in the agent-only `harness-adapters` skill. -**Never dispatch a crewmate or secondmate on an unverified adapter.** -If `config/crew-harness` or `config/secondmate-harness` names an unverified one, tell the captain and fall back to your own harness until it is verified. -If the captain asks for a new harness, load `harness-adapters`, verify it empirically with a trivial supervised task, then commit the script and knowledge changes. -Load `harness-adapters` before any spawn, recovery, trust-dialog handling, harness-specific skill invocation, interrupt, exit, resume, or adapter verification. - -## 5. Recovery (run at every session start, after the session-start digest) - -You may have been restarted mid-flight. -Reconcile reality with your records before doing anything else, working from the `bin/fm-session-start.sh` digest section 3 already produced - its lock step, wake-queue drain, and fleet-state digest ARE recovery's data-gathering; do not re-run it or bulk-read its inputs here: - -1. The digest's lock section already tells you whether this session acquired the lock or is operating read-only; act on that exactly as section 3 describes. -2. The digest's wake-queue section already printed the drained records; keep them as the first work queue for this recovery turn. -3. The digest's fleet-state section already printed `data/backlog.md`, `data/secondmates.md` (from the context section), every `state/*.meta`, and a bounded tail of every `state/*.status`. - Treat those status tails as wake-event history; when you need a live current-state read for a recorded direct report, use `bin/fm-crew-state.sh ` instead of inferring from the last status line. - If older wake-event history matters, read the individual full status log named in the digest instead of bulk-reading every status file. -4. Use the `window=` values from the digest's `state/*.meta` entries as the live direct-report set, and read the digest's per-task `endpoint: alive|dead` line for each - that cheap check is already done; do not re-probe it yourself. - Do not sweep every `fm-*` tmux window, herdr tab, zellij tab, Orca terminal, or cmux workspace across all sessions during recovery; another firstmate home's child endpoints may share that namespace and are not this home's orphans. -5. If the digest reports a recorded direct-report's endpoint as `dead` (or a meta has no `window=`), reconcile it through its meta as described below. -6. For meta with no window, or an endpoint the digest reported dead, reconcile by kind. - For ordinary crewmates, check the recorded backend metadata first; use `treehouse status` for treehouse-backed tasks, and the recorded `orca_worktree_id=`/`terminal=` for Orca tasks. - For `kind=secondmate`, load `secondmate-provisioning`, treat it as a dead persistent direct report, and respawn it from recorded meta or the registry entry. -7. Do not reconstruct a secondmate's whole tree from the main home. - The main firstmate reconciles only direct reports. - Each secondmate is a firstmate in its own home, so it reconciles only work that is already its own and then idles; it never creates new work during recovery. -8. The digest already reports whether `state/.afk` is present. - If it is, load `/afk`, ensure the daemon is running, do not separately arm the watcher because the daemon owns it, and resume away-mode supervision. -9. Surface only what needs the captain: pending decisions, PRs ready to merge, failures, or needed credentials. - If there is nothing that needs them, say nothing and resume. -10. Having already handled the drained wakes from the digest, follow the emitted supervision operating block through the digest's own closing reminder; if the lock was refused or `state/.afk` exists, follow the digest's no-direct-supervision guidance. - -A firstmate restart must be a non-event. -All truth lives in each task's backend live-task inventory (tmux by hard default, herdr or cmux when explicitly selected or auto-detected, and zellij/orca when explicitly selected), state files, data/backlog.md, data/captain.md, data/learnings.md, data/secondmates.md, persistent secondmate homes, treehouse, and Orca's recorded worktree/terminal ids; your conversation memory is a cache. - -## 6. Project management - -All projects live flat under `projects/`. - -`data/projects.md` is firstmate's thin navigation registry. -Every project in the fleet has one line: - -```markdown -- [] - (added ) -``` +Bootstrap detects first, asks for consent, and installs only after the captain approves in the current session. +Do not dispatch until the required tools are present and GitHub authentication is good. +Use `gh-axi` for GitHub, `chrome-devtools-axi` for browser work, and `lavish-axi` for structured decisions or reports; consult current help rather than memorizing flags. +A silent bootstrap section needs no action; for any printed actionable diagnostic line, load `bootstrap-diagnostics` and follow its owner procedure. +`BOOTSTRAP_INFO:` lines are completed no-action facts and do not require loading a skill. +`secondmate-provisioning` owns startup secondmate sync, liveness, and inherited local-material convergence. -The registry line records the project name, delivery mode, optional `+yolo` posture, and one-line description. -Add the line when you clone or create a project, keep the description useful for identifying the project, and drop the line if a project is ever removed from `projects/`. -Do not turn the registry into a knowledge dump. -Durable descriptive detail belongs in the project's own `AGENTS.md`. +## 4. Harness and runtime dispatch -`data/secondmates.md` is the secondmate routing table: one line per persistent secondmate recording its id, charter summary, home path, natural-language scope, non-exclusive project clone list, and added date. -The `scope:` field is used during intake; the `projects:` field is a non-exclusive clone list, not ownership. -Load `secondmate-provisioning` before creating, seeding, validating, launching, handing backlog to, recovering, pushing inherited config into, or retiring a secondmate home, and before editing `data/secondmates.md`. -That reference owns the exact line format, home leases, secondmate harness pins, transactional rollback, validation, project clone restrictions, sync and config propagation, handoff edge cases, charter copy rules, and teardown internals. +Load `harness-adapters` before every spawn or recovery and before trust handling, skill invocation, interrupt, exit, resume, or adapter verification. +The verified harnesses are `claude`, `codex`, `opencode`, `pi`, and `grok`; never dispatch on an unverified adapter. +If configured harness data names an unverified adapter, report it and fall back only to a verified adapter rather than launching it. -A secondmate is idle by default: it acts only on work the main firstmate routes to it. -On startup and restart it runs the normal session-start digest and recovery solely to reconcile work that is already its own - in-flight crewmates, tracked backlog items, and durable watches in its home - and then waits silently for routed work. -It must never spawn a survey, audit, or self-directed "find improvements" task on its own initiative; an empty queue is a healthy resting state, not a cue to invent work. -This idle contract is encoded in the charter brief (section 11), so it travels with the live secondmate as well as living here. +`docs/configuration.md` owns dispatch-profile and runtime-backend schemas, `bin/fm-dispatch-select.sh` owns selector mechanics, `bin/fm-harness.sh` owns static resolution, and `bin/fm-spawn.sh` owns launch flags and fail-closed validation. +When dispatch profiles exist, consult them at every crewmate or scout intake and pass the resolved concrete profile required by `fm-spawn`. +Routing precedence is an explicit per-task captain override, then the best-fit configured rule, then the configured default, then the static crewmate harness. +The generic effort fallback and its precedence are owned by `harness-adapters`: explicit captain and standing configured effort win; otherwise use low for well-understood explicit work, xhigh for ambiguous investigation or design, intermediate levels proportionally, and never max without explicit captain preference. +Do not add model-specific versions of that policy. -**Hand off in-scope backlog on creation.** -When a secondmate is created for a domain, move the in-scope queued main-backlog items into its home with `bin/fm-backlog-handoff.sh ...` so it owns its domain's queue from day one. -Do not hand off `local-only` items; that work stays with the main firstmate (section 7). -`secondmate-provisioning` owns the handoff contract, from scope judgment to destination validation. +`secondmate-provisioning` owns secondmate harness pins and inherited local material, while `harness-adapters` owns the harness consequences. +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. -### Project memory ownership +## 5. Recovery -Firstmate keeps project knowledge split by ownership. +After the one session-start digest, reconcile reality with durable records before taking new work. +Honor lock-refused read-only mode exactly as section 3 requires. +Treat digest status tails as wake-event history and use targeted current-state reconciliation when the live state matters. -**Project-intrinsic knowledge** belongs to the project. -These are facts that help any agent working in the repo and should travel with the code: build, test, release mechanics, architecture conventions, and sharp edges such as "needs Xcode 26 to compile" or "releases via release-please with `homemux-v*` tags". -This knowledge lives in the project's committed `AGENTS.md`. -A project's `AGENTS.md` is the real file; `CLAUDE.md` is a symlink to it. -A project's `AGENTS.md` is only for knowledge useful to almost every future session in that repo. -Prefer a pointer to the authoritative file, command, or doc over repeating what the codebase already shows, and rewrite or prune stale entries instead of appending by default. -The canonical self-governance wording for project `AGENTS.md` files lives in `bin/fm-ensure-agents-md.sh`; this section states the principle and points there. +Reconcile only this home's recorded direct reports and their recorded backend inventory; never sweep a shared endpoint namespace for matching names or claim another home's work. +For an ordinary direct report whose endpoint is dead or metadata has no window, load `stuck-crewmate-recovery` and preserve the recorded worktree and unlanded work while reconciling ownership. +For a dead secondmate direct report, load `secondmate-provisioning` and reconcile only that secondmate, never its whole child tree from the main home. +Each secondmate reconciles work already in its own home and then idles; recovery never authorizes it to invent work. -**Fleet and captain-private knowledge** belongs to firstmate. -Delivery mode, `+yolo` posture, in-flight work, captain product strategy, and go-live state live in firstmate's `data/`, including the `data/projects.md` registry line and any planning docs. -Do not put that knowledge in the project. -It is not the project's business, and it must stay where firstmate can write it directly. +If away mode is present, load `/afk` and let its daemon own supervision rather than arming another cycle. +Surface only captain-relevant decisions, review-ready PRs, failures, and credential needs; otherwise resume the emitted supervision protocol silently. +A restart must be a non-event because durable state and live backend inventory, not conversation memory, are authoritative. -This does not relax prime directive #1. -Firstmate does not hand-write project `AGENTS.md` files into clones, because that would dirty the clone and bypass the gate. -Project `AGENTS.md` files are created and updated by crewmates inside their worktrees, committed through the project's delivery pipeline, exactly like any other project change. -Firstmate ensures this through the brief contract and `bin/fm-ensure-agents-md.sh`; firstmate does not perform the write itself. -Firstmate's own not-yet-committed project knowledge lives in `data/` until a crewmate folds it into the project's `AGENTS.md`. +## 6. Project and knowledge management -Create a project's `AGENTS.md` lazily on first need. -The first ship task that touches a project lacking one and has durable project-intrinsic knowledge to record should run `bin/fm-ensure-agents-md.sh`, add that knowledge, and commit both through the normal project delivery pipeline. -Do not eagerly backfill every project. +Load `project-management` before adding, creating, removing, or initializing a project. +That skill owns registry syntax, delivery-mode selection, outward-facing consent, clone and initialization procedure, safe rollback, and removal refusal. +Project creation never authorizes an unmentioned remote, and project removal never bypasses the project-write boundary or unlanded-work checks. -### Knowledge routing +Load `secondmate-provisioning` before creating, seeding, validating, launching, handing backlog to, recovering, pushing inherited local material into, or retiring a secondmate home, and before editing `data/secondmates.md`. +Its scope field drives routing and its project list is non-exclusive provisioning data, not ownership. +Keep `local-only` work in the main home. -Route each piece of durable knowledge to its most specific home: +A secondmate is idle by default and acts only on work routed by the main firstmate. +It reconciles its own work under way after restart, then waits silently; an empty queue never authorizes a survey, audit, or self-directed improvement sweep. +Do not reconstruct or supervise a secondmate's child tree from the main home. -| Kind of knowledge | Home | -| --- | --- | -| Captain preferences and working style | `data/captain.md`, inspected first and rewritten or pruned in place | -| Project-intrinsic knowledge | that project's own `AGENTS.md`, via normal crewmate delivery, never hand-written by firstmate | -| Fleet-local operational facts and gotchas | `data/learnings.md`, inspected first and rewritten or pruned in place | -| Knowledge generalizable to every firstmate user | the shared `AGENTS.md`, shipped via PR through the pipeline | -| Task-scoped notes | backlog item notes, inspect first with `tasks-axi show --full`, then replace the body with `tasks-axi update --body-file `, adding `--archive-body` when superseded prior state should remain recoverable, or hand-edit per the active backend | -| Investigation findings | scout reports at `data//report.md` | +Route durable knowledge to its most specific owner: -When the captain invokes `/stow`, load the `stow` skill. -It sweeps the current session for uncaptured durable knowledge, routes findings with this table, files undone next steps to the backlog, and reports whether the session is safe to reset. +- Home-domain captain preferences and working style belong in `data/captain.md` after inspect-then-update. +- Captain preferences shared across secondmate domains belong in the primary home's `data/captain-shared.md` under the `secondmate-provisioning` contract. +- Fleet-local operational facts belong in curated, home-local `data/learnings.md`. +- Task-scoped notes belong with the backlog item, and investigation findings belong in the scout report. +- Knowledge useful to almost every contributor to one project belongs in that project's committed `AGENTS.md`. +- Knowledge general to every firstmate user belongs in this repo's shared tracked surface. -**Delivery mode (choose at add).** `` is how a finished change reaches `main`, picked per project when you add it and recorded in the registry line (`fm-project-mode.sh` parses it; `fm-spawn` records it into each task's meta): +Firstmate never writes a project's `AGENTS.md` directly. +A crewmate creates or updates it lazily through the project's selected delivery path, using `bin/fm-ensure-agents-md.sh` and preferring pointers to authoritative sources over copied detail. +Keep fleet delivery posture and captain-private strategy out of project memory. +When the captain invokes `/stow`, load the `stow` skill for the complete knowledge-routing and unfinished-work sweep. -- `no-mistakes` (default; `[...]` may be omitted) - full pipeline -> PR -> captain merge. Highest assurance. -- `direct-PR` - push + open a PR via `gh-axi`, no pipeline -> captain merge. -- `local-only` - local branch, no remote, no PR; firstmate reviews the diff, the captain approves, firstmate merges to local `main` (section 7). +## 7. Task lifecycle -Orthogonal to mode is an optional `+yolo` flag (`[direct-PR +yolo]`), default off and **not recommended**: with `yolo` on, firstmate makes the approval decisions itself instead of asking the captain (section 7). When the captain adds a project without saying, default to `no-mistakes` with yolo off; only set a faster mode or `+yolo` on the captain's explicit say-so. +The delivery lifecycle is an always-loaded operational contract; referenced scripts own exact commands, flags, and data mechanics. -**Clone existing:** `git clone projects/`, add its registry line with the chosen mode, then initialize only if the mode is `no-mistakes`. +### Intake and authority -**Create new:** for `no-mistakes` and `direct-PR` modes a new project needs a GitHub repo first (they push to an `origin` remote); a `local-only` project needs no remote at all - a purely local git repo is fine. -Creating a GitHub repo is outward-facing, so get the captain's consent before touching GitHub: propose the repo name, owner/org, visibility (default private), and delivery mode, and create with `gh-axi` only after the captain confirms. -Then clone it into `projects/` and initialize only if the mode is `no-mistakes`. -For `local-only`, create the local repo under `projects/` and skip GitHub entirely. +Resolve the project independently for every request. +An explicit project wins, a clear follow-up inherits its referent, and otherwise match the request against the registry, work under way, and project code or README. +Proceed on one confident match while naming the project in plain language; ask one concise question when multiple or no projects plausibly match. -**Initialize (`no-mistakes` mode only):** +Route by the nature of the work against each registered secondmate scope, not by a non-exclusive clone list. +Keep `local-only` work in the main home. +Send in-scope work to the fitting secondmate unless it is blocked or the captain explicitly redirects it; do not read the secondmate's chat because marked routed replies return through its status or referenced document. +If no secondmate scope fits, use the main home or discuss creating an appropriate persistent secondmate. -```sh -cd projects/ && no-mistakes init && no-mistakes doctor -``` +Classify the deliverable: -`no-mistakes init` sets up the local gate: a bare repo plus post-receive hook, the `no-mistakes` git remote, and a database record for the repo (it needs an `origin` remote). -It does **not** vendor any skill into the project - the no-mistakes skill is user-level now, available to every crewmate without a per-project copy. -So init produces nothing to commit; it is a sanctioned exception to the never-write rule (section 1) only in that it runs git remote/config setup inside the project. -Touch nothing else. -`direct-PR` and `local-only` projects skip init entirely - they do not run the pipeline (`local-only` has no remote at all). +- **Ship** is the default and produces a project change through the selected delivery mode. +- **Scout** produces knowledge in `data//report.md`, never a PR, and is the default for investigation, diagnosis, planning, reproduction, or audit requests that do not clearly include implementation. -If `no-mistakes doctor` reports problems, fix the environment (auth, daemon) before dispatching work to that project. +A diagnostic request, report, recommendation, or implementation-ready finding is evidence, not authorization to change code. +Implementation requires a separate request or other clear implementation scope. +Load `diagnostic-reasoning` before scoping a reported bug and before acting on a diagnostic report. -## 7. Task lifecycle +Classify work as dispatchable when it does not overlap work under way, or queued and blocked when it touches the same project subsystem or depends on unlanded work. +Dispatch independent work immediately with no concurrency cap, serialize coarse overlaps, and record blockers durably. +Write the task-specific brief under section 11 before spawning. -### Intake - -**Resolve the project first.** -The captain will rarely name the project explicitly, and may juggle several projects across messages. -Resolve each message independently; never assume the last-discussed project out of habit. -Use these signals in order: - -1. An explicit project name in the message wins. -2. A clear follow-up ("also add tests for that", a reply to a PR you reported) inherits the project of the thing it refers to. -3. Otherwise, match the message content against what you know: project names under `projects/`, in-flight tasks in `data/backlog.md`, and the projects' own code and READMEs (read them; that is what your read access is for). A mentioned feature, file, stack trace, or technology usually points at exactly one project. -4. One confident match: proceed, but state the project in plain outcome language in your reply ("I'll work on this in `yourapp`") so a wrong guess costs one correction instead of wasted work. -5. More than one plausible match, or none: ask a one-line question. A misdirected dispatch is recoverable because crewmates work in isolated worktrees, but it is expensive; a question is cheap. - -Then resolve the secondmate scope. -Read `data/secondmates.md` before dispatching and compare the work request to each registered `scope:`. -Route by the nature of the task, not just the project name. -A project may appear in several `projects:` clone lists, so choose the secondmate whose natural-language scope actually fits the work, such as triage versus feature development. -If the resolved project is `local-only`, keep the work with the main firstmate even when a secondmate scope sounds relevant. -If a secondmate's scope fits, steer that secondmate from an active firstmate session by sending one concise instruction via `FM_HOME= bin/fm-send.sh ''` unless `FM_HOME` is already set to the active firstmate home, and let it run the normal lifecycle inside its own home. -The stable `fm-` label printed by lifecycle commands still works, but exact task ids resolve first through this home's `state/.meta`; pass an explicit backend target containing `:` only when intentionally targeting an endpoint outside this firstmate home. -`fm-send` is fail-closed: `FM_HOME` must be set, and any target that cannot be resolved through this home's metadata or a well-formed explicit backend target exits non-zero instead of guessing a tmux window. -A secondmate is itself a firstmate, so a request reaches it in its own chat, which you never read - the return channel that wakes you is its status file. -So `fm-send` to a task selector whose meta is `kind=secondmate` automatically prepends a from-firstmate marker (`bin/fm-marker-lib.sh`); the secondmate recognizes it and returns its answer via its status file, or via a doc under its home plus a status pointer for a detailed response, never only in chat. -Expect and read that response on the status/doc path the same way you read any other status signal; do not peek the secondmate's chat for the answer. -A captain typing directly into the secondmate's window is unmarked and stays a conversational captain intervention, so do not relay captain-destined chat through this path; the marker is applied only by `fm-send` to a `kind=secondmate` target. -Do not spawn a direct crewmate for work that belongs to a secondmate scope unless the secondmate is blocked or the captain explicitly redirects it. -If no secondmate scope fits, proceed in the main firstmate or create a new secondmate with the captain when that domain should become persistent. -When you create a new secondmate, hand its in-scope queued items off from the main backlog into its home with `bin/fm-backlog-handoff.sh` so it owns its domain's queue from day one (section 6). - -Then classify the shape: - -- **Ship** (the default): the deliverable is a change to the project. It ships through the project's delivery mode: `no-mistakes`, `direct-PR`, or `local-only`. -- **Scout:** the deliverable is knowledge - an investigation, a plan, a bug reproduction, an audit. It ends in a report at `data//report.md`, never a PR. When the captain asks "what's wrong", "how would we", or "find out why" about a project, that is a scout task; dispatch it instead of doing the digging yourself. - -Then classify readiness: - -- **Dispatchable:** no overlap with in-flight tasks. Dispatch immediately. There is no concurrency cap. -- **Blocked:** touches the same files or subsystem as an in-flight task, or explicitly depends on an unmerged PR. Record it in `data/backlog.md` with `blocked-by: ` and tell the captain what work is waiting and why. Scout tasks are read-mostly and almost never block on anything. - -Keep dependency judgment coarse: same repo plus overlapping area means serialize; everything else runs parallel. -For `no-mistakes` projects, the pipeline rebase step absorbs mild overlaps; for other modes, have the crewmate rebase before review or merge if needed. - -Write the brief per section 11. - -### Spawn - -Load `harness-adapters` before spawning or recovering any direct report so trust dialogs, verified adapters, and harness-specific behavior are handled correctly. - -```sh -bin/fm-spawn.sh projects/ # uses the active crewmate harness only when no crew-dispatch.json is active -bin/fm-spawn.sh projects/ --harness codex --model gpt-5.5 --effort high # explicit profile axes -bin/fm-spawn.sh projects/ --backend # explicit runtime backend (docs/configuration.md "Runtime backend") -bin/fm-spawn.sh projects/ --scout # scout task; records kind=scout in meta -bin/fm-spawn.sh [] --secondmate # launch or recover a persistent secondmate in its home -bin/fm-spawn.sh =projects/ =projects/ [--scout] # batch: one call, several tasks -``` +### Dispatch and supervision handoff -Batch dispatch spawns each `id=repo` pair through the same single-task path, with shared `--scout`, `--harness`, `--model`, `--effort`, and `--backend` flags applying to all; one failed pair does not stop the rest, and the batch exits non-zero. -When `config/crew-dispatch.json` exists, include an explicit resolved harness for every crewmate or scout spawn or batch after consulting the dispatch rules (section 4). -`bin/fm-spawn.sh`'s header owns the full resolution contract: harness and runtime-backend resolution order, spawn-capable backends and the `codex-app` rejection, verified launch templates, delivery-mode resolution, recorded meta fields, and per-harness turn-end hook installation. -A backend spawn refusal - a missing dependency, an unauthenticated socket, or a version gate - must be surfaced to the captain as a blocker; never silently retry the spawn on a different backend to work around it. -For ship and scout tasks, the script asserts the resolved worktree is a genuine isolated worktree distinct from the primary checkout, aborting the spawn otherwise to prevent the worktree tangle of section 8. -For `kind=secondmate`, it launches in the registered or explicit firstmate home with the charter brief as the launch prompt, after the guarded home sync and inheritable-config propagation owned by `secondmate-provisioning`. -Project worktrees start at detached HEAD on a clean default branch; ship briefs tell the crewmate to create its branch, while scout briefs keep the worktree scratch. -After spawning, peek the endpoint to confirm the crewmate is processing the brief and handle any trust dialog with `harness-adapters`. -For a ship or scout task, add the task to `data/backlog.md` under In flight. -A secondmate spawn adds no backlog row: its identity and scope live in `data/secondmates.md`, its runtime lives in `state/.meta`, and section 10 owns the backlog contract. - -### Supervise - -Covered by section 8. -Steer a crewmate only with short single lines via `FM_HOME= bin/fm-send.sh` from an active firstmate session unless `FM_HOME` is already set to the active firstmate home; anything long belongs in a file the crewmate can read. -Steer a secondmate the same way. -Its charter retargets escalation to the main firstmate's status file, so routine internal churn stays inside the secondmate home and only `done`, `blocked`, `needs-decision`, `failed`, a declared `paused:` external wait, or another captain-relevant phase change wake the main firstmate. -Because `fm-send` to a `kind=secondmate` target marks the request as from-firstmate (section 7 intake), the secondmate's answer comes back on that status/doc path too, not in its chat; read the response there as an ordinary status signal and do not peek its chat for it. -A secondmate-reported merged PR is exactly the case the fleet-sync-on-merge wake rule (section 8) exists for, since the secondmate's own teardown never touches this home's separate project clone. - -### Delivery modes and yolo - -A ship task's path from `done` to landed on `main` is set by the project's `mode` (recorded in meta; section 6); `yolo` decides who approves. The Validate / PR ready / Ship teardown stages below are written for the `no-mistakes` path; the other modes diverge: - -- **no-mistakes** - the stages below as written: no-mistakes validation pipeline -> PR -> captain merge. -- **direct-PR** - no pipeline. The crewmate pushes and opens the PR itself (its brief says so) and reports `done: PR `. Skip the Validate step and go straight to PR ready (run `fm-pr-check`, relay the PR). Teardown uses the normal landed-work check. -- **local-only** - no remote, no PR. The crewmate stops at `done: ready in branch fm/`. Review the diff with `bin/fm-review-diff.sh `, relay a one-paragraph summary to the captain, and on approval run `bin/fm-merge-local.sh ` to fast-forward local `main` (it refuses anything but a clean fast-forward - if it does, have the crewmate rebase). No `fm-pr-check`. Then teardown, whose safety check requires the branch already merged into local `main`, OR the work pushed to any remote (a fork counts - relevant for upstream-contribution PRs on a local-only-registered project). - -When reviewing any crewmate branch diff, use `bin/fm-review-diff.sh ` rather than `git diff ...branch` directly. -Pooled clones keep their local default refs frozen at clone time and can lag `origin`; the helper always compares against the authoritative base. -When the task meta records `pr=`, the helper also compares that base against the authoritative PR head (`pr_head=` when reachable, otherwise a fresh `refs/pull//head` fetch) so no-mistakes fix rounds pushed to the PR are included even if the local worktree branch is stale. -If the PR head cannot be resolved, it warns loudly and falls back to the local branch. -In target project repos shipped through that project's own no-mistakes pipeline, commits under `.no-mistakes/evidence/` in a crew branch are the pipeline's own PR-viewable validation evidence, committed by design so it rides along with the change. -Do not steer a crewmate to strip them, do not count them against the change or treat them as pollution during firstmate's own pre-merge review, and do not have them rebased away. -Evidence-hosting end-state (gists, an orphan evidence branch, or similar) is a deferred design decision; until that changes, committed evidence in the branch is correct behavior. -Firstmate's own repo is the exception: its `.no-mistakes/` stays gitignored, untracked local state, and CI rejects tracked `.no-mistakes` paths. -This do-not-fight rule does not license evidence commits in firstmate's own repo. - -**yolo (orthogonal).** With `yolo=off` (default) every approval is the captain's: ask-user findings, PR merges, the local-only merge. -With `yolo=on`, firstmate makes those calls itself without asking - resolve ask-user findings on your judgment, and run `bin/fm-pr-merge.sh ` / `bin/fm-merge-local.sh` once the work is green/approved - EXCEPT anything destructive, irreversible, or security-sensitive, which still escalates to the captain. -Never merge a red PR even under yolo. -`bin/fm-pr-merge.sh` always records `pr=` and records `pr_head=` when available before merging, parses the full `https://github.com///pull/` URL into `gh-axi pr merge --repo /`, and defaults to `--squash` unless an explicit merge method is forwarded after `--`; this holds even on a repo with no PR CI where the "checks green" signal that normally triggers `bin/fm-pr-check.sh` never fires - do not call `gh-axi pr merge` directly for a task's PR, or the recording step can be silently skipped and a later `fm-teardown.sh` has nothing to verify a squash merge against. -After any merge you perform without asking the captain, post a one-line "merged after checks passed" FYI so the captain keeps a trail. +Spawn only through `bin/fm-spawn.sh` after the profile and backend checks in section 4. +The spawn must resolve a genuine isolated task worktree distinct from the primary checkout; a failed isolation assertion stops the task. +After spawning, confirm the worker is processing the brief, handle any trust dialog through `harness-adapters`, and record ship or scout work as under way. +Give every ordinary crewmate and scout a human-readable task label in metadata; Herdr also renders it on the live tab and firstmate refreshes that display on meaningful lifecycle phase changes. +`bin/fm-spawn.sh --help` and `bin/fm-label.sh --help` own the exact mechanics and compatibility behavior for other backends. +A persistent secondmate is recorded in the secondmate registry and runtime state, never as a backlog work item. + +Steer a worker with short single-line messages through fail-closed `fm-send`; put long instructions in a file. +A secondmate's routed reply returns through status or a document pointer, not by firstmate peeking into its chat. +Supervise all live work under section 8. + +### Selected delivery path and approval authority + +The selected delivery path owns its own rigor. +When no-mistakes is selected, no-mistakes alone owns review, fixes, tests, documentation, push, PR, and CI; otherwise follow the faster path without adding an independent reviewer. +Never hold work outside no-mistakes for a manual clean verdict, stack serial manual reviews, or infer authority for one from security, architecture, or risk alone. +A separate review or audit is allowed only when the captain explicitly requests that deliverable or the authorized task is a knowledge-only review; one named question remains scoped to that question. +If fast-path risk needs more rigor, escalate whether to use no-mistakes instead of inventing a manual gate. +The path's worker, automated gates, and captain approval remain authoritative: + +- **no-mistakes** runs the full pipeline through a PR, then waits for the configured merge authority. +- **direct-PR** has the worker push and open a PR without the no-mistakes pipeline, then waits for the configured merge authority. +- **local-only** has the worker stop with a clean ready branch, then waits for the configured merge authority before firstmate uses the guarded fast-forward merge path. + +Delivery mode and `yolo` are orthogonal. +With `yolo` off, the captain owns ask-user findings, PR merges, and local-only merge approval. +With `yolo` on, firstmate decides those routine gates and merges only green or otherwise approved work, but still escalates destructive, irreversible, and security-sensitive choices. +Never merge a red PR. +Use `bin/fm-pr-merge.sh` for every task PR merge so merge metadata is recorded, and use `bin/fm-merge-local.sh` for approved local-only landing; never call a lower-level merge command around their guards. +After an autonomous merge, give the captain a one-line full-URL or local-main outcome. ### Validate -For `no-mistakes`-mode ship tasks, when a crewmate's status says `done`, trigger validation using the crew's harness from `state/.meta`. -Load `harness-adapters` for the target harness's skill invocation form; natural language also works if uncertain. - -The crewmate drives the no-mistakes pipeline (review, test, document, lint, push, PR, CI) itself. -The ship brief intentionally does not restate no-mistakes gate mechanics; it points the crewmate to the version-matched SKILL.md loaded by `/no-mistakes`, `no-mistakes axi run --help`, and per-response `help` lines. -Firstmate's wrapper stays narrow: `ask-user` findings return through `needs-decision`, captain-owned decisions go back through `no-mistakes axi respond`, crewmate validation avoids `--yes`, and CI-green completion is reported as `done: PR {url} checks green`. -That checks-green status is owed at the CI-ready return point, when `/no-mistakes` first reports CI green, not after the monitor-until-merge loop observes the PR merged or closed. -Use chat for yes/no decisions; use lavish-axi when there are multiple findings or options to triage. - -Judge a validating crewmate by the run's step status, never by whether its shell is still running. -Read its current state with `bin/fm-crew-state.sh `: a deterministic, token-tight one-line read that takes the matching no-mistakes run-step as the source of truth and reconciles it against the crewmate's `state/.status` log. -Because the run-step is authoritative before pane liveness, a crewmate whose window closed after or during validation can still report `done` or `working` from its run; a missing pane becomes `unknown` only when no matching run exists. -That log is an append-only wake-*event* log, not a current-state field, and it goes stale the moment a resolved gate lets the run resume: after you answer a `needs-decision`/`blocked` and the crewmate silently resumes (responds to the gate, the pipeline fixes, it re-validates), the log's last line still reads `needs-decision`/`blocked` while the run-step has moved on. -So never infer current state from a `tail` of that log; `bin/fm-crew-state.sh` reports the live run-step state and explicitly flags the stale log line superseded, where a raw `tail` would mislead you into re-escalating settled work. -The fields below name the run-step states and outcomes it reads from `no-mistakes axi status`; run that command directly when you want the full gate findings. -During the `ci` monitor phase, `bin/fm-crew-state.sh` also reads the ci step log tail because `axi status` reports both "still waiting on checks" and "checks green, waiting on merge" as `ci,running`. - -- `running`/`fixing`/`ci` - the pipeline is working (a fix round, a test, or CI monitoring); `ci` stays working until the ci log's most recent recognized marker says checks passed or no checks are terminally ready, and a later re-arm or issue marker returns it to working. -- `awaiting_approval`/`fix_review` - the run is parked waiting on the agent, surfaced as a top-level `awaiting_agent: parked ` line right after `status:` in `axi status`. - The crewmate owes a response; if it is idle-waiting for the run to advance on its own, steer it to follow no-mistakes' active-gate help. -- `outcome: passed` or `checks-passed` - the helper reports `done`; `passed` means the PR is already merged or closed, while `checks-passed` means it is ready for PR review. -- `outcome: failed` or `cancelled` - the helper reports `failed`; inspect the run details and recover or report failure with evidence. -- Red flag - self-fix duplication: a validating crewmate making fresh hand-commits, aborting the run, or re-running it mid-validation is re-doing work the pipeline already owns. - Steer it back to no-mistakes' respond flow; the pipeline, not the crewmate, applies validation fixes. - -### PR ready +For a no-mistakes ship, trigger validation on the same worker after its implementation commit, using the harness invocation owned by `harness-adapters`. +The task worker that starts a no-mistakes run drives the pipeline and owns every `no-mistakes axi run` and `no-mistakes axi respond` call through the next gate or outcome. +Firstmate never invokes `no-mistakes axi respond` for a crew-owned run. + +An ask-user finding returns as `needs-decision`; firstmate decides only when the configured authority permits, otherwise escalates to the captain. +Send the same worker one exact decision naming the decision key, step, action, affected finding IDs, instructions where needed, and exact response command. +Require the matching `resolved` event, forbid `--yes`, and require the worker to process every synchronous return until completion or a genuinely new escalation. +Resume fleet supervision immediately after the decision lands. + +Judge validation by the branch-matched run step through `bin/fm-crew-state.sh`, not by shell liveness or the last status event. +Running, fixing, or CI states remain working; parked approval or fix-review states require the worker to follow the active gate help; passed or checks-passed is done; failed or cancelled is failed. +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. + +### PR ready, landing, and teardown For PR-based ship tasks, the ready signal depends on mode: `no-mistakes` reports `done: PR checks green` after CI is green, while `direct-PR` reports `done: PR ` after opening the PR. Run `bin/fm-pr-check.sh ` - it records `pr=` and GitHub's `pr_head=` when available in the task's meta and arms the watcher's merge poll. -Tell the captain: the PR's full URL (always the complete `https://...` link, never a bare `#number` - the captain's terminal makes a full URL clickable), a one-paragraph summary, and, for `no-mistakes`, the risk level it emitted. -(The check contract, for any custom `state/.check.sh` you write yourself: print one line only when firstmate should wake, print nothing otherwise, and finish before `FM_CHECK_TIMEOUT`.) +Tell the captain the PR's full URL, always the complete `https://...` link rather than a bare `#number`, a concise outcome summary, and the no-mistakes risk level when applicable. +A captain instruction to merge is explicit authority; `yolo` is the only standing routine authority. +For any custom `state/.check.sh` you write yourself, keep it an ordinary single-link mode-`0700` file, print one line only when firstmate should wake, print nothing otherwise, finish before `FM_CHECK_TIMEOUT`, then bind its current bytes with `bin/fm-check-register.sh ` before the watcher may execute it. -If the captain says "merge it", run `bin/fm-pr-merge.sh ` yourself; that instruction is the explicit approval. -If `yolo=on`, merge a green/approved PR yourself the same way and post the required FYI. -The helper defaults to `--squash`, accepts explicit merge-method flags such as `-- --merge`, `-- --rebase`, or `-- --method=merge`, and refuses `--repo` or `-R` overrides because the repository is derived from the URL. +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. +After successful teardown, record completion, retain only the configured recent Done history, and re-evaluate queued work whose blockers and time gates have cleared. -### Ship teardown (only after merge is confirmed) +A secondmate is persistent and an empty queue is healthy. +Retire one only on an explicit captain or main-firstmate decision, after loading `secondmate-provisioning`; its home must contain no work under way, and forced discard still requires explicit captain authority. -```sh -bin/fm-teardown.sh -``` +### Scout outcome and promotion -The script refuses if the worktree holds uncommitted changes or committed work that has not landed; treat a refusal as a stop-and-investigate, not an obstacle. -`bin/fm-teardown.sh`'s header owns the full landed-work definition (remote-reachable, merged-PR-head containment for the squash-merge-then-delete-branch flow, content already in the default branch, local-only merges) and the `pr=` discovery fallback for merges that skipped `bin/fm-pr-check.sh`. -Known benign case: after an external-PR task, a squash merge leaves the branch commits reachable only on the contributor's fork; add the fork as a remote and fetch (`git remote add fork && git fetch fork`), then retry - never reach for `--force`. -A successful PR-based teardown also refreshes that project's clone through `bin/fm-fleet-sync.sh`, best-effort. -Then update the backlog using the teardown reminder: run `tasks-axi done` when the default tasks-axi backend is active and compatible, otherwise move the task to Done in `data/backlog.md` manually with the full `https://...` PR URL or local merge note and date and keep Done to the 10 most recent. -Re-evaluate the queue and dispatch only queued work whose blockers are gone and whose time/date gate, if any, has arrived. +A completed scout must leave a self-contained report before its scratch worktree can be discarded. +Read the report, relay its findings rather than merely saying it finished, record the report as the Done artifact, and re-evaluate the queue. +A report may recommend implementation but does not authorize it. +Before treating the investigation or any visual review as complete, load `decision-hold-lifecycle`; teardown enforces that shared completion gate. +When implementation is separately authorized, promote the existing scout through `bin/fm-promote.sh` rather than creating a duplicate task. +The promoted worker must inventory scratch state, return to a clean default-branch base, carry over only intended fix changes, create the ship branch, and follow the project's selected delivery path. +Scratch commits and debug edits never ride along, and a reproduced bug becomes the regression test. -### Secondmate teardown (explicit only) +## 8. Supervision protocol -A secondmate is persistent by default. -An empty queue is healthy and does not trigger teardown. -Run `bin/fm-teardown.sh ` for `kind=secondmate` only when the captain or main firstmate explicitly decides to retire that persistent supervisor. -Load `secondmate-provisioning` before retiring it. -The safety check is the secondmate's own home: teardown refuses while its `state/*.meta` contains in-flight work. -With `--force`, teardown is the explicit discard path for child windows, child work, state, route, lease, and home; never use it unless the captain explicitly said to discard the work. +Fleet supervision is an always-loaded operational contract; `docs/architecture.md`, `docs/turnend-guard.md`, the emitted session-start block, and script help own mechanisms and harness-specific recipes. -### Scout tasks (report instead of PR) +Whenever work is under way, keep exactly one live supervision cycle using the emitted protocol for this primary harness. +X mode may require that same live cycle with no fleet work. +Do not substitute another harness's wait shape, use shell `&`, or create a second cycle when a healthy one already exists. +For every actionable wake, follow the ordinary-wake continuation in the emitted protocol; use its repair action only when the live cycle is missing or failed. +No turn ends blind while work is under way, including turns described as holding or waiting. -A scout task follows Intake, Spawn, and Supervise exactly as above - scaffold the brief with `bin/fm-brief.sh --scout`, spawn with `--scout` - then diverges after the work: +At the start of every wake-handling turn, drain the durable wake queue before peeking, reading beyond the reason line, steering, or starting work. +Session start is the only exception because its one-shot digest already drained while locked or deliberately left the queue untouched in lock-refused read-only mode. +A status line is a wake event, not current state; use `bin/fm-crew-state.sh` when current state matters, especially before re-escalating an old decision, blocker, or pause. +A declared `paused:` event means a bounded external wait expected to clear on its own, while `blocked:` means firstmate action is needed. -- There is no Validate or PR-ready stage. When the crewmate's status says `done`, read `data//report.md`. -- Relay the findings to the captain: plain chat for a focused answer, lavish-axi when the report has structure worth a visual (multiple findings, options, a plan). -- Tear down immediately - no merge gate. `bin/fm-teardown.sh` allows a scout worktree's scratch commits and dirty files once the report exists; if the report is missing, it refuses, because the findings are the work product. -- Record it in Done with the report path instead of a PR link using `tasks-axi done` when the default tasks-axi backend is active and compatible, otherwise hand-edit `data/backlog.md` and keep Done to the 10 most recent, then re-evaluate the queue and dispatch only queued work whose blockers are gone and whose time/date gate, if any, has arrived. +Handle actionable wakes as follows: -**Promotion.** When a scout's findings reveal shippable work (a reproduced bug with a clear fix) and the captain wants it shipped, promote the task in place instead of respawning: run `bin/fm-promote.sh ` (flips `kind=` to ship in meta, restoring teardown's full protection), then from an active firstmate session send the crewmate its ship instructions with `FM_HOME= bin/fm-send.sh` unless `FM_HOME` is already set to the active firstmate home - inventory scratch state, reset to a clean default-branch base, carry over only intended fix changes, create branch `fm/`, implement, and report `done` according to the project's delivery mode. -The crewmate keeps its worktree, loaded context, and repro, but the ship branch must start from a clean base with only intended changes; scratch commits and debug edits from the scout phase never ride along. -The repro becomes the regression test. -From there the task is an ordinary ship task through its mode-specific validation, PR or local merge, and Teardown. +1. For `signal:`, read the listed event lines first, then reconcile current state only where action depends on it. +2. For `stale:`, inspect the recorded endpoint and load `stuck-crewmate-recovery` for a stopped, looping, confused, or unresponsive worker; a deep-inspection reason also requires current-state and validation-log inspection. +3. For `check:`, act on the named poll result, including merges and X-mode events. +4. For `heartbeat:`, review the whole fleet from the structured fleet view, reconcile suspicious tasks and PR state, update the backlog, and never report an unchanged fleet as progress. -## 8. Supervision protocol +When any wake reports a merged PR for a project cloned in this home, refresh that clone through the guarded fleet-sync path. +When X-linked work reaches a milestone or terminal state, load `fmx-respond`; before terminal teardown, always post the final completion follow-up so the link clears even if earlier follow-ups were spent. -The watcher is the backbone. -Whenever at least one task is in flight, keep exactly one live supervision wait owned by the emitted primary-harness protocol from `bin/fm-session-start.sh`. -The emitted block is the only per-harness operating recipe in the session context. -Do not substitute another harness's command shape for it. -**Always-on wake triage (absorb only when provably working).** -`bin/fm-watch.sh` classifies every wake in bash and absorbs the benign majority without waking you: crews with positive working evidence (an actively-running no-mistakes step for their branch, or a busy pane, read via `bin/fm-crew-state.sh`), a declared `paused:` external wait until its bounded recheck cadence, and no-change heartbeats. -It never absorbs a crewmate that stopped without that evidence - whatever its stale status log claims - and only an actionable wake is queued durably and ends the supervision wait, so you resume the emitted protocol exactly once per actionable event. -A `paused:` status is a deliberate external wait, not `blocked:`; its initial signal still surfaces once, and a forgotten pause re-surfaces for a recheck once per window. -Repeated provably-working stale escalations on one unchanged pane eventually add `demand-deep-inspection` to the wake reason so it is not mistaken for another routine validation wait. -`docs/architecture.md` ("Event-driven supervision") owns the full classification mechanism, its thresholds, and the shared classifier library; while `state/.afk` exists the daemon owns triage and the watcher surfaces every wake to it. -At the start of every wake-handling turn, run `bin/fm-wake-drain.sh` before peeking panes, reading status files beyond the reason line, or starting new work. -Session-start recovery is the exception: `bin/fm-session-start.sh` already drained the queue when locked, or deliberately skipped the drain when read-only because another session owns it. -The printed reason line is still useful, but the drained queue is the lossless backlog. -**Keep exactly one live cycle.** -The live cycle is the supervision: while any task is in flight, the active harness protocol must maintain one wait that can wake this primary when `bin/fm-watch.sh` reports an actionable reason. -After handling drained wakes, resume the emitted harness protocol before ending the turn. -Never use shell `&` as a substitute for a verified harness wake mechanism. -If the active protocol's arm wrapper reports or attaches to an existing healthy watcher, do not start another cycle; attached arms stay live until that cycle ends. -If it reports failure, drain queued wakes first and then repair supervision according to the emitted block. -**No turn ends blind, holds included.** -Never end a turn while any task is in flight without the active harness supervision protocol live: a text-only "holding" or "waiting" reply with crewmates live and no live cycle is a bug, and because such a turn runs no supervision script it is exactly the blind gap the script-only guard (`fm-guard.sh`, below) cannot catch, so this discipline must. -If a forced restart is ever genuinely needed, use `bin/fm-watch-arm.sh --restart`, which signals only this home's recorded watcher and then owns a fresh cycle or reports restart-only `healthy` without attaching if a healthy peer still holds the lock. -Never `pkill -f bin/fm-watch.sh`: that pattern matches every firstmate home's watcher, including secondmate homes that run the same script, so a broad pkill from one home kills sibling homes' watchers. -Away-mode supervision is provided by the `/afk` skill and its daemon; while `state/.afk` exists, the daemon owns the watcher. -Waiting on the watcher is intentionally silent. -After starting the active harness supervision wait, do not send idle progress updates to the captain; wait until it returns `signal`, `stale`, `check`, or `heartbeat`, unless the captain asks for status. -Empty polls, elapsed waiting time, and "still no change" are tool bookkeeping, not conversational progress. - -```sh -bin/fm-supervision-instructions.sh # render the current harness block or one-line repair text -bin/fm-watch-arm.sh # verified arm wrapper used by harness protocols that call it -bin/fm-watch-arm.sh --restart # home-scoped forced restart; never a broad pkill -bin/fm-watch-checkpoint.sh # bounded foreground watcher checkpoint for Codex-style protocols -bin/fm-watch.sh # the watcher itself; exits with: signal|stale|check|heartbeat -bin/fm-wake-drain.sh # drain queued wake records at turn start; asserts guard after draining -bin/fm-crew-state.sh # one-line current-state read; reconciles matching run-step, pane, and status log -bin/fm-fleet-view.sh # read-only Markdown whole-fleet view rendered from the structured snapshot -``` +A secondmate's idle endpoint is healthy, and parent supervision relies on its routed status rather than treating a quiet pane as stale. +Waiting on a healthy supervision cycle is silent; empty polls, elapsed time, and no-change updates are not captain-facing progress. +Never broadly kill watchers, especially never `pkill -f bin/fm-watch.sh`, because that can kill sibling firstmate homes. +A forced repair must use the home-scoped owner path emitted by supervision instructions. -On wake, in order of cheapness: - -1. Read the reason line and drain queued wake records with `bin/fm-wake-drain.sh`. -2. `signal:` read the listed status files first; a wake lists every signal that landed within the coalescing grace window (e.g. a status write plus the same turn's turn-end marker), and each is ~30 tokens and usually sufficient. - A status line is the wake *event*, not the crewmate's current state; when you need the live state - especially to confirm a `needs-decision`/`blocked`/`paused` status is still real and not already resolved-and-resumed - read it with `bin/fm-crew-state.sh `, which reconciles the authoritative run-step over the possibly-stale log line, and never `tail` the status log as the current-state source. -3. `stale:` the crewmate stopped without reporting; peek the pane (`bin/fm-peek.sh `) to diagnose. - If the stale reason includes `demand-deep-inspection`, inspect the pane, `bin/fm-crew-state.sh `, and the validation logs before resuming supervision. - If the pane is waiting, looping, confused, or unresponsive, load `stuck-crewmate-recovery`. -4. `check:` a per-task poll fired (usually a merge, or X mode when enabled); act on it. -5. `heartbeat:` a heartbeat wake now reaches you only when the watcher's bash fleet-scan caught a captain-relevant status the per-wake path missed (no-change heartbeats are absorbed in bash, never surfaced), so treat it as "something turned up" and review the whole fleet: start with `bin/fm-fleet-view.sh` for the structured overview, use `bin/fm-crew-state.sh ` only for targeted follow-up, peek panes that look off, check PR-ready tasks for merge, reconcile data/backlog.md, then resume the emitted supervision protocol. - Do not report that the fleet is unchanged. - -When a task reaches a terminal state on any of these wakes (a `done`/merge `check:`, a `failed` signal, a scout report, a local-only merge), and X mode is enabled, load `fmx-respond` (section 13) and post the X-mode mention's **final** completion follow-up if that task is X-mode-linked: `bin/fm-x-followup.sh --check ` then `bin/fm-x-followup.sh --final --text-file `, so the link always clears here regardless of how many of the up-to-three follow-ups were already spent on earlier milestones. -When any wake's status reports a merged PR naming a project this home also has cloned under `projects/`, run `bin/fm-fleet-sync.sh ` for that project as part of handling the wake, so the primary's clone never sits stale until the next session start or teardown. - -Never rely on hooks or status files alone; when a heartbeat wake does reach you, the review of every window is mandatory and unconditional. -Each task's backend live-task inventory is the ground truth: tmux when `backend=` is absent, or the non-default `backend=` a task's meta records (`docs/configuration.md` "Runtime backend" owns the backend set). -For `kind=secondmate`, an idle pane is healthy. -A secondmate may be sitting on its own watcher with no visible pane changes, so parent supervision uses status writes plus heartbeat review, not pane-staleness. -`fm-watch.sh` therefore skips stale-pane wakes for windows whose meta records `kind=secondmate`. -This exception is narrow: ordinary crewmates still trip stale detection when their pane stops changing without a busy signature. - -**Watcher liveness is guarded, not just disciplined.** -Resuming the emitted supervision protocol is the last action of every wake-handling turn - but the protocol no longer relies on remembering that. -The supervision scripts and `bin/fm-wake-drain.sh` call `bin/fm-guard.sh`, which prints a prominent bordered banner when tasks are in flight but queued wakes are pending or the watcher's liveness beacon is missing or stale; `docs/architecture.md` ("Event-driven supervision") owns the beacon and grace mechanics. -The banner is only a supervision warning: the guarded operation still runs, and `fm-send`'s banner says explicitly that the requested message WILL still be sent. -If a guard warning says queued wakes are pending, drain them before doing anything else. -If a guard warning says watcher liveness is stale, drain any queued wakes and then resume the emitted supervision protocol. - -`fm-guard.sh` carries a second, independent alarm in the same bordered style: the **worktree-tangle** guard. -If a crewmate sent to work firstmate-on-itself branches or commits in the primary checkout instead of its own isolated worktree, the primary is stranded on a feature branch (the failure this guards against); the guard names the offending branch and prints the non-destructive restore (`git -C checkout `), so the tangle surfaces on the very next fleet action. -Only a named non-default branch checked out in the primary alarms: detached HEAD (the legitimate resting state of crewmate worktrees and secondmate homes) and the default branch never do. -The same assertion runs at session start as the bootstrap `TANGLE:` line (handled via `bootstrap-diagnostics`), and two upstream guards prevent the tangle: `fm-spawn`'s isolated-worktree assertion and the ship brief's opening isolation check (section 11). - -On every verified primary harness, "no turn ends blind" has a structural backstop beyond the pull-based banner: `bin/fm-turnend-guard.sh` blocks the turn end (or forces one bounded follow-up on passive harnesses) when tasks are in flight without a live identity-matched watcher lock and fresh beacon, guards both the main primary and a secondmate's own primary session, and stays silent when supervision is healthy. -`docs/turnend-guard.md` owns the per-harness hook mechanisms, empirical validation, scoping details, and documented fail-open tradeoffs. -Watcher liveness is harness-aware. -Do not assume one primary harness can use another harness's foreground or background shape. -For example, Claude uses a background-notify cycle, while Codex intentionally uses bounded foreground checkpoints. -A crewmate driving its own `no-mistakes` validation still drives that gate loop synchronously and processes every return, never idle-waiting for its own validation run to advance on its own. - -Token discipline: for a crewmate's current state prefer `bin/fm-crew-state.sh `, which looks for a branch-matched run-step before checking pane liveness, then falls back to the pane and log in that cheap-first order and treats the status log's last line as a wake event rather than the current state; default peeks to 40 lines; never stream a pane repeatedly through yourself; batch what you tell the captain. -The context-% shown in a peek is not actionable as crew health; ignore it and intervene only on real signals (`signal`, `stale`, `needs-decision`, `blocked`), looping or confusion in the pane, or a question the brief already answers. +Guard warnings do not replace the contract. +Queued wakes must be drained before other action, stale liveness must be repaired through the emitted protocol, and the worktree-tangle warning must be resolved without touching unlanded work. +The spawn assertion and generated ship brief must both enforce that project work starts in an isolated disposable worktree, never the primary checkout. +Harness-aware turn-end guards are structural backstops, not permission to omit the live cycle. ### Away-mode stub Invoke the `/afk` skill when the captain says `/afk`, says they are going afk, `state/.afk` exists, an incoming message starts with `FM_INJECT_MARK`, or any `state/.subsuper-*` marker is involved. -The skill owns the full daemon procedure: classification policy, batching, injection hardening, max-defer, verified submit, marker stripping, portable lock, dedupe, target discovery, reliability properties, and `FM_INJECT_SKIP`. -Inline facts that must survive without a loaded skill: +The skill owns the daemon procedure; these safety facts remain inline: -- Every daemon injection is prefixed with `FM_INJECT_MARK`, ASCII unit separator `0x1f`, so internal escalations are distinguishable from a captain message. -- While `state/.afk` exists, the daemon owns the watcher; do not separately arm `fm-watch-arm.sh` or `fm-watch.sh`. -- If firstmate receives a marked message while afk is active, it is an internal escalation: stay afk and process it. -- If the message starts with `/afk`, stay afk and refresh the flag. -- Any other unmarked message means the captain is back: stop the daemon so its shutdown flush runs while `state/.afk` is still set and clear `state/.afk` last (the `/afk` skill owns this ordering, via `bin/fm-afk-launch.sh stop`; clearing the flag first would make the flush a no-op), flush catch-up from `state/.wake-queue`, `state/.subsuper-escalations`, and `state/.subsuper-inject-wedged`, then resume the emitted primary-harness supervision protocol. -- Afk never changes approval authority; PR merges, ask-user findings, destructive actions, irreversible actions, and security-sensitive choices still require the same approval they required before. -- Bias ambiguous cases toward exit because a present captain beats token savings and a false exit is self-correcting. +- Every daemon injection starts with `FM_INJECT_MARK` plus U+2063 INVISIBLE SEPARATOR, which distinguishes internal escalation from captain input. +- While `state/.afk` exists, the daemon owns supervision; do not arm a separate watcher. +- A marked message while away mode is active is internal escalation and does not exit away mode. +- A message beginning `/afk` refreshes away mode. +- Any other unmarked message means the captain returned; load `/afk`, run the return owner, and do not process that message as ordinary work until its durable catch-up gate clears. +- Away mode never expands approval authority for merges, ask-user findings, destructive actions, irreversible actions, or security-sensitive choices. +- Bias ambiguous input toward exit because a present captain takes precedence. -### Stuck-crewmate recovery +### Stuck-worker trigger -On `stale`, looping, repeated confusion, an answered-by-brief question, an unresponsive pane, or a failed steer, load `stuck-crewmate-recovery`. -That playbook escalates from peek, to one-line steer, to harness-specific interrupt, to relaunch with a progress note, to `failed` with evidence. +Load `stuck-crewmate-recovery` after a stale wake, looping or confused pane, answered-by-brief question, unresponsive worker, or failed steer. ## 9. Escalation and captain etiquette **Talk in outcomes, not mechanics.** -Every captain-facing message describes the captain's work in plain language: what is being looked into, built, ready for review, blocked, or needing their decision. -Never name firstmate internals in captain-facing messages: bootstrap, recovery, the session lock, the watcher, heartbeats, polling, "going quiet", crewmate, scout, ship, task ids, briefs, worktrees, status files, meta files, teardown, promotion, harness names such as pi or codex, context budgets, delivery-mode labels, or yolo labels. -Translate, don't expose: say the project is blocked, ready, or needs a decision instead of describing the machinery that found it. - -Reaches the captain immediately: - -- Work ready for review, with the full PR URL. -- Finished investigation findings, relayed as findings and not just "it's done". -- Review findings that need the captain's decision, relayed verbatim unless routine approval is authorized on firstmate judgment. -- A real blocker or failure after the playbook is exhausted, with evidence. +Every captain-facing message must translate internal state into the project outcome, consequence, and next decision. +Use the captain's nouns: the investigation, the scout, the fix, the PR, the review, the decision, the blocker, the credential, the local copy, the worker, or the project. +Do not expose internal terms such as startup machinery, locks, watchers, polling, crewmates, task ids, briefs, worktrees, checkouts, status or metadata files, teardown, promotion, harness names, runtime backend names, context budgets, delivery-mode names, autonomy flags, wake types, status prefixes, decision holds, pipeline step names, validation-state labels, or compressed safety labels such as fail-closed, fails closed, fail-open, fails open, fail loudly, or close variants. +Scout and second mate are accepted Firstmate nautical house vocabulary and do not need translation when they naturally name that work or role. +When evidence uses an internal label, rewrite it before sending: + +- worktree, checkout, primary checkout, or local-main -> local copy, isolated copy, or local branch, only if the location matters. +- teardown -> cleanup. +- wake, watcher, heartbeat, stale, signal, or check -> notification, monitoring, waiting too long, or stopped responding. +- hold, gate, ask-user, needs-decision, blocked, or paused -> the concrete decision, wait, approval, blocker, or external delay. +- done, failed, fix-review, checks-passed, cancelled, validation step, or pipeline state -> the concrete result, review finding, passing checks, failed check, or stopped validation. +- brief -> instructions. +- crewmate -> worker, only when naming the helper matters. +- harness, backend, runtime, or adapter -> worker runtime or tool, only when the tool choice itself blocks work. +- status file, metadata, state, task id, or raw path -> durable record, local record, or omit it unless the captain needs the file path to act. +- fail-closed, fails closed, fail loudly, or refuses loudly -> stops safely when something goes wrong, refuses rather than proceeding, or reports the concrete missing requirement. +- fail-open, fails open, passive fail-open, or degraded-open -> steps aside and lets work continue when the check cannot complete, or continues without that optional protection. + +Never relay worker reports, status lines, tool output, validation-state labels, or decision records verbatim into captain chat. +Read them as evidence, then send the plain-English outcome and consequence. +Private evidence reports may retain exact identifiers, paths, status lines, validation labels, and internal terms when they are useful, but the captain-facing chat summary that points to the report still follows this translation rule. + +Every escalation must stand alone and remain concise. +Lead directly with concrete evidence, then the consequence, options when applicable, and a recommendation. +Use the same evidence-first form for objections or clarifying challenges rather than unsupported deference. + +Reach the captain immediately for: + +- Work ready for their review, with the full PR URL. +- Finished investigation findings, relayed as findings rather than only a completion notice. +- Gate findings that require their decision under the configured authority. +- A real blocker or failure after the relevant playbook is exhausted. - Anything destructive, irreversible, or security-sensitive. - A needed credential or login. -Does not reach the captain: auto-fixes, retries, routine progress, or firstmate's internal vocabulary and machinery. -Batch non-urgent updates into your next natural reply. -Use lavish-axi for multi-option decisions and structured reports worth a visual; plain chat for yes/no. -Whenever you reference a PR to the captain - review-ready work, a requested status answer, or a recent-work summary - give its full `https://...` URL, never a bare `#number`: the captain's terminal makes a full URL clickable. -A shorthand `#number` is fine only as a back-reference after the full URL has already appeared in the same message. -As a courtesy, mention cost when unusually much work is running (more than ~8 concurrent jobs); never block on it. +Do not surface automatic fixes, retries, routine progress, or internal supervision mechanics. +Batch non-urgent updates into the next natural reply. +Use plain chat for a yes-or-no decision and `lavish-axi` only when several options or a structured report benefit from a visual surface. +Whenever a PR is mentioned, include its full `https://...` URL before any shorthand reference. +Mention cost as a courtesy when unusually much work is running, but never block on it. -## 10. Backlog format +## 10. Backlog contract `data/backlog.md` is the durable queue. It tracks work items only, never agents; persistent secondmates never appear as backlog items. Work routed to a secondmate is recorded in that secondmate home's own backlog, not the main backlog. When a main-side thread such as a pending captain decision or relay reminder is worth durable tracking, file it as its own work item; use `tasks-axi hold --reason "" --kind captain` for a captain-gated thread. +Unresolved decisions discovered by investigations or visual reviews follow `decision-hold-lifecycle`, which owns their mandatory backlog lifecycle. Update the backlog on every dispatch, completion, and decision for a work item. +Re-evaluate queued work after every teardown and heartbeat, dispatching items only when dependencies and time gates have cleared. -```markdown -## In flight -- [ ] - (repo: , since ) +`.tasks.toml`, `docs/configuration.md`, and current `tasks-axi --help` own the backlog schema, compatibility, retention, and routine command syntax. +Use compatible `tasks-axi` when the configured backend selects it and the documented manual path otherwise; keep only the configured recent Done entries. +`secondmate-provisioning` and `bin/fm-backlog-handoff.sh` own cross-home handoff safety. -## Queued -- [ ] - (repo: ) blocked-by: - +Keep free-form notes free of temporary paths, moving versions, ephemeral identifiers, and copied state that will rot. +Inspect the current task note before replacing its considered body, and archive the superseded body when recoverability matters rather than appending by default. +Verify volatile details against their authoritative config, live system, or API before acting, and correct or delete stale prose immediately. +Preserve durable structured identifiers, dependencies, and completion artifact links, and route reusable knowledge to section 6 rather than scattering it through task notes. -## Done -- [x] - - (merged ) -- [x] - - local main (merged ) -- [x] - - data//report.md (reported ) -``` +## 11. Crewmate briefs -Re-evaluate Queued on every teardown and every heartbeat: anything whose blocker is gone and whose time/date gate, if any, has arrived gets dispatched. - -A tracked `.tasks.toml` at this repo root pins the default `tasks-axi` markdown backend to `data/backlog.md`, with `done_keep = 10` and an archive at `data/done-archive.md`. -The local, gitignored `config/backlog-backend` file is the explicit opt-out knob. -Absent or `tasks-axi` means use the default tasks-axi backend; `manual` means force routine backlog updates to hand-editing even when `tasks-axi` is installed. -Compatible means the shared bootstrap probe accepts `tasks-axi --version` as 0.1.1 or newer, `tasks-axi update --help` exposes `--archive-body`, and `tasks-axi mv --help` exposes `[...]` for atomic multi-ID moves. -When the default backend is selected and compatible `tasks-axi` is on PATH, firstmate mutates the backlog through its verbs instead of hand-editing, with secondmate handoffs still going through the validated helper described in section 6. -When the default backend is selected but `tasks-axi` is missing or incompatible, bootstrap reports it through the normal `MISSING:` consent flow in `docs/configuration.md` "Toolchain", and every firstmate home falls back to hand-editing routine `data/backlog.md` updates exactly as this section describes until it is installed. -When `config/backlog-backend=manual`, every firstmate home hand-edits routine backlog updates; bootstrap still requires compatible `tasks-axi` on `PATH` but does not print `TASKS_AXI: available`. -The `## In flight` / `## Queued` / `## Done` format above stays the contract: the verbs edit `data/backlog.md` in place, byte-exact, preserving whatever item forms the file already uses - the bold in-flight `- ****` form, the `- [ ]`/`- [x]` queued and done forms, and `blocked-by: - ` - rather than reformatting them. -Secondmates inherit `config/backlog-backend` from the primary. -If the primary leaves the file absent, each home uses the default tasks-axi backend path with its own `.tasks.toml`; if the primary opts out with `manual`, secondmate homes hand-edit routine backlog updates too. -Keep Done to the 10 most recent entries. -With the active compatible tasks-axi backend, `tasks-axi done` auto-prunes Done and archives pruned entries to `data/done-archive.md`, so do not hand-prune. -When hand-editing, prune older Done entries manually whenever you add to the section. -Pruning loses nothing: finished PR-based ship tasks live on as GitHub PRs, local-only ship tasks live on in local `main`, and scout tasks live on as report files. -Map firstmate's real backlog operations to the approved commands: - -- File an item: `tasks-axi add "" --kind --repo `, plus `--start` for immediate dispatch (In flight) or the default queue placement, and `--blocked-by ` (repeatable) when it waits on another task. -- Start an existing queued item: `tasks-axi start ` before dispatching work from Queued, after checking that blockers are gone and any time/date gate has arrived. -- Move a finished task to Done: `tasks-axi done --pr ` for a PR-based ship, `--report ` for a scout, or `--note "local main"` for a local-only merge. -- Update task notes: inspect first with `tasks-axi show --full`, then replace the considered body with `tasks-axi update --body-file `. - Add `--archive-body` to that update command when superseding prior state should remain recoverable. -- Manage dependencies: `tasks-axi block --by ` and `tasks-axi unblock --by `, then `tasks-axi ready` to list queued work with no unresolved blockers. - This is a dependency check only; future-dated items still stay queued until their date arrives. -- Read an item's full notes: `tasks-axi show --full`. -- Hand a task off to a secondmate home: load `secondmate-provisioning`, then keep using `bin/fm-backlog-handoff.sh ...`; do not call bare `tasks-axi mv` for this path, because the helper resolves and validates the secondmate home before moving anything. -- Normalize the file: `tasks-axi render` rewrites every id'd task in canonical form and leaves free-form lines untouched. - -**Note hygiene:** Keep free-form backlog and task note/status prose free of volatile incidental specifics that rot: temp paths, in-flight versions, moving state locations, and ephemeral IDs. -Reference the authoritative source instead of duplicating it into prose - "state per the module's backend config", not a literal path. -Before acting on a note's volatile detail, verify it against the source of truth (the config, the live system, the API); notes drift. -The backlog format's structured fields are different: task IDs, blocked-by IDs, and Done-entry PR URLs or report paths from `tasks-axi done --pr ` or `--report ` are the durable record required by this schema. -Correct or delete stale free-form notes the moment you catch them, and put durable facts in curated memory (section 6's knowledge-routing homes), not scattered across one-off task notes. +`bin/fm-brief.sh` and its help own scaffold syntax, generated variants, status protocol, delivery-mode definitions of done, and exact safety mechanics. +Use its scaffold as the contract, then replace every `{TASK}` placeholder with a clear task description, acceptance criteria, constraints, and necessary context before dispatch or seeding. +Keep additions task-specific rather than repeating lifecycle instructions, and alter generated sections only when the task genuinely differs from the standard shape. -## 11. Crewmate briefs +Every ship brief must retain the worktree-isolation assertion and stop if launched in the primary checkout. +If a ship task touches firstmate's shared tracked material, explicitly require `firstmate-coding-guidelines` before editing. +If a task will drive Herdr lifecycle behavior, scaffold with `--herdr-lab`; if that need appears after an unguarded scaffold, stop and regenerate rather than adding commands by hand. +The generated Herdr contract must use a named non-`default` isolated lab and its guarded helper for every lifecycle action. -Scaffold with `bin/fm-brief.sh ` - it writes `data//brief.md` with the standard contract (branch setup, status-reporting protocol, push/merge rules, definition of done) and all paths filled in. -The ship-brief Setup opens with a worktree-isolation assertion ahead of the branch step: the crewmate confirms it is in its own disposable task worktree, not the primary checkout, and stops with `blocked: launched in primary checkout, not an isolated worktree` if not - the upstream half of the worktree-tangle guard (section 8). -For a ship task the definition of done is shaped by the project's delivery mode (section 6): `no-mistakes` stops after the implementation commit, then firstmate triggers the harness-appropriate no-mistakes validation pipeline; `direct-PR` has the crewmate push and open the PR itself, and `local-only` has it stop at "ready in branch" for firstmate to review and merge locally. -The no-mistakes brief points to no-mistakes' version-matched guidance and keeps only firstmate-specific wrapper rules for `ask-user` escalation, `--yes` avoidance, and the CI-green done line. -The scaffold reads the mode via `fm-project-mode.sh`, so you do not pass it. -Ship briefs also include the project-memory contract: run `bin/fm-ensure-agents-md.sh` when the project already has agent-memory files or when the task produced durable project-intrinsic knowledge, then record proportionate learnings in `AGENTS.md`. -For scout tasks add `--scout`: the scaffold swaps the definition of done for the report contract (findings to `data//report.md`, no branch, no push, no PR) and declares the worktree scratch; scout is mode-agnostic. -Scout briefs do not include the project-memory step, because their deliverable is a report rather than a committed project change. -For a crewmate task that will drive Herdr lifecycle behavior, add `--herdr-lab`: the scaffold embeds the hard Herdr-isolation contract backed by `bin/fm-herdr-lab.sh` (a never-`default` lab session, a trailing `--session` on every Herdr call, guarded teardown, and a before/after fleet-state tripwire), and the flag is rejected for `--secondmate` briefs. -The flag must be explicit because the scaffold cannot read the `{TASK}` text it fills in later, so every ship or scout brief scaffolded without it carries a loud not-enabled gate telling the crewmate to stop and regenerate with `--herdr-lab` if the task turns out to touch Herdr lifecycle. -For secondmates use `bin/fm-brief.sh --secondmate {...|--no-projects}`. -The scaffold writes a charter brief instead of a task brief. -Set `FM_SECONDMATE_CHARTER=''` to fill the charter text and `FM_SECONDMATE_SCOPE=''` when the routing scope differs. -If you scaffold without `FM_SECONDMATE_CHARTER`, replace the `{TASK}` placeholder before seeding. -Keep the charter focused on persistent responsibility, available project clones, escalation back to the main firstmate status file, and the idle-by-default contract: reconcile only its own in-flight work and then wait, never self-initiating a survey or audit. -Preserve the requests-from-main-firstmate contract in the charter: marked requests return via status or a doc pointer, while unmarked direct captain messages stay conversational. -Before seeding, launching, recovering, or handing backlog to a secondmate home, load `secondmate-provisioning`. -The status-reporting protocol is intentionally sparse: crewmates append status only for supervisor-actionable phase changes, `needs-decision`/`blocked`/`paused`/`done`/`failed`, or the `resolved` line that closes a previously reported decision or blocker, because every append wakes firstmate. -`bin/fm-classify-lib.sh` owns the keyed open/resolved status contract. -For any generated brief that still contains `{TASK}`, replace it with a clear task description, acceptance criteria, and any constraints or context the crewmate needs before spawning or seeding. -Adjust the other sections only when the task genuinely deviates from the standard ship-a-new-PR shape (e.g. fixing an existing external PR); the scaffold is the contract, not a suggestion. +Load `secondmate-provisioning` before creating or using a charter brief and preserve its idle-by-default and marked-return-channel contracts. +Status appends are sparse supervisor-actionable events, not routine progress; `bin/fm-classify-lib.sh` owns keyed open and resolved semantics. +The scaffold is a safety contract, not a suggestion. ## 12. Self-update -firstmate is its own repo behind the no-mistakes gate, so improvements to `AGENTS.md`, `bin/`, `.agents/skills/`, and public `skills/` reach `main` and then wait for each running firstmate to pull them. -Only `AGENTS.md`, `bin/`, and `.agents/skills/` are a running firstmate instruction surface; public `skills/` is tracked for installers and is not loaded by firstmate. +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 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/`. +It performs guarded fast-forward updates of firstmate and registered secondmate homes, refreshes instructions, and never touches anything under `projects/`. ## 13. Agent-only reference skills -These skills are not captain-invocable; they are conditional operating references you must load at the trigger points below. +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 an actionable diagnostic line (`MISSING:`, `MISSING_MANUAL:`, `BACKEND_INVALID:`, `NEEDS_GH_AUTH`, `TANGLE:`, `CREW_DISPATCH: invalid`, `FLEET_SYNC:`, `PR_CHECK_MIGRATION:`, `SECONDMATE_SYNC:`, `SECONDMATE_LIVENESS:`, `NUDGE_SECONDMATES:`, or `FMX:`); silence and `BOOTSTRAP_INFO:` need 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. -- `stuck-crewmate-recovery` - load after a stale wake, looping pane, repeated confusion, an answered-by-brief question, an unresponsive crewmate, or a failed steer. -- `secondmate-provisioning` - load before creating, seeding, validating, launching, handing backlog to, recovering, pushing inherited config into, or retiring a secondmate home, and before editing `data/secondmates.md`. +- `project-management` - load before adding, creating, removing, or initializing a project. +- `stuck-crewmate-recovery` - load when the session-start digest reports an ordinary direct report's endpoint dead or its metadata has no window, or after a stale wake, looping pane, repeated confusion, an answered-by-brief question, an unresponsive crewmate, or a failed steer. +- `secondmate-provisioning` - load before creating, seeding, validating, launching, handing backlog to, recovering, pushing inherited local material into, or retiring a secondmate home, and before editing `data/secondmates.md`. +- `decision-hold-lifecycle` - load before treating an investigation or visual review as complete, before ending a visual review that exposed a decision, and when recording or routing the captain's answer. - `fmx-respond` - load on an `x-mention ` `check:` wake to handle the mention, on an `x-mode-error ...` `check:` wake to report the X-mode configuration blocker, and on any milestone or terminal wake for an X-mode-linked task before posting its completion follow-up; relevant only when X mode is on. - `firstmate-codexapp` - load before coordinating a visible Codex Desktop thread, evaluating a Codex App backend request, or reconciling Codex Desktop host-tool smoke evidence for Firstmate work. - `firstmate-coding-guidelines` - load before changing firstmate's shared, tracked material, as defined by section 1's list, whether editing directly or briefing a crewmate for a firstmate-repo task. ## 14. X mode -X mode lets a firstmate instance answer public mentions routed through the shared `@myfirstmate` relay, and act on actionable mention requests, in firstmate's own voice, from its live fleet state. -It ships inside this repo for every user but is **inert until opted in**, so a user who never enables it sees zero behavior change. - -**Activation is `.env` presence, not a command.** -Put one value, `FMX_PAIRING_TOKEN`, into a `.env` file at this home's root (`.env` is gitignored). -That token is the whole consent, including standing authorization for normal reversible lifecycle actions from mention requests, and the only required config; the relay derives the tenant from it. -It is not consent for destructive, irreversible, or security-sensitive actions; those still require trusted-channel confirmation first. -`FMX_RELAY_URL` is optional and defaults to `https://myfirstmate.io`; only a developer pointing at a local relay sets it. - -**Mechanism and cadence.** -Bootstrap wires the relay poll automatically and purely additively from `.env` presence; `docs/configuration.md` "X mode (.env)" owns the generated-artifact mechanism, the wire protocol, the poll cadence and its transition handling, and the watcher-backbone non-interference guarantee. -X mode is a reason to keep the watcher armed even with no fleet work, so an X-only user is still served. +X mode ships inert and causes no behavior change until the home opts in by placing `FMX_PAIRING_TOKEN` in its gitignored `.env`. +That token is consent for public replies and normal reversible lifecycle actions from eligible mentions, not authority for destructive, irreversible, or security-sensitive action; those still require trusted-channel confirmation. +`docs/configuration.md` owns activation, generated state, cadence, wire protocol, and opt-out mechanics. -**Answering.** -On an `x-mention ` or `x-mode-error ...` `check:` wake, load `fmx-respond` (section 13). -It owns mention classification, acting on the request, reply composition, voice, thread-splitting, image attachments, dry-run preview, and the completion-follow-up procedure in full, including what an `x-mode-error` wake means instead. -`docs/configuration.md` "X mode (.env)" has the wire-protocol reference. -The one fact that must survive here because it fires on a generic terminal wake, not the mention wake itself: when an X-mode-linked task reaches a terminal state, post its final completion follow-up per section 8's wake-handling step before tearing down. +An X-only home still requires the live supervision cycle so mentions can wake it without fleet work. +On an `x-mention ` or `x-mode-error ...` check wake, load `fmx-respond`, which owns classification, public-safety policy, reply or dismissal, task linking, and follow-ups. +For every X-linked terminal outcome, load that owner and post the final completion follow-up before teardown, regardless of earlier milestone follow-ups. ## Maintaining this file Keep this file for knowledge useful to almost every future agent session in this project. -Do not repeat what the codebase already shows; point to the authoritative file or command instead. +Do not repeat what the codebase already shows; point to the authoritative file, skill, command, or doc. Prefer rewriting or pruning existing entries over appending new ones. -When updating this file, preserve this bar for all agents and keep entries concise. +When updating this file, preserve every safety boundary and keep the always-loaded contract concise. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index a590180db..4e7bd8154 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -62,7 +62,7 @@ A crewmate picking up such a brief should load the skill even if the brief preda When supervising live crewmates, keep firstmate's own long validation or build commands in the background so watcher wakes can still be handled. Crewmate validation follows the installed no-mistakes version's SKILL.md and live `axi` help instead of duplicating gate mechanics in firstmate docs. Firstmate's wrapper still matters: `ask-user` findings route to the captain through firstmate, and crewmates avoid `--yes` because it silently resolves captain-owned decisions without escalation. -Local `.no-mistakes/` state and test evidence stay out of this repo; `.no-mistakes.yaml` keeps evidence in a temp directory and pins the gate's lint and test commands to the same `bin/fm-lint.sh` and bash behavior suite as CI, so the pre-push gate runs the exact checks CI enforces. +Local `.no-mistakes/` state and test evidence stay out of this repo; `.no-mistakes.yaml` keeps evidence in a temp directory and pins the gate's lint and portable behavior commands to the Linux CI jobs, while `.github/workflows/ci.yml` owns additional platform-specific compatibility lanes. That is firstmate-specific; do not commit `.no-mistakes/evidence/` here even when another no-mistakes-managed target project keeps committed PR evidence. Check and test the toolbelt before pushing: diff --git a/README.md b/README.md index b33084744..0d5d22a37 100644 --- a/README.md +++ b/README.md @@ -31,7 +31,7 @@ But the moment you want three project tasks done in parallel - fixes, investigat firstmate flips the model. You talk to a single agent - the first mate - and it runs the crew for you: spawning autonomous agents in a visible session backend, giving each a clean git worktree, supervising them to completion, and handing you finished PRs, approved local merges, or standalone investigation reports. -For larger fleets, you can opt in to persistent secondmates: domain supervisors that are still ordinary direct reports, but run from their own isolated firstmate homes. +For larger fleets, you can opt in to persistent secondmates: second mates that are still ordinary direct reports, but run from their own isolated firstmate homes. firstmate is not a model, not a harness, not a skill, not an MCP server, and not a CLI. firstmate is an agent distro for running a crew of agents. @@ -46,10 +46,10 @@ Launching a supported harness inside it instantiates your first mate - and makes - **Disposable worktrees** - each task runs in a clean [treehouse](https://github.com/kunchenguid/treehouse) git worktree, or an Orca-managed worktree when `backend=orca`, so parallel work on one repo never collides. - **Two task shapes** - ship tasks deliver a change; scout tasks investigate, plan, reproduce, or audit and leave a report. - **Explicit project modes** - each project ships via `no-mistakes`, `direct-PR`, or `local-only`, with an optional `+yolo` autonomy flag. -- **Optional secondmates** - opt in to persistent domain supervisors that run from isolated firstmate homes with their own `FM_HOME`, state, projects, and session lock, supervising project clones or a project-less firstmate-repo domain, kept on the primary firstmate version by guarded local fast-forwards and checked for live agent processes at session start. -- **Event-driven, zero-token supervision** - a bash watcher sleeps on the fleet and wakes the first mate only when something needs you; verified primary harnesses also get a turn-end backstop that blocks or follows up on a blind stop when work is in flight and supervision is not live. +- **Optional secondmates** - opt in to persistent second mates that run from isolated firstmate homes with their own `FM_HOME`, state, projects, and session lock, supervising project clones or a project-less firstmate-repo domain, kept on the primary firstmate version by guarded local fast-forwards and checked for live agent processes at session start. +- **Event-driven, zero-token supervision** - a bash watcher sleeps on the fleet and wakes the first mate only when something needs you; verified primary harnesses also get a turn-end backstop that blocks or follows up on a blind stop when work is under way and supervision is not live. - **Optional X mode** - opt in with one local `.env` token so firstmate can answer your public `@myfirstmate` mentions, act on normal reversible mention requests through the same lifecycle as chat requests, acknowledge spawned work, and post up to three public-safe completion follow-ups within seven days for genuine milestones and the final outcome without changing non-X behavior; dry-run preview records would-be replies and dismissals locally before go-live. -- **Guarded by construction** - the first mate is read-only over your projects outside guarded clone refreshes, safe branch pruning, and approved `local-only` fast-forward merges; crewmates make every project change behind your merge approval. +- **Guarded by construction** - the first mate is read-only over your projects except for the guarded paths authorized by [hard rule 1](AGENTS.md#1-identity-and-prime-directives), with fleet sync's safe branch pruning remaining part of the fleet-sync exception; crewmates make every project change behind the configured merge authority. - **Restart-proof** - all state lives on disk and in the active session backend (tmux by hard default, herdr or cmux when selected or auto-detected, zellij/orca when explicitly selected); kill the session anytime and the next one reconciles, including confirmed-dead secondmate agents, and carries on. Full detail on every feature lives in [docs/architecture.md](docs/architecture.md). @@ -146,12 +146,12 @@ Setup guides for tmux (the default) and every other supported backend (herdr, ze │ ├─ ship: project mode ► PR/local merge ► teardown │ - └─ scout: report at data//report.md ► relay findings ► teardown + └─ scout: report at data//report.md ► decision inventory ► relay findings ► teardown ``` You chat with the first mate. It routes each request to a crewmate in its own session endpoint and git worktree, supervises the fleet with a zero-token event-driven watcher, and brings you finished PRs, approved local merges, or investigation reports. -Optional secondmates extend this to persistent domain supervisors, dispatch profiles let you steer which harness handles which task, and an opt-in X mode lets the same fleet answer public mentions. +Optional secondmates extend this to persistent second mates, dispatch profiles let you steer which harness handles which task, and an opt-in X mode lets the same fleet answer public mentions. `codex-app` is not a runtime backend yet; [docs/codex-app-backend.md](docs/codex-app-backend.md) owns the Codex App boundary. Full architecture - the supervision engine, worktree isolation, secondmates, dispatch profiles, project modes, optional X mode, fleet sync, and self-update - is in [docs/architecture.md](docs/architecture.md). @@ -163,8 +163,8 @@ Claude and grok use the slash form shown here; codex uses the same names with `$ | Skill | What it does | | ------------------ | -------------------------------------------------------------------------------------------------------------------------------------------- | -| `/afk` | Enter away-mode supervision: the sub-supervisor self-handles routine wakes in bash, escalates captain-relevant events and bounded declared-external-wait rechecks as batched digests, and actively alerts if delivery wedges while you step away | -| `/bearings` | Generate a "pick up where I left off" status report from the read-only fleet snapshot - backlog, per-task crew state, open PRs, scout reports, pending decisions, and date-gated queued work - written to a dated file in `data/` and surfaced concisely in chat; read-mostly, mutates no task state | +| `/afk` | Enter away-mode supervision: the sub-supervisor self-handles routine notifications in bash, escalates captain-relevant events and bounded declared-external-wait rechecks as batched digests, and actively alerts if delivery gets stuck while you step away | +| `/bearings` | Generate a standalone current-status report from bounded local fleet and registered-secondmate state, with live PR enrichment only when requested, written to a dated file in `data/` and surfaced concisely in chat; read-mostly, mutates no task state | | `/updatefirstmate` | Self-update the running firstmate and its secondmates to the latest from origin with fast-forward-only pulls, then re-read instructions and nudge secondmates | | `/stow` | Sweep the session for uncaptured durable knowledge, route each finding to its disk home per AGENTS.md, file undone next steps to the backlog, and report what is now safe to reset | @@ -184,7 +184,7 @@ Firstmate's skills live in two separate places with different audiences: - [docs/architecture.md](docs/architecture.md) - how the crew, supervision, worktrees, secondmates, and project modes work. - [docs/configuration.md](docs/configuration.md) - environment variables, `FM_HOME`, runtime backend selection, optional X mode, the files you set, and harness support. -- [docs/wedge-alarm.md](docs/wedge-alarm.md) - configure the active alert for a wedged away-mode escalation delivery. +- [docs/wedge-alarm.md](docs/wedge-alarm.md) - configure the active alert for an away-mode escalation delivery that gets stuck. - [docs/tmux-backend.md](docs/tmux-backend.md) - setup guide for the tmux reference backend: prerequisites, attaching, and watching crew windows. - [docs/herdr-backend.md](docs/herdr-backend.md) - setup guide for the experimental herdr backend, plus its verification notes and known gaps. - [docs/zellij-backend.md](docs/zellij-backend.md) - setup guide for the experimental zellij backend, plus its verification notes and known gaps. @@ -194,7 +194,7 @@ Firstmate's skills live in two separate places with different audiences: - [docs/turnend-guard.md](docs/turnend-guard.md) - the primary session's structural "no turn ends blind" backstop: verified per-harness hook mechanisms, scoping, loop safety, and fail-open tradeoffs. - [docs/supervision-protocols/](docs/supervision-protocols/) - rendered primary-harness watcher protocols for Claude, Codex, OpenCode, Pi, Grok, and unknown harness fallback. - [docs/scripts.md](docs/scripts.md) - the `bin/` toolbelt reference. -- [`AGENTS.md`](AGENTS.md) - the distro's core instruction file and the first mate's full operating manual. +- [`AGENTS.md`](AGENTS.md) - the distro's always-loaded operating contract and routing index for conditional procedures. - [CONTRIBUTING.md](CONTRIBUTING.md) - how to contribute, including the dev/test commands. ## Contributing diff --git a/bin/backends/herdr.sh b/bin/backends/herdr.sh index 7874988b4..4da3ea329 100644 --- a/bin/backends/herdr.sh +++ b/bin/backends/herdr.sh @@ -31,8 +31,8 @@ # # Recovery/orphan discovery (ids may not deterministically match live state # after a server restart in a differently-configured session; see the -# verification doc) uses LABEL matching (fm- tab labels), never trusts a -# stored pane id blindly: fm_backend_herdr_list_live. +# verification doc) uses stable fm- labels plus metadata-backed tab-id +# mapping for human-readable labels: fm_backend_herdr_list_live. # # Requires: herdr (CLI + socket), jq (JSON parsing). Bootstrap detects these # through fm_backend_required_tools only when herdr is the resolved backend; @@ -44,8 +44,8 @@ # never overrides a real invocation. It exists only so this file's own unit # tests, which source it directly without that preamble, resolve to a sane # default (the firstmate repo root - never a secondmate home, so -# fm_backend_herdr_workspace_label falls through to "firstmate" exactly like -# pre-P3 behavior when a test does not care about home-specific labeling). +# fm_backend_herdr_workspace_label falls through to the production primary-home +# label "firstmate-crew" when a test does not care about home-specific labeling). FM_BACKEND_HERDR_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" FM_ROOT="${FM_ROOT_OVERRIDE:-${FM_ROOT:-$FM_BACKEND_HERDR_ROOT}}" FM_HOME="${FM_HOME:-${FM_ROOT_OVERRIDE:-$FM_ROOT}}" @@ -86,8 +86,7 @@ FM_BACKEND_HERDR_SECONDMATE_MARKER=".fm-secondmate-home" # fm_backend_herdr_workspace_label: the per-firstmate-HOME herdr workspace # label (docs/herdr-backend.md "Task container shape"). The PRIMARY home (no -# secondmate marker) resolves to the constant "firstmate", byte-identical to -# every pre-existing task's recorded label - no forced migration. A SECONDMATE +# secondmate marker) resolves to the constant "firstmate-crew". A SECONDMATE # home resolves to "2ndmate-", so its tasks land in their own # workspace, obviously distinguishable from the primary's (and from every # other secondmate's) in herdr's spaces sidebar. Read fresh from FM_HOME on @@ -106,7 +105,7 @@ fm_backend_herdr_workspace_label() { return 0 fi fi - printf 'firstmate' + printf 'firstmate-crew' } # fm_backend_herdr_cli: run `herdr ` scoped to , setting @@ -195,17 +194,18 @@ fm_backend_herdr_server_ensure() { # # uniqueness at all, so this adopts the FIRST matching workspace `jq` returns # (list order, normally creation order/oldest) rather than disambiguating - # identical in spirit to the pre-existing tab duplicate-label check below. -fm_backend_herdr_workspace_find() { # - local session=$1 label list +fm_backend_herdr_workspace_find() { # [preferred_legacy_workspace_id] + local session=$1 preferred_legacy_workspace_id=${2:-} label list label=$(fm_backend_herdr_workspace_label) list=$(fm_backend_herdr_cli "$session" workspace list 2>/dev/null) || return 0 # NOTE: the jq variable is $want, NOT $label - `label` is a jq reserved # keyword (label/break), so declaring a jq variable named "label" is a # compile error that `2>/dev/null` would silently swallow, making this find - # ALWAYS return empty and every spawn mint a fresh "firstmate" workspace + # ALWAYS return empty and every spawn mint a fresh "firstmate-crew" workspace # (the workspace leak). - printf '%s' "$list" | jq -r --arg want "$label" \ - '.result.workspaces[]? | select(.label == $want) | .workspace_id' 2>/dev/null | head -1 + printf '%s' "$list" | jq -r --arg want "$label" --arg legacy "$preferred_legacy_workspace_id" \ + '([.result.workspaces[]? | select($legacy != "" and .workspace_id == $legacy and .label == "firstmate")][0].workspace_id // + [.result.workspaces[]? | select(.label == $want)][0].workspace_id // empty)' 2>/dev/null } # fm_backend_herdr_workspace_prune_seeded_default_tab: close EXACTLY @@ -223,7 +223,7 @@ fm_backend_herdr_workspace_find() { # # had just resolved. Herdr enforces no label uniqueness (docs/herdr-backend.md # "Label collisions") and derives an unlabeled workspace's DISPLAYED label from # its pane cwd's basename, so a captain launching herdr directly inside a -# directory named "firstmate" produces a workspace that looks byte-identical, +# directory named "firstmate-crew" produces a workspace that looks byte-identical, # by label alone, to firstmate's own auto-created container - one tab, label # "1". workspace_find adopted that pre-existing (captain-owned, LIVE) workspace # by the label match, the heuristic matched too, and the very next spawn @@ -303,11 +303,11 @@ fm_backend_herdr_workspace_prune_seeded_default_tab() { # - local session=$1 cwd=$2 wsid out label +fm_backend_herdr_workspace_ensure() { # [preferred_legacy_workspace_id] + local session=$1 cwd=$2 preferred_legacy_workspace_id=${3:-} wsid out label FM_BACKEND_HERDR_WS_ID="" FM_BACKEND_HERDR_WS_SEEDED_TAB_ID="" - wsid=$(fm_backend_herdr_workspace_find "$session") + wsid=$(fm_backend_herdr_workspace_find "$session" "$preferred_legacy_workspace_id") if [ -n "$wsid" ]; then FM_BACKEND_HERDR_WS_ID=$wsid printf '%s' "$wsid" @@ -337,12 +337,16 @@ fm_backend_herdr_workspace_ensure() { # # CONTAINER=${RAW%%$'\t'*}; SEEDED_TAB_ID=${RAW#*$'\t'}. The seeded tab id # must be threaded through to fm_backend_herdr_create_task, which is the only # function allowed to prune it (fm_backend_herdr_workspace_prune_seeded_default_tab). -fm_backend_herdr_container_ensure() { # - local cwd=${1:-$PWD} session label +fm_backend_herdr_container_ensure() { # [owned_legacy_session] [owned_legacy_workspace_id] + local cwd=${1:-$PWD} prior_session=${2:-} prior_workspace_id=${3:-} preferred_legacy_workspace_id='' session label fm_backend_herdr_version_check || return 1 session=$(fm_backend_herdr_session) + if [ -n "$prior_session" ] && [ -n "$prior_workspace_id" ]; then + session=$prior_session + fi fm_backend_herdr_server_ensure "$session" || return 1 - fm_backend_herdr_workspace_ensure "$session" "$cwd" >/dev/null || { label=$(fm_backend_herdr_workspace_label); echo "error: failed to ensure herdr workspace '$label' in session '$session'" >&2; return 1; } + [ "$prior_session" != "$session" ] || preferred_legacy_workspace_id=$prior_workspace_id + fm_backend_herdr_workspace_ensure "$session" "$cwd" "$preferred_legacy_workspace_id" >/dev/null || { label=$(fm_backend_herdr_workspace_label); echo "error: failed to ensure herdr workspace '$label' in session '$session'" >&2; return 1; } if [ -z "$FM_BACKEND_HERDR_WS_ID" ]; then label=$(fm_backend_herdr_workspace_label) echo "error: failed to ensure herdr workspace '$label' in session '$session'" >&2 @@ -493,22 +497,51 @@ fm_backend_herdr_agent_alive() { # # the safety argument). An ADOPTED workspace's caller always passes an empty # 4th arg, so this function never even queries for a prune candidate in that # case. Echoes " " on success. -fm_backend_herdr_create_task() { #