opencode-agent-harness 0.2.0 → 0.3.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,10 @@
1
1
  # Project Rules & Operating Guidelines
2
2
 
3
- The canonical rulebook. The always-loaded summary is `.agents/rules/00-operating.md`.
3
+ The canonical rulebook. It carries the durable **standards**; the always-on digest
4
+ is the root `AGENTS.md`, and the operating mechanics (dispatch economics, bounded
5
+ retries, context budget, capacity guards, session checklist) live in
6
+ `.agents/rules/00-operating.md`. Read both first — this file is the detail of
7
+ record for the rules they point at, not a second copy of either.
4
8
 
5
9
  ## 1. Fact-Based, Zero-Guessing SDLC
6
10
 
@@ -13,7 +17,7 @@ The canonical rulebook. The always-loaded summary is `.agents/rules/00-operating
13
17
  ## 2. Dynamic Data & Business-Logic Integrity
14
18
 
15
19
  - **No Hardcoded Mock Lists**: Never create hardcoded lists (fake records, mock reviews, static fallback arrays) without explicit user approval. Prefer dynamic queries and database-backed settings.
16
- - **Environment data boundary (never leak test data forward)**: three environments — `development` (dirty by design: QA/test data lives here), `uat`, and `production` (both enforced clean). Only code, schema migrations, and idempotent seeds move FORWARD (dev → uat → prod); data never does — no `pg_dump`/restore/copy of one environment's database into another. The canonical registry is `.agents/memory/environments.md`.
20
+ - **Environment data boundary**: three environments — `development` (dirty by design: QA/test data lives here), `uat`, and `production` (both enforced clean). Only code, schema migrations, and idempotent seeds move FORWARD (dev → uat → prod); data never does — no `pg_dump`/restore/copy of one environment's database into another. Registry: `.agents/memory/environments.md`; promotion and QA rules: §7.
17
21
 
18
22
  ## 3. UI, Mobile Ergonomics & RTL Support
19
23
 
@@ -30,19 +34,15 @@ The canonical rulebook. The always-loaded summary is `.agents/rules/00-operating
30
34
  - **Verify Stack Versions First**: Confirm versions against `.agents/memory/stack-versions.md` before writing framework-specific code. Never assume a newer/older convention.
31
35
  - **Stack-Specific Gotchas**: Framework/library gotchas (async route params, strict-typing quirks, ORM generator/config layout, native runtime caveats) live in `.agents/memory/stack-versions.md` — read the relevant section before coding against that layer.
32
36
  - **Privacy & Visibility Tiers**: Enforce the project's tier model (`.agents/memory/domain-map.md` §Visibility tiers) across all data-access endpoints.
33
- - **Environments**: read `.agents/memory/environments.md` for the three environments (dev/uat/prod), their databases, deploy commands, and seed commands. Live/QA tiers target the `development` DB only.
34
-
35
- ## 5. Token Efficiency & Workflow Discipline
36
-
37
- - **When NOT to Plan**: No heavy planning docs for simple fixes, CSS/layout tweaks, or single-file changes — execute directly.
38
- - **Use the dedicated tools, not the shell, for file work**: inspect with `Read` (targeted `offset`/`limit`), `Grep`, and `Glob`; edit with `Edit`/`Write` — never shell `cat`/`ls`/`grep`/`find`/`sed -i` to do what they already do (they ignore the project `.ignore`, return noisy output, and bloat the transcript). Reserve the shell for real commands and pipelines. Carry the working tree with the `shell` tool's `workdir` argument, never a leading `cd <tree> &&` (the context-guard nudges both; it also reroots an exact `cd`).
39
- - **Precise File Inspections**: Search first (`Grep` / `npm run search`), then read targeted line ranges — never whole 800+ line files blind. Batch independent searches/reads in parallel.
40
- - **Don't Re-read Unchanged Files**: Edit files already in context directly. A second read of the same path means the region, not the file — use `offset`/`limit` or `Grep` for the changed lines.
41
- - **Delegate Big Searches**: Use the `explore` subagent for broad multi-file exploration — but bound it first with the `bounded-explore` skill: name the exact paths, one answerable question, and a result budget (≤20 `file:line` pointers + a ≤15-line summary; no whole-file dumps, no transcript replay). An unbounded explore is the most expensive dispatch in the harness (~465K input tokens/call, `0.1.120` recon). A known path or single-symbol lookup is orchestrator work — search/read it inline, don't dispatch.
42
- - **Locations Map first**: before reading an unknown path, check `.agents/memory/locations.md` (the canonical index) or `Glob` — never guess a path (`read` failures on guessed paths are a measured waste).
43
- - **Prefer Memory over Re-derivation**: Persist non-obvious facts to `.agents/memory/`; read the relevant memory files before starting.
44
- - **Run/verify via the `dev-loop` skill**: before running a test tier, single test, seed/reset, the emulator, or the dev server, load the `dev-loop` skill (`skill` tool → `dev-loop`) and read `.agents/memory/dev-loop.md` (project-owned concrete commands, digested by `orient`). It carries the tier map, single-test invocation, `serve.js` lifecycle, `gates`/`where`, and "read the failing gate, don't re-run it blind" — so no session re-derives how to run things.
45
- - **Step Zero — Subagent & Model Routing (non-negotiable)**: Before touching code, satisfy the dispatch gate (`.agents/rules/00-operating.md` §Step Zero). Personas: `planner`, `frontend-engineer`, `mobile-engineer`, `ui-designer`, `qa-architect`, `qa-runner`, `security-engineer`, `product-manager`, `system-architect`, `diagnostics-expert`, `data-engineer`, `devops-engineer`, `handoff`, `features`, `docs`. Dispatch via the `subagent` tool — each runs its own `model:`. Do NOT inline persona-owned work on the main model. Read `.agents/memory/model-routing.md` at session start. Dispatch subagents in parallel only when their work is disjoint (see below).
37
+
38
+ ## 5. Dispatch Standards & Workflow Discipline
39
+
40
+ Operating mechanics live in `.agents/rules/00-operating.md` (§Step Zero,
41
+ §Dispatch economics, §Context budget & lifecycle, §Machine capacity, §Verification
42
+ & retry discipline). This section is the detail of record those point at, plus the
43
+ gotchas that do not belong in a digest.
44
+
45
+ - **Step Zero — subagent & model routing (non-negotiable)**: Dispatch the relevant persona via the `subagent` tool — each runs its own `model:`. Do NOT inline persona-owned work on the main model. Read `.agents/memory/model-routing.md` at session start; trivial or single-surface/single-file changes execute directly (00-operating §Dispatch economics).
46
46
  - **Persona map**:
47
47
  | Work area | Persona |
48
48
  |---|---|
