opencode-agent-harness 0.0.0-stage → 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.
Files changed (171) hide show
  1. package/CHANGELOG.md +217 -0
  2. package/LICENSE +21 -0
  3. package/README.md +636 -2
  4. package/bin/agent-harness.js +3182 -0
  5. package/contrib/global-plugins/README.md +49 -0
  6. package/contrib/global-plugins/harness-freshness.ts +355 -0
  7. package/package.json +86 -4
  8. package/templates/.agents/AGENTS.md +148 -0
  9. package/templates/.agents/features/INDEX.md +10 -0
  10. package/templates/.agents/handoffs/README.md +87 -0
  11. package/templates/.agents/memory/dev-loop.md +59 -0
  12. package/templates/.agents/memory/domain-map.md +29 -0
  13. package/templates/.agents/memory/environments.md +35 -0
  14. package/templates/.agents/memory/flow-map.md +23 -0
  15. package/templates/.agents/memory/history.md +7 -0
  16. package/templates/.agents/memory/locations.md +14 -0
  17. package/templates/.agents/memory/model-routing.md +261 -0
  18. package/templates/.agents/memory/orchestration.md +183 -0
  19. package/templates/.agents/memory/owned-files.md +19 -0
  20. package/templates/.agents/memory/product-principles.md +37 -0
  21. package/templates/.agents/memory/quality-parameters.md +37 -0
  22. package/templates/.agents/memory/stack-versions.md +35 -0
  23. package/templates/.agents/memory/test-design-parameters.md +36 -0
  24. package/templates/.agents/nightly.json +17 -0
  25. package/templates/.agents/qa-plans/README.md +70 -0
  26. package/templates/.agents/qa-runs/README.md +21 -0
  27. package/templates/.agents/reviews/README.md +47 -0
  28. package/templates/.agents/rules/00-operating.md +199 -0
  29. package/templates/.agents/skills/data-engineer/SKILL.md +31 -0
  30. package/templates/.agents/skills/devops-engineer/SKILL.md +50 -0
  31. package/templates/.agents/skills/diagnostics-expert/SKILL.md +44 -0
  32. package/templates/.agents/skills/docs/SKILL.md +140 -0
  33. package/templates/.agents/skills/features/SKILL.md +187 -0
  34. package/templates/.agents/skills/frontend-engineer/SKILL.md +81 -0
  35. package/templates/.agents/skills/handoff/SKILL.md +85 -0
  36. package/templates/.agents/skills/mobile-engineer/SKILL.md +101 -0
  37. package/templates/.agents/skills/planner/SKILL.md +112 -0
  38. package/templates/.agents/skills/product-manager/SKILL.md +115 -0
  39. package/templates/.agents/skills/qa-architect/SKILL.md +224 -0
  40. package/templates/.agents/skills/qa-runner/SKILL.md +64 -0
  41. package/templates/.agents/skills/security-engineer/SKILL.md +53 -0
  42. package/templates/.agents/skills/system-architect/SKILL.md +42 -0
  43. package/templates/.agents/skills/ui-designer/SKILL.md +71 -0
  44. package/templates/.github/workflows/ci.yml +148 -0
  45. package/templates/.github/workflows/deploy-uat.yml +95 -0
  46. package/templates/.github/workflows/nightly.yml +83 -0
  47. package/templates/.github/workflows/uat-health.yml +41 -0
  48. package/templates/.husky/pre-push +23 -0
  49. package/templates/.ignore +28 -0
  50. package/templates/.opencode/agents/data-engineer.md +37 -0
  51. package/templates/.opencode/agents/devops-engineer.md +37 -0
  52. package/templates/.opencode/agents/diagnostics-expert.md +37 -0
  53. package/templates/.opencode/agents/docs.md +37 -0
  54. package/templates/.opencode/agents/features.md +21 -0
  55. package/templates/.opencode/agents/frontend-engineer.md +37 -0
  56. package/templates/.opencode/agents/handoff.md +21 -0
  57. package/templates/.opencode/agents/mobile-engineer.md +37 -0
  58. package/templates/.opencode/agents/planner.md +34 -0
  59. package/templates/.opencode/agents/product-manager.md +29 -0
  60. package/templates/.opencode/agents/qa-architect.md +27 -0
  61. package/templates/.opencode/agents/qa-runner.md +17 -0
  62. package/templates/.opencode/agents/security-engineer.md +37 -0
  63. package/templates/.opencode/agents/system-architect.md +37 -0
  64. package/templates/.opencode/agents/ui-designer.md +37 -0
  65. package/templates/.opencode/commands/board.md +15 -0
  66. package/templates/.opencode/commands/checkpoint.md +25 -0
  67. package/templates/.opencode/commands/feature.md +56 -0
  68. package/templates/.opencode/commands/finish.md +36 -0
  69. package/templates/.opencode/commands/next.md +49 -0
  70. package/templates/.opencode/commands/report.md +55 -0
  71. package/templates/.opencode/commands/resume.md +39 -0
  72. package/templates/.opencode/commands/switch-model.md +34 -0
  73. package/templates/.opencode/commands/tidy.md +49 -0
  74. package/templates/.opencode/plugins/backlog-notify.ts +57 -0
  75. package/templates/.opencode/plugins/backlog.ts +272 -0
  76. package/templates/.opencode/plugins/checkpoint.ts +160 -0
  77. package/templates/.opencode/plugins/context-guard.ts +1164 -0
  78. package/templates/.opencode/plugins/diff.ts +85 -0
  79. package/templates/.opencode/plugins/gates.ts +71 -0
  80. package/templates/.opencode/plugins/job-notify.ts +241 -0
  81. package/templates/.opencode/plugins/orient.ts +67 -0
  82. package/templates/.opencode/plugins/session.ts +89 -0
  83. package/templates/.opencode/plugins/wait.ts +101 -0
  84. package/templates/.opencode/plugins/where.ts +70 -0
  85. package/templates/.opencode/skills/bounded-explore/SKILL.md +38 -0
  86. package/templates/.opencode/skills/dev-loop/SKILL.md +87 -0
  87. package/templates/.vercelignore +16 -0
  88. package/templates/AGENTS.md +27 -0
  89. package/templates/BACKLOG.md +95 -0
  90. package/templates/docs/ci-cd-pipeline.md +81 -0
  91. package/templates/docs/gates.md +128 -0
  92. package/templates/docs/mcp-integrations.md +97 -0
  93. package/templates/docs/mobile-testing.md +555 -0
  94. package/templates/docs/nightly-testing.md +106 -0
  95. package/templates/docs/wsl-optimizations.md +290 -0
  96. package/templates/opencode.json +188 -0
  97. package/templates/scripts/agent-report.js +541 -0
  98. package/templates/scripts/agent-search.sh +117 -0
  99. package/templates/scripts/backlog.js +1924 -0
  100. package/templates/scripts/board-service.sh +214 -0
  101. package/templates/scripts/checkpoint.js +290 -0
  102. package/templates/scripts/finalize.js +416 -0
  103. package/templates/scripts/nightly.js +913 -0
  104. package/templates/scripts/orient.js +514 -0
  105. package/templates/scripts/qa/board-client.js +323 -0
  106. package/templates/scripts/qa/board-lib.js +96 -0
  107. package/templates/scripts/qa/board-sync.js +499 -0
  108. package/templates/scripts/qa/capacity-lib.js +916 -0
  109. package/templates/scripts/qa/check-backlog.js +434 -0
  110. package/templates/scripts/qa/check-capacity.js +85 -0
  111. package/templates/scripts/qa/check-ci-policy.js +164 -0
  112. package/templates/scripts/qa/check-concurrency.js +344 -0
  113. package/templates/scripts/qa/check-dispatch-config.js +296 -0
  114. package/templates/scripts/qa/check-docs.js +288 -0
  115. package/templates/scripts/qa/check-integrate.js +98 -0
  116. package/templates/scripts/qa/check-linger.js +160 -0
  117. package/templates/scripts/qa/check-prefix-stability.js +187 -0
  118. package/templates/scripts/qa/check-product.js +177 -0
  119. package/templates/scripts/qa/check-qa-plan.js +378 -0
  120. package/templates/scripts/qa/check-qa-scripts.js +85 -0
  121. package/templates/scripts/qa/check-quality.js +249 -0
  122. package/templates/scripts/qa/check-test-wiring.js +253 -0
  123. package/templates/scripts/qa/check-worktrees.js +93 -0
  124. package/templates/scripts/qa/ci-triage.js +346 -0
  125. package/templates/scripts/qa/ci-usage-lib.js +185 -0
  126. package/templates/scripts/qa/ci-wait-lib.js +294 -0
  127. package/templates/scripts/qa/command-classifier.js +552 -0
  128. package/templates/scripts/qa/context-guard-core.js +1618 -0
  129. package/templates/scripts/qa/diff.js +174 -0
  130. package/templates/scripts/qa/feature-scaffold.js +224 -0
  131. package/templates/scripts/qa/fixtures/backlog.md +104 -0
  132. package/templates/scripts/qa/governance.js +174 -0
  133. package/templates/scripts/qa/hash-file.js +32 -0
  134. package/templates/scripts/qa/lease-lib.js +263 -0
  135. package/templates/scripts/qa/merge-backlog.js +324 -0
  136. package/templates/scripts/qa/mobile-e2e/analyze-timings.js +300 -0
  137. package/templates/scripts/qa/mobile-e2e/apk-cache.js +420 -0
  138. package/templates/scripts/qa/mobile-e2e/backend-build-cache.js +203 -0
  139. package/templates/scripts/qa/mobile-e2e/boot-emulator.sh +432 -0
  140. package/templates/scripts/qa/mobile-e2e/build-apk.sh +210 -0
  141. package/templates/scripts/qa/mobile-e2e/check-flows.js +568 -0
  142. package/templates/scripts/qa/mobile-e2e/config.yaml +18 -0
  143. package/templates/scripts/qa/mobile-e2e/device-down.sh +88 -0
  144. package/templates/scripts/qa/mobile-e2e/device-up.sh +258 -0
  145. package/templates/scripts/qa/mobile-e2e/ios-simulator-down.sh +72 -0
  146. package/templates/scripts/qa/mobile-e2e/ios-simulator-up.sh +153 -0
  147. package/templates/scripts/qa/mobile-e2e/job-events.js +181 -0
  148. package/templates/scripts/qa/mobile-e2e/prewarm.sh +56 -0
  149. package/templates/scripts/qa/mobile-e2e/run-detached.sh +222 -0
  150. package/templates/scripts/qa/mobile-e2e/run-maestro.js +1543 -0
  151. package/templates/scripts/qa/mobile-e2e/ui-dump.js +327 -0
  152. package/templates/scripts/qa/models.allowlist.txt +32 -0
  153. package/templates/scripts/qa/provider-stats.js +878 -0
  154. package/templates/scripts/qa/run-clean.js +83 -0
  155. package/templates/scripts/qa/run-gates.js +213 -0
  156. package/templates/scripts/qa/run-loop.js +220 -0
  157. package/templates/scripts/qa/session-recon.js +512 -0
  158. package/templates/scripts/qa/store-lib.js +324 -0
  159. package/templates/scripts/qa/tool-lib.js +134 -0
  160. package/templates/scripts/qa/where.js +214 -0
  161. package/templates/scripts/qa/worktree-hygiene.js +217 -0
  162. package/templates/scripts/qa/wslconfig-merge.js +157 -0
  163. package/templates/scripts/serve.js +1328 -0
  164. package/templates/scripts/setup-nightly.sh +185 -0
  165. package/templates/scripts/setup-tmpfs.sh +374 -0
  166. package/templates/scripts/ship.js +586 -0
  167. package/templates/scripts/switch-reasoning-model.ps1 +101 -0
  168. package/templates/scripts/switch-reasoning-model.sh +104 -0
  169. package/templates/scripts/wait-for.js +342 -0
  170. package/templates/scripts/wsl-gpu.sh +180 -0
  171. package/templates/scripts/wsl-tune.sh +319 -0
