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,260 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ /*
4
+ * board-client — HTTP client for the shared board service (ADR 0001).
5
+ *
6
+ * The service is the external, project-scoped board (its own Next.js + Prisma
7
+ * app). This module is the single home for talking to it, so the CLI
8
+ * (scripts/backlog.js), the opencode tools, and any future consumer share one
9
+ * transport. `scripts/backlog.js` picks a backend via `BACKLOG_BACKEND`:
10
+ * - service : all board reads/writes go to the HTTP service
11
+ * - file : the legacy BACKLOG.md path (unchanged)
12
+ *
13
+ * Config is resolved from the project's `.harness.json` `board` block first
14
+ * (per project, survives harness updates), then the environment:
15
+ * .harness.json -> { "board": { "url", "token", "project" } }
16
+ * BACKLOG_API_URL / BACKLOG_API_TOKEN / BACKLOG_PROJECT (env override)
17
+ *
18
+ * The functions mirror `backlog.js` command results so `formatResult` prints the
19
+ * same text for either backend.
20
+ */
21
+ const fs = require("fs");
22
+ const path = require("path");
23
+
24
+ /* Read the per-project board config block from `.harness.json`, if present.
25
+ * The `token` there is honored but discouraged (it is a committed secret); the
26
+ * machine-level token store below is the recommended home. */
27
+ function projectBoardConfig(root) {
28
+ try {
29
+ const cfg = JSON.parse(fs.readFileSync(path.join(root, ".harness.json"), "utf8"));
30
+ const b = cfg && cfg.board;
31
+ if (b && typeof b === "object") {
32
+ return {
33
+ url: typeof b.url === "string" ? b.url : "",
34
+ token: typeof b.token === "string" ? b.token : "",
35
+ project: typeof b.project === "string" ? b.project : "",
36
+ };
37
+ }
38
+ } catch {
39
+ /* no .harness.json / no board block */
40
+ }
41
+ return { url: "", token: "", project: "" };
42
+ }
43
+
44
+ /* Machine-level token store: `~/.config/agent-harness/tokens.json` maps a
45
+ * project key to its service token (never committed). */
46
+ function tokenStore(project) {
47
+ const base = process.env.XDG_CONFIG_HOME || path.join(require("os").homedir(), ".config");
48
+ try {
49
+ const store = JSON.parse(fs.readFileSync(path.join(base, "agent-harness", "tokens.json"), "utf8"));
50
+ if (project && typeof store[project] === "string") return store[project];
51
+ } catch {
52
+ /* no store */
53
+ }
54
+ return "";
55
+ }
56
+
57
+ function config(root) {
58
+ const file = root ? projectBoardConfig(root) : { url: "", token: "", project: "" };
59
+ const project = process.env.BACKLOG_PROJECT || file.project || "";
60
+ const url = (process.env.BACKLOG_API_URL || file.url || "").replace(/\/+$/, "");
61
+ const token = process.env.BACKLOG_API_TOKEN || file.token || tokenStore(project) || "";
62
+ return { url, token, project };
63
+ }
64
+
65
+ /**
66
+ * True when the CLI should use the service backend.
67
+ *
68
+ * `opts.forceFile` pins the legacy file backend unconditionally. An explicit
69
+ * `--root <dir>` names a local checkout, so an ambient service config
70
+ * (`BACKLOG_BACKEND=service`, `BACKLOG_API_URL`/`TOKEN`, or a `.harness.json`
71
+ * board block) must never redirect that write to the shared board — the F-333
72
+ * leak, where file-backend QA tests passing `--root <tmp>` added fixture rows to
73
+ * the live service because the ambient config re-enabled it.
74
+ *
75
+ * Auto mode requires the root's OWN `.harness.json` `board.url` — i.e. the
76
+ * project itself declares a board. Ambient environment alone (the
77
+ * `board-service.sh` shell hook exports `BACKLOG_API_URL`/`TOKEN`/`PROJECT`
78
+ * globally) must NOT auto-select the service, or any file-backend run under a
79
+ * board-configured shell (e.g. `npm test` in the harness) writes its local
80
+ * fixtures into the live shared board — the F-339 fixture-row leak. An
81
+ * env-only setup opts in explicitly with `BACKLOG_BACKEND=service`.
82
+ */
83
+ function enabled(root, opts) {
84
+ if (opts && opts.forceFile) return false;
85
+ if (process.env.BACKLOG_BACKEND === "file") return false;
86
+ if (process.env.BACKLOG_BACKEND === "service") return true;
87
+ if (!projectBoardConfig(root).url) return false;
88
+ const c = config(root);
89
+ return Boolean(c.url && c.token);
90
+ }
91
+
92
+ function projectKey(root) {
93
+ const c = config(root);
94
+ if (c.project) return c.project;
95
+ try {
96
+ const cfg = JSON.parse(fs.readFileSync(path.join(root, ".harness.json"), "utf8"));
97
+ if (cfg && typeof cfg.projectName === "string" && cfg.projectName.trim()) return cfg.projectName.trim();
98
+ } catch {
99
+ /* no .harness.json — fall back to the directory name */
100
+ }
101
+ return path.basename(root);
102
+ }
103
+
104
+ /**
105
+ * Synchronous HTTP via a tiny child that uses fetch and prints the response.
106
+ * The CLI is synchronous end-to-end (execFileSync-based), so a blocking bridge
107
+ * keeps the call sites unchanged and avoids rewriting every command async.
108
+ */
109
+ function httpSync(root, method, endpoint, body) {
110
+ const c = config(root);
111
+ if (!c.url) throw new Error("board service not configured: set BACKLOG_API_URL");
112
+ if (!c.token) throw new Error("board service token missing: set BACKLOG_API_TOKEN");
113
+
114
+ const payload = JSON.stringify({
115
+ url: `${c.url}${endpoint}`,
116
+ method,
117
+ token: c.token,
118
+ project: projectKey(root),
119
+ body: body === undefined ? null : body,
120
+ });
121
+
122
+ const script = `
123
+ const p = JSON.parse(require("fs").readFileSync(0, "utf8"));
124
+ const headers = { Authorization: "Bearer " + p.token, "X-Project": p.project };
125
+ const init = { method: p.method, headers };
126
+ if (p.body !== null) { headers["Content-Type"] = "application/json"; init.body = JSON.stringify(p.body); }
127
+ fetch(p.url, init).then(async (r) => {
128
+ const text = await r.text();
129
+ process.stdout.write(JSON.stringify({ status: r.status, body: text }));
130
+ }).catch((e) => { process.stdout.write(JSON.stringify({ status: 0, error: String(e && e.message || e) })); });
131
+ `;
132
+
133
+ const res = require("child_process").execFileSync(process.execPath, ["-e", script], {
134
+ input: payload,
135
+ encoding: "utf8",
136
+ maxBuffer: 32 * 1024 * 1024,
137
+ });
138
+ let parsed;
139
+ try {
140
+ parsed = JSON.parse(res);
141
+ } catch {
142
+ throw new Error(`board service: unparseable response: ${res.slice(0, 200)}`);
143
+ }
144
+ if (parsed.status === 0) throw new Error(`board service unreachable at ${c.url}: ${parsed.error}`);
145
+ const json = parsed.body ? JSON.parse(parsed.body) : {};
146
+ if (parsed.status >= 400) throw new Error(json.error || `board service error ${parsed.status}`);
147
+ return json;
148
+ }
149
+
150
+ /** The frozen BacklogBoard shape. */
151
+ function getBoard(root) {
152
+ return httpSync(root, "GET", "/api/board");
153
+ }
154
+
155
+ function cmdResult(root, action, id, body) {
156
+ const endpoint = id ? `/api/items/${encodeURIComponent(id)}/${action}` : `/api/items`;
157
+ return httpSync(root, "POST", endpoint, body || {});
158
+ }
159
+
160
+ function add(root, args) {
161
+ return httpSync(root, "POST", "/api/items", {
162
+ task: args._[0],
163
+ priority: args.p,
164
+ evidence: args.evidence,
165
+ epic: args.epic,
166
+ dependsOn: args["depends-on"] || args.depends,
167
+ id: args.id,
168
+ }).result;
169
+ }
170
+
171
+ /** Look up a row in the live board so results carry task/closed for output parity. */
172
+ function rowById(board, id) {
173
+ for (const key of ["open", "queued", "inprogress", "frozen", "archive"]) {
174
+ const row = (board[key] || []).find((r) => r.id === id);
175
+ if (row) return { key, row };
176
+ }
177
+ return { key: null, row: null };
178
+ }
179
+
180
+ function take(root, id, handoff) {
181
+ const json = httpSync(root, "POST", `/api/items/${encodeURIComponent(id)}/take`, { handoff });
182
+ const { row } = rowById(json.board, id);
183
+ return { ...json.result, handoff: row ? row.handoff : handoff };
184
+ }
185
+ function queue(root, id) {
186
+ const json = httpSync(root, "POST", `/api/items/${encodeURIComponent(id)}/queue`, {});
187
+ const { row } = rowById(json.board, id);
188
+ return { ...json.result, task: row ? row.task : undefined };
189
+ }
190
+ function unqueue(root, id) {
191
+ const json = httpSync(root, "POST", `/api/items/${encodeURIComponent(id)}/unqueue`, {});
192
+ const { row } = rowById(json.board, id);
193
+ return { ...json.result, task: row ? row.task : undefined };
194
+ }
195
+ function archive(root, id, closed) {
196
+ const json = httpSync(root, "POST", `/api/items/${encodeURIComponent(id)}/archive`, { closed });
197
+ const { row } = rowById(json.board, id);
198
+ return { ...json.result, task: row ? row.task : undefined, closed: row ? row.closed : closed };
199
+ }
200
+ function freeze(root, id, why, reopen) {
201
+ const json = httpSync(root, "POST", `/api/items/${encodeURIComponent(id)}/freeze`, { why, reopen });
202
+ const { row } = rowById(json.board, id);
203
+ return { ...json.result, cond: row ? row.condition : [why, reopen ? `reopen when ${reopen}` : ""].filter(Boolean).join(" — ") };
204
+ }
205
+ function reopen(root, id, reason, priority) {
206
+ const json = httpSync(root, "POST", `/api/items/${encodeURIComponent(id)}/reopen`, { reason, priority });
207
+ const { row } = rowById(json.board, id);
208
+ return { ...json.result, reason: reason || "reopened", priority: row ? row.priority : priority };
209
+ }
210
+ function priority(root, id, p) {
211
+ return httpSync(root, "POST", `/api/items/${encodeURIComponent(id)}/priority`, { priority: p }).result;
212
+ }
213
+ function setEpic(root, id, to) {
214
+ return httpSync(root, "POST", `/api/items/${encodeURIComponent(id)}/epic`, { to }).result;
215
+ }
216
+ function depends(root, id, on) {
217
+ return httpSync(root, "POST", `/api/items/${encodeURIComponent(id)}/depends`, { on }).result;
218
+ }
219
+ function owns(root, id, files) {
220
+ return httpSync(root, "POST", `/api/items/${encodeURIComponent(id)}/owns`, { files }).result;
221
+ }
222
+ function worktreeRecord(root, id, dir, branch, handoff) {
223
+ return httpSync(root, "POST", `/api/items/${encodeURIComponent(id)}/worktree`, { dir, branch, handoff }).result;
224
+ }
225
+ function epicAdd(root, key, label, goal) {
226
+ return httpSync(root, "POST", "/api/epics", { key, label, goal }).result;
227
+ }
228
+ function next(root) {
229
+ return httpSync(root, "GET", "/api/next");
230
+ }
231
+ function nextTake(root, handoff) {
232
+ return httpSync(root, "POST", "/api/next/take", { handoff }).result;
233
+ }
234
+
235
+ /**
236
+ * The `list --json` shape is the board contract; both backends share it via
237
+ * `getBoard`. The human `list` renderer needs the same arrays, so callers use
238
+ * this directly.
239
+ */
240
+ module.exports = {
241
+ enabled,
242
+ projectKey,
243
+ getBoard,
244
+ add,
245
+ take,
246
+ queue,
247
+ unqueue,
248
+ archive,
249
+ freeze,
250
+ reopen,
251
+ priority,
252
+ setEpic,
253
+ depends,
254
+ owns,
255
+ worktreeRecord,
256
+ epicAdd,
257
+ next,
258
+ nextTake,
259
+ httpSync,
260
+ };
@@ -0,0 +1,96 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ /*
4
+ * board-lib — shared BACKLOG.md row primitives (harness-shipped).
5
+ *
6
+ * One home for the markdown-table row logic the board toolchain shares, so a
7
+ * parse/format bug is fixed in exactly one place instead of being copy-pasted
8
+ * across backlog.js + the QA gates (check-backlog / check-concurrency /
9
+ * merge-backlog). F-094 was the cautionary tale: the write-path sanitizer was
10
+ * added only to a deployed copy and silently reverted by the next harness
11
+ * update because it never reached a shared source.
12
+ *
13
+ * Exports:
14
+ * splitCells(row) split a markdown table row on unescaped `|`
15
+ * isSep(cells) true when a row is a `|---|` separator
16
+ * sanitizeCell(value) make a single cell table-safe (single line, no `|`)
17
+ * formatRow(cells) join cells into one physical `| a | b |` row
18
+ */
19
+ function splitCells(row) {
20
+ const cells = [];
21
+ let cur = "";
22
+ let esc = false;
23
+ for (const ch of row) {
24
+ if (esc) {
25
+ cur += ch;
26
+ esc = false;
27
+ } else if (ch === "\\") {
28
+ esc = true;
29
+ cur += ch;
30
+ } else if (ch === "|") {
31
+ cells.push(cur.trim());
32
+ cur = "";
33
+ } else {
34
+ cur += ch;
35
+ }
36
+ }
37
+ cells.push(cur.trim());
38
+ return cells;
39
+ }
40
+
41
+ function isSep(cells) {
42
+ return cells.every((c) => /^[-:|\s]*$/.test(c));
43
+ }
44
+
45
+ /* A markdown table cell is one token on one physical line. A raw newline (or any
46
+ * other control char) or an unescaped `|` would split one logical row into
47
+ * corrupt fragments — the F-094 newline corruption and the F-127 pipe corruption
48
+ * both came from cells written verbatim. Sanitize before ANY cell is written, so
49
+ * no caller (CLI add, backlog_* tools, reports/admin routes that shell the CLI)
50
+ * can corrupt the board through the shared write path. */
51
+ function sanitizeCell(value) {
52
+ return String(value)
53
+ .replace(/[\x00-\x1f\x7f]/g, " ") // control chars (incl \n, \r, \t) -> space
54
+ .replace(/\s+/g, " ") // collapse whitespace runs (incl ones we just made)
55
+ .replace(/\|/g, "/") // a pipe can never become a column delimiter
56
+ .trim();
57
+ }
58
+
59
+ function formatRow(cells) {
60
+ return "| " + cells.map(sanitizeCell).join(" | ") + " |";
61
+ }
62
+
63
+ /* Return a cycle (as an `A -> B -> A` id list) in a dependency graph
64
+ * (Map<id, string[]>), or null. A cycle leaves every member permanently
65
+ * "blocked" with no mechanical signal, so the board write path and the gate
66
+ * both reject it. Pure — shared by backlog.js and check-backlog.js. */
67
+ function findCycle(graph) {
68
+ const WHITE = 0;
69
+ const GRAY = 1;
70
+ const BLACK = 2;
71
+ const color = new Map();
72
+ const stack = [];
73
+ let cycle = null;
74
+ const visit = (node) => {
75
+ color.set(node, GRAY);
76
+ stack.push(node);
77
+ for (const dep of graph.get(node) || []) {
78
+ if (!graph.has(dep)) continue; // unknown/archived refs are handled elsewhere
79
+ const c = color.get(dep) || WHITE;
80
+ if (c === GRAY) {
81
+ cycle = stack.slice(stack.indexOf(dep)).concat(dep);
82
+ return true;
83
+ }
84
+ if (c === WHITE && visit(dep)) return true;
85
+ }
86
+ stack.pop();
87
+ color.set(node, BLACK);
88
+ return false;
89
+ };
90
+ for (const node of graph.keys()) {
91
+ if ((color.get(node) || WHITE) === WHITE && visit(node)) break;
92
+ }
93
+ return cycle;
94
+ }
95
+
96
+ module.exports = { splitCells, isSep, sanitizeCell, formatRow, findCycle };