opencode-agent-harness 0.0.0-stage → 0.2.0

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