@@ -0,0 +1,1924 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ /*
4
+ * backlog — deterministic BACKLOG.md editor (no LLM).
5
+ *
6
+ * The canonical task list is `BACKLOG.md` at the repo root. This script reads
7
+ * and mutates it directly, so humans and agents can accumulate / review /
8
+ * delegate work without a model round-trip. It is the single implementation
9
+ * behind the opencode custom tools (`.opencode/plugins/backlog.ts`) and the human
10
+ * CLI (`npm run backlog -- <cmd>`).
11
+ *
12
+ * Commands:
13
+ * list [--all] show active rows (In progress + Open)
14
+ * add <task> [--p P1..P4] [--evidence x] [--id F-xxx] [--depends-on ids]
15
+ * take <id> [--handoff path] Open/Queued -> In progress (pick it up)
16
+ * queue <id> Open -> Queued (allocate to a worker)
17
+ * unqueue <id> Queued -> Open (return an allocated row
18
+ * to the triage pool)
19
+ * next [--take] [--handoff path] pick the top unblocked Queued row
20
+ * archive <id> [--closed note] -> Archive (shipped · done)
21
+ * freeze <id> [--why x] [--reopen x] -> Frozen (parked)
22
+ * depends <id> --on <ids|?> set a row's "Depends on" cell (Open/Queued)
23
+ * owns <id> --files "glob, glob" record the files/globs a row owns
24
+ * worktree <id> [--branch b] [--dir d] [--handoff path] [--no-fetch] [--open]
25
+ * create a git worktree + branch for <id>
26
+ * and record it in the row's Handoff cell.
27
+ * Branches from the current upstream
28
+ * (origin/main), not a stale local HEAD.
29
+ * Default location: <repo>/../.worktrees/<repo>/<id>
30
+ * (a single container sibling, so one worktree
31
+ * per feature never pollutes the parent folder).
32
+ * --open launches the agent CLI in the new
33
+ * worktree after the board is written (so
34
+ * the session's lease + gates scope there).
35
+ *
36
+ * Every mutation writes well-formed rows that `npm run test:backlog` accepts:
37
+ * priority P1..P4, non-empty evidence/handoff/reopen, unique IDs, and
38
+ * `Depends on` cells that reference existing rows.
39
+ *
40
+ * `worktree` is the harness's isolation primitive: concurrent sessions should
41
+ * each claim a separate `git worktree` + branch so one session's uncommitted
42
+ * work can never leak into another's pre-push gate (`test:concurrency` fails a
43
+ * push when that collision is provable). Run it from the MAIN tree — or with
44
+ * `--open`, which also launches the agent CLI in the new worktree so the session
45
+ * is root-scoped there and never writes a `main` lease. `archive` reverses it: a
46
+ * shipped feature's worktree + merged branch are removed, so per-feature
47
+ * checkouts never pile up after sessions close.
48
+ *
49
+ * Because a feature's commits reach `origin/main` from its own worktree, the
50
+ * MAIN checkout's board can lag origin until it is pulled. Every mutating command
51
+ * in the MAIN checkout is therefore a transaction (`qa/board-sync.js`): reconcile
52
+ * the working board against `origin/main` row-aware (an archived-upstream row
53
+ * wins over a stale local take; local-only rows survive), apply the change, then
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 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`.
60
+ * `--defer` (used by the superadmin API) commits the board locally but skips the
61
+ * network push entirely, so a request path never blocks on fetch/push; a later
62
+ * `sync` (the API schedules it in the background) converges and publishes.
63
+ */
64
+ const fs = require("fs");
65
+ const path = require("path");
66
+ const { spawnSync } = require("child_process");
67
+ const { splitCells, isSep, formatRow, findCycle } = require("./qa/board-lib.js");
68
+ const leases = require("./qa/lease-lib.js");
69
+ const boardSync = require("./qa/board-sync.js");
70
+ const boardClient = require("./qa/board-client.js");
71
+
72
+ const PRIORITIES = { P1: 0, P2: 1, P3: 2, P4: 3 };
73
+
74
+ const SECTIONS = {
75
+ active: { heading: "## Active / next" },
76
+ epics: { heading: "## Epics", header: ["Key", "Label", "Goal"] },
77
+ inprogress: { heading: "## In progress", header: ["ID", "Epic", "Task", "Handoff"] },
78
+ queued: { heading: "## Queued", header: ["ID", "P", "Epic", "Task", "Evidence", "Depends on"] },
79
+ open: { heading: "## Open", header: ["ID", "P", "Epic", "Task", "Evidence", "Depends on"] },
80
+ frozen: { heading: "## Frozen", header: ["ID", "Epic", "Task", "Why frozen / reopen when"] },
81
+ archive: { heading: "## Archive (shipped · done)", header: ["ID", "Epic", "Task", "Closed"] },
82
+ };
83
+
84
+ // ---------------------------------------------------------------- helpers
85
+
86
+ function normalizeHeading(text) {
87
+ return text.replace(/^#+\s*/, "").replace(/\s+/g, " ").trim().toLowerCase();
88
+ }
89
+
90
+ /* Map a raw heading to its canonical short key (tolerates spacing/variant). */
91
+ function canonKey(heading) {
92
+ const h = normalizeHeading(heading);
93
+ if (h === "open") return "open";
94
+ if (h === "queued") return "queued";
95
+ if (h === "in progress") return "inprogress";
96
+ if (h === "frozen") return "frozen";
97
+ if (h === "active / next") return "active";
98
+ if (h === "epics") return "epics";
99
+ if (h.startsWith("archive")) return "archive";
100
+ return null;
101
+ }
102
+
103
+ /* Walk up from `startDir` to the project root. ADR 0001: the board no longer
104
+ * lives in a BACKLOG.md, so when the service is configured the root is the
105
+ * nearest directory with a `.harness.json` (or, failing that, the git
106
+ * toplevel); the legacy file board still anchors on BACKLOG.md. */
107
+ function findRoot(startDir) {
108
+ let dir = path.resolve(startDir || process.cwd());
109
+ for (;;) {
110
+ if (fs.existsSync(path.join(dir, "BACKLOG.md"))) return dir;
111
+ const parent = path.dirname(dir);
112
+ if (parent === dir) break;
113
+ dir = parent;
114
+ }
115
+ // No BACKLOG.md anywhere up the tree — resolve a service-backed root.
116
+ dir = path.resolve(startDir || process.cwd());
117
+ for (;;) {
118
+ if (fs.existsSync(path.join(dir, ".harness.json"))) return dir;
119
+ const parent = path.dirname(dir);
120
+ if (parent === dir) break;
121
+ dir = parent;
122
+ }
123
+ const top = require("child_process").spawnSync("git", ["rev-parse", "--show-toplevel"], {
124
+ cwd: path.resolve(startDir || process.cwd()),
125
+ encoding: "utf8",
126
+ });
127
+ if (top.status === 0 && (top.stdout || "").trim()) return (top.stdout || "").trim();
128
+ return null;
129
+ }
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
+
168
+ function readBacklog(root) {
169
+ const p = path.join(root, "BACKLOG.md");
170
+ if (!fs.existsSync(p)) {
171
+ throw new Error("BACKLOG.md not found (repo root) — run `npx opencode-agent-harness init` first.");
172
+ }
173
+ const src = fs.readFileSync(p, "utf8");
174
+ const eol = src.includes("\r\n") ? "\r\n" : "\n";
175
+ return { p, eol, lines: src.split(/\r?\n/) };
176
+ }
177
+
178
+ /* Serialize the in-memory board back to disk. `readBacklog` splits on newlines,
179
+ * so a source that ended in a newline carries a trailing "" element and
180
+ * join(eol) already emits that final newline. Appending eol unconditionally
181
+ * (the old `join(eol) + eol`) added one blank line at EOF on every mutation. */
182
+ function serializeBacklog(state) {
183
+ const body = state.lines.join(state.eol);
184
+ return state.lines[state.lines.length - 1] === "" ? body : body + state.eol;
185
+ }
186
+
187
+ /* Locate a section (## heading) by its normalized key. */
188
+ function findSection(lines, key) {
189
+ for (let i = 0; i < lines.length; i++) {
190
+ const m = lines[i].match(/^#{2,3}\s+(.*)$/);
191
+ if (m && canonKey(m[1]) === key) {
192
+ let end = lines.length;
193
+ for (let j = i + 1; j < lines.length; j++) {
194
+ if (/^#{2,3}\s/.test(lines[j])) {
195
+ end = j;
196
+ break;
197
+ }
198
+ }
199
+ return { headingIdx: i, endIdx: end };
200
+ }
201
+ }
202
+ return null;
203
+ }
204
+
205
+ /* Find the markdown table block (header / separator / data rows) in a section. */
206
+ function tableBlock(lines, headingIdx, endIdx) {
207
+ let headerIdx = -1;
208
+ let sepIdx = -1;
209
+ let dataStart = -1;
210
+ let dataEnd = -1;
211
+ for (let i = headingIdx + 1; i < endIdx; i++) {
212
+ if (!/^\s*\|.*\|\s*$/.test(lines[i])) continue;
213
+ if (headerIdx === -1) {
214
+ headerIdx = i;
215
+ continue;
216
+ }
217
+ if (sepIdx === -1) {
218
+ if (isSep(splitCells(lines[i].slice(1, -1)))) {
219
+ sepIdx = i;
220
+ dataStart = i + 1;
221
+ dataEnd = i;
222
+ } else {
223
+ dataEnd = i;
224
+ }
225
+ continue;
226
+ }
227
+ dataEnd = i;
228
+ }
229
+ return { headerIdx, sepIdx, dataStart, dataEnd };
230
+ }
231
+
232
+ /* Non-empty data rows (cell arrays) in a section's table. */
233
+ function dataRows(lines, block) {
234
+ if (block.sepIdx === -1) return [];
235
+ const rows = [];
236
+ for (let i = block.dataStart; i <= block.dataEnd; i++) {
237
+ const cells = splitCells(lines[i].slice(1, -1));
238
+ if (cells.every((c) => c.trim() === "")) continue;
239
+ rows.push({ idx: i, cells });
240
+ }
241
+ return rows;
242
+ }
243
+
244
+ function getRows(lines, key) {
245
+ const s = findSection(lines, key);
246
+ if (!s) return [];
247
+ return dataRows(lines, tableBlock(lines, s.headingIdx, s.endIdx));
248
+ }
249
+
250
+ function requireSection(lines, key) {
251
+ const s = findSection(lines, key);
252
+ if (!s) {
253
+ throw new Error(`BACKLOG.md is missing the "${SECTIONS[key].heading}" section — restore it from the template.`);
254
+ }
255
+ return s;
256
+ }
257
+
258
+ /* Canonical header / separator lines for a section's table. */
259
+ function headerLine(key) {
260
+ return "| " + SECTIONS[key].header.join(" | ") + " |";
261
+ }
262
+ function sepLine(key) {
263
+ return "|" + SECTIONS[key].header.map(() => "---").join("|") + "|";
264
+ }
265
+
266
+ /* Replace a section's table (header + separator + data rows) with the canonical
267
+ * header and `newCellsList`, preserving the section's prose. Short cells are
268
+ * padded to the section's column count so a legacy row (e.g. an Open row written
269
+ * before the `Depends on` column existed) normalizes to the current schema. */
270
+ function setRows(lines, key, newCellsList) {
271
+ const s = requireSection(lines, key);
272
+ const block = tableBlock(lines, s.headingIdx, s.endIdx);
273
+ const out = lines.slice();
274
+ const width = SECTIONS[key].header.length;
275
+ const dataLines = newCellsList.map((cells) => {
276
+ const padded = cells.slice();
277
+ while (padded.length < width) padded.push("?");
278
+ return formatRow(padded.slice(0, width));
279
+ });
280
+ if (block.headerIdx === -1) {
281
+ const insertAt = s.headingIdx + 1;
282
+ out.splice(insertAt, 0, headerLine(key), sepLine(key), ...dataLines);
283
+ return out;
284
+ }
285
+ const start = block.headerIdx;
286
+ const end = block.dataEnd >= block.dataStart ? block.dataEnd : block.sepIdx;
287
+ out.splice(start, end - start + 1, headerLine(key), sepLine(key), ...dataLines);
288
+ return out;
289
+ }
290
+
291
+ function nextId(lines) {
292
+ let max = 0;
293
+ for (const key of ["open", "queued", "inprogress", "frozen", "archive"]) {
294
+ for (const r of getRows(lines, key)) {
295
+ const m = /^(?:F|T)-(\d+)$/i.exec((r.cells[0] || "").trim());
296
+ if (m) max = Math.max(max, parseInt(m[1], 10));
297
+ }
298
+ }
299
+ return "F-" + String(max + 1).padStart(3, "0");
300
+ }
301
+
302
+ function getAllIds(lines) {
303
+ const ids = new Set();
304
+ for (const key of ["open", "queued", "inprogress", "frozen", "archive"]) {
305
+ for (const r of getRows(lines, key)) if (r.cells[0]) ids.add(r.cells[0]);
306
+ }
307
+ return ids;
308
+ }
309
+
310
+ function priorityRank(p) {
311
+ return Object.prototype.hasOwnProperty.call(PRIORITIES, p) ? PRIORITIES[p] : 4;
312
+ }
313
+
314
+ /* Insert an open row in priority order (P1 -> P4, unknown last). */
315
+ function insertOpen(rows, newRow) {
316
+ const newRank = priorityRank(newRow[1]);
317
+ const out = rows.slice();
318
+ let idx = out.length;
319
+ for (let i = 0; i < out.length; i++) {
320
+ if (priorityRank(out[i][1] || "?") > newRank) {
321
+ idx = i;
322
+ break;
323
+ }
324
+ }
325
+ out.splice(idx, 0, newRow);
326
+ return out;
327
+ }
328
+
329
+ function findRow(lines, id) {
330
+ for (const key of ["open", "queued", "inprogress", "frozen", "archive"]) {
331
+ for (const r of getRows(lines, key)) {
332
+ if ((r.cells[0] || "").trim() === id) return { key, cells: r.cells };
333
+ }
334
+ }
335
+ return null;
336
+ }
337
+
338
+ // ---------------------------------------------------------------- locking
339
+ /* The board write path (take / next --take / queue / archive / worktree / ...)
340
+ * is a read-modify-write of BACKLOG.md. Two concurrent sessions could otherwise
341
+ * both read the same Queued row and both claim it. `withLock` serializes that
342
+ * write path across processes via an exclusive `.backlog.lock` DIRECTORY:
343
+ * `fs.mkdirSync(lockPath)` is atomic and the directory's existence *is* the
344
+ * lock, so there is no `open(O_CREAT|O_EXCL)`→`write` window in which a waiter
345
+ * can read an empty lock and mistake it for stale. (The old file lock did
346
+ * exactly that: it read `""`, `pidAlive(NaN)` was false, and it unlinked a live
347
+ * lock under contention — losing rows and assigning duplicate IDs.)
348
+ *
349
+ * The holder's PID is published inside `<lockPath>/pid` via temp-file + rename
350
+ * (atomic), so a waiter never reads a partial pid. A missing/unparseable PID
351
+ * means the creator is mid-setup, so the lock is treated as HELD, never stale;
352
+ * it is broken only when a valid, positive PID is provably dead — never by age
353
+ * alone, since a slow `git worktree add` under the lock must not be mistaken
354
+ * for a stale lock. */
355
+ const LOCK_RETRY_MS = 25;
356
+ const LOCK_TIMEOUT_MS = 15000;
357
+ const LOCK_PID_FILE = "pid";
358
+
359
+ function sleep(ms) {
360
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
361
+ }
362
+
363
+ function pidAlive(pid) {
364
+ if (!Number.isFinite(pid) || pid <= 0) return false;
365
+ try {
366
+ process.kill(pid, 0);
367
+ return true;
368
+ } catch (e) {
369
+ return e.code === "EPERM"; // exists but not signalable — still alive
370
+ }
371
+ }
372
+
373
+ function breakLock(lockPath) {
374
+ try {
375
+ fs.rmSync(lockPath, { recursive: true, force: true });
376
+ } catch {
377
+ /* vanished — retry */
378
+ }
379
+ }
380
+
381
+ function withLock(root, fn) {
382
+ const lockPath = path.join(root, ".backlog.lock");
383
+ const pidPath = path.join(lockPath, LOCK_PID_FILE);
384
+ const deadline = Date.now() + LOCK_TIMEOUT_MS;
385
+ let acquired = false;
386
+ while (!acquired) {
387
+ try {
388
+ fs.mkdirSync(lockPath);
389
+ acquired = true;
390
+ } catch (e) {
391
+ if (e.code !== "EEXIST") throw e;
392
+ let holderPid = NaN;
393
+ try {
394
+ holderPid = parseInt(fs.readFileSync(pidPath, "utf8"), 10);
395
+ } catch {
396
+ /* pid not published yet (creator mid-setup) — held, never stale */
397
+ }
398
+ if (Number.isFinite(holderPid) && holderPid > 0 && !pidAlive(holderPid)) {
399
+ breakLock(lockPath);
400
+ continue;
401
+ }
402
+ if (Date.now() > deadline) {
403
+ throw new Error("backlog: timed out waiting for the board lock (another session is mid-write).");
404
+ }
405
+ sleep(LOCK_RETRY_MS);
406
+ }
407
+ }
408
+ try {
409
+ const tmp = path.join(
410
+ lockPath,
411
+ `.pid.${process.pid}.${Math.random().toString(36).slice(2)}`
412
+ );
413
+ fs.writeFileSync(tmp, String(process.pid));
414
+ fs.renameSync(tmp, pidPath); // atomic publish — no partial pid ever visible
415
+ return fn();
416
+ } finally {
417
+ breakLock(lockPath);
418
+ }
419
+ }
420
+
421
+ // ---------------------------------------------------------------- epics
422
+
423
+ /* The top-level ## Epics registry table → [{ key, label, goal }]. */
424
+ function readEpics(lines) {
425
+ return getRows(lines, "epics").map((r) => ({
426
+ key: (r.cells[0] || "").trim(),
427
+ label: (r.cells[1] || "").trim(),
428
+ goal: (r.cells[2] || "").trim(),
429
+ }));
430
+ }
431
+
432
+ function getEpicKeys(lines) {
433
+ return new Set(readEpics(lines).map((e) => e.key));
434
+ }
435
+
436
+ /* A valid epic cell is the literal `?` or a registered ## Epics key. */
437
+ function isEpicKey(key, lines) {
438
+ return key === "?" || getEpicKeys(lines).has(key);
439
+ }
440
+
441
+ /* Row shapes differ per section — read the right cell by section key.
442
+ * open/queued: [id, p, epic, task, evidence];
443
+ * inprogress/frozen/archive: [id, epic, task, ...]. */
444
+ function taskOf(cells, key) {
445
+ return key === "open" || key === "queued" ? cells[3] : cells[2];
446
+ }
447
+
448
+ /* Index of the epic cell within a section's row. */
449
+ function epicIndex(key) {
450
+ if (key === "open" || key === "queued") return 2;
451
+ if (key === "inprogress" || key === "frozen" || key === "archive") return 1;
452
+ return -1;
453
+ }
454
+
455
+ function epicOf(cells, key) {
456
+ const i = epicIndex(key);
457
+ return i === -1 ? "?" : (cells[i] || "?");
458
+ }
459
+
460
+ /* Member-report provenance survives the row lifecycle. `reports:sync` stamps an
461
+ * imported report with `source member-report <uuid>` in the Open row's Evidence
462
+ * cell, and both the sync dedup and the superadmin pending notice scan the board
463
+ * for that marker across every section. The In progress / Frozen / Archive
464
+ * sections have no Evidence column, so a marker living only in Evidence would be
465
+ * dropped the moment a report is taken or archived — the handled report then
466
+ * looks pending again (F-276) and the next sync re-imports it as a duplicate.
467
+ * These helpers carry the marker(s) into the destination's free-form cell
468
+ * (Handoff / condition / closed) so provenance is never lost. */
469
+ const REPORT_MARKER_PATTERN = /source member-report\s+[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi;
470
+
471
+ function reportMarkersInCells(cells) {
472
+ const found = [];
473
+ for (const cell of cells) {
474
+ const matches = String(cell || "").match(REPORT_MARKER_PATTERN);
475
+ if (matches) for (const m of matches) found.push(m.replace(/\s+/g, " ").toLowerCase());
476
+ }
477
+ return [...new Set(found)];
478
+ }
479
+
480
+ /* Append any markers not already present to a free-form destination note. */
481
+ function appendReportMarkers(note, markers) {
482
+ const base = (note || "").trim();
483
+ const haystack = base.toLowerCase();
484
+ const missing = markers.filter((m) => !haystack.includes(m));
485
+ if (!missing.length) return base;
486
+ return [base, ...missing].filter(Boolean).join(" | ");
487
+ }
488
+
489
+ /* "Depends on" cell (Open/Queued only): a comma/space-separated list of row IDs,
490
+ * or `?`/empty for none. */
491
+ function dependsOf(cells, key) {
492
+ return key === "open" || key === "queued" ? (cells[5] || "").trim() : "";
493
+ }
494
+
495
+ function isArchived(lines, id) {
496
+ return getRows(lines, "archive").some((r) => (r.cells[0] || "").trim() === id);
497
+ }
498
+
499
+ /* The IDs this row depends on that are NOT yet archived (its blockers). */
500
+ function blockedBy(lines, cells, key) {
501
+ const dep = dependsOf(cells, key);
502
+ if (!dep || dep === "?") return [];
503
+ return dep.split(/[\s,]+/).filter(Boolean).filter((d) => !isArchived(lines, d));
504
+ }
505
+
506
+ /* The dependency graph over Open/Queued rows: id -> [ids it depends on]. */
507
+ function dependencyGraph(lines) {
508
+ const graph = new Map();
509
+ for (const key of ["open", "queued"]) {
510
+ for (const r of getRows(lines, key)) {
511
+ const id = (r.cells[0] || "").trim();
512
+ if (!id) continue;
513
+ const dep = dependsOf(r.cells, key);
514
+ graph.set(id, !dep || dep === "?" ? [] : dep.split(/[\s,]+/).filter(Boolean));
515
+ }
516
+ }
517
+ return graph;
518
+ }
519
+
520
+ /* Reject a mutation that would introduce a dependency cycle. `extra` is the
521
+ * row being (re)written: { id, deps }. The DFS lives in board-lib.js so the
522
+ * write path and `test:backlog` share one implementation. */
523
+ function assertNoCycle(lines, extra) {
524
+ const graph = dependencyGraph(lines);
525
+ if (extra) graph.set(extra.id, extra.deps);
526
+ const cycle = findCycle(graph);
527
+ if (cycle) {
528
+ throw new Error(
529
+ `dependency cycle: ${cycle.join(" -> ")} — a cycle leaves every row in it permanently blocked.`
530
+ );
531
+ }
532
+ }
533
+
534
+ /* ---------------------------------------------------------------- owned-files registry */
535
+ /* `.agents/memory/owned-files.md` maps an active row -> the files/globs it owns,
536
+ * powering the cross-session overlap check in `test:concurrency`. */
537
+
538
+ function ownedFilesPath(root) {
539
+ return path.join(root, ".agents", "memory", "owned-files.md");
540
+ }
541
+
542
+ function readOwnedRegistry(root) {
543
+ const p = ownedFilesPath(root);
544
+ const map = new Map();
545
+ if (!fs.existsSync(p)) return { map, eol: "\n" };
546
+ const src = fs.readFileSync(p, "utf8");
547
+ const eol = src.includes("\r\n") ? "\r\n" : "\n";
548
+ for (const raw of src.split(/\r?\n/)) {
549
+ const m = raw.match(/^\s*[-*]\s+([A-Za-z]+-\d+)\s*:\s*(.+)$/);
550
+ if (m) map.set(m[1].toUpperCase(), m[2].trim());
551
+ }
552
+ return { map, eol };
553
+ }
554
+
555
+ function writeOwnedRegistry(root, map) {
556
+ const p = ownedFilesPath(root);
557
+ fs.mkdirSync(path.dirname(p), { recursive: true });
558
+ const header = [
559
+ "# Owned files per active row",
560
+ "",
561
+ "One row per in-progress feature: the files/globs it owns. Drives the",
562
+ "cross-session overlap check in `test:concurrency` (two In-progress rows must",
563
+ "not own the same file). Format: `- <ID>: <glob>[, <glob>...]`.",
564
+ "",
565
+ ];
566
+ const body = [...map.entries()]
567
+ .sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0))
568
+ .map(([id, globs]) => `- ${id}: ${globs}`);
569
+ fs.writeFileSync(p, header.concat(body).join("\n") + "\n", "utf8");
570
+ }
571
+
572
+ // ---------------------------------------------------------------- commands
573
+
574
+ function truncate(s, n) {
575
+ if (s.length <= n) return s;
576
+ return s.slice(0, n).trimEnd() + "…";
577
+ }
578
+
579
+ function stripEmphasis(s) {
580
+ return s.replace(/[*_]+/g, "").trim();
581
+ }
582
+
583
+ /* Bounded by default: the tool/board path is read by an LLM, so dumping an
584
+ * ever-growing board is a silent context leak. Every section still prints its
585
+ * true count first; rows are shown in file order (Open/Queued are priority-
586
+ * sorted), so the hidden rows are the lowest-priority tail. `--limit 0` = all. */
587
+ const LIST_DEFAULT_LIMIT = 40;
588
+
589
+ function cmdList(state, argv) {
590
+ const full = !!argv.full;
591
+ const TASK_W = full ? Infinity : 120;
592
+ const SUB_W = full ? Infinity : 90;
593
+ let limit = LIST_DEFAULT_LIMIT;
594
+ if (argv.limit != null) {
595
+ const n = Number.parseInt(argv.limit, 10);
596
+ limit = Number.isFinite(n) && n >= 0 ? n : LIST_DEFAULT_LIMIT;
597
+ }
598
+
599
+ const active = findSection(state.lines, "active");
600
+ if (active) {
601
+ let printed = 0;
602
+ for (let i = active.headingIdx + 1; i < active.endIdx; i++) {
603
+ const t = state.lines[i].trim();
604
+ if (/^\s*[-*]\s+/.test(t) && !/^\s*[-*]\s+_.*_\s*$/.test(t)) {
605
+ console.log(stripEmphasis(t));
606
+ printed++;
607
+ }
608
+ }
609
+ if (printed) console.log("");
610
+ }
611
+
612
+ const groups = [["inprogress", "In progress"], ["queued", "Queued"], ["open", "Open"]];
613
+ if (argv.all) groups.push(["frozen", "Frozen"], ["archive", "Archive"]);
614
+
615
+ for (const [key, label] of groups) {
616
+ const rows = getRows(state.lines, key).map((r) => r.cells);
617
+ console.log(`${label} (${rows.length})`);
618
+ const shown = limit > 0 && rows.length > limit ? rows.slice(0, limit) : rows;
619
+ for (const c of shown) {
620
+ if (key === "open" || key === "queued") {
621
+ console.log(` ${c[0]} [${c[1]}] [${c[2]}] ${truncate(c[3] || "", TASK_W)}`);
622
+ if (c[4] && c[4] !== "?") console.log(` evidence: ${truncate(c[4], SUB_W)}`);
623
+ } else if (key === "inprogress") {
624
+ console.log(` ${c[0]} [${c[1]}] ${truncate(c[2] || "", TASK_W)}`);
625
+ if (c[3] && c[3] !== "?") console.log(` handoff: ${truncate(c[3], SUB_W)}`);
626
+ } else if (key === "frozen") {
627
+ console.log(` ${c[0]} [${c[1]}] ${truncate(c[2] || "", TASK_W)}`);
628
+ if (c[3]) console.log(` reopen: ${truncate(c[3], SUB_W)}`);
629
+ } else {
630
+ console.log(` ${c[0]} [${c[1]}] ${truncate(c[2] || "", TASK_W)}`);
631
+ if (c[3]) console.log(` closed: ${truncate(c[3], SUB_W)}`);
632
+ }
633
+ }
634
+ if (shown.length < rows.length) {
635
+ console.log(` … +${rows.length - shown.length} row(s) omitted (--limit ${limit}, 0 = all)`);
636
+ }
637
+ console.log("");
638
+ }
639
+ }
640
+
641
+ /* Build the board's machine-readable snapshot (consumed by the superadmin API).
642
+ * Shape is the JSON contract documented in `.agents/features/superadmin-backlog/scope.md`.
643
+ * `open` rows are returned priority-sorted (P1 -> P4). */
644
+ function toBoardJson(state) {
645
+ const active = [];
646
+ const act = findSection(state.lines, "active");
647
+ if (act) {
648
+ for (let i = act.headingIdx + 1; i < act.endIdx; i++) {
649
+ const t = state.lines[i].trim();
650
+ if (/^\s*[-*]\s+/.test(t) && !/^\s*[-*]\s+_.*_\s*$/.test(t)) {
651
+ active.push(stripEmphasis(t).replace(/^\s*[-*]\s+/, "").trim());
652
+ }
653
+ }
654
+ }
655
+
656
+ const epics = readEpics(state.lines);
657
+ const open = getRows(state.lines, "open")
658
+ .map((r) => ({ id: r.cells[0], priority: r.cells[1], epic: r.cells[2] || "?", task: r.cells[3] || "", evidence: r.cells[4] || "", dependsOn: r.cells[5] || "" }))
659
+ .sort((a, b) => priorityRank(a.priority) - priorityRank(b.priority));
660
+ const queued = getRows(state.lines, "queued")
661
+ .map((r) => ({ id: r.cells[0], priority: r.cells[1], epic: r.cells[2] || "?", task: r.cells[3] || "", evidence: r.cells[4] || "", dependsOn: r.cells[5] || "" }))
662
+ .sort((a, b) => priorityRank(a.priority) - priorityRank(b.priority));
663
+ const inprogress = getRows(state.lines, "inprogress")
664
+ .map((r) => ({ id: r.cells[0], epic: r.cells[1] || "?", task: r.cells[2] || "", handoff: r.cells[3] || "" }));
665
+ const frozen = getRows(state.lines, "frozen")
666
+ .map((r) => ({ id: r.cells[0], epic: r.cells[1] || "?", task: r.cells[2] || "", condition: r.cells[3] || "" }));
667
+ const archive = getRows(state.lines, "archive")
668
+ .map((r) => ({ id: r.cells[0], epic: r.cells[1] || "?", task: r.cells[2] || "", closed: r.cells[3] || "" }));
669
+
670
+ return { epics, active, inprogress, queued, open, frozen, archive };
671
+ }
672
+
673
+ function cmdAdd(state, argv) {
674
+ const task = argv._[0];
675
+ if (!task) throw new Error("add: missing <task>.");
676
+ const priority = (argv.p || "P3").toUpperCase();
677
+ if (!(priority in PRIORITIES)) throw new Error(`add: priority must be P1..P4 (got "${priority}").`);
678
+ const evidence = argv.evidence || "?";
679
+ const epic = argv.epic || "?";
680
+ if (!isEpicKey(epic, state.lines)) {
681
+ throw new Error(`add: unknown epic "${epic}" (not in ## Epics) — use ? or epic-add first`);
682
+ }
683
+ const dependsOn = argv["depends-on"] || "?";
684
+ const known = getAllIds(state.lines);
685
+ const deps = dependsOn.split(/[\s,]+/).filter(Boolean).filter((d) => d !== "?");
686
+ for (const d of deps) {
687
+ if (!known.has(d)) throw new Error(`add: depends on unknown row ${d}.`);
688
+ }
689
+ const id = argv.id || nextId(state.lines);
690
+ if (getAllIds(state.lines).has(id)) throw new Error(`add: duplicate ID ${id}.`);
691
+ assertNoCycle(state.lines, { id, deps });
692
+
693
+ const openRows = getRows(state.lines, "open").map((r) => r.cells);
694
+ const merged = insertOpen(openRows, [id, priority, epic, task, evidence, dependsOn]);
695
+ state.lines = setRows(state.lines, "open", merged);
696
+ return { id, priority, epic, task, evidence, dependsOn };
697
+ }
698
+
699
+ /* epic-add <key> --label <x> [--goal <y>] — append a row to the ## Epics registry. */
700
+ function cmdEpicAdd(state, argv) {
701
+ const key = argv._[0];
702
+ if (!key) throw new Error("epic-add: missing <key>.");
703
+ const label = argv.label;
704
+ if (!label) throw new Error("epic-add: missing --label.");
705
+ const goal = argv.goal || "";
706
+ if (getEpicKeys(state.lines).has(key)) throw new Error(`epic-add: duplicate epic "${key}"`);
707
+
708
+ const epics = getRows(state.lines, "epics").map((r) => r.cells);
709
+ epics.push([key, label, goal]);
710
+ state.lines = setRows(state.lines, "epics", epics);
711
+ return { key, label, goal };
712
+ }
713
+
714
+ /* epic <id> --to <key> — rewrite a row's epic cell in place (any section). */
715
+ function cmdEpic(state, argv) {
716
+ const id = argv._[0];
717
+ if (!id) throw new Error("epic: missing <id>.");
718
+ const to = argv.to;
719
+ if (!isEpicKey(to, state.lines)) throw new Error(`epic: unknown epic "${to}"`);
720
+ const found = findRow(state.lines, id);
721
+ if (!found) throw new Error(`epic: no row ${id}`);
722
+
723
+ const i = epicIndex(found.key);
724
+ if (i === -1) throw new Error(`epic: ${id} is ${found.key} — rows there carry no epic column.`);
725
+
726
+ const srcRows = getRows(state.lines, found.key).map((r) => r.cells);
727
+ const idx = srcRows.findIndex((c) => (c[0] || "").trim() === id);
728
+ const newRow = srcRows[idx].slice();
729
+ newRow[i] = to;
730
+ srcRows[idx] = newRow;
731
+ state.lines = setRows(state.lines, found.key, srcRows);
732
+ return { id, epic: to };
733
+ }
734
+
735
+ /* A session's Handoff cell must point at a real file under `.agents/handoffs/`
736
+ * named `<id>.md` (or a hyphenated slug — see the handoff skill). Fail fast on a
737
+ * placeholder like `.agents/handoffs/F-<id>.md` (the template's example path —
738
+ * F-104's session recorded that literal and only a later explicit `--handoff`
739
+ * corrected it) or any value that cannot be a real path. */
740
+ function validateHandoff(id, raw) {
741
+ const v = (raw || "").trim();
742
+ if (!v || v === "?") return v; // "?" is an allowed "unknown" sentinel
743
+ if (!/^\.agents[\\/]handoffs[\\/].+\.md$/.test(v)) {
744
+ throw new Error(
745
+ `handoff must be a real path under .agents/handoffs/ ending in .md ` +
746
+ `(e.g. .agents/handoffs/${id}.md), not "${raw}"`
747
+ );
748
+ }
749
+ const stem = v.replace(/\.agents[\\/]handoffs[\\/]/i, "").replace(/\.md$/, "");
750
+ if (!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(stem)) {
751
+ throw new Error(
752
+ `handoff filename "${stem}" is not a valid <id> or slug ` +
753
+ `(use .agents/handoffs/${id}.md or a hyphenated slug)`
754
+ );
755
+ }
756
+ return v;
757
+ }
758
+
759
+ function cmdTake(state, argv) {
760
+ const id = argv._[0];
761
+ if (!id) throw new Error("take: missing <id>.");
762
+ const found = findRow(state.lines, id);
763
+ if (!found) throw new Error(`take: no row ${id} in BACKLOG.md.`);
764
+ if (found.key === "inprogress") return { id, note: "already In progress" };
765
+ if (found.key === "frozen") throw new Error(`take: ${id} is Frozen — unfreeze it first.`);
766
+ if (found.key === "archive") throw new Error(`take: ${id} is archived.`);
767
+
768
+ const blockers = blockedBy(state.lines, found.cells, found.key);
769
+ if (blockers.length) {
770
+ throw new Error(`take: ${id} is blocked — depends on ${blockers.join(", ")} (not yet archived).`);
771
+ }
772
+
773
+ const task = taskOf(found.cells, found.key) || id;
774
+ const epic = epicOf(found.cells, found.key);
775
+ const handoff = appendReportMarkers(
776
+ validateHandoff(id, argv.handoff) || "?",
777
+ reportMarkersInCells(found.cells)
778
+ );
779
+
780
+ const srcRows = getRows(state.lines, found.key).map((r) => r.cells).filter((c) => c[0].trim() !== id);
781
+ state.lines = setRows(state.lines, found.key, srcRows);
782
+
783
+ const inprog = getRows(state.lines, "inprogress").map((r) => r.cells);
784
+ inprog.push([id, epic, task, handoff]);
785
+ state.lines = setRows(state.lines, "inprogress", inprog);
786
+ return { id, epic, task, handoff };
787
+ }
788
+
789
+ function cmdQueue(state, argv) {
790
+ const id = argv._[0];
791
+ if (!id) throw new Error("queue: missing <id>.");
792
+ const found = findRow(state.lines, id);
793
+ if (!found) throw new Error(`queue: no row ${id} in BACKLOG.md.`);
794
+ if (found.key === "queued") return { id, note: "already queued" };
795
+ if (found.key !== "open") {
796
+ const where = found.key === "inprogress" ? "In progress" : found.key === "frozen" ? "Frozen" : "Archived";
797
+ throw new Error(`queue: ${id} is ${where} — only Open rows can be queued.`);
798
+ }
799
+
800
+ const cells = found.cells.slice(); // open cells: [id, p, epic, task, evidence]
801
+ const srcRows = getRows(state.lines, "open").map((r) => r.cells).filter((c) => c[0].trim() !== id);
802
+ state.lines = setRows(state.lines, "open", srcRows);
803
+
804
+ const queuedRows = getRows(state.lines, "queued").map((r) => r.cells);
805
+ state.lines = setRows(state.lines, "queued", insertOpen(queuedRows, cells));
806
+ return { id, epic: cells[2], task: cells[3] };
807
+ }
808
+
809
+ /* unqueue <id> — Queued -> Open (return an allocated row to the triage pool,
810
+ * e.g. re-triaging a row that was queued in error). The inverse of `queue`. */
811
+ function cmdUnqueue(state, argv) {
812
+ const id = argv._[0];
813
+ if (!id) throw new Error("unqueue: missing <id>.");
814
+ const found = findRow(state.lines, id);
815
+ if (!found) throw new Error(`unqueue: no row ${id} in BACKLOG.md.`);
816
+ if (found.key === "open") return { id, note: "already Open" };
817
+ if (found.key !== "queued") {
818
+ const where = found.key === "inprogress" ? "In progress" : found.key === "frozen" ? "Frozen" : "Archived";
819
+ throw new Error(`unqueue: ${id} is ${where} — only Queued rows can be returned to Open.`);
820
+ }
821
+
822
+ const cells = found.cells.slice(); // queued cells: [id, p, epic, task, evidence, dependsOn]
823
+ const srcRows = getRows(state.lines, "queued").map((r) => r.cells).filter((c) => c[0].trim() !== id);
824
+ state.lines = setRows(state.lines, "queued", srcRows);
825
+
826
+ const openRows = getRows(state.lines, "open").map((r) => r.cells);
827
+ state.lines = setRows(state.lines, "open", insertOpen(openRows, cells));
828
+ return { id, priority: cells[1], task: cells[3] };
829
+ }
830
+
831
+ /* next [--take] — report the top-priority UNBLOCKED Queued row; with --take,
832
+ * move it to In progress (the pick-then-go primitive behind /next). A queued row
833
+ * whose "Depends on" IDs are not all archived is skipped (blocked). */
834
+ function cmdNext(state, argv) {
835
+ const queued = getRows(state.lines, "queued").map((r) => r.cells);
836
+ if (queued.length === 0) return { empty: true };
837
+
838
+ const sorted = queued.slice().sort((a, b) => priorityRank(a[1]) - priorityRank(b[1]));
839
+ let row = null;
840
+ const blocked = [];
841
+ for (const r of sorted) {
842
+ if (blockedBy(state.lines, r, "queued").length) {
843
+ blocked.push(r[0]);
844
+ continue;
845
+ }
846
+ row = r;
847
+ break;
848
+ }
849
+ if (!row) return { empty: true, blocked };
850
+
851
+ const id = row[0];
852
+ const priority = row[1];
853
+ const epic = row[2] || "?";
854
+ const task = row[3] || id;
855
+ const evidence = row[4] || "?";
856
+ if (!argv.take) return { id, priority, epic, task, evidence };
857
+
858
+ const srcRows = queued.filter((c) => (c[0] || "").trim() !== id);
859
+ state.lines = setRows(state.lines, "queued", srcRows);
860
+
861
+ const handoff = validateHandoff(id, argv.handoff) || `.agents/handoffs/${id}.md`;
862
+ const inprog = getRows(state.lines, "inprogress").map((r) => r.cells);
863
+ inprog.push([id, epic, task, handoff]);
864
+ state.lines = setRows(state.lines, "inprogress", inprog);
865
+ return { id, epic, task, handoff };
866
+ }
867
+
868
+ /* A `worktree` row records its isolation target in the Handoff cell as
869
+ * "<handoff> (worktree: <rel>; branch: <branch>)". Parse it back out so
870
+ * `archive` can clean the worktree up when the feature ships. */
871
+ function parseWorktree(handoff) {
872
+ if (!handoff) return null;
873
+ const m = /\(worktree:\s*([^;]+);\s*branch:\s*([^)]+)\)/.exec(handoff);
874
+ if (!m) return null;
875
+ return { rel: m[1].trim(), branch: m[2].trim() };
876
+ }
877
+
878
+ /* A session that creates its worktree mid-session keeps `context.worktree`
879
+ * pinned to the MAIN tree (`context.worktree` is fixed at launch), so the
880
+ * `backlog_*` tools would keep writing the board to main while the feature lives
881
+ * in the worktree. When the calling tool forwards its session id
882
+ * (`HARNESS_SESSION_ID`), `worktree` records the target under the gitignored
883
+ * `.serve/sessions/` container and `archive` clears it; the tools read it back
884
+ * and root board/handoff/telemetry ops in the worktree. */
885
+ function sessionWorktreeFile(root, sessionID) {
886
+ return leases.worktreeFile(root, sessionID);
887
+ }
888
+
889
+ /* The parent pid of `pid` from `/proc/<pid>/stat` (field 4). Parsing past the
890
+ * final `)` avoids a comm containing spaces/parens. Linux/WSL only; returns null
891
+ * elsewhere so the ancestry probe degrades to "no session". */
892
+ function parentPid(pid) {
893
+ try {
894
+ const stat = fs.readFileSync(`/proc/${pid}/stat`, "utf8");
895
+ const close = stat.lastIndexOf(")");
896
+ if (close === -1) return null;
897
+ const ppid = Number(stat.slice(close + 2).trim().split(/\s+/)[1]);
898
+ return Number.isInteger(ppid) && ppid > 1 ? ppid : null;
899
+ } catch {
900
+ return null;
901
+ }
902
+ }
903
+
904
+ /* The session that owns this process. A tool call forwards HARNESS_SESSION_ID;
905
+ * the documented bash invocation (`node scripts/backlog.js worktree <id>`) does
906
+ * NOT, so walk the process ancestry to the live lease that owns this shell. The
907
+ * context-guard plugin heartbeats the lease on the `tool.execute.before` of the
908
+ * very bash call that runs this, so it is live and its pid is an ancestor.
909
+ * Without this the mid-session reroot never happens and later tools
910
+ * (`checkpoint_write`) keep writing to the main tree — the F-246 stray handoff. */
911
+ function ancestorSessionId(root) {
912
+ const env = process.env.HARNESS_SESSION_ID;
913
+ if (env) return env;
914
+ return leaseAncestorIn(root);
915
+ }
916
+
917
+ /* A live lease under `root` whose pid is this process or an ancestor — i.e. this
918
+ * process is running INSIDE that session's tree. Unlike `ancestorSessionId` this
919
+ * ignores HARNESS_SESSION_ID (which names a session, not a directory), so it can
920
+ * answer "is this specific checkout a session's root?" — the `--open` guard in
921
+ * `cmdWorktreePrune`. */
922
+ function leaseAncestorIn(root) {
923
+ let live;
924
+ try {
925
+ live = leases.liveLeases(root);
926
+ } catch {
927
+ return "";
928
+ }
929
+ const byPid = new Map(
930
+ live.filter((r) => typeof r.pid === "number" && r.sessionID).map((r) => [r.pid, r.sessionID])
931
+ );
932
+ if (byPid.size === 0) return "";
933
+ let pid = process.pid;
934
+ for (let i = 0; i < 64 && pid > 1; i++) {
935
+ if (byPid.has(pid)) return byPid.get(pid);
936
+ const next = parentPid(pid);
937
+ if (!next || next === pid) break;
938
+ pid = next;
939
+ }
940
+ return "";
941
+ }
942
+
943
+ function readSessionWorktree(root, sessionID) {
944
+ return leases.readWorktree(root, sessionID);
945
+ }
946
+
947
+ function writeSessionWorktree(root, sessionID, dir) {
948
+ leases.writeWorktree(root, sessionID, dir);
949
+ }
950
+
951
+ function clearSessionWorktree(root, sessionID, onlyDir) {
952
+ leases.clearWorktree(root, sessionID, onlyDir);
953
+ }
954
+
955
+ /* Worktree checkouts a LIVE session still owns, from the `.serve/sessions/
956
+ * <id>.worktree` pointers (written by `worktree`, cleared when that worktree is
957
+ * removed). `worktree-prune` must never remove one of these: a session can be
958
+ * mid-`ship`, watching CI from that very checkout, and deleting it blinds the
959
+ * watch — every `gh` spawn fails on the dead cwd, so a green run looks like a
960
+ * 20-minute timeout and the session is left believing CI is unconfirmed (F-252).
961
+ * A pointer whose lease is stale/dead is ignored, so abandoned worktrees still
962
+ * converge. `worktree-prune --self` lifts this guard for the caller's OWN
963
+ * finished worktree only (see `cmdWorktreePrune`); a foreign session pruning
964
+ * concurrently has no such authorization and still sees the owner's pointer
965
+ * (F-252). */
966
+ function liveSessionWorktreeDirs(root) {
967
+ const dirs = new Set();
968
+ let live;
969
+ try {
970
+ live = leases.liveLeases(root);
971
+ } catch {
972
+ return dirs;
973
+ }
974
+ for (const rec of live) {
975
+ const sid = rec.sessionID || (rec.name && rec.name.replace(/\.json$/, ""));
976
+ if (!sid) continue;
977
+ const dir = readSessionWorktree(root, sid);
978
+ if (dir) dirs.add(path.resolve(dir));
979
+ }
980
+ return dirs;
981
+ }
982
+
983
+ /* Best-effort cleanup of a shipped feature's isolation: remove its worktree
984
+ * checkout (the folder that would otherwise hang around) and, if the branch was
985
+ * merged, delete it. Never blocks the board write — a dirty/locked worktree is
986
+ * left in place with a warning rather than force-discarded (zero data loss), and
987
+ * a worktree the archiving session is standing in is never yanked out from under
988
+ * it. */
989
+ function cleanupWorktree(root, rel, branch, opts) {
990
+ const abs = path.resolve(root, rel);
991
+ const notes = [];
992
+ const skipRemove = !!(opts && opts.skipRemove);
993
+ if (skipRemove) {
994
+ notes.push(
995
+ `worktree ${rel} left in place (in use by this session) — remove it from the main tree: git worktree remove ${rel}`
996
+ );
997
+ } else {
998
+ const rm = spawnSync("git", ["-C", root, "worktree", "remove", abs], { encoding: "utf8" });
999
+ if (rm.status === 0) {
1000
+ notes.push(`removed worktree ${rel}`);
1001
+ } else {
1002
+ notes.push(`worktree ${rel} left in place (${(rm.stderr || rm.stdout || "not a worktree").trim()})`);
1003
+ }
1004
+ }
1005
+ if (branch) {
1006
+ const del = spawnSync("git", ["-C", root, "branch", "-d", branch], { encoding: "utf8" });
1007
+ if (del.status === 0) notes.push(`deleted branch ${branch}`);
1008
+ }
1009
+ return notes;
1010
+ }
1011
+
1012
+ function cmdArchive(state, argv) {
1013
+ const id = argv._[0];
1014
+ if (!id) throw new Error("archive: missing <id>.");
1015
+ const found = findRow(state.lines, id);
1016
+ if (!found) throw new Error(`archive: no row ${id} in BACKLOG.md.`);
1017
+ if (found.key === "archive") {
1018
+ // Idempotent repair path: an already-archived row is normally a no-op, but a
1019
+ // caller supplying `--closed` may rewrite its closed note (used to backfill
1020
+ // provenance, e.g. a member-report marker dropped before this preservation
1021
+ // existed — F-276). Markers already on the row are kept.
1022
+ if (!argv.closed) return { id, note: "already archived" };
1023
+ const repaired = appendReportMarkers(argv.closed, reportMarkersInCells(found.cells));
1024
+ const rows = getRows(state.lines, "archive").map((r) => r.cells);
1025
+ const idx = rows.findIndex((c) => (c[0] || "").trim() === id);
1026
+ rows[idx] = [id, epicOf(found.cells, found.key), taskOf(found.cells, found.key), repaired];
1027
+ state.lines = setRows(state.lines, "archive", rows);
1028
+ return { id, note: "already archived", closed: repaired };
1029
+ }
1030
+
1031
+ const task = taskOf(found.cells, found.key);
1032
+ const epic = epicOf(found.cells, found.key);
1033
+ const closed = appendReportMarkers(argv.closed || "shipped", reportMarkersInCells(found.cells));
1034
+
1035
+ // A shipped feature no longer needs its isolated checkout: remove the worktree
1036
+ // (and merged branch) it recorded in its Handoff cell, so worktrees don't pile
1037
+ // up after each session. Never remove a worktree the archiving process is
1038
+ // inside (that would delete the running session's cwd), and clear the session
1039
+ // pointer from BOTH the launch tree and the worktree it points at (the pointer
1040
+ // was written by whichever tree `backlog worktree` ran in).
1041
+ const wt = found.key === "inprogress" ? parseWorktree(found.cells[3]) : null;
1042
+ let cleanup = [];
1043
+ if (wt) {
1044
+ const cur = path.dirname(state.p);
1045
+ const wtAbs = path.resolve(cur, wt.rel);
1046
+ const cwd = process.cwd();
1047
+ const inside = cwd === wtAbs || cwd.startsWith(wtAbs + path.sep);
1048
+ cleanup = cleanupWorktree(cur, wt.rel, wt.branch, { skipRemove: inside });
1049
+ // Drop the session pointer ONLY once we are no longer standing in the
1050
+ // worktree. `finalize` archives from inside the feature checkout and only
1051
+ // THEN runs `ship` (which watches CI from it); clearing the pointer here
1052
+ // would make the still-live worktree look abandoned, so a concurrent
1053
+ // `worktree-prune` could delete it out from under the CI watch (F-252).
1054
+ // When archive runs from the main tree the checkout is being removed, so
1055
+ // clearing is safe.
1056
+ if (!inside) {
1057
+ const sid = process.env.HARNESS_SESSION_ID;
1058
+ clearSessionWorktree(cur, sid, wtAbs);
1059
+ const main = mainWorktreeRoot(cur);
1060
+ if (main && path.resolve(main) !== path.resolve(cur)) clearSessionWorktree(main, sid, wtAbs);
1061
+ }
1062
+ }
1063
+
1064
+ const srcRows = getRows(state.lines, found.key).map((r) => r.cells).filter((c) => c[0].trim() !== id);
1065
+ state.lines = setRows(state.lines, found.key, srcRows);
1066
+
1067
+ const archiveRows = getRows(state.lines, "archive").map((r) => r.cells);
1068
+ archiveRows.push([id, epic, task, closed]);
1069
+ state.lines = setRows(state.lines, "archive", archiveRows);
1070
+ return { id, epic, task, closed, cleanup };
1071
+ }
1072
+
1073
+ function cmdFreeze(state, argv) {
1074
+ const id = argv._[0];
1075
+ if (!id) throw new Error("freeze: missing <id>.");
1076
+ const why = argv.why || "";
1077
+ const reopen = argv.reopen || "";
1078
+ if (!why && !reopen) {
1079
+ throw new Error("freeze: provide --why and/or --reopen (the reopen condition is required by test:backlog).");
1080
+ }
1081
+ const found = findRow(state.lines, id);
1082
+ if (!found) throw new Error(`freeze: no row ${id} in BACKLOG.md.`);
1083
+ if (found.key === "frozen") return { id, note: "already frozen" };
1084
+
1085
+ const task = taskOf(found.cells, found.key);
1086
+ const epic = epicOf(found.cells, found.key);
1087
+ const cond = appendReportMarkers(
1088
+ [why, reopen ? `reopen when ${reopen}` : ""].filter(Boolean).join(" — "),
1089
+ reportMarkersInCells(found.cells)
1090
+ );
1091
+
1092
+ const srcRows = getRows(state.lines, found.key).map((r) => r.cells).filter((c) => c[0].trim() !== id);
1093
+ state.lines = setRows(state.lines, found.key, srcRows);
1094
+
1095
+ const frozenRows = getRows(state.lines, "frozen").map((r) => r.cells);
1096
+ frozenRows.push([id, epic, task, cond]);
1097
+ state.lines = setRows(state.lines, "frozen", frozenRows);
1098
+ return { id, epic, task, cond };
1099
+ }
1100
+
1101
+ /* reopen <id> [--reason x] [--p P1..P4] — Archive/Frozen -> Open, preserving the
1102
+ * row's ID and Task cell. This is the convergence half of the nightly E2E loop:
1103
+ * a nightly run reopens a shipped fix whose journey still fails, so the same row
1104
+ * (and its `[nightly:flow=<journey>]` Task marker) is worked again the next day
1105
+ * instead of a duplicate being filed. The default priority is P2 (an unresolved
1106
+ * regression outranks routine open work); the existing member-report provenance
1107
+ * markers are carried into the Open row's Evidence cell so they are not lost. */
1108
+ function cmdReopen(state, argv) {
1109
+ const id = argv._[0];
1110
+ if (!id) throw new Error("reopen: missing <id>.");
1111
+ const priority = (argv.p || "P2").toUpperCase();
1112
+ if (!(priority in PRIORITIES)) throw new Error(`reopen: priority must be P1..P4 (got "${priority}").`);
1113
+ const found = findRow(state.lines, id);
1114
+ if (!found) throw new Error(`reopen: no row ${id} in BACKLOG.md.`);
1115
+ if (found.key === "open") return { id, note: "already Open" };
1116
+ if (found.key === "queued" || found.key === "inprogress") {
1117
+ const where = found.key === "inprogress" ? "In progress" : "Queued";
1118
+ throw new Error(`reopen: ${id} is ${where} — only Archive/Frozen rows are reopened.`);
1119
+ }
1120
+
1121
+ const task = taskOf(found.cells, found.key) || id;
1122
+ const epic = epicOf(found.cells, found.key);
1123
+ const reason = appendReportMarkers(argv.reason || "reopened", reportMarkersInCells(found.cells));
1124
+
1125
+ const srcRows = getRows(state.lines, found.key).map((r) => r.cells).filter((c) => c[0].trim() !== id);
1126
+ state.lines = setRows(state.lines, found.key, srcRows);
1127
+
1128
+ const openRows = getRows(state.lines, "open").map((r) => r.cells);
1129
+ state.lines = setRows(state.lines, "open", insertOpen(openRows, [id, priority, epic, task, reason, "?"]));
1130
+ return { id, priority, epic, task, reason };
1131
+ }
1132
+
1133
+ function cmdPriority(state, argv) {
1134
+ const id = argv._[0];
1135
+ if (!id) throw new Error("priority: missing <id>.");
1136
+ const priority = (argv.p || "").toUpperCase();
1137
+ if (!(priority in PRIORITIES)) throw new Error(`priority: priority must be P1..P4 (got "${priority || "none"}").`);
1138
+
1139
+ const found = findRow(state.lines, id);
1140
+ if (!found) throw new Error(`priority: no row ${id} in BACKLOG.md.`);
1141
+ if (found.key !== "open" && found.key !== "queued") {
1142
+ const where = found.key === "inprogress" ? "In progress" : found.key === "frozen" ? "Frozen" : "Archive";
1143
+ throw new Error(`priority: ${id} is ${where} — only Open/Queued rows have a priority.`);
1144
+ }
1145
+
1146
+ const srcRows = getRows(state.lines, found.key).map((r) => r.cells).filter((c) => c[0].trim() !== id);
1147
+ const newRow = found.cells.slice();
1148
+ newRow[1] = priority;
1149
+ state.lines = setRows(state.lines, found.key, insertOpen(srcRows, newRow));
1150
+ return { id, priority };
1151
+ }
1152
+
1153
+ /* depends <id> --on <ids|?> — set/clear a row's "Depends on" cell (Open/Queued). */
1154
+ function cmdDepends(state, argv) {
1155
+ const id = argv._[0];
1156
+ if (!id) throw new Error("depends: missing <id>.");
1157
+ const on = (argv.on || "").trim();
1158
+ const found = findRow(state.lines, id);
1159
+ if (!found) throw new Error(`depends: no row ${id} in BACKLOG.md.`);
1160
+ if (found.key !== "open" && found.key !== "queued") {
1161
+ const where = found.key === "inprogress" ? "In progress" : found.key === "frozen" ? "Frozen" : "Archive";
1162
+ throw new Error(`depends: ${id} is ${where} — only Open/Queued rows carry dependencies.`);
1163
+ }
1164
+ const deps = on === "" || on === "?" ? [] : on.split(/[\s,]+/).filter(Boolean);
1165
+ const known = getAllIds(state.lines);
1166
+ for (const d of deps) {
1167
+ if (!known.has(d)) throw new Error(`depends: ${id} references unknown row ${d}.`);
1168
+ }
1169
+ assertNoCycle(state.lines, { id, deps });
1170
+ const srcRows = getRows(state.lines, found.key).map((r) => r.cells).filter((c) => c[0].trim() !== id);
1171
+ const newRow = found.cells.slice();
1172
+ newRow[5] = on || "?";
1173
+ state.lines = setRows(state.lines, found.key, insertOpen(srcRows, newRow));
1174
+ return { id, dependsOn: on || "?" };
1175
+ }
1176
+
1177
+ /* owns <id> --files "glob, glob" — record the files/globs a row owns in the
1178
+ * `.agents/memory/owned-files.md` registry (feeds `test:concurrency` overlap). */
1179
+ function cmdOwns(state, argv) {
1180
+ const id = (argv._[0] || "").toUpperCase();
1181
+ if (!id) throw new Error("owns: missing <id>.");
1182
+ const files = (argv.files || "").trim();
1183
+ if (files === "") throw new Error('owns: provide --files "glob1, glob2" (or --files "?" to clear).');
1184
+ const found = findRow(state.lines, id);
1185
+ if (!found) throw new Error(`owns: no row ${id} in BACKLOG.md.`);
1186
+ const root = path.dirname(state.p);
1187
+ const reg = readOwnedRegistry(root);
1188
+ if (files === "?") reg.map.delete(id);
1189
+ else reg.map.set(id, files);
1190
+ writeOwnedRegistry(root, reg.map);
1191
+ return { id, files };
1192
+ }
1193
+
1194
+ // ---------------------------------------------------------------- main checkout sync
1195
+ /* The board is per-checkout: a feature committed + pushed from its own worktree
1196
+ * lands on `origin/main`, but the main checkout's checked-out BACKLOG.md stays
1197
+ * put until it is pulled — so the main tree shows a stale board and, worse, a
1198
+ * later local/auto-commit on that base diverges from origin. The shared
1199
+ * board-sync module owns the git-facing logic (classify dirty files, row-aware
1200
+ * reconcile, converge, publish); these thin wrappers root it in backlog.js.
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. */
1204
+ function gitCmd(root, args, opts) {
1205
+ return boardSync.gitCmd(root, args, opts);
1206
+ }
1207
+
1208
+ function currentUpstream(root) {
1209
+ return boardSync.currentUpstream(root);
1210
+ }
1211
+
1212
+ /* The MAIN worktree's path, or null. Used to clear a session's `.worktree`
1213
+ * pointer from the tree the pointer was actually written in — a linked feature
1214
+ * worktree's git dir cannot see the main tree's `.serve/`. */
1215
+ function mainWorktreeRoot(root) {
1216
+ return boardSync.mainWorktreeRoot(root);
1217
+ }
1218
+
1219
+ /* Sync the canonical checkout before a board read/mutation, returning the notes
1220
+ * to print. Best-effort: offline or no-upstream is a quiet no-op, and a linked
1221
+ * worktree is skipped. Unlike the old dirty-only reconcile, redundant non-board
1222
+ * dirt is cleared and genuine local changes fail the caller closed (see
1223
+ * `convergeCanonical`) instead of leaving main silently stale. */
1224
+ function refreshMainCheckout(root, opts) {
1225
+ const notes = [];
1226
+ const inside = gitCmd(root, ["rev-parse", "--is-inside-work-tree"]);
1227
+ if (inside.status !== 0 || (inside.stdout || "").trim() !== "true") return notes;
1228
+ if (!boardSync.isCanonicalCheckout(root)) return notes;
1229
+ const upstream = currentUpstream(root);
1230
+ if (!upstream) return notes;
1231
+ return boardSync.convergeCanonical(root, upstream, { fetch: !opts || opts.fetch !== false }).notes;
1232
+ }
1233
+
1234
+ /* Run a project-supplied worktree bootstrap after `git worktree add`, so a fresh
1235
+ * checkout is immediately gate-runnable. The harness is project-agnostic, so the
1236
+ * setup is a CONVENTION script: `scripts/worktree-setup.js`, looked up in the new
1237
+ * worktree first and then in the main checkout (so it works before the script
1238
+ * itself is committed). It receives the worktree path as argv[2]. Best-effort:
1239
+ * a failure warns but never fails the board write. */
1240
+ function runWorktreeSetup(mainRoot, dir) {
1241
+ const candidates = [
1242
+ path.join(dir, "scripts", "worktree-setup.js"),
1243
+ path.join(mainRoot, "scripts", "worktree-setup.js"),
1244
+ ];
1245
+ const script = candidates.find((p) => fs.existsSync(p));
1246
+ if (!script) return { ran: false };
1247
+ process.stdout.write(`worktree: running ${path.relative(mainRoot, script)} ${dir}\n`);
1248
+ const res = spawnSync(process.execPath, [script, dir], { cwd: dir, stdio: "inherit" });
1249
+ if (res.status !== 0) {
1250
+ process.stderr.write(
1251
+ `worktree: setup script exited ${res.status === null ? res.signal : res.status} — ` +
1252
+ `the worktree may need manual setup (F-183/F-228).\n`
1253
+ );
1254
+ return { ran: true, ok: false };
1255
+ }
1256
+ return { ran: true, ok: true };
1257
+ }
1258
+
1259
+ /* Plan the board half of `worktree`: validate, ensure the row is In progress,
1260
+ * and record the isolation target in its Handoff cell. Split from the filesystem
1261
+ * half (`cmdWorktreeApply`) so the canonical transaction can PUBLISH the take
1262
+ * before the worktree is created — the new checkout is then based on an
1263
+ * `origin/main` that already carries the In-progress row, so the feature's
1264
+ * finalize/archive rebases without a same-row conflict. Run from the MAIN tree:
1265
+ * a worktree's BACKLOG.md is only a snapshot. */
1266
+ function cmdWorktreePlan(state, argv) {
1267
+ const id = argv._[0];
1268
+ if (!id) throw new Error("worktree: missing <id>.");
1269
+ const root = path.dirname(state.p);
1270
+ const slug = id.toLowerCase();
1271
+ const branch = argv.branch || slug;
1272
+ const dir = argv.dir
1273
+ ? path.resolve(argv.dir)
1274
+ : path.resolve(root, "..", ".worktrees", path.basename(root), slug);
1275
+
1276
+ // A worktree inside the repository pollutes `git status` (the nested
1277
+ // `.worktrees/` shows as untracked in every session) and confuses the
1278
+ // board/landing gates. Guard it even though the default is outside (a
1279
+ // mis-resolved root once left `<repo>/.worktrees/<repo>/f-301` behind).
1280
+ const rootAbs = path.resolve(root);
1281
+ if (dir === rootAbs || dir.startsWith(rootAbs + path.sep)) {
1282
+ throw new Error(
1283
+ `worktree: refusing a worktree inside the repository (${dir}). ` +
1284
+ `Use the default ../.worktrees/${path.basename(rootAbs)}/${slug} or a --dir outside the repo.`
1285
+ );
1286
+ }
1287
+
1288
+ const found = findRow(state.lines, id);
1289
+ if (!found) throw new Error(`worktree: no row ${id} in BACKLOG.md.`);
1290
+ if (found.key === "archive") throw new Error(`worktree: ${id} is archived.`);
1291
+ if (found.key === "frozen") throw new Error(`worktree: ${id} is Frozen — unfreeze it first.`);
1292
+
1293
+ if (found.key === "open" || found.key === "queued") {
1294
+ const blockers = blockedBy(state.lines, found.cells, found.key);
1295
+ if (blockers.length) {
1296
+ throw new Error(`worktree: ${id} is blocked — depends on ${blockers.join(", ")} (not yet archived).`);
1297
+ }
1298
+ }
1299
+
1300
+ // Ensure the row is In progress (auto-take if Open/Queued).
1301
+ const claimed = argv.handoff !== undefined ? validateHandoff(id, argv.handoff) : "";
1302
+ let handoff = claimed || `.agents/handoffs/${id}.md`;
1303
+ if (found.key === "open" || found.key === "queued") {
1304
+ const task = taskOf(found.cells, found.key) || id;
1305
+ const epic = epicOf(found.cells, found.key);
1306
+ const srcRows = getRows(state.lines, found.key).map((r) => r.cells).filter((c) => c[0].trim() !== id);
1307
+ state.lines = setRows(state.lines, found.key, srcRows);
1308
+ const inprog = getRows(state.lines, "inprogress").map((r) => r.cells);
1309
+ inprog.push([id, epic, task, handoff]);
1310
+ state.lines = setRows(state.lines, "inprogress", inprog);
1311
+ } else {
1312
+ const existing = found.key === "inprogress" ? (found.cells[3] || "").split(/\s*[|(]/)[0].trim() : "";
1313
+ handoff = claimed || existing || `.agents/handoffs/${id}.md`;
1314
+ }
1315
+
1316
+ // Record the isolation target in the Handoff cell.
1317
+ const rel = path.relative(root, dir) || dir;
1318
+ const handoffCell = appendReportMarkers(
1319
+ `${handoff} (worktree: ${rel}; branch: ${branch})`,
1320
+ reportMarkersInCells(found.cells)
1321
+ );
1322
+ const inprog = getRows(state.lines, "inprogress").map((r) => r.cells);
1323
+ const idx = inprog.findIndex((c) => (c[0] || "").trim() === id);
1324
+ if (idx !== -1) {
1325
+ inprog[idx] = [id, inprog[idx][1], inprog[idx][2], handoffCell];
1326
+ state.lines = setRows(state.lines, "inprogress", inprog);
1327
+ }
1328
+
1329
+ return { id, branch, dir: rel, dirAbs: dir, handoff };
1330
+ }
1331
+
1332
+ /* Create the isolated `git worktree` + branch for a planned row. Runs AFTER the
1333
+ * canonical transaction publishes the take, so it is based on the CURRENT
1334
+ * upstream (`origin/main`), not a stale local HEAD. `--no-track` keeps the
1335
+ * feature branch from silently tracking main (a bare `git push` in the worktree
1336
+ * can't target main). */
1337
+ function cmdWorktreeApply(root, plan) {
1338
+ const base = currentUpstream(root) || "HEAD";
1339
+ const res = spawnSync("git", ["-C", root, "worktree", "add", "--no-track", "-b", plan.branch, plan.dirAbs, base], {
1340
+ encoding: "utf8",
1341
+ });
1342
+ if (res.status !== 0) {
1343
+ const err = (res.stderr || res.stdout || "").trim();
1344
+ throw new Error(`worktree: git worktree add failed: ${err}`);
1345
+ }
1346
+
1347
+ // Bootstrap the fresh checkout (node_modules / generated client / .env / hooks).
1348
+ runWorktreeSetup(root, plan.dirAbs);
1349
+
1350
+ // Root this session's tool calls in the worktree even though opencode's
1351
+ // `context.worktree` stays pinned to the main tree it launched in. A bash
1352
+ // invocation carries no HARNESS_SESSION_ID, so fall back to the live lease
1353
+ // that owns this shell (see ancestorSessionId).
1354
+ const sessionID = ancestorSessionId(root);
1355
+ writeSessionWorktree(root, sessionID, plan.dirAbs);
1356
+ if (!sessionID) {
1357
+ console.warn(
1358
+ "worktree: could not attribute this worktree to the calling session (no HARNESS_SESSION_ID, no live lease ancestor) —\n" +
1359
+ " later tool calls (e.g. checkpoint_write) will keep acting on the MAIN tree. Re-run via the `backlog_worktree`\n" +
1360
+ " tool, or create it with --open so the session is rooted in the worktree."
1361
+ );
1362
+ }
1363
+
1364
+ return { ...plan, base };
1365
+ }
1366
+
1367
+ /* Backward-compatible wrapper: plan + apply in one call (used by direct
1368
+ * callers/tests; the CLI splits them around the board publish). */
1369
+ function cmdWorktree(state, argv) {
1370
+ return cmdWorktreeApply(path.dirname(state.p), cmdWorktreePlan(state, argv));
1371
+ }
1372
+
1373
+ /* `worktree --open` makes the new worktree the session root: launch the agent
1374
+ * CLI with its cwd set to the worktree, so the context-guard plugin's lease
1375
+ * lands in the worktree's `.serve/sessions/` (not main's) and `test:concurrency`
1376
+ * sees one session per checkout. Runs AFTER the board lock is released — the
1377
+ * launched session can be long-lived, and holding the lock would freeze the
1378
+ * board. Override the binary with `--open-cmd` or `HARNESS_OPEN_CMD` (tests). */
1379
+ function openWorktreeSession(dir, command) {
1380
+ const bin = command || process.env.HARNESS_OPEN_CMD || "opencode";
1381
+ const label = path.basename(dir);
1382
+ process.stdout.write(`worktree: opening ${bin} in ${dir} (session root = ${label})\n`);
1383
+ const res = spawnSync(bin, { cwd: dir, stdio: "inherit", shell: true, encoding: "utf8" });
1384
+ if (res.error) {
1385
+ process.stderr.write(`worktree: could not launch ${bin}: ${res.error.message}\n`);
1386
+ process.exitCode = 1;
1387
+ }
1388
+ return res.status === null ? 1 : res.status;
1389
+ }
1390
+
1391
+ /* `worktree-prune` — converge the worktree set: remove every linked worktree
1392
+ * (outside the main tree) whose branch is already merged into the current
1393
+ * upstream AND whose checkout is clean, then delete the merged branch and clear
1394
+ * any session pointer that referenced it. Worktrees with uncommitted work or an
1395
+ * unmerged branch are reported and left alone (zero data loss). This is the
1396
+ * convergence path for worktrees whose session ended without an `archive`
1397
+ * (archive only cleans the row it ships).
1398
+ *
1399
+ * Named branches (`worktree-prune <branch...>`) are pruned explicitly: this is
1400
+ * the escape hatch for SQUASH merges, whose commits are not ancestors of the
1401
+ * upstream, so `git branch --merged` can never classify them as merged even
1402
+ * though the content is fully landed. Explicit names still require a clean
1403
+ * checkout and never touch the main tree. */
1404
+ function cmdWorktreePrune(state, argv) {
1405
+ const root = path.dirname(state.p);
1406
+ const notes = [];
1407
+ const explicit = new Set((argv._ || []).map((s) => String(s).trim()).filter(Boolean));
1408
+ const inside = gitCmd(root, ["rev-parse", "--is-inside-work-tree"]);
1409
+ if (inside.status !== 0) return { notes: ["not a git repo — nothing to prune"] };
1410
+ const list = gitCmd(root, ["worktree", "list", "--porcelain"]);
1411
+ if (list.status !== 0) return { notes: ["could not list worktrees"] };
1412
+
1413
+ const entries = [];
1414
+ let cur = null;
1415
+ for (const line of (list.stdout || "").split(/\r?\n/)) {
1416
+ if (line.startsWith("worktree ")) {
1417
+ cur = { path: line.slice("worktree ".length).trim(), branch: "" };
1418
+ entries.push(cur);
1419
+ } else if (cur && line.startsWith("branch ")) {
1420
+ cur.branch = line.slice("branch ".length).replace(/^branch\s+/, "").replace(/^refs\/heads\//, "").trim();
1421
+ }
1422
+ }
1423
+ const main = mainWorktreeRoot(root) || root;
1424
+ const upstream = argv["no-fetch"] ? currentUpstream(root) : (refreshMainCheckout(root, { fetch: true }), currentUpstream(root));
1425
+ // Without an upstream there is no trustworthy "merged" reference — refuse
1426
+ // rather than guess, UNLESS the caller named the branches explicitly.
1427
+ if (!upstream && explicit.size === 0) {
1428
+ return { notes: ["no upstream tracking branch — cannot determine merged branches; name them explicitly to prune"], pruned: 0 };
1429
+ }
1430
+ const mergedOut = upstream ? gitCmd(root, ["branch", "--merged", upstream]) : null;
1431
+ const merged = new Set(
1432
+ mergedOut && mergedOut.status === 0
1433
+ ? (mergedOut.stdout || "")
1434
+ .split(/\r?\n/)
1435
+ .map((l) => l.replace(/^[*+ ]+/, "").trim())
1436
+ .filter(Boolean)
1437
+ : []
1438
+ );
1439
+ const matched = new Set();
1440
+ // `--self` is the authorization token `ship` passes after CI is green, so the
1441
+ // session that just finished may prune its OWN worktree. It resolves the
1442
+ // caller by process ancestry (a bash invocation carries no HARNESS_SESSION_ID)
1443
+ // against the MAIN tree's live leases, then lifts the guard ONLY for a
1444
+ // checkout the caller's pointer actually names (`isSelf` below). A plain
1445
+ // `worktree-prune` (a foreign/concurrent caller, e.g. the F-252 prune) passes
1446
+ // no token; and because several sessions can share one opencode pid, the
1447
+ // exact-pointer match means a same-pid sibling can never be mistaken for the
1448
+ // caller. `--dir <path>` narrows a `--self` run to the single just-shipped
1449
+ // checkout, so it can never converge (and thus never remove) another
1450
+ // session's worktree.
1451
+ const onlyDir = argv.dir ? path.resolve(argv.dir) : null;
1452
+ const selfSession = argv.self ? process.env.HARNESS_SESSION_ID || ancestorSessionId(main) : "";
1453
+ const selfPointer = selfSession ? readSessionWorktree(main, selfSession) : "";
1454
+ const isSelf = (p) => !!(selfPointer && path.resolve(selfPointer) === path.resolve(p));
1455
+ const inUse = liveSessionWorktreeDirs(main);
1456
+
1457
+ let pruned = 0;
1458
+ for (const e of entries) {
1459
+ const label = path.basename(e.path);
1460
+ if (path.resolve(e.path) === path.resolve(main)) continue; // never the main tree
1461
+ if (onlyDir && path.resolve(e.path) !== onlyDir) continue; // a --self run stays narrow
1462
+ if (!e.branch) {
1463
+ notes.push(`kept ${label} (detached HEAD)`);
1464
+ continue;
1465
+ }
1466
+ if (explicit.has(e.branch)) matched.add(e.branch);
1467
+ // Never remove a checkout this very session is rooted IN. A `--open`
1468
+ // session's opencode process lives in the worktree (its lease is under the
1469
+ // worktree's own `.serve/sessions/`), so removing it would yank the running
1470
+ // session's cwd. A mid-session owner launched in main leaves no lease here,
1471
+ // so its finished worktree is still removable.
1472
+ if (leaseAncestorIn(e.path)) {
1473
+ notes.push(`kept ${label} (this session is rooted in it — prune after the session closes)`);
1474
+ continue;
1475
+ }
1476
+ // A worktree a live session still owns is off-limits even when merged and
1477
+ // clean: that session may be mid-`ship`, watching CI from it (F-252). The
1478
+ // owner's own `--self` request releases exactly its own checkout.
1479
+ if (inUse.has(path.resolve(e.path)) && !isSelf(e.path)) {
1480
+ notes.push(`kept ${label} (in use by a live session)`);
1481
+ continue;
1482
+ }
1483
+ const dirty = gitCmd(e.path, ["status", "--porcelain"]);
1484
+ if ((dirty.stdout || "").trim()) {
1485
+ notes.push(`kept ${label} (uncommitted work)`);
1486
+ continue;
1487
+ }
1488
+ const isMerged = explicit.has(e.branch) || merged.has(e.branch);
1489
+ if (!isMerged) {
1490
+ notes.push(
1491
+ `kept ${label} (branch ${e.branch} not merged into ${upstream || "upstream"} — name it to prune a squash-merged branch)`
1492
+ );
1493
+ continue;
1494
+ }
1495
+ const rm = gitCmd(main, ["worktree", "remove", e.path]);
1496
+ if (rm.status !== 0) {
1497
+ notes.push(`could not remove ${label}: ${(rm.stderr || rm.stdout || "").trim()}`);
1498
+ continue;
1499
+ }
1500
+ gitCmd(root, ["branch", "-d", e.branch]);
1501
+ clearSessionWorktree(main, isSelf(e.path) ? selfSession : process.env.HARNESS_SESSION_ID, e.path);
1502
+ notes.push(`pruned ${label} (${e.branch})`);
1503
+ pruned += 1;
1504
+ }
1505
+ for (const name of explicit) {
1506
+ if (!matched.has(name)) notes.push(`no linked worktree on branch ${name}`);
1507
+ }
1508
+ if (!notes.length) notes.push("no linked worktrees to consider");
1509
+ return { notes, pruned };
1510
+ }
1511
+
1512
+ // ---------------------------------------------------------------- dispatch
1513
+
1514
+ function formatResult(cmd, out) {
1515
+ if (cmd === "add") return `added ${out.id} [${out.priority}] ${out.task}`;
1516
+ if (cmd === "take") return out.note ? `${out.id}: ${out.note}` : `took ${out.id} -> In progress (${out.handoff})`;
1517
+ if (cmd === "queue") return out.note ? `${out.id}: ${out.note}` : `queued ${out.id} (${out.task})`;
1518
+ if (cmd === "unqueue") return out.note ? `${out.id}: ${out.note}` : `unqueued ${out.id} -> Open (${out.task})`;
1519
+ if (cmd === "next") {
1520
+ if (out.empty && out.blocked) return `next: all queued rows are blocked (${out.blocked.join(", ")})`;
1521
+ if (out.empty) return "no queued rows";
1522
+ return out.handoff ? `next -> took ${out.id} (${out.handoff})` : `next: ${out.id} [${out.priority}] ${out.task}`;
1523
+ }
1524
+ if (cmd === "archive") {
1525
+ const base = out.note
1526
+ ? `${out.id}: ${out.note}${out.closed ? "; closed note updated" : ""}`
1527
+ : `archived ${out.id} (${out.closed})`;
1528
+ return out.cleanup && out.cleanup.length ? `${base} — ${out.cleanup.join("; ")}` : base;
1529
+ }
1530
+ if (cmd === "freeze") return out.note ? `${out.id}: ${out.note}` : `froze ${out.id} (${out.cond})`;
1531
+ if (cmd === "reopen") return out.note ? `${out.id}: ${out.note}` : `reopened ${out.id} -> Open [${out.priority}] (${out.reason})`;
1532
+ if (cmd === "priority") return `set ${out.id} -> ${out.priority}`;
1533
+ if (cmd === "depends") return `set ${out.id} -> depends on ${out.dependsOn}`;
1534
+ if (cmd === "owns") return `recorded ${out.id} owns: ${out.files}`;
1535
+ if (cmd === "worktree")
1536
+ return `isolated ${out.id} -> worktree: ${out.dir} (branch: ${out.branch}${out.base && out.base !== "HEAD" ? `; base: ${out.base}` : ""})`;
1537
+ if (cmd === "epic-add") return `added epic ${out.key} (${out.label})`;
1538
+ if (cmd === "epic") return `set ${out.id} -> ${out.epic}`;
1539
+ return "";
1540
+ }
1541
+
1542
+ function parseArgs(argv) {
1543
+ const args = { _: [] };
1544
+ for (let i = 0; i < argv.length; i++) {
1545
+ const a = argv[i];
1546
+ if (a === "--p" || a === "--priority") args.p = argv[++i];
1547
+ else if (a === "--evidence" || a === "-e") args.evidence = argv[++i];
1548
+ else if (a === "--handoff") args.handoff = argv[++i];
1549
+ else if (a === "--closed") args.closed = argv[++i];
1550
+ else if (a === "--why") args.why = argv[++i];
1551
+ else if (a === "--reason") args.reason = argv[++i];
1552
+ else if (a === "--reopen") args.reopen = argv[++i];
1553
+ else if (a === "--id") args.id = argv[++i];
1554
+ else if (a === "--branch") args.branch = argv[++i];
1555
+ else if (a === "--dir") args.dir = argv[++i];
1556
+ else if (a === "--epic") args.epic = argv[++i];
1557
+ else if (a === "--to") args.to = argv[++i];
1558
+ else if (a === "--label") args.label = argv[++i];
1559
+ else if (a === "--goal") args.goal = argv[++i];
1560
+ else if (a === "--depends-on" || a === "--depends") args["depends-on"] = argv[++i];
1561
+ else if (a === "--on") args.on = argv[++i];
1562
+ else if (a === "--files") args.files = argv[++i];
1563
+ else if (a === "--take") args.take = true;
1564
+ else if (a === "--self") args.self = true;
1565
+ else if (a === "--open") args.open = true;
1566
+ else if (a === "--open-cmd") args["open-cmd"] = argv[++i];
1567
+ else if (a === "--no-fetch") args["no-fetch"] = true;
1568
+ else if (a === "--defer") args.defer = true;
1569
+ else if (a === "--all") args.all = true;
1570
+ else if (a === "--full") args.full = true;
1571
+ else if (a === "--limit") args.limit = argv[++i];
1572
+ else if (a === "--json") args.json = true;
1573
+ else if (a === "--root") args.root = argv[++i];
1574
+ else args._.push(a);
1575
+ }
1576
+ return args;
1577
+ }
1578
+
1579
+ function usage() {
1580
+ console.log(
1581
+ "backlog — deterministic BACKLOG.md editor (no LLM)\n\n" +
1582
+ " node scripts/backlog.js list [--all] [--full] [--limit N] [--json]\n" +
1583
+ " node scripts/backlog.js add <task> [--p P1..P4] [--epic key] [--evidence x] [--id F-xxx] [--depends-on ids]\n" +
1584
+ " node scripts/backlog.js take <id> [--handoff path]\n" +
1585
+ " node scripts/backlog.js queue <id>\n" +
1586
+ " node scripts/backlog.js unqueue <id>\n" +
1587
+ " node scripts/backlog.js next [--take] [--handoff path]\n" +
1588
+ " node scripts/backlog.js archive <id> [--closed note]\n" +
1589
+ " node scripts/backlog.js freeze <id> [--why x] [--reopen x]\n" +
1590
+ " node scripts/backlog.js reopen <id> [--reason x] [--p P1..P4]\n" +
1591
+ " node scripts/backlog.js priority <id> --p P1..P4\n" +
1592
+ " node scripts/backlog.js depends <id> --on <ids|?>\n" +
1593
+ " node scripts/backlog.js owns <id> --files \"glob, glob\"\n" +
1594
+ " node scripts/backlog.js sync [--root <dir>] [--no-fetch]\n" +
1595
+ " node scripts/backlog.js worktree <id> [--branch b] [--dir d] [--handoff path] [--no-fetch] [--open]\n" +
1596
+ " node scripts/backlog.js worktree-prune [<branch>...] [--self] [--dir d] [--no-fetch]\n" +
1597
+ " node scripts/backlog.js epic-add <key> --label <x> [--goal <y>]\n" +
1598
+ " node scripts/backlog.js epic <id> --to <key>\n"
1599
+ );
1600
+ }
1601
+
1602
+ /* Render the service `BacklogBoard` with the same layout as `cmdList`, so a
1603
+ * session's `list` output is identical whichever backend it uses. */
1604
+ function renderServiceList(board, argv) {
1605
+ const full = !!argv.full;
1606
+ const TASK_W = full ? Infinity : 120;
1607
+ const SUB_W = full ? Infinity : 90;
1608
+ let limit = LIST_DEFAULT_LIMIT;
1609
+ if (argv.limit != null) {
1610
+ const n = Number.parseInt(argv.limit, 10);
1611
+ limit = Number.isFinite(n) && n >= 0 ? n : LIST_DEFAULT_LIMIT;
1612
+ }
1613
+
1614
+ for (const line of board.active || []) console.log(`- ${stripEmphasis(line)}`);
1615
+ if ((board.active || []).length) console.log("");
1616
+
1617
+ const groups = [["inprogress", "In progress"], ["queued", "Queued"], ["open", "Open"]];
1618
+ if (argv.all) groups.push(["frozen", "Frozen"], ["archive", "Archive"]);
1619
+
1620
+ for (const [key, label] of groups) {
1621
+ const rows = board[key] || [];
1622
+ console.log(`${label} (${rows.length})`);
1623
+ const shown = limit > 0 && rows.length > limit ? rows.slice(0, limit) : rows;
1624
+ for (const r of shown) {
1625
+ if (key === "open" || key === "queued") {
1626
+ console.log(` ${r.id} [${r.priority}] [${r.epic}] ${truncate(r.task || "", TASK_W)}`);
1627
+ if (r.evidence && r.evidence !== "?") console.log(` evidence: ${truncate(r.evidence, SUB_W)}`);
1628
+ } else if (key === "inprogress") {
1629
+ console.log(` ${r.id} [${r.epic}] ${truncate(r.task || "", TASK_W)}`);
1630
+ if (r.handoff && r.handoff !== "?") console.log(` handoff: ${truncate(r.handoff, SUB_W)}`);
1631
+ } else if (key === "frozen") {
1632
+ console.log(` ${r.id} [${r.epic}] ${truncate(r.task || "", TASK_W)}`);
1633
+ if (r.condition) console.log(` reopen: ${truncate(r.condition, SUB_W)}`);
1634
+ } else {
1635
+ console.log(` ${r.id} [${r.epic}] ${truncate(r.task || "", TASK_W)}`);
1636
+ if (r.closed) console.log(` closed: ${truncate(r.closed, SUB_W)}`);
1637
+ }
1638
+ }
1639
+ if (shown.length < rows.length) console.log(` … +${rows.length - shown.length} row(s) omitted (--limit ${limit}, 0 = all)`);
1640
+ console.log("");
1641
+ }
1642
+ }
1643
+
1644
+ /* The service-backed command path (ADR 0001 Phase 2). Mirrors every read/write
1645
+ * the file backend supports; `worktree` does its local git work here and records
1646
+ * the row through the service. Returns true when it handled the command. */
1647
+ function runService(root, cmd, argv) {
1648
+ const out = (result, extra) => {
1649
+ const formatted = formatResult(cmd, { ...result, ...(extra || {}) });
1650
+ if (formatted) console.log(formatted);
1651
+ return true;
1652
+ };
1653
+
1654
+ if (cmd === "list") {
1655
+ const board = boardClient.getBoard(root);
1656
+ if (argv.json) console.log(JSON.stringify(board, null, 2));
1657
+ else renderServiceList(board, argv);
1658
+ return true;
1659
+ }
1660
+ if (cmd === "next" && !argv.take) return out(boardClient.next(root));
1661
+ if (cmd === "next" && argv.take) return out(boardClient.nextTake(root, argv.handoff));
1662
+ if (cmd === "add") return out(boardClient.add(root, argv));
1663
+ if (cmd === "take") return out(boardClient.take(root, argv._[0], argv.handoff));
1664
+ if (cmd === "queue") return out(boardClient.queue(root, argv._[0]));
1665
+ if (cmd === "unqueue") return out(boardClient.unqueue(root, argv._[0]));
1666
+ if (cmd === "archive") return out(boardClient.archive(root, argv._[0], argv.closed));
1667
+ if (cmd === "freeze") return out(boardClient.freeze(root, argv._[0], argv.why, argv.reopen));
1668
+ if (cmd === "reopen") return out(boardClient.reopen(root, argv._[0], argv.reason, argv.p));
1669
+ if (cmd === "priority") return out(boardClient.priority(root, argv._[0], argv.p));
1670
+ if (cmd === "epic") return out(boardClient.setEpic(root, argv._[0], argv.to));
1671
+ if (cmd === "depends") return out(boardClient.depends(root, argv._[0], argv.on));
1672
+ if (cmd === "owns") {
1673
+ const r = boardClient.owns(root, argv._[0], argv.files);
1674
+ return out(r, { files: r.files });
1675
+ }
1676
+ if (cmd === "epic-add") return out(boardClient.epicAdd(root, argv._[0], argv.label, argv.goal));
1677
+
1678
+ if (cmd === "worktree") {
1679
+ const id = argv._[0];
1680
+ if (!id) throw new Error("worktree: missing <id>.");
1681
+ const slug = id.toLowerCase();
1682
+ const branch = argv.branch || slug;
1683
+ const dir = argv.dir ? path.resolve(argv.dir) : path.resolve(root, "..", ".worktrees", path.basename(root), slug);
1684
+ const rootAbs = path.resolve(root);
1685
+ if (dir === rootAbs || dir.startsWith(rootAbs + path.sep)) {
1686
+ throw new Error(`worktree: refusing a worktree inside the repository (${dir}).`);
1687
+ }
1688
+ const handoff = argv.handoff !== undefined ? validateHandoff(id, argv.handoff) : `.agents/handoffs/${id}.md`;
1689
+ const rel = path.relative(root, dir) || dir;
1690
+
1691
+ // Record the In-progress row + isolation target through the service first.
1692
+ boardClient.worktreeRecord(root, id, rel, branch, handoff);
1693
+ // Then create the checkout locally (git-side effect stays on this machine).
1694
+ const base = currentUpstream(root) || "HEAD";
1695
+ const res = spawnSync("git", ["-C", root, "worktree", "add", "--no-track", "-b", branch, dir, base], { encoding: "utf8" });
1696
+ if (res.status !== 0) throw new Error(`worktree: git worktree add failed: ${(res.stderr || res.stdout || "").trim()}`);
1697
+ runWorktreeSetup(root, dir);
1698
+ const sessionID = ancestorSessionId(root);
1699
+ writeSessionWorktree(root, sessionID, dir);
1700
+ const plan = { id, branch, dir: rel, dirAbs: dir, handoff, base };
1701
+ out(plan);
1702
+ if (argv.open) openWorktreeSession(dir, argv["open-cmd"]);
1703
+ return true;
1704
+ }
1705
+
1706
+ usage();
1707
+ process.exitCode = 1;
1708
+ return true;
1709
+ }
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
+
1734
+ function main() {
1735
+ const raw = process.argv.slice(2);
1736
+ const cmd = raw[0];
1737
+ if (!cmd || cmd === "help" || cmd === "--help" || cmd === "-h") {
1738
+ usage();
1739
+ return;
1740
+ }
1741
+ const args = parseArgs(raw.slice(1));
1742
+
1743
+ const explicitRoot = Boolean(args.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).");
1747
+ process.exitCode = 1;
1748
+ return;
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] });
1753
+
1754
+ // Service backend (ADR 0001): the board lives in the external service, so
1755
+ // every read/write goes over HTTP. Git-side effects (worktree add/remove) stay
1756
+ // local. `BACKLOG_BACKEND=file` forces the legacy path. An explicit `--root`
1757
+ // names a local checkout, so it too forces the file backend and can never be
1758
+ // redirected to the shared service by ambient config (F-333/F-338).
1759
+ if (boardClient.enabled(root, { forceFile: explicitRoot }) && cmd !== "worktree-prune" && cmd !== "sync") {
1760
+ try {
1761
+ return runService(root, cmd, args);
1762
+ } catch (e) {
1763
+ console.error(`backlog: ${e.message}`);
1764
+ process.exitCode = 1;
1765
+ return;
1766
+ }
1767
+ }
1768
+
1769
+ // Read-only commands never lock or write. They show the working board
1770
+ // reconciled against the last-known upstream, so a stale main checkout can't
1771
+ // mislead a decision (a shipped row that still shows Open locally).
1772
+ if (cmd === "list" || (cmd === "next" && !args.take)) {
1773
+ const state = readBacklog(root);
1774
+ const upstream = boardSync.isCanonicalCheckout(root) ? currentUpstream(root) : "";
1775
+ const disp = boardSync.displayBoard(root, upstream);
1776
+ if (disp.board) state.lines = disp.board.split(/\r?\n/);
1777
+ if (disp.behind > 0) {
1778
+ console.log(`board: main is ${disp.behind} behind ${upstream} — showing the reconciled view`);
1779
+ }
1780
+ if (cmd === "list") {
1781
+ if (args.json) console.log(JSON.stringify(toBoardJson(state), null, 2));
1782
+ else cmdList(state, args);
1783
+ } else {
1784
+ console.log(formatResult("next", cmdNext(state, args)));
1785
+ }
1786
+ return;
1787
+ }
1788
+
1789
+ // Mutating commands read-modify-write BACKLOG.md (or owned-files.md) under an
1790
+ // exclusive lock, so two concurrent sessions can't both claim the same row.
1791
+ // In the canonical checkout every mutation is a transaction: converge against
1792
+ // origin first, apply the row change, then commit + publish it. Main therefore
1793
+ // never carries an uncommitted board copy, and a mutation can never resurrect
1794
+ // a row that already landed in Archive upstream.
1795
+ let worktreeOut = null;
1796
+ const defer = !!args.defer;
1797
+ try {
1798
+ withLock(root, () => {
1799
+ const canonical = boardSync.isCanonicalCheckout(root);
1800
+ const upstream = canonical ? currentUpstream(root) : "";
1801
+ const notes = [];
1802
+ let canPublish = true;
1803
+
1804
+ if (canonical && upstream && cmd !== "worktree-prune") {
1805
+ const conv = boardSync.convergeCanonical(root, upstream, { fetch: !args["no-fetch"] && !defer });
1806
+ notes.push(...conv.notes);
1807
+ if (!conv.ok) throw new Error(conv.notes[conv.notes.length - 1] || "canonical checkout is not converged");
1808
+ canPublish = conv.canPublish !== false;
1809
+ } else if (cmd === "worktree" || cmd === "archive") {
1810
+ notes.push(...refreshMainCheckout(root, { fetch: !args["no-fetch"] && !defer }));
1811
+ }
1812
+
1813
+ if (cmd === "sync") {
1814
+ if (!canonical || !upstream) {
1815
+ notes.push("not the canonical checkout (or no upstream) — nothing to publish");
1816
+ } else if (!canPublish) {
1817
+ notes.push("main is diverged — reconcile manually: git pull --rebase");
1818
+ } else {
1819
+ const pub = boardSync.publishBoard(root, upstream, "chore(board): sync local rows");
1820
+ if (pub.published && pub.committed) notes.push(`published board to ${upstream}`);
1821
+ else if (!pub.published) notes.push(publishFailureNote(pub));
1822
+ }
1823
+ for (const note of notes) console.log(`board: ${note}`);
1824
+ return;
1825
+ }
1826
+
1827
+ const state = readBacklog(root);
1828
+ let out;
1829
+ let after = null;
1830
+ let publishMessage = null;
1831
+ if (cmd === "add") out = cmdAdd(state, args);
1832
+ else if (cmd === "take") out = cmdTake(state, args);
1833
+ else if (cmd === "queue") out = cmdQueue(state, args);
1834
+ else if (cmd === "unqueue") out = cmdUnqueue(state, args);
1835
+ else if (cmd === "next") out = cmdNext(state, args);
1836
+ else if (cmd === "archive") out = cmdArchive(state, args);
1837
+ else if (cmd === "freeze") out = cmdFreeze(state, args);
1838
+ else if (cmd === "reopen") out = cmdReopen(state, args);
1839
+ else if (cmd === "priority") out = cmdPriority(state, args);
1840
+ else if (cmd === "depends") out = cmdDepends(state, args);
1841
+ else if (cmd === "owns") out = cmdOwns(state, args);
1842
+ else if (cmd === "worktree") {
1843
+ out = cmdWorktreePlan(state, args);
1844
+ after = () => {
1845
+ out = cmdWorktreeApply(root, out);
1846
+ };
1847
+ } else if (cmd === "worktree-prune") out = cmdWorktreePrune(state, args);
1848
+ else if (cmd === "epic-add") out = cmdEpicAdd(state, args);
1849
+ else if (cmd === "epic") out = cmdEpic(state, args);
1850
+ else {
1851
+ usage();
1852
+ process.exitCode = 1;
1853
+ return;
1854
+ }
1855
+
1856
+ if (cmd === "worktree-prune") {
1857
+ for (const note of out.notes) console.log(`worktree-prune: ${note}`);
1858
+ } else if (cmd === "owns") {
1859
+ publishMessage = `chore(board): owns ${out.id}`;
1860
+ } else {
1861
+ fs.writeFileSync(state.p, serializeBacklog(state), "utf8");
1862
+ publishMessage = `chore(board): ${cmd}${out && out.id ? " " + out.id : ""}`;
1863
+ }
1864
+
1865
+ // Publish the board BEFORE any filesystem side effect: the worktree must
1866
+ // be based on an origin that already carries the In-progress row.
1867
+ if (canonical && upstream && publishMessage && canPublish) {
1868
+ const pub = boardSync.publishBoard(root, upstream, publishMessage, { deferPush: defer });
1869
+ if (pub.published && pub.committed) notes.push(`published board to ${upstream}`);
1870
+ else if (!pub.published) notes.push(publishFailureNote(pub));
1871
+ } else if (canonical && upstream && publishMessage && !canPublish) {
1872
+ notes.push(`not published (main is diverged) — resolve with git pull --rebase, then \`node scripts/backlog.js sync\``);
1873
+ }
1874
+
1875
+ if (after) after();
1876
+ if (cmd !== "worktree-prune") console.log(formatResult(cmd, out));
1877
+ if (cmd === "worktree") worktreeOut = out;
1878
+ for (const note of notes) console.log(`board: ${note}`);
1879
+ });
1880
+ } catch (e) {
1881
+ console.error(`backlog: ${e.message}`);
1882
+ process.exitCode = 1;
1883
+ }
1884
+
1885
+ // The lock is released; now make the worktree the interactive session root.
1886
+ if (cmd === "worktree" && args.open && worktreeOut) {
1887
+ openWorktreeSession(worktreeOut.dirAbs, args["open-cmd"]);
1888
+ }
1889
+ }
1890
+
1891
+ if (require.main === module) main();
1892
+
1893
+ module.exports = {
1894
+ splitCells,
1895
+ findRoot,
1896
+ readBacklog,
1897
+ findSection,
1898
+ tableBlock,
1899
+ dataRows,
1900
+ getRows,
1901
+ setRows,
1902
+ nextId,
1903
+ cmdAdd,
1904
+ cmdTake,
1905
+ cmdQueue,
1906
+ cmdUnqueue,
1907
+ cmdNext,
1908
+ cmdArchive,
1909
+ cmdFreeze,
1910
+ cmdReopen,
1911
+ cmdPriority,
1912
+ cmdDepends,
1913
+ cmdOwns,
1914
+ cmdWorktree,
1915
+ cmdWorktreePlan,
1916
+ cmdWorktreeApply,
1917
+ cmdEpicAdd,
1918
+ cmdEpic,
1919
+ readEpics,
1920
+ toBoardJson,
1921
+ withLock,
1922
+ dependencyGraph,
1923
+ findCycle,
1924
+ };