opencode-agent-harness 0.0.0-stage → 0.3.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (171) hide show
  1. package/CHANGELOG.md +217 -0
  2. package/LICENSE +21 -0
  3. package/README.md +636 -2
  4. package/bin/agent-harness.js +3182 -0
  5. package/contrib/global-plugins/README.md +49 -0
  6. package/contrib/global-plugins/harness-freshness.ts +355 -0
  7. package/package.json +86 -4
  8. package/templates/.agents/AGENTS.md +148 -0
  9. package/templates/.agents/features/INDEX.md +10 -0
  10. package/templates/.agents/handoffs/README.md +87 -0
  11. package/templates/.agents/memory/dev-loop.md +59 -0
  12. package/templates/.agents/memory/domain-map.md +29 -0
  13. package/templates/.agents/memory/environments.md +35 -0
  14. package/templates/.agents/memory/flow-map.md +23 -0
  15. package/templates/.agents/memory/history.md +7 -0
  16. package/templates/.agents/memory/locations.md +14 -0
  17. package/templates/.agents/memory/model-routing.md +261 -0
  18. package/templates/.agents/memory/orchestration.md +183 -0
  19. package/templates/.agents/memory/owned-files.md +19 -0
  20. package/templates/.agents/memory/product-principles.md +37 -0
  21. package/templates/.agents/memory/quality-parameters.md +37 -0
  22. package/templates/.agents/memory/stack-versions.md +35 -0
  23. package/templates/.agents/memory/test-design-parameters.md +36 -0
  24. package/templates/.agents/nightly.json +17 -0
  25. package/templates/.agents/qa-plans/README.md +70 -0
  26. package/templates/.agents/qa-runs/README.md +21 -0
  27. package/templates/.agents/reviews/README.md +47 -0
  28. package/templates/.agents/rules/00-operating.md +199 -0
  29. package/templates/.agents/skills/data-engineer/SKILL.md +31 -0
  30. package/templates/.agents/skills/devops-engineer/SKILL.md +50 -0
  31. package/templates/.agents/skills/diagnostics-expert/SKILL.md +44 -0
  32. package/templates/.agents/skills/docs/SKILL.md +140 -0
  33. package/templates/.agents/skills/features/SKILL.md +187 -0
  34. package/templates/.agents/skills/frontend-engineer/SKILL.md +81 -0
  35. package/templates/.agents/skills/handoff/SKILL.md +85 -0
  36. package/templates/.agents/skills/mobile-engineer/SKILL.md +101 -0
  37. package/templates/.agents/skills/planner/SKILL.md +112 -0
  38. package/templates/.agents/skills/product-manager/SKILL.md +115 -0
  39. package/templates/.agents/skills/qa-architect/SKILL.md +224 -0
  40. package/templates/.agents/skills/qa-runner/SKILL.md +64 -0
  41. package/templates/.agents/skills/security-engineer/SKILL.md +53 -0
  42. package/templates/.agents/skills/system-architect/SKILL.md +42 -0
  43. package/templates/.agents/skills/ui-designer/SKILL.md +71 -0
  44. package/templates/.github/workflows/ci.yml +148 -0
  45. package/templates/.github/workflows/deploy-uat.yml +95 -0
  46. package/templates/.github/workflows/nightly.yml +83 -0
  47. package/templates/.github/workflows/uat-health.yml +41 -0
  48. package/templates/.husky/pre-push +23 -0
  49. package/templates/.ignore +28 -0
  50. package/templates/.opencode/agents/data-engineer.md +37 -0
  51. package/templates/.opencode/agents/devops-engineer.md +37 -0
  52. package/templates/.opencode/agents/diagnostics-expert.md +37 -0
  53. package/templates/.opencode/agents/docs.md +37 -0
  54. package/templates/.opencode/agents/features.md +21 -0
  55. package/templates/.opencode/agents/frontend-engineer.md +37 -0
  56. package/templates/.opencode/agents/handoff.md +21 -0
  57. package/templates/.opencode/agents/mobile-engineer.md +37 -0
  58. package/templates/.opencode/agents/planner.md +34 -0
  59. package/templates/.opencode/agents/product-manager.md +29 -0
  60. package/templates/.opencode/agents/qa-architect.md +27 -0
  61. package/templates/.opencode/agents/qa-runner.md +17 -0
  62. package/templates/.opencode/agents/security-engineer.md +37 -0
  63. package/templates/.opencode/agents/system-architect.md +37 -0
  64. package/templates/.opencode/agents/ui-designer.md +37 -0
  65. package/templates/.opencode/commands/board.md +15 -0
  66. package/templates/.opencode/commands/checkpoint.md +25 -0
  67. package/templates/.opencode/commands/feature.md +56 -0
  68. package/templates/.opencode/commands/finish.md +36 -0
  69. package/templates/.opencode/commands/next.md +49 -0
  70. package/templates/.opencode/commands/report.md +55 -0
  71. package/templates/.opencode/commands/resume.md +39 -0
  72. package/templates/.opencode/commands/switch-model.md +34 -0
  73. package/templates/.opencode/commands/tidy.md +49 -0
  74. package/templates/.opencode/plugins/backlog-notify.ts +57 -0
  75. package/templates/.opencode/plugins/backlog.ts +272 -0
  76. package/templates/.opencode/plugins/checkpoint.ts +160 -0
  77. package/templates/.opencode/plugins/context-guard.ts +1164 -0
  78. package/templates/.opencode/plugins/diff.ts +85 -0
  79. package/templates/.opencode/plugins/gates.ts +71 -0
  80. package/templates/.opencode/plugins/job-notify.ts +241 -0
  81. package/templates/.opencode/plugins/orient.ts +67 -0
  82. package/templates/.opencode/plugins/session.ts +89 -0
  83. package/templates/.opencode/plugins/wait.ts +101 -0
  84. package/templates/.opencode/plugins/where.ts +70 -0
  85. package/templates/.opencode/skills/bounded-explore/SKILL.md +38 -0
  86. package/templates/.opencode/skills/dev-loop/SKILL.md +87 -0
  87. package/templates/.vercelignore +16 -0
  88. package/templates/AGENTS.md +27 -0
  89. package/templates/BACKLOG.md +95 -0
  90. package/templates/docs/ci-cd-pipeline.md +81 -0
  91. package/templates/docs/gates.md +128 -0
  92. package/templates/docs/mcp-integrations.md +97 -0
  93. package/templates/docs/mobile-testing.md +555 -0
  94. package/templates/docs/nightly-testing.md +106 -0
  95. package/templates/docs/wsl-optimizations.md +290 -0
  96. package/templates/opencode.json +188 -0
  97. package/templates/scripts/agent-report.js +541 -0
  98. package/templates/scripts/agent-search.sh +117 -0
  99. package/templates/scripts/backlog.js +1924 -0
  100. package/templates/scripts/board-service.sh +214 -0
  101. package/templates/scripts/checkpoint.js +290 -0
  102. package/templates/scripts/finalize.js +416 -0
  103. package/templates/scripts/nightly.js +913 -0
  104. package/templates/scripts/orient.js +514 -0
  105. package/templates/scripts/qa/board-client.js +323 -0
  106. package/templates/scripts/qa/board-lib.js +96 -0
  107. package/templates/scripts/qa/board-sync.js +499 -0
  108. package/templates/scripts/qa/capacity-lib.js +916 -0
  109. package/templates/scripts/qa/check-backlog.js +434 -0
  110. package/templates/scripts/qa/check-capacity.js +85 -0
  111. package/templates/scripts/qa/check-ci-policy.js +164 -0
  112. package/templates/scripts/qa/check-concurrency.js +344 -0
  113. package/templates/scripts/qa/check-dispatch-config.js +296 -0
  114. package/templates/scripts/qa/check-docs.js +288 -0
  115. package/templates/scripts/qa/check-integrate.js +98 -0
  116. package/templates/scripts/qa/check-linger.js +160 -0
  117. package/templates/scripts/qa/check-prefix-stability.js +187 -0
  118. package/templates/scripts/qa/check-product.js +177 -0
  119. package/templates/scripts/qa/check-qa-plan.js +378 -0
  120. package/templates/scripts/qa/check-qa-scripts.js +85 -0
  121. package/templates/scripts/qa/check-quality.js +249 -0
  122. package/templates/scripts/qa/check-test-wiring.js +253 -0
  123. package/templates/scripts/qa/check-worktrees.js +93 -0
  124. package/templates/scripts/qa/ci-triage.js +346 -0
  125. package/templates/scripts/qa/ci-usage-lib.js +185 -0
  126. package/templates/scripts/qa/ci-wait-lib.js +294 -0
  127. package/templates/scripts/qa/command-classifier.js +552 -0
  128. package/templates/scripts/qa/context-guard-core.js +1618 -0
  129. package/templates/scripts/qa/diff.js +174 -0
  130. package/templates/scripts/qa/feature-scaffold.js +224 -0
  131. package/templates/scripts/qa/fixtures/backlog.md +104 -0
  132. package/templates/scripts/qa/governance.js +174 -0
  133. package/templates/scripts/qa/hash-file.js +32 -0
  134. package/templates/scripts/qa/lease-lib.js +263 -0
  135. package/templates/scripts/qa/merge-backlog.js +324 -0
  136. package/templates/scripts/qa/mobile-e2e/analyze-timings.js +300 -0
  137. package/templates/scripts/qa/mobile-e2e/apk-cache.js +420 -0
  138. package/templates/scripts/qa/mobile-e2e/backend-build-cache.js +203 -0
  139. package/templates/scripts/qa/mobile-e2e/boot-emulator.sh +432 -0
  140. package/templates/scripts/qa/mobile-e2e/build-apk.sh +210 -0
  141. package/templates/scripts/qa/mobile-e2e/check-flows.js +568 -0
  142. package/templates/scripts/qa/mobile-e2e/config.yaml +18 -0
  143. package/templates/scripts/qa/mobile-e2e/device-down.sh +88 -0
  144. package/templates/scripts/qa/mobile-e2e/device-up.sh +258 -0
  145. package/templates/scripts/qa/mobile-e2e/ios-simulator-down.sh +72 -0
  146. package/templates/scripts/qa/mobile-e2e/ios-simulator-up.sh +153 -0
  147. package/templates/scripts/qa/mobile-e2e/job-events.js +181 -0
  148. package/templates/scripts/qa/mobile-e2e/prewarm.sh +56 -0
  149. package/templates/scripts/qa/mobile-e2e/run-detached.sh +222 -0
  150. package/templates/scripts/qa/mobile-e2e/run-maestro.js +1543 -0
  151. package/templates/scripts/qa/mobile-e2e/ui-dump.js +327 -0
  152. package/templates/scripts/qa/models.allowlist.txt +32 -0
  153. package/templates/scripts/qa/provider-stats.js +878 -0
  154. package/templates/scripts/qa/run-clean.js +83 -0
  155. package/templates/scripts/qa/run-gates.js +213 -0
  156. package/templates/scripts/qa/run-loop.js +220 -0
  157. package/templates/scripts/qa/session-recon.js +512 -0
  158. package/templates/scripts/qa/store-lib.js +324 -0
  159. package/templates/scripts/qa/tool-lib.js +134 -0
  160. package/templates/scripts/qa/where.js +214 -0
  161. package/templates/scripts/qa/worktree-hygiene.js +217 -0
  162. package/templates/scripts/qa/wslconfig-merge.js +157 -0
  163. package/templates/scripts/serve.js +1328 -0
  164. package/templates/scripts/setup-nightly.sh +185 -0
  165. package/templates/scripts/setup-tmpfs.sh +374 -0
  166. package/templates/scripts/ship.js +586 -0
  167. package/templates/scripts/switch-reasoning-model.ps1 +101 -0
  168. package/templates/scripts/switch-reasoning-model.sh +104 -0
  169. package/templates/scripts/wait-for.js +342 -0
  170. package/templates/scripts/wsl-gpu.sh +180 -0
  171. package/templates/scripts/wsl-tune.sh +319 -0