@@ -61,75 +61,25 @@ The canonical rulebook. The always-loaded summary is `.agents/rules/00-operating
61
61
  | Session wrap-up / handoff | `handoff` |
62
62
  | Feature backlog registration + doc-tree scaffolding (registrar only — not authoring) | `features` |
63
63
  | Human-facing docs (README / CHANGELOG / docs / ADRs) | `docs` |
64
- - **Feature docs, not ceremony**: capture a found item as one light row in
65
- the canonical `BACKLOG.md` (repo root). **Update the board with the `backlog_*`
66
- tools (or `node scripts/backlog.js`), never hand-edit `BACKLOG.md`.** `features`
67
- is a registrar only — it
68
- registers rows and scaffolds the `.agents/features/<slug>/` tree, never authors
69
- content. When a feature is picked up, author the doc chain by dispatching each
70
- author persona **directly** — `intent` (product-manager) → `scope`
71
- (system-architect, HIGH-risk only) → `plan` (planner) → `tests` (qa-architect).
72
- For an "investigate + plan" request (no code), dispatch `planner` and/or
73
- `product-manager` directly — never `features`. Match ceremony to blast radius:
74
- trivial → none, low → single `intent.md`, high (auth/DB/API/flow-siblings) →
75
- full chain. Write back first (update the doc before continuing when
76
- implementation invalidates it), archive on ship. Feature docs are durable and
77
- complementary to the per-session
78
- `.agents/qa-plans/<feature-id>.md`/`.agents/handoffs/<feature-id>.md`; the `tests` doc points to the
79
- feature's QA plan, never duplicates it. The moment a session starts dealing
80
- with a backlog item, move its `BACKLOG.md` row `Open` → `In progress` (`backlog_take`, pointing
81
- `Handoff` at the session's handoff file) so active work is visible on the board.
82
- A `Queued` row is a ready-to-pull lane: `backlog queue <id>` allocates an `Open` row
83
- into it, and `/next` (or `backlog next --take`) pulls the top-priority `Queued` row
84
- into `In progress` to start a session (empty queue = stop, never invent work).
85
- - **Product intent is never optional (no silent skip)**: planning is
86
- product-first. `intent.md` must define Actor(s) → Need → Outcome → Acceptance
87
- criteria, and `plan.md` a Value-first sequence + Product concepts applied, read
88
- against `.agents/memory/product-principles.md`. `npm run test:product` fails any
89
- feature doc missing these, or a `plan.md` with no `intent.md` — mirroring the
90
- "QA planning is never optional" ladder: `product-manager`/`planner` →
91
- orchestrator fallback → (never a silent skip).
92
- - **QA planning is never optional (no silent skip)**: every change that touches
93
- code paths MUST get a QA plan before it is verified. The plan is authored by
94
- `qa-architect` (thinker). If `qa-architect` is not dispatched — for ANY reason,
95
- including dispatch failure or simply not invoking it — the **main orchestrator
96
- performs the qa-architect role itself** and writes the same coverage plan into
97
- a per-change file under `.agents/qa-plans/` (one file per change, named by
98
- `BACKLOG.md` ID or slug — never edit another change's plan file). The QA
99
- plan/copy escalation ladder NEVER leaves a code change unplanned: `qa-architect` ->
100
- orchestrator fallback -> (never a silent skip). `npm run test:qa-plan` enforces
101
- that every changed code path has a covering assertion or a waivered reason.
102
- - **Waivers** (the only way to skip a persona): a persona may be skipped only when (a) the change is fully covered by an automated gate on push or in the QA tiers, AND (b) the skip is pre-audited in `.agents/memory/` with a cited pointer. Log every waiver as `waived: <persona>` with `reason: <gate|pointer>`.
103
- - **Dispatch failure ladder & bounded retries** (never silent): **a provider funds/quota error is a STOP, not a failure to work around** — do not retry, do not degrade inline, do not silently skip; announce the failed provider/model + the exact unfinished step, checkpoint, and wait for the user's explicit top-up-complete / continue message before resuming (provider priority: OpenCode Go `opencode-go/*` first, DeepSeek direct `deepseek/*` fallback — the V4 Pro architect tier pins `opencode-go/deepseek-v4-pro#high`, with direct `deepseek/deepseek-v4-pro` as the announced fallback; every fallback announced immediately — see `.agents/memory/model-routing.md`). Otherwise: retry once (resume the same `task_id`); a second retry MUST materially change one of instructions / context / model / decomposition / diagnostics — identical prompt + context + model + failure repeated twice is a loop, so stop and escalate or report instead of repeating. If it still fails, do the work inline and log `degraded: <persona> model: <reason>`; never silently skip.
104
- - **Bound every dispatch (task spec)** — never hand a persona a bare metric ("get under N lines", "type everything"). Each dispatch prompt carries: `Objective` (one deliverable) → `Working tree` (the exact feature-worktree path/branch — or `main` — this task edits; the subagent verifies it before touching a file) → `Owned files` (exact paths) → `Read-only files` → `Shared contracts (owns|consumes)` → `Done = <gate command + observable metric>` → `Out-of-scope`.
105
- - **Parallel = disjoint** — run personas in parallel only when their owned files AND shared contracts are disjoint; otherwise serialize, with the shared-contract owner dispatched first.
106
- - **Orchestrator acceptance gate** — after a persona reports done, re-run the gate yourself (`tsc --noEmit`, `npm run lint:hooks`, `npm run test:quick`) and grep the metric before integrating or committing. A subagent's `Evidence` is a claim, not proof.
107
- - **No suppression shortcuts** — never accept (or produce) file-level `/* eslint-disable */`, `@ts-nocheck`, or `@ts-ignore` to hit a metric. Suppressions are line-level only and each carries a reason — a file-level disable is a rules violation, not a fix.
108
- - **Dispatch-value gate** — the existence of a persona is NEVER itself a reason to dispatch it. Dispatch only when the persona produces a distinct deliverable with clear ownership and a measurable `Done =` gate that the main model cannot cheaply do itself. Reads, `git status`/`diff`, worktree/branch ops, commits, merges, final integration, simple moves/search-replace, collecting outputs, summarizing results, and simple command runs are ORCHESTRATOR work — never a subagent. A dispatch that is only a repository read, a search, a git op, a trivial edit, or context the orchestrator already holds is unnecessary and must be done inline.
109
- - **Complexity threshold → direct execution** — trivial or single-surface/single-file changes (rename, typo, constant, one-line doc, simple CSS, config tweak) bypass planning + fan-out: main model implements → targeted gate → done. The planner may emit `execution_mode: direct` (with a reason) instead of a multi-agent dispatch — planning may REDUCE the number of agents, not just choose which to spawn.
110
- - **Absorb before spawn** — before a new dispatch, ask whether an already-running or just-completed persona can safely absorb the work within its owned scope and contract; extend that dispatch instead of spawning another. Never cross ownership/contract boundaries to save a dispatch.
111
- - **Stuck-agent detection** — stop a persona that repeats the same reads, tool calls, test failures, or rewrites the same region with no new evidence or changed files. Classify the blocker, attempt one targeted recovery, then escalate (if justified) or report the blocker — never burn more turns.
112
- - **Early stop** — a persona terminates as soon as its `Done =` gate passes and its deliverable is verified; it must not keep "improving" past the acceptance bar. Completion is evidence-based (the gate output), never self-reported confidence.
113
- - **Evidence-based escalation** — escalate a persona to the Pro tier only on: repeated failure after materially different fixes, contradictory evidence, cross-module reasoning failure, security-sensitive ambiguity, unresolved concurrency/state issues, or a genuinely-blocking workaround risk. Do NOT escalate on a long answer, technical complexity alone, a request for more context, or uncertainty without evidence. Model tiers: `.agents/memory/model-routing.md`.
114
- - **Compact result propagation** — when one persona's output feeds another, pass the structured `Result`/`Evidence`/`Deferred & risks` summary (or the structured facts: changed files, commands run, test results, contracts changed, blocking issue) — never a full verbose transcript — so later personas consume established facts instead of re-discovering requirements, architecture, or locations.
115
- - **Synchronous Terminal Commands**: Prefer sync one-shot commands (build/test/lint) that return inline, over background servers/watchers. When a tier genuinely needs a live server (runtime/API tiers) — or any long-lived daemon (emulator, Metro, the adb server, a Maestro driver) — start it detached with `node scripts/serve.js start --cmd "<command>" [--url <health url> | --port <n>] [--name <label>]` — it returns immediately and records the PID under `.serve/`. Never background a long-lived process in your own shell (foreground, `&`, `setsid … &`, `Start-Job`, `Start-Process -NoNewWindow`, or any launch that shares the tool's console): the tree stays attached to the tool's console, so the call hangs until you interrupt it. **A `setsid bash -c '… > log 2>&1' &` is NOT detached**: the redirect lands on the *inner* command, so the detached wrapper keeps the tool's stdout/stderr socket open and the call hangs even after its own shell exits — no timeout fires, because the command itself already finished. `serve.js` spawns with `stdio: "ignore"` (POSIX detached session / Windows hidden console) so the tool returns; if you must launch by hand, redirect the wrapper's own fds: `setsid sh -c 'exec <command>' </dev/null >log 2>&1 &`. `serve.js` prints a "launching" line + heartbeats while waiting (a live start is never silent). Poll the health URL/port to know it is up — with the **bounded waiter**, never `sleep`-and-pray: `node scripts/wait-for.js --health <url>` / `--port <n>` (or the `wait` tool) blocks until ready and returns a terminal status on timeout; on a failed start read `.serve/<name>.out.log`; stop with `node scripts/serve.js stop` / `stop-all` when the tier passes — never leave a dev server running (a device/emulator is reused across runs, not stopped between them). Never pipe a `serve` start or a long test run through a buffering filter (`| Select-Object -Last N`, redirect-to-file-then-read) — let it stream, or the run looks frozen and gets aborted mid-flight. If a live-tier call IS interrupted, don't infer the server state from the abort: verify with `node scripts/serve.js list`, `.serve/<name>.out.log`, `adb devices`, and the health URL before continuing. Never kill a process on a port you didn't start (`node scripts/serve.js list` / port owner first) as a "leftover".
116
- - **No Output Bloat**: Never paste large files/diffs into chat; apply edits with the edit tool, never print a code block of a change.
117
- - **Right-Size the QA Tier**: Never run the full regression suite for a CSS/copy tweak.
118
- - **Gate batching**: make a coherent set of related edits, THEN run the gate once — never edit → gate → edit → gate for micro-edits in the same batch. A gate stays mandatory when the dispatch says so, a dependency needs its result, the batch is complete, or the agent is about to report done. If one edit's failure blocks the batch, resolve it first — but do not re-run an unchanged gate as a ritual.
119
- - **Repeated-command / retry-loop detection**: never re-run the same command in the same session with the same state expecting a different result. When a command would repeat (`same_failure_turns` / `identical_tool_calls` / `no_state_change_turns` — thresholds in `.agents/memory/orchestration.md`), stop, change something material (instructions / context / model / decomposition / diagnostics), or report. A gate repeated with `files_changed = 0`, the same command, and the same failure is a retry loop, not a retry.
120
- - **Patch / file-write recovery**: on a failed patch or write, refresh the target file, regenerate a targeted patch, and retry ONCE — never blindly replay the identical patch. Record `patch_failure`/`retry` in the session handoff. On repeated failure, switch editing strategy (smaller patch, different anchor, write full file).
121
- - **Web / network failure handling**: one retry when the failure is transient; then fall back (`webfetch`, repository-local evidence, vendor docs already in context) or report the blocker. Never loop query variations hoping the network changes. Record the failure + fallback in the handoff.
122
- - **Context budget & checkpointing** (see also `.agents/rules/00-operating.md` §Context budget & lifecycle): the main context is a cumulative cost. One bounded orchestration context per work unit; checkpoint compact deterministic state (task/feature/objective/phase, completed + active dispatches, files changed, contracts, known facts, decisions, risks, next_action) into `.agents/handoffs/<feature-id>.md` when approaching the budgets in `.agents/memory/orchestration.md`; resume in a fresh bounded context from the checkpoint, never by replaying the transcript. `checkpoint_write`/`/checkpoint` and `/resume` make it mechanical (`scripts/checkpoint.js`), and `npm run test:prefix` guards the always-loaded prefix against per-run content. Never kill a running tool call — let it finish, then checkpoint/finish — **except a confirmed wedged launch**: the command's own shell has already exited (no child of the agent process) yet a detached descendant still holds the tool's output socket, so the call can never return. Interrupt it, then verify state (`node scripts/serve.js list`, `.serve/<name>.out.log`, `adb devices`, the health URL/port) before continuing; never wait on it indefinitely, and never infer state from the abort. Keep the stable leading context (rules → persona → project rules) byte-stable so it stays cache-friendly.
123
-
124
- - **Machine capacity & heavy tiers (never freeze the box)**: parallel sessions are welcome; **parallel heavy tiers are not**. WSL2 is one Linux VM with no per-agent limits, so an emulator + two agents + `next dev` + a gate exhausts RAM, thrashes swap, and starves the host↔VM relay — freezing every terminal at once (2026-09-29: `memory=10GB`, 4 GB swap full, load 60). The machine-readable envelope (min free RAM, max live serves, max heavy tiers, idle-reap age) lives in `.agents/memory/orchestration.md`; `serve.js start` checks it plus a machine-wide heavy lock and **refuses** a heavy launch that would exceed it (naming what is already up; `--force` overrides), `test:capacity` (`node scripts/qa/check-capacity.js`) reports free RAM/swap/load/live serves and fails when the envelope is already exceeded, and `agent-harness doctor` adds host + `.wslconfig` advice. Classification is by **program** (`scripts/qa/command-classifier.js`): a read-only probe that merely names a device serial (`adb -s emulator-5554 …`) or an artifact path (`~/.maestro/…`) is never heavy, and a single live `--group` (the device tier's emulator + dev server) counts as ONE tier so a heavy one-shot runs alongside it (a second long-lived tier is still refused). Diagnose a failed device step with `node scripts/qa/mobile-e2e/ui-dump.js` (live or from a Maestro `screen-hierarchy` artifact), never a hand-rolled `adb`/`python` probe. Stop a dev server when its tier passes; reuse an emulator within a session but stop it at session end (`node scripts/serve.js stop --name <label>` / `stop-all`; `list` shows ages; `prune [--worktrees]` clears dead records so a stopped emulator is not misreported as live). `serve.js` also **auto-closes** an orphaned/idle serve: `reap` stops a serve whose owning session's lease is gone/stale (or an untagged one past `idle_reap_minutes` with no recent log activity) and reconciles an untracked `agent-serve-*` unit left by a killed session — it runs at every `start` and when the context-guard plugin sees `session.deleted`, so a dev server/emulator is not kept alive and orphaned. `stop` now verifies the teardown and **keeps the record** if the process survives (an unverified stop was how a live unit became invisible to `list`/`stop-all`). The RAM-backed tmpfs cache is RAM too — keep it small (`AGENT_TMPFS_PERCENT=25`) during device tiers. Heavy tiers are capped **by default**: `serve.js start` runs them as a transient `user.slice` cgroup with `MemoryMax` from the envelope (`heavy_mem_max_mb`, default 5 GB; `--mem-max 4G --cpu-max 250%` overrides, `--no-cap` opts out). A heavy **one-shot** (an APK/Gradle build, a heavy test tier) runs capped and synchronously through `node scripts/serve.js run --cmd "<cmd>" [--mem-max 3G]` — never inline uncapped (the 2026-09-30 Gradle freeze); `scripts/qa/mobile-e2e/build-apk.sh` does this automatically. Members of one `serve.js --group` share a single combined `group_mem_max_mb` budget (so the `mobile` emulator + dev server cannot each take the full `heavy_mem_max_mb`). Apply the one-time host/VM tuning with `sudo bash scripts/wsl-tune.sh apply` (sysctls + `user.slice` ceiling + a soft `init.scope` `MemoryHigh` backstop for the cgroup agents actually run in + `.wslconfig`; only `wsl --shutdown` on Windows is manual). Details: `docs/wsl-optimizations.md`, `docs/mobile-testing.md`.
125
- - **MCP servers are context + RAM, so scope them per agent, dev-only.** An MCP tool schema is billed on every request that can see it, and opencode spawns the server outside the `serve.js` capacity envelope. Wire MCP project-side (`opencode.json`): deny the server's tools globally (a `<server>_*` rule in `permissions`) and re-enable only for the persona that needs live external state; point any DB server at the **development** database only (never uat/prod — `.agents/memory/environments.md`). Do not enable GitHub MCP (the most token-heavy, mostly obviated by direct-land). Details, config shape, and the included servers: `docs/mcp-integrations.md`.
64
+ - **Waivers** (the only way to skip a persona): a persona may be skipped only when (a) the change is fully covered by an automated gate on push or in the QA tiers, AND (b) the skip is pre-audited in `.agents/memory/` with a cited pointer. Log every waiver as `waived: <persona>` with `reason: <gate|pointer>`.
65
+ - **Evidence-based escalation**: escalate to the Pro tier only on repeated failure after materially different fixes, contradictory evidence, cross-module reasoning failure, security-sensitive ambiguity, unresolved concurrency/state issues, or a genuinely-blocking workaround risk. Do NOT escalate on a long answer, technical complexity alone, a request for more context, or uncertainty without evidence. Model tiers: `.agents/memory/model-routing.md`.
66
+ - **Dispatch failure ladder**: a provider funds/quota error is a STOP, not a failure to work around — announce the failed provider/model and the exact unfinished step, checkpoint, and wait for the user's explicit top-up-complete message; never retry, degrade inline, or silently skip. Any other failure gets one retry with a materially changed input (instructions / context / model / decomposition / diagnostics); after that, do the work inline and log `degraded: <persona> model: <reason>`. Provider priority and model tiers: `.agents/memory/model-routing.md`; full ladder: 00-operating §Dispatch economics.
67
+ - **No suppression shortcuts**: never accept (or produce) file-level `/* eslint-disable */`, `@ts-nocheck`, or `@ts-ignore` to hit a metric. Suppressions are line-level only and each carries a reason — a file-level disable is a rules violation, not a fix.
68
+ - **No output bloat**: never paste large files/diffs into chat; apply edits with the edit tool, never print a change as a code block.
69
+ - **Repeated-command / retry-loop detection**: never re-run the same command in the same session with the same state expecting a different result. When a command would repeat (`same_failure_turns` / `identical_tool_calls` / `no_state_change_turns` — thresholds in `.agents/memory/orchestration.md`), stop, change something material, or report. A gate repeated with `files_changed = 0`, the same command, and the same failure is a retry loop, not a retry.
70
+ - **Read narrowly**: search first (`Grep`/`Glob`, `npm run search`), then read a targeted `offset`/`limit` range — never read a big file blind. Batch independent reads/searches in parallel; do not re-read a file already in context (use `offset`/`limit` or `Grep` for the changed lines). Tool mechanics: 00-operating §Non-negotiable laws (law 6).
71
+ - **Long-lived processes**: start a dev server, emulator, Metro, or Maestro driver detached through `node scripts/serve.js start --cmd "<command>" [--url <health url> | --port <n>] [--name <label>]`; poll it with `node scripts/wait-for.js` (never `sleep`-and-pray), read `.serve/<name>.out.log` on failure, and `serve.js stop`/`stop-all` when the tier passes. Never background a long-lived process in your own shell — the tree stays attached to the tool's console and the call hangs. A bare `setsid bash -c '… > log 2>&1' &` is NOT detached (the wrapper keeps the tool's socket open); if you must launch by hand, redirect the wrapper's own fds: `setsid sh -c 'exec <command>' </dev/null >log 2>&1 &`. Anti-pattern and recovery: `.agents/skills/mobile-engineer/SKILL.md`, `docs/mobile-testing.md`.
72
+ - **Wedged launch**: never kill a running tool call — let it finish, then checkpoint/finish — except a confirmed wedged launch (the command's shell has exited yet a detached descendant holds the tool's output socket, so the call can never return). Interrupt it, then verify state (`serve.js list`, `.serve/<name>.out.log`, `adb devices`, the health URL/port) before continuing; never wait indefinitely or infer state from the abort.
73
+ - **Capacity classification**: heavy tiers are classified by **program** (`scripts/qa/command-classifier.js`), not by a device serial or artifact path in the arguments; one live `--group` (device tier's emulator + dev server) counts as ONE tier. Diagnose a failed device step with `node scripts/qa/mobile-e2e/ui-dump.js`, never a hand-rolled `adb`/`python` probe. Envelope and guards: 00-operating §Machine capacity; details: `docs/wsl-optimizations.md`.
74
+ - **MCP servers are context + RAM, so scope them per agent, dev-only**: deny the server's tools globally (a `<server>_*` rule in `permissions`) and re-enable only for the persona that needs live external state; point any DB server at the **development** database only. Do not enable GitHub MCP. Details: `docs/mcp-integrations.md`.
75
+ - **Prefer memory over re-derivation**: persist non-obvious facts to `.agents/memory/`, and check `.agents/memory/locations.md` (or `Glob`) before reading an unknown path — never guess a path.
126
76
 
127
77
  ## 6. Smart Tiered Testing & Progression Protocol
128
78
 
129
79
  - Never run heavy regression suites blindly for small changes.
130
- - Split QA personas: `qa-architect` (thinks — inspects the diff, audits gaps, selects the minimal tier, authors progression tests) vs `qa-runner` (does — executes the chosen tier, reports pass/fail verbatim). The thinker never runs; the doer never designs. Because `qa-architect` denies the `shell` action, an architect-authored progression is NOT verifiable until `qa-runner` load-gates it first (`node --check` for `.js` suites; load + ≥ 1 executed assertion for `.ts`) — never let an architect-authored file reach "done" on the strength of a plan alone.
131
- - **Static ≠ Runtime rule**: never declare UI/mobile/API changes verified from static typing alone — execute a real runtime path.
132
- - **Coverage ≠ label rule**: a tier command verifies a change ONLY when its backing suite actually exercises the changed path. A suite that touches unrelated code proves nothing about this change. `npm run test:qa-plan` mechanically asserts every changed code path is covered by the QA plan (or waivered) before verification — and, via `flow-map.md`, that every touched flow's sibling surfaces and declared optional variants are addressed in the plan's audit (the "fix one, fix all" gate: a web-only diff must still say what the mobile twin does).
80
+ - **Split QA personas**: `qa-architect` (thinks — inspects the diff, audits gaps, selects the minimal tier, authors progression tests) vs `qa-runner` (does — executes the chosen tier, reports pass/fail verbatim). The thinker never runs; the doer never designs. Because `qa-architect` denies the `shell` action, an architect-authored progression is NOT verifiable until `qa-runner` load-gates it first (`node --check` for `.js` suites; load + ≥ 1 executed assertion for `.ts`) — never let an architect-authored file reach "done" on the strength of a plan alone.
81
+ - **Static ≠ runtime**: never declare UI/mobile/API changes verified from static typing alone — execute a real runtime path that exercises the MODIFIED code.
82
+ - **Coverage ≠ label**: a tier command verifies a change ONLY when its backing suite actually exercises the changed path. `npm run test:qa-plan` mechanically asserts every changed code path is covered by the QA plan (or waivered) — and, via `flow-map.md`, that every touched flow's sibling surfaces and declared optional variants are addressed in the plan's audit.
133
83
  - **Test quality & economics rule (T1–T10)**: coverage without test quality produces suites that are green, prove little, and cost a lot. Every proposed assertion must pass the architect's 10-point test-design checklist — independent oracle, executed proof (command + executed assertion count ≥ 1), single owner (no duplicate of an existing gate), hermetic isolation, exit contract + wall-clock budget, cheapest tier that still executes it, wired (not orphaned), a `behavior`/`drift-guard`/`constant-pin` label, a negative fixture for guard claims, and bounded fail-fast prerequisites. Mechanically: `npm run test:wiring` fails any `*.test.*` file no package script executes (T7), and `node scripts/qa/check-linger.js -- <tier command>` fails a suite whose process wall-clock grossly exceeds its runner-reported test time (T1/T6/T9). Tag definitions: `.agents/memory/test-design-parameters.md`; checklist: `.agents/skills/qa-architect/SKILL.md`.
134
84
  - **Tiers** (commands are **project-provided** — the target project must define them; the harness ships only its own gates: `test:dispatch`, `test:governance`, `test:qa-plan`, `test:backlog`, `test:product`, `test:docs`, `test:concurrency`, `test:integrate`, `test:quality`, `test:wiring`, `test:linger`, `test:prefix`):
135
85
  | Tier | Scope | Command |
@@ -140,14 +90,10 @@ The canonical rulebook. The always-loaded summary is `.agents/rules/00-operating
140
90
  | 4 | Data ingestion | the project's data E2E script |