@@ -0,0 +1,32 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ /*
4
+ * hash-file — deterministic file digests for QA evidence integrity.
5
+ *
6
+ * Prints `<sha256> <path>` per file (sha256sum-style) so qa-runner can report
7
+ * a tamper-evident hash of `.agents/qa-runs/<id>/evidence.txt` without inline
8
+ * shell quoting hazards. Pure Node, no dependencies, cross-platform.
9
+ *
10
+ * Usage:
11
+ * node scripts/qa/hash-file.js <file> [<file>...]
12
+ */
13
+ const fs = require("fs");
14
+ const crypto = require("crypto");
15
+
16
+ const files = process.argv.slice(2);
17
+ if (files.length === 0) {
18
+ console.error("usage: node scripts/qa/hash-file.js <file> [<file>...]");
19
+ process.exit(2);
20
+ }
21
+
22
+ let failed = false;
23
+ for (const file of files) {
24
+ try {
25
+ const digest = crypto.createHash("sha256").update(fs.readFileSync(file)).digest("hex");
26
+ console.log(`${digest} ${file}`);
27
+ } catch (e) {
28
+ console.error(`hash-file: ${file}: ${e.message}`);
29
+ failed = true;
30
+ }
31
+ }
32
+ process.exit(failed ? 1 : 0);
@@ -0,0 +1,263 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ /*
4
+ * Session-lease primitives (harness-shipped). One home for the `.serve/sessions/`
5
+ * lease format + liveness rules, shared by the context-guard plugin (writer) and
6
+ * `check-concurrency.js` (reader) so the two can never disagree on what "live"
7
+ * means.
8
+ *
9
+ * A lease is `.serve/sessions/<sessionID>.json`:
10
+ * { sessionID, pid, bootId, procStart, startedAt, heartbeatAt }
11
+ *
12
+ * Liveness is deliberately conservative — a false "live" blocks an innocent
13
+ * push, so every signal must agree:
14
+ * - the pid must exist (EPERM counts as alive: it exists, just not ours);
15
+ * - the process BIRTH TOKEN must match. `bootId` + `/proc/<pid>/stat`
16
+ * starttime identify one specific process incarnation, so a recycled pid
17
+ * (the OS handing the number to a new opencode) is not mistaken for the
18
+ * session that wrote the lease — the 0.1.67 false-positive this fixes;
19
+ * - the lease must carry a fresh heartbeat. The plugin touches it on every
20
+ * event/tool call, so a session that ended without a `session.deleted`
21
+ * event (TUI closed, server still alive) goes stale instead of lingering
22
+ * forever.
23
+ *
24
+ * The birth token is Linux/WSL-only (`/proc`); elsewhere `bootId`/`procStart`
25
+ * are null and liveness falls back to pid + heartbeat.
26
+ */
27
+ const fs = require("fs");
28
+ const path = require("path");
29
+
30
+ /* Heartbeat freshness window. A session that ended without a
31
+ * `session.deleted` event (TUI closed, server still alive) stops heartbeating,
32
+ * so this window is the sole convergence bound for an abandoned lease. It is
33
+ * deliberately long enough that a genuinely active session — which heartbeats
34
+ * on every event/tool call — is never mistaken for stale, and short enough that
35
+ * an abandoned lease does not block the concurrency gate / branch-switch guard
36
+ * for most of a day. */
37
+ const DEFAULT_MAX_AGE_MS = 4 * 60 * 60 * 1000; // 4h heartbeat freshness window
38
+
39
+ let cachedBootId;
40
+ function bootId() {
41
+ if (cachedBootId !== undefined) return cachedBootId;
42
+ try {
43
+ cachedBootId = fs.readFileSync("/proc/sys/kernel/random/boot_id", "utf8").trim() || null;
44
+ } catch {
45
+ cachedBootId = null;
46
+ }
47
+ return cachedBootId;
48
+ }
49
+
50
+ function processAlive(pid) {
51
+ if (typeof pid !== "number" || !Number.isInteger(pid) || pid <= 0) return false;
52
+ try {
53
+ process.kill(pid, 0);
54
+ return true;
55
+ } catch (err) {
56
+ return !!(err && err.code === "EPERM"); // exists, owned by another user
57
+ }
58
+ }
59
+
60
+ /* Field 22 (`starttime`, clock ticks since boot) of /proc/<pid>/stat. Parsing
61
+ * past the final `)` avoids comm containing spaces/parens. */
62
+ function processStart(pid) {
63
+ try {
64
+ const stat = fs.readFileSync(`/proc/${pid}/stat`, "utf8");
65
+ const close = stat.lastIndexOf(")");
66
+ if (close === -1) return null;
67
+ const fields = stat.slice(close + 2).split(" ");
68
+ const starttime = fields[19]; // field 3 begins here, so field 22 is index 19
69
+ return starttime || null;
70
+ } catch {
71
+ return null;
72
+ }
73
+ }
74
+
75
+ function birthToken(pid) {
76
+ return { bootId: bootId(), procStart: processStart(pid) };
77
+ }
78
+
79
+ function leaseDir(root) {
80
+ return path.join(root, ".serve", "sessions");
81
+ }
82
+
83
+ /* A session that creates its worktree mid-session keeps opencode's
84
+ * `context.worktree` pinned to the MAIN tree, so the session's tree is recorded
85
+ * separately as `.serve/sessions/<sessionID>.worktree` (written by
86
+ * `scripts/backlog.js worktree`, cleared by `archive`/lease cleanup). The guard
87
+ * plugin reads it to reroot bash calls into the worktree. One home for the path
88
+ * shape, shared by backlog.js and the plugin. */
89
+ function worktreeFile(root, sessionID) {
90
+ return path.join(leaseDir(root), `${sessionID}.worktree`);
91
+ }
92
+
93
+ function readWorktree(root, sessionID) {
94
+ if (!sessionID) return null;
95
+ try {
96
+ return fs.readFileSync(worktreeFile(root, sessionID), "utf8").trim() || null;
97
+ } catch {
98
+ return null;
99
+ }
100
+ }
101
+
102
+ function writeWorktree(root, sessionID, dir) {
103
+ if (!sessionID) return false;
104
+ const file = worktreeFile(root, sessionID);
105
+ fs.mkdirSync(path.dirname(file), { recursive: true });
106
+ fs.writeFileSync(file, String(dir), "utf8");
107
+ return true;
108
+ }
109
+
110
+ function clearWorktree(root, sessionID, onlyDir) {
111
+ if (!sessionID) return;
112
+ if (onlyDir && readWorktree(root, sessionID) !== path.resolve(onlyDir)) return;
113
+ try {
114
+ fs.rmSync(worktreeFile(root, sessionID), { force: true });
115
+ } catch {
116
+ /* best-effort */
117
+ }
118
+ }
119
+
120
+ function readLeases(root) {
121
+ const dir = leaseDir(root);
122
+ if (!fs.existsSync(dir)) return [];
123
+ const out = [];
124
+ for (const name of fs.readdirSync(dir)) {
125
+ if (!name.endsWith(".json")) continue;
126
+ const file = path.join(dir, name);
127
+ let rec;
128
+ try {
129
+ rec = JSON.parse(fs.readFileSync(file, "utf8"));
130
+ } catch {
131
+ rec = { sessionID: name.replace(/\.json$/, "") };
132
+ }
133
+ out.push({ file, name, ...rec });
134
+ }
135
+ return out;
136
+ }
137
+
138
+ function heartbeatAt(rec) {
139
+ if (typeof rec.heartbeatAt === "number") return rec.heartbeatAt;
140
+ if (typeof rec.startedAt === "number") return rec.startedAt;
141
+ return 0;
142
+ }
143
+
144
+ /* { live, reason } where reason is one of: live | no-pid | dead | recycled |
145
+ * stale. `now`/`maxAgeMs` are injectable for deterministic tests. */
146
+ function leaseStatus(rec, opts = {}) {
147
+ const now = opts.now || Date.now();
148
+ const maxAgeMs = opts.maxAgeMs || DEFAULT_MAX_AGE_MS;
149
+ if (typeof rec.pid !== "number") return { live: false, reason: "no-pid" };
150
+ if (!processAlive(rec.pid)) return { live: false, reason: "dead" };
151
+ if (rec.bootId) {
152
+ const cur = birthToken(rec.pid);
153
+ if (cur.bootId && cur.bootId !== rec.bootId) return { live: false, reason: "recycled" };
154
+ // The pid exists under our boot but is a different incarnation than the one
155
+ // that wrote the lease.
156
+ if (cur.procStart && rec.procStart && cur.procStart !== rec.procStart) {
157
+ return { live: false, reason: "recycled" };
158
+ }
159
+ }
160
+ const hb = heartbeatAt(rec);
161
+ if (!hb || now - hb >= maxAgeMs) return { live: false, reason: "stale" };
162
+ return { live: true, reason: "live" };
163
+ }
164
+
165
+ function liveLeases(root, opts) {
166
+ return readLeases(root).filter((rec) => leaseStatus(rec, opts).live);
167
+ }
168
+
169
+ /* Write/replace this process's lease for a primary session. */
170
+ function writeLease(root, sessionID, meta = {}) {
171
+ const dir = leaseDir(root);
172
+ fs.mkdirSync(dir, { recursive: true });
173
+ const now = Date.now();
174
+ const tok = birthToken(process.pid);
175
+ const rec = {
176
+ sessionID,
177
+ pid: process.pid,
178
+ bootId: tok.bootId,
179
+ procStart: tok.procStart,
180
+ startedAt: now,
181
+ heartbeatAt: now,
182
+ ...meta,
183
+ };
184
+ fs.writeFileSync(path.join(dir, `${sessionID}.json`), JSON.stringify(rec));
185
+ return rec;
186
+ }
187
+
188
+ /* Refresh the heartbeat so an active-but-quiet session stays live. If the lease
189
+ * is missing (never created, pruned as stale, or lost) it is RE-CREATED: a
190
+ * session that comes back after the freshness window must re-arm its lease on
191
+ * its first activity, not run unleased. */
192
+ function touchLease(root, sessionID) {
193
+ const file = path.join(leaseDir(root), `${sessionID}.json`);
194
+ try {
195
+ const rec = JSON.parse(fs.readFileSync(file, "utf8"));
196
+ rec.heartbeatAt = Date.now();
197
+ fs.writeFileSync(file, JSON.stringify(rec));
198
+ } catch {
199
+ try {
200
+ writeLease(root, sessionID);
201
+ } catch {
202
+ /* best-effort */
203
+ }
204
+ }
205
+ }
206
+
207
+ function clearLease(root, sessionID) {
208
+ // Also drop the session's mid-session worktree pointer (`.worktree`), so a
209
+ // closed session can't leave the tools rooted in a worktree it no longer owns.
210
+ try {
211
+ fs.rmSync(path.join(leaseDir(root), `${sessionID}.json`), { force: true });
212
+ fs.rmSync(worktreeFile(root, sessionID), { force: true });
213
+ } catch {
214
+ /* best-effort */
215
+ }
216
+ }
217
+
218
+ /* Remove every lease that is not live. Returns [{sessionID, reason, pid}]. */
219
+ function pruneLeases(root, opts = {}) {
220
+ const removed = [];
221
+ for (const rec of readLeases(root)) {
222
+ const status = leaseStatus(rec, opts);
223
+ if (status.live) continue;
224
+ try {
225
+ fs.rmSync(rec.file, { force: true });
226
+ if (rec.name) {
227
+ fs.rmSync(path.join(leaseDir(root), rec.name.replace(/\.json$/, ".worktree")), { force: true });
228
+ }
229
+ removed.push({ sessionID: rec.sessionID || rec.name, reason: status.reason, pid: rec.pid });
230
+ } catch {
231
+ /* best-effort */
232
+ }
233
+ }
234
+ return removed;
235
+ }
236
+
237
+ function describeLease(rec, opts = {}) {
238
+ const status = leaseStatus(rec, opts);
239
+ const age = typeof rec.startedAt === "number" ? Math.round((Date.now() - rec.startedAt) / 60000) : null;
240
+ return `${rec.sessionID || rec.name} (pid ${rec.pid}, age ${age == null ? "?" : age + "m"}, ${status.reason})`;
241
+ }
242
+
243
+ module.exports = {
244
+ DEFAULT_MAX_AGE_MS,
245
+ bootId,
246
+ processAlive,
247
+ processStart,
248
+ birthToken,
249
+ leaseDir,
250
+ worktreeFile,
251
+ readWorktree,
252
+ writeWorktree,
253
+ clearWorktree,
254
+ readLeases,
255
+ heartbeatAt,
256
+ leaseStatus,
257
+ liveLeases,
258
+ writeLease,
259
+ touchLease,
260
+ clearLease,
261
+ pruneLeases,
262
+ describeLease,
263
+ };
@@ -0,0 +1,324 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ /*
4
+ * merge-backlog — row-aware 3-way merge driver for BACKLOG.md.
5
+ *
6
+ * Registered as a git merge driver: `.gitattributes` carries
7
+ * `BACKLOG.md merge=backlog`, and `agent-harness init/update` wires the driver
8
+ * via `git config merge.backlog.driver "node <abs>/scripts/qa/merge-backlog.js %O %A %B"`.
9
+ * Git invokes it as:
10
+ *
11
+ * node scripts/qa/merge-backlog.js <base> <ours> <theirs> [<marker-size>]
12
+ *
13
+ * It writes the merged board to <ours> and exits:
14
+ * 0 — clean merge
15
+ * 1 — genuine row conflict (both sides changed the same row differently);
16
+ * conflict markers are left in <ours> for the human to resolve.
17
+ *
18
+ * Rows are keyed by their first cell (ID for work rows, `Key` for ## Epics), so
19
+ * two sessions that edit DISJOINT rows — the normal concurrent case (one takes
20
+ * F-052, the other archives F-041) — merge without touching each other's edits.
21
+ * Row MOVES (Open→In progress, In progress→Archive) are resolved by 3-way
22
+ * comparison, not by line position, so `merge=union`'s duplicate-row failure mode
23
+ * is avoided. Prose and "Active / next" bullets resolve to the <ours> side
24
+ * (they are explanatory, not row data).
25
+ */
26
+ const fs = require("fs");
27
+ const { splitCells } = require("./board-lib.js");
28
+
29
+ // ---- small self-contained markdown-table helpers -------------------------
30
+
31
+ function isSep(cells) {
32
+ return cells.every((c) => /^[-:|\s]*$/.test(c));
33
+ }
34
+
35
+ function canonKey(heading) {
36
+ const h = heading.replace(/^#+\s*/, "").replace(/\s+/g, " ").trim().toLowerCase();
37
+ if (h === "open") return "open";
38
+ if (h === "queued") return "queued";
39
+ if (h === "in progress") return "inprogress";
40
+ if (h === "frozen") return "frozen";
41
+ if (h.startsWith("archive")) return "archive";
42
+ if (h === "epics") return "epics";
43
+ return null;
44
+ }
45
+
46
+ /* Parse a board into ordered sections: { key, rowOrder: [rowKey], rowLines: Map }. */
47
+ function parseBoard(src) {
48
+ const sections = [];
49
+ let cur = null;
50
+ for (const raw of String(src || "").split(/\r?\n/)) {
51
+ const h = raw.match(/^#{2,3}\s+(.*)$/);
52
+ if (h) {
53
+ const key = canonKey(h[1]);
54
+ cur = key ? { key, rowOrder: [], rowLines: new Map() } : null;
55
+ if (cur) sections.push(cur);
56
+ continue;
57
+ }
58
+ if (!cur) continue;
59
+ const row = raw.trim();
60
+ if (!/^\|.*\|$/.test(row)) continue;
61
+ const cells = splitCells(row.slice(1, -1));
62
+ if (isSep(cells)) continue;
63
+ if (cells.every((c) => c.trim() === "")) continue;
64
+ if (cells.some((c) => /^(ID|Key)$/.test(c.trim()))) continue; // header row
65
+ const rowKey = (cells[0] || "").trim();
66
+ if (!rowKey) continue;
67
+ if (!cur.rowLines.has(rowKey)) cur.rowOrder.push(rowKey);
68
+ cur.rowLines.set(rowKey, row);
69
+ }
70
+ return sections;
71
+ }
72
+
73
+ /* Locate each section's table block within a raw line array. */
74
+ function sectionBlocks(lines) {
75
+ const blocks = [];
76
+ for (let i = 0; i < lines.length; i++) {
77
+ const m = lines[i].match(/^#{2,3}\s+(.*)$/);
78
+ if (!m) continue;
79
+ const key = canonKey(m[1]);
80
+ if (!key) continue;
81
+ let end = lines.length;
82
+ for (let j = i + 1; j < lines.length; j++) {
83
+ if (/^#{2,3}\s/.test(lines[j])) {
84
+ end = j;
85
+ break;
86
+ }
87
+ }
88
+ let headerIdx = -1;
89
+ let sepIdx = -1;
90
+ let dataStart = -1;
91
+ let dataEnd = -1;
92
+ for (let j = i + 1; j < end; j++) {
93
+ if (!/^\s*\|.*\|\s*$/.test(lines[j])) continue;
94
+ if (headerIdx === -1) {
95
+ headerIdx = j;
96
+ continue;
97
+ }
98
+ if (sepIdx === -1) {
99
+ if (isSep(splitCells(lines[j].slice(1, -1)))) {
100
+ sepIdx = j;
101
+ dataStart = j + 1;
102
+ dataEnd = j;
103
+ } else {
104
+ dataEnd = j;
105
+ }
106
+ continue;
107
+ }
108
+ dataEnd = j;
109
+ }
110
+ blocks.push({ key, headerIdx, sepIdx, dataStart, dataEnd });
111
+ }
112
+ return blocks;
113
+ }
114
+
115
+ /* Decode a `<section>\0<row line>` value into a resolved row. The row KEY is
116
+ * carried through explicitly: `rebuild()` orders and de-dupes by `r.key`, so
117
+ * dropping it here collapsed every section to a single row (last wins) on any
118
+ * merge that took the driver path. */
119
+ function decode(key, v) {
120
+ const i = v.indexOf("\u0000");
121
+ return { key, section: v.slice(0, i), line: v.slice(i + 1) };
122
+ }
123
+
124
+ function priorityRank(line) {
125
+ const cells = splitCells(line.slice(1, -1));
126
+ const p = (cells[1] || "").trim().toUpperCase();
127
+ const ranks = { P1: 0, P2: 1, P3: 2, P4: 3 };
128
+ return Object.prototype.hasOwnProperty.call(ranks, p) ? ranks[p] : 4;
129
+ }
130
+
131
+ /* 3-way merge keyed by row ID/Key. Returns { resolved: Map, conflicts: [] }. */
132
+ function merge(baseSrc, oursSrc, theirsSrc) {
133
+ const toMap = (sections) => {
134
+ const m = new Map();
135
+ for (const s of sections) {
136
+ for (const k of s.rowOrder) m.set(k, s.key + "\u0000" + s.rowLines.get(k));
137
+ }
138
+ return m;
139
+ };
140
+ const bm = toMap(parseBoard(baseSrc));
141
+ const om = toMap(parseBoard(oursSrc));
142
+ const tm = toMap(parseBoard(theirsSrc));
143
+
144
+ const keys = new Set([...bm.keys(), ...om.keys(), ...tm.keys()]);
145
+ const resolved = new Map();
146
+ const conflicts = [];
147
+
148
+ for (const k of keys) {
149
+ const bv = bm.get(k);
150
+ const ov = om.get(k);
151
+ const tv = tm.get(k);
152
+ if (ov === tv) {
153
+ if (ov !== undefined) resolved.set(k, decode(k, ov));
154
+ // else: deleted in both -> drop
155
+ continue;
156
+ }
157
+ if (ov === bv) {
158
+ // ours unchanged -> take theirs (or deletion)
159
+ if (tv !== undefined) resolved.set(k, decode(k, tv));
160
+ continue;
161
+ }
162
+ if (tv === bv) {
163
+ // theirs unchanged -> take ours (or deletion)
164
+ if (ov !== undefined) resolved.set(k, decode(k, ov));
165
+ continue;
166
+ }
167
+ // both sides changed the same row, and differently -> conflict
168
+ conflicts.push({ key: k, ours: ov, theirs: tv });
169
+ }
170
+
171
+ return { resolved, conflicts };
172
+ }
173
+
174
+ /* A board-aware reconcile for a DIRTY main checkout that is strictly behind the
175
+ * integration branch. `base` is the checkout's committed board, `ours` its
176
+ * working board (carrying the `backlog worktree` take + any local-only rows),
177
+ * `theirs` the landed upstream board. A row archived upstream is authoritative
178
+ * over a stale local take, so that conflict resolves to the archive and the
179
+ * stale local copy is dropped; local-only rows survive. Genuine same-row
180
+ * conflicts (neither side an archive) return ok:false with the keys. */
181
+ function reconcileBoard(baseSrc, oursSrc, theirsSrc) {
182
+ const { resolved, conflicts } = merge(baseSrc, oursSrc, theirsSrc);
183
+ const dropped = [];
184
+ const unresolved = [];
185
+ for (const c of conflicts) {
186
+ if (c.theirs && c.theirs.startsWith("archive\u0000")) {
187
+ const i = c.theirs.indexOf("\u0000");
188
+ resolved.set(c.key, {
189
+ key: c.key,
190
+ section: c.theirs.slice(0, i),
191
+ line: c.theirs.slice(i + 1),
192
+ });
193
+ dropped.push(c.key);
194
+ continue;
195
+ }
196
+ unresolved.push(c);
197
+ }
198
+ if (unresolved.length) {
199
+ return { ok: false, board: null, dropped: [], conflicts: unresolved.map((c) => c.key) };
200
+ }
201
+ return { ok: true, board: rebuild(oursSrc, resolved), dropped, conflicts: [] };
202
+ }
203
+
204
+ /* Rebuild the board from the OURS skeleton, replacing each section's table data
205
+ * rows with the merged rows. Preserves OURS prose, headings, header/separator. */
206
+ function rebuild(oursSrc, resolved) {
207
+ const eol = oursSrc.includes("\r\n") ? "\r\n" : "\n";
208
+ const lines = oursSrc.split(/\r?\n/);
209
+ const blocks = sectionBlocks(lines);
210
+
211
+ const bySection = new Map();
212
+ for (const [, r] of resolved) {
213
+ if (!bySection.has(r.section)) bySection.set(r.section, []);
214
+ bySection.get(r.section).push(r);
215
+ }
216
+
217
+ const oursOrder = new Map();
218
+ for (const s of parseBoard(oursSrc)) oursOrder.set(s.key, s.rowOrder.slice());
219
+
220
+ for (const [section, rows] of bySection) {
221
+ const ordered = new Map();
222
+ const seen = new Set();
223
+ for (const k of oursOrder.get(section) || []) {
224
+ const r = rows.find((x) => x.key === k);
225
+ if (r) {
226
+ seen.add(k);
227
+ ordered.set(k, r.line);
228
+ }
229
+ }
230
+ for (const r of rows) if (!seen.has(r.key)) ordered.set(r.key, r.line);
231
+
232
+ let arr = [...ordered.entries()].map(([key, line]) => ({ key, line }));
233
+ if (section === "open" || section === "queued") {
234
+ arr.sort(
235
+ (a, b) =>
236
+ priorityRank(a.line) - priorityRank(b.line) ||
237
+ (a.key < b.key ? -1 : a.key > b.key ? 1 : 0)
238
+ );
239
+ }
240
+ bySection.set(section, arr);
241
+ }
242
+
243
+ // splice from the last block backwards so earlier indices stay valid
244
+ for (let bi = blocks.length - 1; bi >= 0; bi--) {
245
+ const b = blocks[bi];
246
+ const rows = (bySection.get(b.key) || []).map((r) => r.line);
247
+ if (b.headerIdx === -1) continue;
248
+ const headerLine = lines[b.headerIdx];
249
+ // Normalize the separator to the canonical narrow form the board tools emit
250
+ // (`|---|---|`), so a rewritten section is byte-identical to the landed
251
+ // upstream board. The template ships column-aligned separators
252
+ // (`|----|------|`); a section a tool has not rewritten keeps its original
253
+ // separator (preserved below), so untouched sections stay byte-stable.
254
+ const canonicalSep = "|" + splitCells(headerLine.slice(1, -1)).map(() => "---").join("|") + "|";
255
+ const start = b.headerIdx;
256
+ const end = b.dataEnd >= b.dataStart ? b.dataEnd : b.sepIdx;
257
+ const replacement = [headerLine];
258
+ if (rows.length) {
259
+ replacement.push(canonicalSep, ...rows);
260
+ } else {
261
+ // An empty resolved section normally emits just the header + separator.
262
+ // But the template's empty tables carry a blank placeholder row
263
+ // (`| | | |`); replacing it with nothing makes a reconcile of an
264
+ // otherwise-untouched board byte-different from upstream, which then
265
+ // reads as working-tree dirt. Preserve the original block only when its
266
+ // data lines are all placeholders — a section whose real rows moved to
267
+ // Archive must still be emptied.
268
+ const origData = lines.slice(b.dataStart, end + 1);
269
+ const onlyPlaceholders =
270
+ origData.length > 0 &&
271
+ origData.every((l) => {
272
+ if (!/^\s*\|.*\|\s*$/.test(l)) return false;
273
+ return splitCells(l.slice(1, -1)).every((c) => c.trim() === "");
274
+ });
275
+ if (onlyPlaceholders) replacement.push(lines[b.sepIdx] || canonicalSep, ...origData);
276
+ else replacement.push(canonicalSep);
277
+ }
278
+ lines.splice(start, end - start + 1, ...replacement);
279
+ }
280
+ return lines.join(eol);
281
+ }
282
+
283
+ function conflictBlock(conflicts, eol) {
284
+ const out = ["<<<<<<< ours"];
285
+ for (const c of conflicts) {
286
+ out.push(c.ours ? c.ours.slice(c.ours.indexOf("\u0000") + 1) : `(deleted) ${c.key}`);
287
+ }
288
+ out.push("=======");
289
+ for (const c of conflicts) {
290
+ out.push(c.theirs ? c.theirs.slice(c.theirs.indexOf("\u0000") + 1) : `(deleted) ${c.key}`);
291
+ }
292
+ out.push(">>>>>>> theirs");
293
+ return out.join(eol);
294
+ }
295
+
296
+ function main() {
297
+ const base = process.argv[2];
298
+ const ours = process.argv[3];
299
+ const theirs = process.argv[4];
300
+
301
+ const oursSrc = ours && fs.existsSync(ours) ? fs.readFileSync(ours, "utf8") : "";
302
+ const baseSrc = base && fs.existsSync(base) ? fs.readFileSync(base, "utf8") : "";
303
+ const theirsSrc = theirs && fs.existsSync(theirs) ? fs.readFileSync(theirs, "utf8") : "";
304
+
305
+ const { resolved, conflicts } = merge(baseSrc, oursSrc, theirsSrc);
306
+ const eol = oursSrc.includes("\r\n") ? "\r\n" : "\n";
307
+ let out = rebuild(oursSrc, resolved);
308
+
309
+ if (conflicts.length) {
310
+ out = out.replace(/\s*$/, "") + eol + eol + conflictBlock(conflicts, eol) + eol;
311
+ fs.writeFileSync(ours, out, "utf8");
312
+ console.error(
313
+ `merge-backlog: ${conflicts.length} conflicting row(s): ${conflicts.map((c) => c.key).join(", ")}`
314
+ );
315
+ process.exit(1);
316
+ }
317
+
318
+ fs.writeFileSync(ours, out, "utf8");
319
+ process.exit(0);
320
+ }
321
+
322
+ if (require.main === module) main();
323
+
324
+ module.exports = { splitCells, parseBoard, merge, rebuild, reconcileBoard, priorityRank };