141
91
  | 5 | Major release / breaking refactor | `npm run test:verify` |
142
92
  | 6 | Security / deps | `npm run test:security` |
143
- - **Live-server tiers (3+)**: a runtime/API tier that hits real routes needs the
144
- dev server running. Start it detached with `node scripts/serve.js start --cmd "<dev command>" --url <health url>`
145
- and stop it when the tier passes (`node scripts/serve.js stop`) — see §5. Live-tier calls: never pipe a start or the
146
- tier run through a buffering filter (`Select-Object -Last N`) — it looks frozen and invites an abort; if a call IS
147
- interrupted, don't infer state — verify via `node scripts/serve.js list` + `.serve/<name>.out.log` + the health URL.
93
+ - **Live-server tiers (3+)**: a runtime/API tier that hits real routes needs the dev server running; start it detached and stop it when the tier passes (see §5, 00-operating §Machine capacity). Never pipe a live start or tier run through a buffering filter — it looks frozen and invites an abort.
148
94
  - **The expensive device/Maestro tier is NIGHTLY, not part of the day loop.** The day loop lands on cheap gates (`test:quick` / `test:api` / `test:routes` / the project's web E2E); it must NOT boot the emulator or run the Maestro matrix by default. `scripts/nightly.js` (installed as a systemd `--user` timer by `agent-harness install-nightly`) runs the full battery off-hours against a `nightly` worktree fast-forwarded to `origin/main`, then reconciles the board: a failing journey with no row → `backlog add "[nightly:flow=<journey>] …"`; a shipped (archived, pending-validation) row whose journey now passes → `backlog archive <id> --closed "nightly-validated …"`; a still-failing journey → `backlog reopen <id>` (journey-level; one row per broken journey, reopened until green). A device-only path is therefore addressed in the QA plan as `audited: device tier deferred to nightly [nightly:flow=<journey>]` — a valid `audited:`/`waived:` reason, not a silent skip. Run a device tier in-session only when the user explicitly asks. See `docs/nightly-testing.md`.
149
- - **Live QA targets the development environment only**: runtime/API tiers and data-E2E runs execute against the dev database (`DATABASE_URL`). They never touch uat/prod; the forward boundary (`.agents/memory/environments.md`) is enforced at deploy time by `test:data-hygiene -- --env uat|prod`, not by dev-time runs.
150
- - **Progression Workflow**: for new routes/endpoints/states, (1) author a dedicated assertion path, (2) run the targeted progression test, (3) graduate it into the permanent regression suite. A change is NOT verified if the executed tier's backing suite never exercised the modified path — author a progression test for that path first (this is the "GAP" rule).
95
+ - **Live QA targets the development environment only**: runtime/API tiers and data-E2E runs execute against the dev database (`DATABASE_URL`). They never touch uat/prod; the forward boundary (§2, `.agents/memory/environments.md`) is enforced at deploy time by `test:data-hygiene -- --env uat|prod`.
96
+ - **Progression Workflow**: for new routes/endpoints/states, (1) author a dedicated assertion path, (2) run the targeted progression test, (3) graduate it into the permanent regression suite. A change is NOT verified if the executed tier's backing suite never exercised the modified path — author a progression test for that path first (the "GAP" rule).
151
97
 
152
98
  ## 7. Definition of Done & Continuous Backup
153
99
 
@@ -165,40 +111,38 @@ them. Steps 3-7 are the unconditional session close; they are NOT gated by QA.
165
111
  - [ ] No modified file over ~500 lines without extracting components.
166
112
  - [ ] No blanket file-level `eslint-disable`/`@ts-nocheck`/`@ts-ignore` suppressions (line-level only, each with a reason).
167
113
  - [ ] No dead export / oversized file introduced in NEW/GROWN code — `npm run test:quality` green on the diff (rubric: `.agents/memory/quality-parameters.md` P1/P3).
168
- 1. **QA tier** (code changes only) — `qa-architect` inspects the diff, picks the tier BY COVERAGE (not path-label), records the coverage map in a per-change plan under `.agents/qa-plans/` (one file per change — never edit another change's plan), and authors progression tests for any GAP; if `qa-architect` is not dispatched the orchestrator plans in its place. `qa-runner` executes and makes it pass (§6). A change is not verified until `npm run test:qa-plan` passes: every changed code path covered or waivered, **and** every touched flow (`.agents/memory/flow-map.md`) has every sibling surface and declared variant addressed in the plan's `## Parallel-surface & variant audit`, **AND** the executed tier exercised the modified path. The plan also carries `## Test budget` (wall-clock + teardown + tier), `## Oracle & owner` (independent behavior + single owner), and `## Test-design self-check` (T1–T10) — and `npm run test:wiring` is green: an authored test that no package script executes is not coverage (T7), and a suite that passes then idles past its budget is a defect (linger check, T1/T6/T9).
114
+ 1. **QA tier** (code changes only) — `qa-architect` inspects the diff, picks the tier BY COVERAGE (not path-label), records the coverage map in a per-change plan under `.agents/qa-plans/` (one file per change — never edit another change's plan), and authors progression tests for any GAP; if `qa-architect` is not dispatched, the orchestrator plans in its place. `qa-runner` executes and makes it pass (§6). A change is not verified until `npm run test:qa-plan` passes (every changed code path covered or waivered; every touched flow's sibling surfaces and variants addressed in `## Parallel-surface & variant audit`; the executed tier exercised the modified path) and `npm run test:wiring` is green. The plan also carries `## Test budget`, `## Oracle & owner`, and `## Test-design self-check` (T1–T10).
169
115
  2. **Security check** (code changes only) — apply `security-engineer` when the change touches data/auth/input/secrets/deps.
170
- 3. **Backlog write-back** (always) — move every task this session shipped from `In progress` to `Archive (shipped · done)` in `BACKLOG.md` (`backlog_archive`, with date/commit), then stage it explicitly: `git add BACKLOG.md` (it starts untracked — `git commit -am` / `git commit` without `add` will NOT pick it up). The board syncs across sessions only through git, so this delta is committed with the code, never left uncommitted. (At session start, the inverse: move the picked-up row `Open` → `In progress` via `backlog_take`, pointing `Handoff` at the session's `.agents/handoffs/<id>.md`, so the board always shows what is actively being worked.)
171
- 4. **Docs write-back** (always, on land) — dispatch the `docs` persona to keep human-facing docs in sync with this session's shipped change: append a `CHANGELOG.md` line that cites the commit short hash (`git rev-parse --short HEAD`), and update `README.md` / `docs/**` / ADRs when the change adds or renames a subsystem, flow, public API, or hard-to-reverse decision (`.agents/skills/docs/SKILL.md`). `npm run test:docs` fails on any shipped commit with no changelog entry, so a docs-only `chore`/`docs` commit is not enough — the changelog delta ships in the same commit as the code. Right-size: a copy/CSS tweak needs at most a changelog line.
172
- 5. **Commit** (always) — concise `feat:` / `fix:` / `refactor:` message, including the `BACKLOG.md` and `CHANGELOG.md` deltas.
173
- 6. **Land the branch** (always) — `npm run finalize -- --feature <id>` (or `npm run ship`) integrates on `origin/main`, runs the branch gates (and, when no pre-push hook is installed, the harness process gates itself, so a missing hook cannot skip them), and lands the branch with a **direct fast-forward push to `main`**. There is no PR, no landing label, and no merge train. **Integrate early first**: `git fetch origin && git rebase origin/main` (ship does this), so conflicts surface before the gates. **Ship then waits for CI**: it polls the CI workflow on the landed SHA and exits 0 only once CI is green (or non-zero with the blocker). A concurrent landing (another session pushed first) is resolved automatically by re-fetch + rebase + retry. `--no-ci-wait` stops after landing but is a **pause, not a completion** — the CI run is the completion contract. A session that stops before the branch is landed (and CI confirmed) is not done. `agent-harness doctor --target .` reports whether the cycle is ready.
174
- 7. **Deploy to UAT** (CI-owned) — the `CI` workflow completing successfully on `main` triggers `.github/workflows/deploy-uat.yml`, which deploys the landed SHA to `uat` as a prebuilt artifact (`vercel build` → `vercel deploy --prebuilt`), then runs `prisma migrate deploy` over the direct URL (F-136) + idempotent seed + alias/parity/smoke verification + `npm run test:data-hygiene -- --env uat`. Do NOT run a local `deploy:uat` in the normal flow — it is the emergency path (CI sets `DEPLOY_CI=1`; a local run must not). Production is human-gated and NOT part of a normal task. Never forward dev data — code + schema + idempotent seeds only (`.agents/memory/environments.md`).
116
+ 3. **Backlog write-back** (always) — move every task this session shipped from `In progress` to `Archive (shipped · done)` (`backlog_archive`, with date/commit), then stage it explicitly: `git add BACKLOG.md` (a bare `git commit -am` will not pick up an untracked board). At session start, the inverse: `backlog_take` moves the picked-up row `Open` → `In progress` with `Handoff` pointing at the session's handoff file. The board syncs across sessions only through git, so these deltas ship with the code.
117
+ 4. **Docs write-back** (always, on land) — keep `CHANGELOG.md` current with a line citing the commit short hash (`git rev-parse --short HEAD`), and update `README.md` / `docs/**` / ADRs when the change adds or renames a subsystem, flow, public API, or hard-to-reverse decision (`.agents/skills/docs/SKILL.md`). `npm run test:docs` fails a shipped commit with no changelog entry, so the changelog delta ships in the same commit as the code. A copy/CSS tweak needs at most a changelog line.
118
+ 5. **Commit** (always) — concise `feat:` / `fix:` / `refactor:` message including the `BACKLOG.md` and `CHANGELOG.md` deltas.
119
+ 6. **Land the branch** (always) — `npm run finalize -- --feature <id>` (or `npm run ship`) integrates on `origin/main`, runs the branch gates (including the harness process gates when no pre-push hook is installed), lands with a **direct fast-forward push to `main`**, then waits for **CI to go green on the landed SHA**. There is no PR, no landing label, and no merge train; a concurrent landing is resolved by re-fetch + rebase + retry. `--no-ci-wait` is a pause, not a completion.
120
+ 7. **Deploy to UAT** (CI-owned) — the `CI` workflow completing on `main` triggers `.github/workflows/deploy-uat.yml`, which deploys the landed SHA to `uat` as a prebuilt artifact, runs `prisma migrate deploy` + idempotent seed + alias/parity/smoke verification, then `npm run test:data-hygiene -- --env uat`. A local `deploy:uat` is the emergency path only; production is human-gated. Never forward dev data — code + schema + idempotent seeds only (§2, `.agents/memory/environments.md`).
175
121
  - **Mechanical floor**: a pre-push hook should run `npm run test:quick` (project-provided; the harness does not install git hooks).
176
- - **Concurrency isolation (never let a concurrent session's WIP block yours)**: the board + a shared working tree means one session's half-done files (e.g. a page referencing translation keys not yet in `messages/*.json`) can fail *another* session's push for no fault of its own. The harness ships mechanical counters:
177
- - `test:concurrency` (`node scripts/qa/check-concurrency.js`) fails a push when the board shows 2+ `In progress` rows while the working tree has uncommitted changes — the collision is *provable*, so it fails fast instead of surfacing as a random `check-translations`/`tsc` error. Declare each row's owned files (`.agents/memory/owned-files.md`, via `backlog owns <id> --files ...`) and the gate fails *exactly* when a dirty file is owned by two In-progress rows (or a tree mixes two sessions' WIP), instead of on every "2+ In progress + dirty" tree. It also reports the live *primary sessions* sharing a checkout via `.serve/sessions/` leases (written/heartbeat by the context-guard plugin): liveness requires the pid **and** a matching process birth token (`bootId` + `/proc` starttime) **and** a fresh heartbeat, so a recycled pid or a session closed without a `session.deleted` event can't linger. That report is **advisory** — two live sessions on a clean tree never fail a push (a clean tree has no WIP to collide over), so a legitimate finalization can no longer be stranded behind an unrelated live session; only the provable dirty-tree contention above fails. `node scripts/qa/check-concurrency.js --prune` clears dead/recycled/stale leases.
178
- - **Isolate per feature** with `backlog worktree <id>` (or the `backlog_worktree` tool): it creates a `git worktree` + branch for the feature and records the path in the row's `Handoff` cell. Run it from the **main** tree before starting ANY feature — `main` stays board + shippable code only, every feature works in its own checkout, and another session's WIP can't leak into your gates. When a human starts the worktree at a terminal, `--open` launches the agent CLI *inside* it, so the session's lease + gates are scoped to the worktree instead of `main`. Worktrees live in a hidden sibling container (`<repo>/../.worktrees/<repo>/<id>`), and `backlog archive <id>` removes a shipped feature's worktree + merged branch — so the parent folder stays clean and a session leaves nothing hanging after it closes. If a session ended without archiving, `backlog worktree-prune` converges the set: it removes clean worktrees whose branch is already merged and keeps anything unmerged or dirty.
179
- - **Row-aware merge driver**: `.gitattributes` routes `BACKLOG.md` through `scripts/qa/merge-backlog.js`, so two sessions editing *disjoint* rows merge by ID instead of conflicting (`agent-harness init/update` wires the driver).
180
- - **Ordering**: a row's `Depends on` cell (`backlog depends <id> --on <ids>`) makes ordering machine-readable — `/next`/`take`/`worktree` skip or refuse a row whose dependencies aren't archived.
181
- - **Snapshot gating**: `node scripts/qa/run-clean.js -- npm run test:quick` runs a project gate against the *committed* state (stashes + restores any dirty files), so a pre-push gate verifies *your* committed work, not the tree. Prefer this wrapper in the pre-push hook for tree-scoped gates.
122
+ - **Concurrency isolation (never let a concurrent session's WIP block yours)**:
123
+ - `test:concurrency` (`node scripts/qa/check-concurrency.js`) fails a push when the board shows 2+ `In progress` rows while the working tree has uncommitted changes. Declare each row's owned files (`backlog owns <id> --files ...`; `.agents/memory/owned-files.md`) so it fails *exactly* when a dirty file is owned by two In-progress rows. The live-session lease report (`.serve/sessions/`, written by the context-guard plugin) is **advisory** — a clean tree never fails a push. `--prune` clears dead/recycled/stale leases.
124
+ - **Isolate per feature** with `backlog worktree <id>` (or the `backlog_worktree` tool) from the **main** tree before starting ANY feature: it creates a `git worktree` + branch and records the path in the row's `Handoff`. `main` stays board + shippable code only. `--open` launches the agent CLI inside the worktree. Worktrees live under `<repo>/../.worktrees/<repo>/<id>`; `backlog archive <id>` removes a shipped feature's worktree + merged branch, and `backlog worktree-prune` converges the set (removes clean merged worktrees, keeps unmerged or dirty ones).
125
+ - **Row-aware merge driver**: `.gitattributes` routes `BACKLOG.md` through `scripts/qa/merge-backlog.js`, so two sessions editing *disjoint* rows merge by ID instead of conflicting (`agent-harness init/update` wires the driver). A row's `Depends on` cell (`backlog depends <id> --on <ids>`) makes ordering machine-readable — `/next`/`take`/`worktree` skip or refuse a row whose dependencies aren't archived.
126
+ - **Snapshot gating**: `node scripts/qa/run-clean.js -- npm run test:quick` runs a project gate against the *committed* state (stashes + restores dirty files), so a pre-push gate verifies your committed work, not the tree.
182
127
  - **Lean permissions**: grant only the narrowest `git`/`gh` action needed; escalate only after a command has actually failed.
183
128
  - Git may not be on PATH in the default shell — use the full path (`.agents/memory/locations.md`).
184
129
 
185
130
  ## 8. Session & Traceability Discipline
186
131
 
187
- - **One session = one coherent task**; keep a short checklist as the single source of truth. Use opencode's todo panel (`todowrite`) for multi-step work: create it early, exactly ONE item `in_progress`, mark each item `completed` right after its own verification step, and close every finished item before checkpointing or reporting. A single-step fix needs no list; a stale panel is worse than none.
188
132
  - **Harness-update awareness**: `npx opencode-agent-harness update` auto-commits the harness files it changes as `chore(harness): opencode-agent-harness <old> -> <new>`. If you see such a commit (or modified `.agents/**`, `scripts/qa/**`, `AGENTS.md`, `opencode.json` you didn't touch), do NOT treat it as unexplained — run `git log -1 --stat` / `git show` to see exactly which harness files changed and why, then read the rulebook. Never guess at the cause.
189
- - **Harness-owned files are fixed upstream, never in this project**: `scripts/qa/**`, `scripts/*.js`, `.opencode/**`, `.agents/skills/**`, `.agents/rules/**`, `.agents/AGENTS.md`, `AGENTS.md`, and opencode config are copied from the harness `templates/` on every `update`. If a feature needs one changed (a gate or QA-script fix), make the change in the harness repo's `templates/` (with a drift-guard test when it is a gate/QA script), release it, and re-run `update` here — do NOT hand-edit the deployed copy. **Route (F-12):** you cannot edit the harness from a session rooted in *this* project — the main-checkout guard blocks a code edit aimed at another checkout, and worktree isolation is per-repo. Make the fix from a session rooted in the harness checkout itself (`opencode` in `~/develop/agent-harness`), edit `templates/` there, release, then `agent-harness update .`; record the harness gap on the board so it is not lost when the project session ends. As of harness `0.1.100` an `update` **fails closed** on a hand-edited harness file (naming it and pointing at `templates/`); `--accept-harness` overwrites deliberately after a backup and rolls the clobber back if `test:quick` goes red. The F-289 incident was exactly this: a project-side `board-sync.js` fix was silently reverted by the next deploy.
133
+ - **Harness-owned files are fixed upstream, never in this project**: `scripts/qa/**`, `scripts/*.js`, `.opencode/**`, `.agents/skills/**`, `.agents/rules/**`, `.agents/AGENTS.md`, `AGENTS.md`, and opencode config are copied from the harness `templates/` on every `update`. Make a needed change in the harness repo's `templates/` (with a drift-guard test when it is a gate/QA script), release it, and re-run `update` — do NOT hand-edit the deployed copy. **Route (F-12):** a session rooted in this project cannot edit another checkout (the main-checkout guard blocks it, and worktree isolation is per-repo); make the fix from a session rooted in the harness checkout itself, then `agent-harness update .`, and record the harness gap on the board. Since harness `0.1.100`, `update` **fails closed** on a hand-edited harness file; `--accept-harness` overwrites deliberately after a backup and rolls back if `test:quick` goes red (the F-289 incident: a project-side `board-sync.js` fix silently reverted by the next deploy).
190
134
  - **Planned vs. Shipped**: at session end, record a "planned → shipped → deferred" delta so aspirational docs are never mistaken for reality. Always verify against live code and schema.
191
- - **Value-first completion report**: close a session by telling the user, in plain language, **what value shipped** (what they now get / what changed for them) and the main **how** — before any file/test/technical detail. The same summary is recorded durably in the handoff's `## Value shipped` + `## How` sections.
192
- - **Explain at the reader's level**: all user-facing prose (progress updates, plans, explanations, and completion reports) is written for someone who knows the product but not the codebase. Lead with the observable behavior and the affected part of the system in plain terms; treat a code identifier (`syncCatalog()`, `OrderRouter`, a table/route name) as supporting detail — introduced only when precision needs it, and glossed on first use. This is a *level*, not abstraction: stay concrete and technical (no theory or business-speak), but never make an internal symbol the subject of a sentence. Example — low-level: "`dedupeById()` early-returns when `seen.has(id)`."; reader-level: "the importer now skips duplicates it has already seen, so a book no longer appears twice."
193
- - **Dispatch Log (mandatory)**: every wrap-up opens with `subagent → model → shipped/deferred`. An empty log is non-compliant.
135
+ - **Value-first completion report**: close a session by telling the user, in plain language, **what value shipped** and the main **how**, before any file/test/technical detail; record the same summary in the handoff's `## Value shipped` + `## How`. Full guidance: root `AGENTS.md` and 00-operating §Step Zero.
136
+ - **Explain at the reader's level**: write for someone who knows the product but not the codebase. Lead with observable behavior in plain terms; name a code identifier only when precision needs it, and gloss it on first use. Stay concrete and technical — never make an internal symbol the subject of a sentence. Full guidance: 00-operating §Step Zero.
137
+ - **Dispatch Log (mandatory)**: every wrap-up opens with `subagent → model → shipped/deferred`; a log with 5+ entries also needs a `## Fan-out justification`. An empty log is non-compliant.
194
138
  - **Structured session telemetry**: every handoff records, when known and never fabricated:
195
139
  - `session` — the primary orchestrator session id from the `session_info` tool. This is the join key for `npm run report -- --cost`, which attaches observed provider cost/tokens/turns (primary + subagent sessions) to the feature.
196
140
  - `work_type` — one of `feature | bugfix | investigation | architecture | planning | qa | security | maintenance | process | conversation | other`.
197
141
  - `outcome` — one of `shipped | resolved | deferred | investigation-complete | abandoned | superseded | conversation-only`.
198
142
  - `termination_reason` — why the session ended (e.g. `gate-pass`, `checkpoint`, `blocked`, `escalated`, `abandoned`).
199
- - `model_escalation_evidence` — when the primary session ran on an `escalation_models:` model (`.agents/memory/model-routing.md`), the reason (or `none` when no escalation happened). `npm run report -- --cost` flags a pro-model primary session with no recorded evidence.
200
- - Retries/escalations with `attempt` numbers and reasons (see §5 bounded retries).
143
+ - `model_escalation_evidence` — when the primary session ran on an `escalation_models:` model (`.agents/memory/model-routing.md`), the reason (or `none`). `npm run report -- --cost` flags a pro-model primary session with no recorded evidence.
144
+ - Retries/escalations with `attempt` numbers and reasons.
201
145
  - `null` / `unknown` when the runtime cannot know a value — never infer exact token/cost numbers from character counts, and never invent values.
202
146
  These feed the deterministic `npm run report` (agent-report) so feature economics are measurable without reading transcripts; `--cost` reads only observed provider data from the opencode store.
203
- - **Persist Continuity**: use the `handoff` skill to write your session's file under `.agents/handoffs/` (one per session — never edit another session's). Project history lives in `.agents/memory/history.md`; stack facts in `.agents/memory/stack-versions.md`.
147
+ - **Persist continuity & checkpoint**: use the `handoff` skill to write your session's file under `.agents/handoffs/` (one per session — never edit another session's). At the `orchestration.md` budget bands, write the bounded state block with `checkpoint_write`/`/checkpoint` and resume with `/resume` — never replay the transcript. Project history lives in `.agents/memory/history.md`; stack facts in `.agents/memory/stack-versions.md`.
204
148
  - **Pointers Map Hygiene**: record every created/discovered/changed important location (session archives, scratch scripts, logs, docs, DB targets, env files) in `.agents/memory/locations.md`.
@@ -1,6 +1,6 @@
1
1
  # {{PROJECT_NAME}} Operating Rules (summary)
2
2
 
3
- Always in effect. Full detail lives in `.agents/AGENTS.md`; read it before non-trivial work.
3
+ Always in effect. Operating mechanics live here; the durable standards — and the detail of record for the rules below — live in `.agents/AGENTS.md`. Read it before non-trivial work.
4
4
 
5
5
  ## Step Zero — subagent dispatch gate (non-negotiable)
6
6
 
@@ -6,7 +6,7 @@ It governs: Step Zero subagent dispatch, zero-speculation debugging, data integr
6
6
 
7
7
  - **Dispatch personas** via the `subagent` tool (see `.agents/rules/00-operating.md` §Step Zero); consult the relevant `.agents/skills/<persona>/SKILL.md`.
8
8
  - **Todo list discipline**: for multi-step work keep opencode's right-hand todo panel current with the `todowrite` tool — create it before the second/third step, exactly ONE item `in_progress`, mark each item `completed` immediately after its own verification step, and close every finished item before you checkpoint/report. A single-step/single-file fix needs no list; a panel that lags the work is worse than none. The context-guard nudges "create / sync / close" mechanically when it falls behind.
9
- - **Features**: capture a found item as one light row on the canonical board (the shared board service, ADR 0001) — `features` is a registrar only. Update the board with the `backlog_*` tools (or `node scripts/backlog.js`); never hand-edit a board file. When a feature is picked up, author the per-feature doc chain (intent/scope/plan/tests) by dispatching each author persona **directly** (`product-manager` → intent, `system-architect` → scope, `planner` → plan, `qa-architect` → tests) — never via `features`. For an "investigate + plan" request, dispatch `planner` / `product-manager` directly.
9
+ - **Features**: capture a found item as one light row on the canonical board (the shared board service, ADR 0001) — `features` is a registrar only. Update the board with the `backlog_*` tools (or `node scripts/backlog.js`); never hand-edit a board file. The board is **project-scoped**: a write from a feature worktree lands on the shared service or main board, never a worktree copy. When a feature is picked up, author the per-feature doc chain (intent/scope/plan/tests) by dispatching each author persona **directly** (`product-manager` → intent, `system-architect` → scope, `planner` → plan, `qa-architect` → tests) — never via `features`. For an "investigate + plan" request, dispatch `planner` / `product-manager` directly.
10
10
  - **Provider funds stop**: a provider funds/quota error (`insufficient balance`/`funds`/`credits`, usage limit, 402) pauses the session — announce the failed provider/model and the exact unfinished step, checkpoint, and wait for the user's explicit top-up-complete message; never retry, degrade inline, or silently skip. Model priority is OpenCode Go (`opencode-go/*`) first, DeepSeek direct (`deepseek/*`) fallback — the V4 Pro architect tier (`planner`/`qa-architect`/`system-architect`/`security-engineer`) pins `opencode-go/deepseek-v4-pro#high`, with direct `deepseek/deepseek-v4-pro` as the announced fallback — announce every fallback immediately.
11
11
  - **Product-first planning**: planning is value-led, not tech-led — define the user (actor/need/outcome/acceptance) before code, sequence work value-first against `.agents/memory/product-principles.md`, and let `npm run test:product` enforce it.
12
12
  - **Report value-first, at the reader's level**: completion reports open with what value shipped (plain language — what the user now gets, why it matters) + the main "how", before any file/test/commit detail. Write for someone who knows the product, not the code: lead with behavior in plain terms and use a code identifier only when precision needs it (glossed on first use); stay concrete and technical, never abstract.
@@ -52,9 +52,11 @@
52
52
  * the working board against `origin/main` row-aware (an archived-upstream row
53
53
  * wins over a stale local take; local-only rows survive), apply the change, then
54
54
  * commit + fast-forward push it. Main never carries an uncommitted board copy,
55
- * so it cannot resurrect a shipped row. A linked feature worktree writes its own
56
- * snapshot and ships it with the branch. `--no-fetch` skips the network step for
57
- * offline use; an offline edit is committed locally and published by `sync`.
55
+ * so it cannot resurrect a shipped row. A linked feature worktree is CODE
56
+ * isolation only: every board read/write resolves to the MAIN checkout's board
57
+ * (or the shared service), so a row filed mid-feature can never land in a
58
+ * private worktree copy. `--no-fetch` skips the network step for offline use; an
59
+ * offline edit is committed locally and published by `sync`.
58
60
  * `--defer` (used by the superadmin API) commits the board locally but skips the
59
61
  * network push entirely, so a request path never blocks on fetch/push; a later
60
62
  * `sync` (the API schedules it in the background) converges and publishes.
@@ -126,6 +128,43 @@ function findRoot(startDir) {
126
128
  return null;
127
129
  }
128
130
 
131
+ /* The canonical board root. ADR 0001 gives the board ONE home per project: the
132
+ * shared service when declared, else the MAIN checkout's BACKLOG.md. A linked
133
+ * feature worktree isolates CODE, not the board — resolving board reads and
134
+ * writes to the main checkout means a row filed mid-feature (e.g. a security
135
+ * finding) can never land in a private worktree copy that main's board never
136
+ * sees.
137
+ *
138
+ * `archive` is the deliberate exception in legacy file mode when the row is
139
+ * CLAIMED in this checkout (In progress): `finalize` archives its own taken row
140
+ * from inside the feature worktree BEFORE the branch lands, and that archive
141
+ * must travel with the branch so a failed ship does not mark unlanded work done
142
+ * on main. A row that is merely inherited from main's snapshot (Open/Queued/
143
+ * Frozen) was never claimed here, so archiving it locally would strand the
144
+ * archive in a private copy the branch may never ship — that archive resolves to
145
+ * main instead (F-007: archiving the subsumed F-003 Open row from a finished
146
+ * feature worktree wrote that worktree's copy and had to be redone by hand). A
147
+ * row absent from the local snapshot is likewise a mid-branch capture, so it
148
+ * also resolves to main. In service mode there is no checkout-local board, so
149
+ * the service is used either way.
150
+ *
151
+ * An explicit `--root` names a local checkout for migration/tests and is left
152
+ * untouched (F-333/F-338). */
153
+ function resolveBoardRoot(root, opts) {
154
+ if (!root || (opts && opts.explicitRoot)) return root;
155
+ if (opts && opts.cmd === "archive" && opts.id) {
156
+ try {
157
+ const found = findRow(readBacklog(root).lines, opts.id);
158
+ if (found && found.key === "inprogress") return root;
159
+ } catch {
160
+ /* no local board (service-backed) — resolve the canonical root below */
161
+ }
162
+ }
163
+ const main = boardSync.mainWorktreeRoot(root);
164
+ if (main && path.resolve(main) !== path.resolve(root) && fs.existsSync(main)) return path.resolve(main);
165
+ return root;
166
+ }
167
+
129
168
  function readBacklog(root) {
130
169
  const p = path.join(root, "BACKLOG.md");
131
170
  if (!fs.existsSync(p)) {
@@ -1159,8 +1198,9 @@ function cmdOwns(state, argv) {
1159
1198
  * later local/auto-commit on that base diverges from origin. The shared
1160
1199
  * board-sync module owns the git-facing logic (classify dirty files, row-aware
1161
1200
  * reconcile, converge, publish); these thin wrappers root it in backlog.js.
1162
- * Only the MAIN checkout is authoritative — a linked feature worktree carries a
1163
- * snapshot that ship's rebase converges, so syncing is a no-op there. */
1201
+ * Only the MAIN checkout is authoritative. `resolveBoardRoot` reroutes a linked
1202
+ * feature worktree's board commands there before this code runs, so a worktree
1203
+ * never carries a mutable board snapshot. */
1164
1204
  function gitCmd(root, args, opts) {
1165
1205
  return boardSync.gitCmd(root, args, opts);
1166
1206
  }
@@ -1668,6 +1708,29 @@ function runService(root, cmd, argv) {
1668
1708
  return true;
1669
1709
  }
1670
1710
 
1711
+ /* One honest note for a publish that did not land. The old fixed "remote is
1712
+ * unreachable" wording hid local git failures for weeks: a `git add` rejected on
1713
+ * a gitignored tracked path read as a network problem (F-004). Name the git
1714
+ * operation, carry its first error line, and say whether the change is committed
1715
+ * (durable, just unpublished) or only in the working tree. */
1716
+ function publishFailureNote(pub) {
1717
+ const detail = pub.detail ? `: ${pub.detail}` : "";
1718
+ switch (pub.reason) {
1719
+ case "deferred":
1720
+ return "committed locally; a background sync will publish it";
1721
+ case "add-failed":
1722
+ return `not committed \u2014 git add failed${detail}`;
1723
+ case "commit-failed":
1724
+ return `not committed \u2014 git commit failed${detail}`;
1725
+ case "replay-conflict":
1726
+ return `committed locally but the board replay conflicted${detail} \u2014 run git pull --rebase, then \`node scripts/backlog.js sync\``;
1727
+ default:
1728
+ return pub.committed
1729
+ ? `committed locally; push failed (${pub.reason})${detail} \u2014 run \`node scripts/backlog.js sync\` when the remote is reachable`
1730
+ : `not published (${pub.reason})${detail} \u2014 run \`node scripts/backlog.js sync\``;
1731
+ }
1732
+ }
1733
+
1671
1734
  function main() {
1672
1735
  const raw = process.argv.slice(2);
1673
1736
  const cmd = raw[0];
@@ -1678,12 +1741,15 @@ function main() {
1678
1741
  const args = parseArgs(raw.slice(1));
1679
1742
 
1680
1743
  const explicitRoot = Boolean(args.root);
1681
- const root = explicitRoot ? path.resolve(args.root) : findRoot(process.cwd());
1682
- if (!root) {
1683
- console.error("backlog: BACKLOG.md not found (repo root).");
1744
+ const foundRoot = explicitRoot ? path.resolve(args.root) : findRoot(process.cwd());
1745
+ if (!foundRoot) {
1746
+ console.error("backlog: no board root found (no BACKLOG.md/.harness.json up the tree).");
1684
1747
  process.exitCode = 1;
1685
1748
  return;
1686
1749
  }
1750
+ // Board ops from a linked worktree always act on the project's canonical board
1751
+ // (the shared service or the main checkout), never the worktree's own copy.
1752
+ const root = resolveBoardRoot(foundRoot, { explicitRoot, cmd, id: args._[0] });
1687
1753
 
1688
1754
  // Service backend (ADR 0001): the board lives in the external service, so
1689
1755
  // every read/write goes over HTTP. Git-side effects (worktree add/remove) stay
@@ -1752,7 +1818,7 @@ function main() {
1752
1818
  } else {
1753
1819
  const pub = boardSync.publishBoard(root, upstream, "chore(board): sync local rows");
1754
1820
  if (pub.published && pub.committed) notes.push(`published board to ${upstream}`);
1755
- else if (!pub.published) notes.push("committed locally; run `node scripts/backlog.js sync` when the remote is reachable");
1821
+ else if (!pub.published) notes.push(publishFailureNote(pub));
1756
1822
  }
1757
1823
  for (const note of notes) console.log(`board: ${note}`);
1758
1824
  return;
@@ -1801,13 +1867,7 @@ function main() {
1801
1867
  if (canonical && upstream && publishMessage && canPublish) {
1802
1868
  const pub = boardSync.publishBoard(root, upstream, publishMessage, { deferPush: defer });
1803
1869
  if (pub.published && pub.committed) notes.push(`published board to ${upstream}`);
1804
- else if (!pub.published) {
1805
- notes.push(
1806
- defer
1807
- ? "committed locally; a background sync will publish it"
1808
- : "committed locally; run `node scripts/backlog.js sync` when the remote is reachable"
1809
- );
1810
- }
1870
+ else if (!pub.published) notes.push(publishFailureNote(pub));
1811
1871
  } else if (canonical && upstream && publishMessage && !canPublish) {
1812
1872
  notes.push(`not published (main is diverged) — resolve with git pull --rebase, then \`node scripts/backlog.js sync\``);
1813
1873
  }
@@ -135,6 +135,13 @@ write_unit() {
135
135
  echo "WorkingDirectory=$dir"
136
136
  [ -f "$SERVICE_ENV_FILE" ] && echo "EnvironmentFile=$SERVICE_ENV_FILE"
137
137
  echo "Environment=NODE_ENV=production"
138
+ # `next`'s shebang is `#!/usr/bin/env node`, and systemd --user's default
139
+ # PATH omits user-level Node installs (nvm/volta/~/.local/bin), so the unit
140
+ # restart-loops with `env: 'node': No such file or directory` (exit 127).
141
+ # Pin the directory of the node that generated this unit.
142
+ local node_dir
143
+ node_dir="$(dirname "$(command -v node 2>/dev/null || printf '%s' /usr/bin/node)")"
144
+ echo "Environment=PATH=$node_dir:/usr/local/bin:/usr/bin:/bin"
138
145
  # Best-effort gate: wait (bounded, ~60s) for the DB port before the app
139
146
  # boots. Uses bash (the `/dev/tcp` redirect is a bash feature).
140
147
  echo "ExecStartPre=-/bin/bash -c 'for i in \$(seq 1 30); do (exec 3<>/dev/tcp/127.0.0.1/5432) 2>/dev/null && exit 0; sleep 2; done; exit 0'"