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,3059 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ /*
4
+ * agent-harness — deploy the agent harness (personas, skills, rules, model
5
+ * routing, QA gates) into a target project.
6
+ *
7
+ * Commands:
8
+ * init [--target <dir>] [--name <project>] [--domain <desc>] [--yes] [--dry-run]
9
+ * update [--target <dir>] [--dry-run]
10
+ * migrate-backlog [--target <dir>]
11
+ * list
12
+ * --version | -v
13
+ * --help | -h
14
+ *
15
+ * `init`/`update` materialize templates/ into the target and substitute {{
16
+ * PROJECT_NAME }} / {{ PROJECT_DOMAIN }}.
17
+ *
18
+ * Ownership model:
19
+ * - `.agents/memory/*` + `.agents/features/*` is project data -> create-if-missing (never overwrite).
20
+ * - `BACKLOG.md` (repo root) is project data -> create-if-missing (never overwrite); it is the
21
+ * canonical task list, and `update` must never clobber the project's live board.
22
+ * - `opencode.json` is MERGED: harness manages $schema/model and the `agents`
23
+ * defaults (title/build/explore) + the `permissions` baseline; every other
24
+ * key the project adds is preserved. (Native V2 shape: no `small_model`,
25
+ * singular `agent`, or keyed `permission`.)
26
+ * - `.gitattributes` and `.ignore` are MERGED as a harness-managed begin/end
27
+ * block; project entries outside the block are preserved.
28
+ * - all other harness-owned files are overwritten. If a harness-owned file was
29
+ * modified locally since the last deploy (tracked by checksum in
30
+ * `.harness.json`), it is backed up to `.harness-backup/<timestamp>/` first.
31
+ */
32
+
33
+ const fs = require("fs");
34
+ const path = require("path");
35
+ const os = require("os");
36
+ const crypto = require("crypto");
37
+ const readline = require("readline");
38
+ const { spawnSync } = require("child_process");
39
+
40
+ const PKG = require("../package.json");
41
+ const TEMPLATES_DIR = path.resolve(__dirname, "..", "templates");
42
+ /* Repo-only global-plugin sources (NOT under templates/, so `init`/`update` never
43
+ * deploy them into a project). `install-global` links these into the user's
44
+ * opencode global plugin dir. */
45
+ const GLOBAL_PLUGINS_SRC = path.resolve(__dirname, "..", "contrib", "global-plugins");
46
+ const CONFIG_FILE = ".harness.json";
47
+ const BACKUP_DIR = ".harness-backup";
48
+
49
+ // ---------------------------------------------------------------- helpers
50
+
51
+ /* Numeric semver compare (major.minor.patch; prerelease tags ignored).
52
+ * Returns <0 / 0 / >0 like a normal comparator. */
53
+ function compareVersions(a, b) {
54
+ const pa = String(a || "0").split(".").map((n) => parseInt(n, 10) || 0);
55
+ const pb = String(b || "0").split(".").map((n) => parseInt(n, 10) || 0);
56
+ for (let i = 0; i < 3; i++) {
57
+ if ((pa[i] || 0) !== (pb[i] || 0)) return (pa[i] || 0) > (pb[i] || 0) ? 1 : -1;
58
+ }
59
+ return 0;
60
+ }
61
+
62
+ /* Best-effort: the latest `dist-tags.latest` for PKG.name on the configured
63
+ * registry. Returns null when the registry is unreachable / package unknown,
64
+ * so the check never blocks a deploy. */
65
+ function publishedLatestVersion() {
66
+ const npmCli = process.env.npm_execpath
67
+ ? path.join(path.dirname(process.env.npm_execpath), "npm-cli.js")
68
+ : null;
69
+ const args = ["view", PKG.name, "version", "--json", "--fetch-timeout=5000", "--fetch-retries=0"];
70
+ const r = npmCli
71
+ ? spawnSync(process.execPath, [npmCli, ...args], { encoding: "utf8", timeout: 10000 })
72
+ : spawnSync("npm", args, { encoding: "utf8", timeout: 10000 });
73
+ if (r.status !== 0) return null;
74
+ try {
75
+ return JSON.parse(r.stdout.trim());
76
+ } catch (_) {
77
+ return r.stdout.trim() || null;
78
+ }
79
+ }
80
+
81
+ function listFiles(dir, base = dir) {
82
+ const out = [];
83
+ if (!fs.existsSync(dir)) return out;
84
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
85
+ const abs = path.join(dir, entry.name);
86
+ if (entry.isDirectory()) out.push(...listFiles(abs, base));
87
+ else out.push({ abs, rel: path.relative(base, abs) });
88
+ }
89
+ return out;
90
+ }
91
+
92
+ function substitute(text, vars) {
93
+ let out = text;
94
+ for (const [key, value] of Object.entries(vars)) {
95
+ out = out.split("{{" + key + "}}").join(value == null ? "" : String(value));
96
+ }
97
+ return out;
98
+ }
99
+
100
+ function relKey(rel) {
101
+ return rel.split(path.sep).join("/");
102
+ }
103
+
104
+ /* A session handoff must never live in the shipped template tree: the dogfood
105
+ * symlinks repo `scripts` -> `templates/scripts`, so an `__dirname`-rooted
106
+ * checkpoint could drop one there, and `update` would scaffold it into every
107
+ * project (F-26/H-49). Refuse the deploy and name the stray. README.md is the
108
+ * shipped placeholder and is allowed. */
109
+ function assertNoTemplateHandoffs() {
110
+ const dir = path.join(TEMPLATES_DIR, ".agents", "handoffs");
111
+ if (!fs.existsSync(dir)) return;
112
+ const strays = fs
113
+ .readdirSync(dir)
114
+ .filter((f) => f !== "README.md" && !f.startsWith("."))
115
+ .sort();
116
+ if (strays.length) {
117
+ throw new Error(
118
+ `templates/.agents/handoffs/ has stray file(s) that \`update\` would ship to every project:\n` +
119
+ strays.map((f) => ` - templates/.agents/handoffs/${f}`).join("\n") +
120
+ `\n A checkpoint handoff belongs in the PROJECT root (cwd), not the template tree. ` +
121
+ `Delete the stray(s) (F-26/H-49) and re-run.`
122
+ );
123
+ }
124
+ }
125
+
126
+ /* `.agents/memory/*` (session memory), `.agents/features/*` (feature doc tree),
127
+ * `.agents/reviews/*` (durable review/audit deliverables), `.agents/qa-plans/*`
128
+ * (one QA plan file per change), `.agents/qa-runs/*` (one directory of verbatim
129
+ * QA evidence per change) and `.agents/handoffs/*` (one session handoff file per
130
+ * session) are project data — scaffolded create-if-missing, never overwritten,
131
+ * and never tracked in the manifest. qa-plans/qa-runs/handoffs are sharded per
132
+ * change/session so concurrent sessions never collide on a single shared file.
133
+ * Note: the check matches the directory DIRECTLY under `.agents` (not any
134
+ * segment), so `.agents/skills/features/SKILL.md` stays harness-owned. */
135
+ function isProjectScaffold(rel) {
136
+ const key = relKey(rel);
137
+ // `.agents/nightly.json` is the project-owned nightly-cycle config (phases,
138
+ // quiesce window, seed command): seeded once, never overwritten.
139
+ if (key === ".agents/nightly.json") return true;
140
+ const parts = rel.split(path.sep);
141
+ const idx = parts.indexOf(".agents");
142
+ if (idx === -1) return false;
143
+ const sub = parts[idx + 1];
144
+ return (
145
+ sub === "memory" ||
146
+ sub === "features" ||
147
+ sub === "reviews" ||
148
+ sub === "qa-plans" ||
149
+ sub === "qa-runs" ||
150
+ sub === "handoffs"
151
+ );
152
+ }
153
+ /* The canonical `BACKLOG.md` at the repo root is also project data (a live task
154
+ * list the project owns): scaffolded create-if-missing, never overwritten so an
155
+ * `update` can never clobber the project's board, and never tracked in the
156
+ * manifest (its content is the project's, not the harness's). */
157
+ function isBacklogFile(rel) {
158
+ return relKey(rel) === "BACKLOG.md";
159
+ }
160
+ /* The CI/CD release scaffold is also project data: `init` seeds a working
161
+ * pipeline (CI gate, CI-triggered artifact deploy, health probe, Vercel
162
+ * build-context hygiene, and the reference doc) exactly once, and `update`
163
+ * NEVER overwrites a project's edited workflows. This is what makes the
164
+ * self-contained agent cycle reproducible on a fresh project instead of only in
165
+ * the one repo it was hand-built in. */
166
+ function isReleaseScaffold(rel) {
167
+ const key = relKey(rel);
168
+ if (key === ".vercelignore") return true;
169
+ if (key === ".husky/pre-push") return true;
170
+ if (key === "docs/ci-cd-pipeline.md") return true;
171
+ if (key.startsWith(".github/workflows/") && /\.ya?ml$/i.test(key)) return true;
172
+ return false;
173
+ }
174
+ /* Combined: any file that must be scaffolded create-if-missing rather than
175
+ * overwritten. */
176
+ function isCreateIfMissing(rel) {
177
+ return isProjectScaffold(rel) || isBacklogFile(rel) || isReleaseScaffold(rel);
178
+ }
179
+ /* Back-compat alias (kept for any external caller referencing the old name). */
180
+ function isMemoryFile(rel) {
181
+ return isProjectScaffold(rel);
182
+ }
183
+
184
+ function isOpencodeJson(rel) {
185
+ return relKey(rel) === "opencode.json";
186
+ }
187
+
188
+ /* Canonical text form for checksums: CRLF is folded to LF so a file's line
189
+ * endings can never masquerade as a local edit. `.gitattributes` pins `*.ps1`
190
+ * to CRLF on checkout, so a correctly-checked-out Windows script arrives CRLF
191
+ * while the harness template is LF — hashing raw bytes flagged that as a
192
+ * hand-edit and made `update` fail closed (and rewriting it LF left git dirty).
193
+ * Templates are LF-pinned, so folding CRLF→LF leaves every existing recorded
194
+ * hash valid. */
195
+ function normalizeEol(text) {
196
+ return String(text).replace(/\r\n/g, "\n");
197
+ }
198
+
199
+ function sha256(str) {
200
+ return crypto.createHash("sha256").update(normalizeEol(str), "utf8").digest("hex");
201
+ }
202
+
203
+ function safeJson(text, fallback) {
204
+ if (text == null) return fallback;
205
+ try {
206
+ return JSON.parse(text);
207
+ } catch (_) {
208
+ return fallback;
209
+ }
210
+ }
211
+
212
+ function readConfig(target) {
213
+ const p = path.join(target, CONFIG_FILE);
214
+ if (fs.existsSync(p)) return safeJson(fs.readFileSync(p, "utf8"), {});
215
+ return {};
216
+ }
217
+
218
+ function ask(question, fallback, yes) {
219
+ if (yes) return Promise.resolve(fallback || "");
220
+ if (!process.stdin.isTTY) return Promise.resolve(fallback || "");
221
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
222
+ return new Promise((resolve) => {
223
+ rl.question(question, (answer) => {
224
+ rl.close();
225
+ resolve(answer.trim());
226
+ });
227
+ });
228
+ }
229
+
230
+ /* The work root a target's sibling worktrees live under: the target's parent
231
+ * directory — e.g. `/home/ronen/develop` for `~/develop/PublicVirtualLibrary`.
232
+ * Normalized to forward slashes so it is a valid glob on every platform. This
233
+ * is substituted into `templates/opencode.json` as `{{WORKSPACE_ROOT}}` so the
234
+ * `external_directory` policy allows the repo + its sibling worktrees without
235
+ * hardcoding a machine-specific path. */
236
+ function workspaceRootFor(target) {
237
+ return path.dirname(path.resolve(target)).split(path.sep).join("/");
238
+ }
239
+
240
+ function resolveVars(target, args) {
241
+ const existing = readConfig(target);
242
+ const projectName = args["--name"] || existing.projectName || path.basename(target);
243
+ const projectDomain = args["--domain"] || existing.projectDomain || "";
244
+ return {
245
+ projectName,
246
+ projectDomain,
247
+ existing,
248
+ VARIABLES: {
249
+ PROJECT_NAME: projectName,
250
+ PROJECT_DOMAIN: projectDomain,
251
+ WORKSPACE_ROOT: workspaceRootFor(target),
252
+ },
253
+ };
254
+ }
255
+
256
+ // ---------------------------------------------------------------- opencode.json
257
+
258
+ function templateOpencodeJson() {
259
+ const p = path.join(TEMPLATES_DIR, "opencode.json");
260
+ return safeJson(fs.readFileSync(p, "utf8"), {});
261
+ }
262
+
263
+ // Merge harness-managed keys into the project's existing opencode.json,
264
+ // preserving every other key the project has added.
265
+ function mergeOpencodeJson(target, variables) {
266
+ const harness = safeJson(
267
+ substitute(fs.readFileSync(path.join(TEMPLATES_DIR, "opencode.json"), "utf8"), variables),
268
+ {}
269
+ );
270
+ const p = path.join(target, "opencode.json");
271
+ const existing = fs.existsSync(p) ? safeJson(fs.readFileSync(p, "utf8"), {}) : {};
272
+
273
+ const merged = { ...existing, ...harness };
274
+
275
+ // --- V1 -> V2 config convergence -------------------------------------------
276
+ // An older deploy wrote harness-managed V1 keys (`small_model`, the singular
277
+ // `agent` map, the keyed `permission` map, the `tools` enable/disable map, and an
278
+ // `instructions` entry). V2 normalizes V1 shapes, but the file would then keep
279
+ // both forms forever, so migrate the project's own values into the native V2
280
+ // shape and drop the V1 key.
281
+ //
282
+ // `tools` (G1): V2 has no top-level or per-agent `tools` field, so a project's
283
+ // MCP gating (`tools: { "pg*": false }` + `agents.<name>.tools: { "pg*": true }`)
284
+ // lost the per-agent allow and left the server connected but unusable. Migrate
285
+ // both maps into ordered `permissions` rules; per-agent rules are appended to
286
+ // that agent's own rules, so the agent allow still wins over the global deny.
287
+ const absorbAgentTools = (cfg) => {
288
+ if (!cfg || typeof cfg !== "object" || Array.isArray(cfg) || !("tools" in cfg)) return cfg;
289
+ const rules = convertV1Tools(cfg.tools);
290
+ const out = { ...cfg };
291
+ delete out.tools;
292
+ if (rules.length) {
293
+ out.permissions = [...(Array.isArray(cfg.permissions) ? cfg.permissions : []), ...rules];
294
+ }
295
+ return out;
296
+ };
297
+ const priorAgents = {};
298
+ for (const src of [existing.agent, existing.agents]) {
299
+ if (!src || typeof src !== "object" || Array.isArray(src)) continue;
300
+ for (const [name, cfg] of Object.entries(src)) priorAgents[name] = absorbAgentTools(cfg);
301
+ }
302
+ if (
303
+ typeof existing.small_model === "string" &&
304
+ !(priorAgents.title && typeof priorAgents.title === "object" && priorAgents.title.model)
305
+ ) {
306
+ priorAgents.title = { ...(priorAgents.title || {}), model: existing.small_model };
307
+ }
308
+ const priorPermissions = [
309
+ ...(Array.isArray(existing.permissions) ? existing.permissions : []),
310
+ ...convertV1Permission(existing.permission),
311
+ ...convertV1Tools(existing.tools),
312
+ ];
313
+ delete merged.agent;
314
+ delete merged.small_model;
315
+ delete merged.permission;
316
+ delete merged.tools;
317
+ if (Array.isArray(merged.instructions)) {
318
+ const kept = merged.instructions.filter((x) => x !== ".agents/rules/00-operating.md");
319
+ if (kept.length) merged.instructions = kept;
320
+ else delete merged.instructions;
321
+ }
322
+
323
+ // ADD-ONLY agent defaults (project values win; every project agent preserved).
324
+ if (harness.agents && typeof harness.agents === "object" && !Array.isArray(harness.agents)) {
325
+ const agents = { ...priorAgents };
326
+ for (const [name, cfg] of Object.entries(harness.agents)) {
327
+ const prior = agents[name] && typeof agents[name] === "object" ? agents[name] : {};
328
+ agents[name] = { ...cfg, ...prior };
329
+ }
330
+ merged.agents = agents;
331
+ } else if (Object.keys(priorAgents).length) {
332
+ merged.agents = priorAgents;
333
+ }
334
+
335
+ // The `permissions` baseline is an ordered array (V2: the last matching rule
336
+ // wins), so a plain keyed merge is impossible. Union it: harness rules first,
337
+ // the project's own rules appended after so they win a resource collision, and
338
+ // exact duplicates dropped.
339
+ if (Array.isArray(harness.permissions)) {
340
+ const seen = new Set();
341
+ const permissions = [];
342
+ for (const rule of [...harness.permissions, ...priorPermissions]) {
343
+ const key = JSON.stringify(rule);
344
+ if (seen.has(key)) continue;
345
+ seen.add(key);
346
+ permissions.push(rule);
347
+ }
348
+ merged.permissions = permissions;
349
+ } else if (priorPermissions.length) {
350
+ merged.permissions = priorPermissions;
351
+ }
352
+ // MCP servers live under `mcp.servers` in V2. A project owns its own `mcp`
353
+ // block (servers are project-side, e.g. a dev-DB server), so if the harness
354
+ // ever ships a default server the top-level spread would replace the WHOLE
355
+ // block. Deep-merge by server NAME instead: a project's same-named server wins
356
+ // (its keys win on a collision), project-only servers are preserved,
357
+ // harness-only servers are added. This is the guard the backlog requires
358
+ // before any default `mcp` block can ship in templates/opencode.json.
359
+ if (harness.mcp && typeof harness.mcp === "object" && !Array.isArray(harness.mcp)) {
360
+ merged.mcp = mergeMcp(harness.mcp, existing.mcp);
361
+ }
362
+ return JSON.stringify(merged, null, 2) + "\n";
363
+ }
364
+
365
+ /* V1 -> V2 renamed tool/permission actions (docs/opencode-v2-migration:
366
+ * "Permission actions also changed"). A V1 name that is not here either already
367
+ * matches its V2 action (`edit`, `read`, `skill`, a `<server>_*` MCP action) or
368
+ * has no V2 equivalent and would produce a rule that can never match. Shared by
369
+ * `convertV1Permission` (the keyed `permission` map) and `convertV1Tools` (the
370
+ * `tools` enable/disable map) so the two migrations can never drift.
371
+ *
372
+ * `apply_patch` is included even though V1's `tools`/`permission` maps exposed it
373
+ * as `patch`: V2's runtime maps the `apply_patch` TOOL to the `patch` category and
374
+ * then to the `edit` permission action (verified against the 2.0.31 binary). So
375
+ * mapping it to `edit` here is what makes the narrow `edit`-deny grants
376
+ * (planner/product-manager) actually cover `apply_patch` — otherwise that tool
377
+ * would leak past a persona whose whole write surface is one artifact. */
378
+ const V1_ACTION = { bash: "shell", task: "subagent", write: "edit", patch: "edit", apply_patch: "edit" };
379
+
380
+ /* Convert a V1 keyed `permission` map (`{ <action>: { <resource>: effect } }`, or
381
+ * `{ <action>: effect }`) into the V2 ordered rules array, mapping the renamed V1
382
+ * actions (`bash`/`write`/`patch`/`task`) to their V2 names. Entry order is
383
+ * preserved so the V2 "last matching rule wins" semantics match the V1 glob map as
384
+ * closely as possible. */
385
+ function convertV1Permission(v1) {
386
+ const out = [];
387
+ if (!v1 || typeof v1 !== "object" || Array.isArray(v1)) return out;
388
+ for (const [action, rule] of Object.entries(v1)) {
389
+ const actionName = V1_ACTION[action] || action;
390
+ if (rule && typeof rule === "object" && !Array.isArray(rule)) {
391
+ for (const [resource, effect] of Object.entries(rule)) {
392
+ if (typeof effect === "string") out.push({ action: actionName, resource, effect });
393
+ }
394
+ } else if (typeof rule === "string") {
395
+ out.push({ action: actionName, resource: "*", effect: rule });
396
+ }
397
+ }
398
+ return out;
399
+ }
400
+
401
+ /* Convert a V1 `tools` map (`{ <tool-or-glob>: boolean }`) into V2 permission
402
+ * rules. V2 has **no top-level or per-agent `tools` field** (confirmed against
403
+ * `Agent.Info` in `@opencode/schema@2.0.29`): tool enablement is an ordered
404
+ * permission rule whose `action` is the tool name (`<server>_<tool>` for MCP) and
405
+ * whose `resource` is `"*"`. Without this the V1 global disable survived as a
406
+ * `permission` rule but the per-agent re-enable was silently dropped, so an MCP
407
+ * server showed `connected` yet no agent could call its tools (G1, LibraryOS).
408
+ * V1 tool names that V2 renamed go through the same `V1_ACTION` map. */
409
+ function convertV1Tools(v1) {
410
+ const out = [];
411
+ if (!v1 || typeof v1 !== "object" || Array.isArray(v1)) return out;
412
+ for (const [name, enabled] of Object.entries(v1)) {
413
+ if (typeof enabled !== "boolean") continue;
414
+ out.push({ action: V1_ACTION[name] || name, resource: "*", effect: enabled ? "allow" : "deny" });
415
+ }
416
+ return out;
417
+ }
418
+
419
+ /* Merge a harness `mcp` block with a project's, by server name under
420
+ * `mcp.servers` (the V2 location). Two plain-object server configs for the same
421
+ * name are shallow-merged (project last, so it wins a key collision); anything
422
+ * else (e.g. a project replacing a server) is taken from the project. Servers
423
+ * only the harness defines are added. Any other top-level `mcp` key is preserved
424
+ * (project wins). */
425
+ function mergeMcp(harnessMcp, priorMcp) {
426
+ const prior =
427
+ priorMcp && typeof priorMcp === "object" && !Array.isArray(priorMcp) ? priorMcp : {};
428
+ const out = { ...harnessMcp };
429
+ for (const [k, v] of Object.entries(prior)) if (k !== "servers") out[k] = v;
430
+ const harnessServers =
431
+ harnessMcp.servers && typeof harnessMcp.servers === "object" ? harnessMcp.servers : {};
432
+ const priorServers = prior.servers && typeof prior.servers === "object" ? prior.servers : {};
433
+ const servers = { ...harnessServers };
434
+ for (const [name, server] of Object.entries(priorServers)) {
435
+ const base = servers[name];
436
+ const bothObjects =
437
+ base &&
438
+ typeof base === "object" &&
439
+ !Array.isArray(base) &&
440
+ server &&
441
+ typeof server === "object" &&
442
+ !Array.isArray(server);
443
+ servers[name] = bothObjects ? { ...base, ...server } : server;
444
+ }
445
+ if (harnessMcp.servers || prior.servers || Object.keys(servers).length) out.servers = servers;
446
+ return out;
447
+ }
448
+
449
+ // Harness-shipped npm scripts auto-wired into the target project's package.json
450
+ // scripts (merged, not clobbered). Every other script the project has is preserved.
451
+ // These gates ship with the harness, so a deploy wires them up like opencode.json.
452
+ const HARNESS_SCRIPTS = {
453
+ backlog: "node scripts/backlog.js",
454
+ ship: "node scripts/ship.js",
455
+ finalize: "node scripts/finalize.js",
456
+ "test:dispatch": "node scripts/qa/check-dispatch-config.js",
457
+ "test:governance": "node scripts/qa/governance.js",
458
+ "test:qa-plan": "node scripts/qa/check-qa-plan.js",
459
+ "test:backlog": "node scripts/qa/check-backlog.js",
460
+ "test:product": "node scripts/qa/check-product.js",
461
+ "test:docs": "node scripts/qa/check-docs.js",
462
+ "test:concurrency": "node scripts/qa/check-concurrency.js",
463
+ "test:integrate": "node scripts/qa/check-integrate.js",
464
+ "test:quality": "node scripts/qa/check-quality.js",
465
+ "test:wiring": "node scripts/qa/check-test-wiring.js",
466
+ "test:linger": "node scripts/qa/check-linger.js",
467
+ "test:capacity": "node scripts/qa/check-capacity.js",
468
+ "test:ci-policy": "node scripts/qa/check-ci-policy.js",
469
+ "test:prefix": "node scripts/qa/check-prefix-stability.js",
470
+ "ci-triage": "node scripts/qa/ci-triage.js",
471
+ gates: "node scripts/qa/run-gates.js",
472
+ where: "node scripts/qa/where.js",
473
+ diff: "node scripts/qa/diff.js",
474
+ "feature:scaffold": "node scripts/qa/feature-scaffold.js",
475
+ report: "node scripts/agent-report.js",
476
+ "report:cost": "node scripts/agent-report.js --cost --since=14d",
477
+ "report:recon": "node scripts/qa/session-recon.js --since=14d",
478
+ nightly: "node scripts/nightly.js",
479
+ "report:nightly": "node scripts/nightly.js report",
480
+ checkpoint: "node scripts/checkpoint.js",
481
+ orient: "node scripts/orient.js",
482
+ wait: "node scripts/wait-for.js",
483
+ serve: "node scripts/serve.js",
484
+ search: "bash scripts/agent-search.sh",
485
+ ramdisk: "bash scripts/setup-tmpfs.sh up",
486
+ "ramdisk:down": "bash scripts/setup-tmpfs.sh down",
487
+ "wsl-tune": "bash scripts/wsl-tune.sh",
488
+ gpu: "bash scripts/wsl-gpu.sh",
489
+ };
490
+
491
+ /* Detect a project's own indentation so a merge never reformats package.json
492
+ * (a deploy that only normalizes whitespace still counts as a change and would
493
+ * be swept into the `chore(harness)` auto-commit). */
494
+ function detectIndent(text) {
495
+ const m = String(text).match(/^([ \t]+)"/m);
496
+ return m ? m[1] : " ";
497
+ }
498
+
499
+ // Merge harness gate scripts into the project's existing package.json, preserving
500
+ // every other script. ADD-ONLY: an existing script is never overwritten, so a
501
+ // project's deliberate customization of a gate survives re-deploys. When every
502
+ // harness script is already present this is a NO-OP (returns the byte-identical
503
+ // current text, `changed:false`) so the file is not rewritten/re-committed for
504
+ // formatting. Returns { text, hadPkg, changed, unparseable }.
505
+ function mergePackageJson(target) {
506
+ const p = path.join(target, "package.json");
507
+ const hadPkg = fs.existsSync(p);
508
+ if (!hadPkg) {
509
+ return { text: JSON.stringify({ scripts: { ...HARNESS_SCRIPTS } }, null, 2) + "\n", hadPkg, changed: true };
510
+ }
511
+ const current = fs.readFileSync(p, "utf8");
512
+ const existing = safeJson(current, null);
513
+ if (existing == null || typeof existing !== "object" || Array.isArray(existing)) {
514
+ // Never clobber a package.json we cannot parse (JSONC / hand-edited).
515
+ return { text: current, hadPkg, changed: false, unparseable: true };
516
+ }
517
+ const scripts = Object.assign({}, existing.scripts || {});
518
+ let added = false;
519
+ for (const [name, cmd] of Object.entries(HARNESS_SCRIPTS)) {
520
+ if (!(name in scripts)) {
521
+ scripts[name] = cmd;
522
+ added = true;
523
+ }
524
+ }
525
+ if (!added) return { text: current, hadPkg, changed: false };
526
+ const merged = { ...existing, scripts };
527
+ return { text: JSON.stringify(merged, null, detectIndent(current)) + "\n", hadPkg, changed: true };
528
+ }
529
+
530
+ /* Harness local-only ignore entries: rollback artifacts, the transient board
531
+ * lock, serve pid/log dir, and the guard telemetry log. These are LOCAL-ONLY
532
+ * artifacts (never committed), so they are recorded in the clone-local
533
+ * `.git/info/exclude` — NOT in the project's committed `.gitignore`.
534
+ *
535
+ * The harness deliberately never writes the project's `.gitignore`: an earlier
536
+ * design merged a marked section into it, but that merge truncated every
537
+ * project entry that followed the marker, silently un-ignoring secrets (`.env`,
538
+ * `data/`) that the harness auto-commit then exposed/pushed (FamilyBudget
539
+ * F-020). `.git/info/exclude` is untracked, per-clone, and never pushed, so it
540
+ * cannot alter or expose project files. */
541
+ const HARNESS_IGNORE_MARKER = "# agent-harness (managed below)";
542
+ const HARNESS_IGNORE_ENTRIES = [
543
+ ".harness-backup/",
544
+ ".harness.lock/",
545
+ ".serve/",
546
+ ".agents/guard-events.jsonl",
547
+ ];
548
+
549
+ /* Add-only merge of the harness local-only entries into the clone's
550
+ * `.git/info/exclude`. No-op outside a git repo (nothing can commit there) and
551
+ * when every entry is already present. Entries are prefixed with the target's
552
+ * path within the repo, so a nested harness project (`mobile/`) gets patterns
553
+ * that match its own tree. Never enters the deploy manifest/commit — the file
554
+ * is not part of the project. */
555
+ function mergeGitInfoExclude(target) {
556
+ if (!isGitRepo(target)) return;
557
+ const rp = runGit(target, ["rev-parse", "--git-path", "info/exclude"]);
558
+ if (!rp.ok || !rp.out) return;
559
+ const pf = runGit(target, ["rev-parse", "--show-prefix"]);
560
+ const prefix = pf.ok ? pf.out.replace(/\\/g, "/") : "";
561
+ const entries = HARNESS_IGNORE_ENTRIES.map((e) => prefix + e);
562
+ const p = path.isAbsolute(rp.out) ? rp.out : path.join(target, rp.out);
563
+ const existing = fs.existsSync(p) ? fs.readFileSync(p, "utf8") : "";
564
+ const lines = existing.split(/\r?\n/);
565
+ const missing = entries.filter((e) => !lines.includes(e));
566
+ if (missing.length === 0) return;
567
+ const hasMarker = lines.includes(HARNESS_IGNORE_MARKER);
568
+ const base = existing.replace(/\s*$/, "");
569
+ const block = (hasMarker ? [] : [HARNESS_IGNORE_MARKER]).concat(missing).join("\n");
570
+ const out = (base ? base + "\n\n" : "") + block + "\n";
571
+ fs.mkdirSync(path.dirname(p), { recursive: true });
572
+ fs.writeFileSync(p, out, "utf8");
573
+ }
574
+
575
+ /* Harness-managed .gitattributes entries: route BACKLOG.md through the row-aware
576
+ * merge driver (scripts/qa/merge-backlog.js) so concurrent board edits merge by
577
+ * row ID instead of conflicting. Merged into the project's own .gitattributes,
578
+ * preserving every project entry.
579
+ *
580
+ * The driver name is PER-PROJECT (`backlog-<project-slug>`), not a shared
581
+ * `backlog`. Two harness projects can live in one git repo (e.g. a repo root +
582
+ * a nested `mobile/` project); each carries a distinct `.gitattributes` driver
583
+ * name and registers its own `merge.<driver>.driver`, so one project's `update`
584
+ * can never clobber the other's driver registration. */
585
+ const GITATTRIBUTES_MARKER = "# agent-harness (managed below)";
586
+ const GITATTRIBUTES_END = "# agent-harness (managed end)";
587
+
588
+ function slugify(s) {
589
+ const slug = String(s || "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
590
+ return slug || "project";
591
+ }
592
+
593
+ function backlogDriverName(projectName) {
594
+ return `backlog-${slugify(projectName)}`;
595
+ }
596
+
597
+ /* Remove a previously-managed block delimited by an explicit begin/end pair. New
598
+ * files carry the end marker, so any project entry after it is preserved. A
599
+ * legacy file (begin marker only) has its block removed to EOF — the block was
600
+ * always appended last, so this matches the old behaviour with no data loss for
601
+ * real files while new merges can never truncate a trailing project entry. */
602
+ function stripManagedBlock(text, beginMarker, endMarker) {
603
+ const lines = String(text || "").split(/\r?\n/);
604
+ const begin = lines.findIndex((l) => l === beginMarker);
605
+ if (begin === -1) return lines;
606
+ const end = lines.findIndex((l, i) => i > begin && l === endMarker);
607
+ if (end === -1) return lines.slice(0, begin);
608
+ return [...lines.slice(0, begin), ...lines.slice(end + 1)];
609
+ }
610
+
611
+ function stripGitattributesBlock(text) {
612
+ return stripManagedBlock(text, GITATTRIBUTES_MARKER, GITATTRIBUTES_END);
613
+ }
614
+
615
+ /* Merge the canonical search-ignore set (`templates/.ignore`) into the target's
616
+ * `.ignore` idempotently. `.ignore` is the file ripgrep/fd read (git does not),
617
+ * so this is where the harness owns the high-cost-tree exclusions; the project's
618
+ * committed `.gitignore` is never touched. Project entries outside the managed
619
+ * markers are preserved and the managed block is replaced in place, so repeated
620
+ * updates never duplicate or truncate anything. */
621
+ function isIgnoreFile(rel) {
622
+ return relKey(rel) === ".ignore";
623
+ }
624
+
625
+ function mergeIgnoreFile(target) {
626
+ const tmpl = path.join(TEMPLATES_DIR, ".ignore");
627
+ const source = fs.existsSync(tmpl) ? fs.readFileSync(tmpl, "utf8") : "";
628
+ const srcLines = source.split(/\r?\n/);
629
+ const b = srcLines.findIndex((l) => l === GITATTRIBUTES_MARKER);
630
+ const e = srcLines.findIndex((l, i) => i > b && l === GITATTRIBUTES_END);
631
+ let managed = b !== -1 && e !== -1 ? srcLines.slice(b + 1, e) : srcLines.slice();
632
+ while (managed.length && managed[managed.length - 1].trim() === "") managed.pop();
633
+ const p = path.join(target, ".ignore");
634
+ const existing = fs.existsSync(p) ? fs.readFileSync(p, "utf8") : "";
635
+ const kept = stripManagedBlock(existing, GITATTRIBUTES_MARKER, GITATTRIBUTES_END);
636
+ while (kept.length && kept[kept.length - 1].trim() === "") kept.pop();
637
+ while (kept.length && kept[0].trim() === "") kept.shift();
638
+ const block = [GITATTRIBUTES_MARKER, ...managed, GITATTRIBUTES_END, ""];
639
+ const out = kept.length ? [...kept, "", ...block] : [...block];
640
+ return out.join("\n");
641
+ }
642
+
643
+ function mergeGitattributes(target, driverName) {
644
+ const p = path.join(target, ".gitattributes");
645
+ const existing = fs.existsSync(p) ? fs.readFileSync(p, "utf8") : "";
646
+ const kept = stripGitattributesBlock(existing);
647
+ while (kept.length && kept[kept.length - 1].trim() === "") kept.pop();
648
+ while (kept.length && kept[0].trim() === "") kept.shift();
649
+ const managed = [
650
+ GITATTRIBUTES_MARKER,
651
+ "*.sh text eol=lf",
652
+ "*.ps1 text eol=crlf",
653
+ GITATTRIBUTES_END,
654
+ "",
655
+ ];
656
+ const out = kept.length ? [...kept, "", ...managed] : [...managed];
657
+ return out.join("\n");
658
+ }
659
+
660
+ /* ADR 0001 retired the BACKLOG.md row-aware merge driver: the board lives in
661
+ * the external service, so there is no in-repo file to merge. Remove the
662
+ * per-clone registration a previous harness version may have written, so a
663
+ * stale absolute pointer (once a worktree it referenced is gone) cannot linger.
664
+ * Best-effort: a fresh clone simply has nothing to remove. */
665
+ function unregisterBacklogMergeDriver(target, projectName) {
666
+ if (!isGitRepo(target)) return;
667
+ const driverName = backlogDriverName(projectName);
668
+ runGit(target, ["config", "--unset", `merge.${driverName}.name`]);
669
+ runGit(target, ["config", "--unset", `merge.${driverName}.driver`]);
670
+ }
671
+
672
+ // ---------------------------------------------------------------- git helpers
673
+
674
+ function runGit(target, args, opts) {
675
+ const result = require("child_process").spawnSync("git", args, {
676
+ cwd: target,
677
+ encoding: "utf8",
678
+ ...(opts && opts.timeout ? { timeout: opts.timeout } : {}),
679
+ });
680
+ return { ok: result.status === 0, status: result.status, out: (result.stdout || "").trim(), err: (result.stderr || "").trim() };
681
+ }
682
+
683
+ function isGitRepo(target) {
684
+ const r = runGit(target, ["rev-parse", "--is-inside-work-tree"]);
685
+ return r.ok;
686
+ }
687
+
688
+ /* The currently checked-out branch, or "" when detached / not a repo. */
689
+ function currentBranch(target) {
690
+ const r = runGit(target, ["rev-parse", "--abbrev-ref", "HEAD"]);
691
+ if (!r.ok || !r.out || r.out === "HEAD") return "";
692
+ return r.out;
693
+ }
694
+
695
+ /* The repo's canonical branch: `origin/HEAD` (set by clone) when available,
696
+ * else `main` or `master` when one exists remotely/locally. Null when it cannot
697
+ * be determined (e.g. a local-only repo with no remote), so a project without a
698
+ * remote is never blocked. */
699
+ function defaultBranch(target) {
700
+ const sym = runGit(target, ["symbolic-ref", "--short", "refs/remotes/origin/HEAD"]);
701
+ if (sym.ok && sym.out) return sym.out.replace(/^origin\//, "");
702
+ for (const name of ["main", "master"]) {
703
+ if (runGit(target, ["show-ref", "--verify", "--quiet", `refs/remotes/origin/${name}`]).ok) return name;
704
+ if (runGit(target, ["show-ref", "--verify", "--quiet", `refs/heads/${name}`]).ok) return name;
705
+ }
706
+ return null;
707
+ }
708
+
709
+ /* Cross-process deploy lock (an exclusive `.harness.lock` DIRECTORY, the same
710
+ * atomic primitive the board lock uses). Two `update` runs against one target —
711
+ * or an update racing a worktree push — must not interleave their read-modify-
712
+ * write of `.harness.json` and the harness tree. The holder's pid is published
713
+ * inside the directory; a missing/unparseable pid is treated as held (creator
714
+ * mid-setup), and a provably-dead pid is broken. No-op outside a git repo. */
715
+ const DEPLOY_LOCK = ".harness.lock";
716
+ function pidAlive(pid) {
717
+ if (!Number.isFinite(pid) || pid <= 0) return false;
718
+ try {
719
+ process.kill(pid, 0);
720
+ return true;
721
+ } catch (e) {
722
+ return e.code === "EPERM";
723
+ }
724
+ }
725
+ function sleepMs(ms) {
726
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
727
+ }
728
+ async function withDeployLock(target, fn) {
729
+ if (!isGitRepo(target)) return fn();
730
+ const lockPath = path.join(target, DEPLOY_LOCK);
731
+ const pidPath = path.join(lockPath, "pid");
732
+ const deadline = Date.now() + 15000;
733
+ let acquired = false;
734
+ while (!acquired) {
735
+ try {
736
+ fs.mkdirSync(lockPath);
737
+ acquired = true;
738
+ } catch (e) {
739
+ if (e.code !== "EEXIST") throw e;
740
+ let holder = NaN;
741
+ try {
742
+ holder = parseInt(fs.readFileSync(pidPath, "utf8"), 10);
743
+ } catch {
744
+ /* creator mid-setup — held, never stale */
745
+ }
746
+ if (Number.isFinite(holder) && holder > 0 && !pidAlive(holder)) {
747
+ try {
748
+ fs.rmSync(lockPath, { recursive: true, force: true });
749
+ } catch {
750
+ /* vanished — retry */
751
+ }
752
+ continue;
753
+ }
754
+ if (Date.now() > deadline) {
755
+ throw new Error(
756
+ "agent-harness: timed out waiting for the deploy lock — another update is writing this target."
757
+ );
758
+ }
759
+ sleepMs(25);
760
+ }
761
+ }
762
+ try {
763
+ fs.writeFileSync(pidPath, String(process.pid));
764
+ return await fn();
765
+ } finally {
766
+ try {
767
+ fs.rmSync(lockPath, { recursive: true, force: true });
768
+ } catch {
769
+ /* best-effort release */
770
+ }
771
+ }
772
+ }
773
+
774
+ /* WSL mounts Windows drives at `/mnt/<drive>/...` (9p / virtio-fs) — file I/O,
775
+ * especially node_modules churn, is far slower there than on the ext4
776
+ * filesystem the WSL checkout lives on. Detect it so a deploy into a
777
+ * Windows-mount project warns instead of silently crawling. `platform` is
778
+ * injectable so the check is unit-testable on any host. */
779
+ function isWindowsMount(target, platform = process.platform) {
780
+ return platform !== "win32" && /^\/mnt\/[a-z]\//i.test(String(target));
781
+ }
782
+
783
+ /* Compare HEAD to its upstream tracking branch after a best-effort fetch. Pure
784
+ * read — never mutates. `known` is true only when a tracking branch exists and
785
+ * the ahead/behind counts were read, so a repo without a remote is a no-op. */
786
+ function upstreamState(target) {
787
+ const st = { upstream: "", ahead: 0, behind: 0, known: false };
788
+ if (!isGitRepo(target)) return st;
789
+ runGit(target, ["fetch", "--quiet", "origin"], { timeout: 10000 });
790
+ const track = runGit(target, ["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{u}"]);
791
+ if (!track.ok || !track.out) return st;
792
+ st.upstream = track.out;
793
+ const counts = runGit(target, ["rev-list", "--left-right", "--count", `HEAD...${st.upstream}`]);
794
+ if (!counts.ok) return st;
795
+ const [ahead, behind] = counts.out.split(/\s+/).map((n) => parseInt(n, 10) || 0);
796
+ st.ahead = ahead || 0;
797
+ st.behind = behind || 0;
798
+ st.known = true;
799
+ return st;
800
+ }
801
+
802
+ /* Keep the target's branch current before the harness writes or commits onto it.
803
+ * Feature work committed and pushed from its own `backlog worktree` leaves the
804
+ * main checkout behind; if `update` then auto-commits a `chore(harness)` commit
805
+ * on that stale base, the local branch diverges (behind AND ahead of origin) and
806
+ * the push is rejected. A clean, strictly-behind branch is fast-forwarded so the
807
+ * deploy lands on the current base; a diverged branch is refused so the operator
808
+ * reconciles first (`git pull --rebase`) instead of deepening the split. Dry-run
809
+ * only reports. Returns { blocked, notes, state, synced? }. */
810
+ function syncTargetBranch(target, dryRun) {
811
+ const notes = [];
812
+ const st = upstreamState(target);
813
+ if (!st.known || st.behind === 0) return { blocked: false, notes, state: st };
814
+ if (st.ahead > 0) {
815
+ notes.push(
816
+ `target branch is ${st.behind} behind and ${st.ahead} ahead of ${st.upstream} — ` +
817
+ `refusing to write/commit onto a diverged branch; reconcile first: git pull --rebase`
818
+ );
819
+ return { blocked: true, notes, state: st };
820
+ }
821
+ if (dryRun) {
822
+ notes.push(`would fast-forward ${st.behind} commit(s) to ${st.upstream}`);
823
+ return { blocked: false, notes, state: st };
824
+ }
825
+ // A redundant local edit (working content already identical to upstream) must
826
+ // not block the fast-forward — that silent block is what let the checkout
827
+ // drift stale across landings. Genuine local edits are still never touched.
828
+ const cleared = clearRedundantDirty(target, st.upstream);
829
+ if (cleared.length) {
830
+ notes.push(`cleared redundant local changes already in ${st.upstream}: ${cleared.join(", ")}`);
831
+ }
832
+ const ff = runGit(target, ["merge", "--ff-only", st.upstream]);
833
+ if (!ff.ok) {
834
+ notes.push(
835
+ `target is ${st.behind} behind ${st.upstream} but could not fast-forward ` +
836
+ `(uncommitted changes overlap) — reconcile first: git pull --rebase`
837
+ );
838
+ return { blocked: true, notes, state: st };
839
+ }
840
+ notes.push(`fast-forwarded ${st.behind} commit(s) to ${st.upstream}`);
841
+ return { blocked: false, notes, state: st, synced: true };
842
+ }
843
+
844
+ /* Restore tracked non-board files whose working content already matches
845
+ * `upstream` — they carry no local information, so clearing them is lossless and
846
+ * lets the fast-forward proceed. Genuine local edits are left untouched (the
847
+ * merge then fails and the operator reconciles). */
848
+ function clearRedundantDirty(target, upstream) {
849
+ const status = runGit(target, ["status", "--porcelain", "--untracked-files=no"]);
850
+ if (!status.ok || !status.out) return [];
851
+ const cleared = [];
852
+ for (const line of status.out.split(/\r?\n/).filter(Boolean)) {
853
+ const p = line.slice(3).trim();
854
+ if (!p || p === "BACKLOG.md") continue;
855
+ const diff = runGit(target, ["diff", "--quiet", upstream, "--", p]);
856
+ if (diff.status !== 0) continue;
857
+ if (runGit(target, ["checkout", upstream, "--", p]).ok) cleared.push(p);
858
+ }
859
+ return cleared;
860
+ }
861
+
862
+ // Auto-commit ONLY the harness-owned files an update just changed, so the target
863
+ // project's next session never sees "unexplained" modified harness files. Scoped
864
+ // to this run's changed harness files (never `git add -A`) so unrelated
865
+ // uncommitted work is NEVER swept in — including work another session already
866
+ // STAGED: the diff and the commit both carry a pathspec, so pre-staged paths are
867
+ // left in the index instead of being swept into the harness commit. Memory/backup
868
+ // files are excluded (project data / rollback).
869
+ // Harness-owned paths are force-added (`-f`): target projects often gitignore
870
+ // .agents/ .opencode/ AGENTS.md (inherited from the harness's own .gitignore), and
871
+ // a plain `git add` would fail on the first ignored path and commit NOTHING.
872
+ // Returns { committed:boolean, staged:string[], skipped:string[], pushed:boolean|null, forceAdded:string[] }.
873
+ function commitHarnessChanges(target, changedRels, opts) {
874
+ const out = { committed: false, staged: [], skipped: [], pushed: null, forceAdded: [] };
875
+ if (!opts.commit) return out;
876
+ if (!isGitRepo(target)) {
877
+ out.skipped.push("not a git repo");
878
+ return out;
879
+ }
880
+ // Final integrate guard: never create the commit on a stale base. The deploy
881
+ // path fast-forwards a clean behind branch first; if origin advanced again
882
+ // mid-deploy, refuse rather than bake in a divergent local commit.
883
+ if (opts.checkUpstream !== false) {
884
+ const st = upstreamState(target);
885
+ if (st.known && st.behind > 0) {
886
+ out.skipped.push(
887
+ `branch is ${st.behind} behind ${st.upstream} — not committing (would diverge); ` +
888
+ `run git pull --rebase and re-run update`
889
+ );
890
+ return out;
891
+ }
892
+ }
893
+ if (changedRels.length === 0) {
894
+ out.skipped.push("no harness files changed");
895
+ return out;
896
+ }
897
+ const ignored = runGit(target, ["check-ignore", ...changedRels]);
898
+ if (ignored.ok && ignored.out) {
899
+ out.forceAdded = ignored.out.split(/\r?\n/).filter(Boolean).map(relKey);
900
+ }
901
+ const addR = runGit(target, ["add", "-f", "--", ...changedRels]);
902
+ if (!addR.ok) {
903
+ out.skipped.push("git add failed: " + firstGitErrorLine(addR.err));
904
+ return out;
905
+ }
906
+ // Scope the "what changed" report AND the commit to this run's paths. A bare
907
+ // `git diff --cached` / `git commit` operate on the WHOLE index, which is how a
908
+ // concurrent session's pre-staged work ended up in a harness `chore` commit.
909
+ const diffCached = runGit(target, ["diff", "--cached", "--name-only", "--", ...changedRels]);
910
+ const staged = (diffCached.out || "").split(/\r?\n/).filter(Boolean).map(relKey);
911
+ if (staged.length === 0) {
912
+ out.skipped.push("no harness changes staged");
913
+ return out;
914
+ }
915
+ out.staged = staged;
916
+ const prior = opts.priorVersion ? opts.priorVersion + " -> " : "";
917
+ const message = `chore(harness): opencode-agent-harness ${prior}${PKG.version}`;
918
+ const commitR = runGit(target, ["commit", "-m", message, "--", ...changedRels]);
919
+ if (!commitR.ok) {
920
+ out.skipped.push("commit failed: " + firstGitErrorLine(commitR.err));
921
+ return out;
922
+ }
923
+ out.committed = true;
924
+ if (opts.push) {
925
+ const hasRemote = runGit(target, ["remote"]).ok && runGit(target, ["remote"]).out;
926
+ if (hasRemote) {
927
+ // Harness maintenance pushes its own `chore(harness)` commit to the
928
+ // canonical branch. Run it with --no-verify: the project's pre-push
929
+ // battery is project-owned and may (rightly) refuse a direct main push or
930
+ // trip a gate on a harness-only diff, which would otherwise strand the
931
+ // harness commit unpushed. The branch guard above already keeps this off
932
+ // any non-canonical branch.
933
+ const pushR = runGit(target, ["push", "--no-verify", "origin", "HEAD"]);
934
+ out.pushed = pushR.ok;
935
+ if (!pushR.ok) out.skipped.push("push failed: " + firstGitErrorLine(pushR.err));
936
+ } else {
937
+ out.skipped.push("no git remote to push");
938
+ }
939
+ }
940
+ return out;
941
+ }
942
+
943
+ /* Pull the first real error line out of git's stderr, dropping the LF/CRLF
944
+ * warnings and `hint:` noise that bury the actual message. */
945
+ function firstGitErrorLine(err) {
946
+ const line = String(err || "")
947
+ .split(/\r?\n/)
948
+ .map((l) => l.trim())
949
+ .find((l) => l && !/^warning:/i.test(l) && !/^hint:/i.test(l));
950
+ return line || "git command failed";
951
+ }
952
+
953
+ /* The V1 -> V2 layout moved `.opencode/tools/*.ts` into `.opencode/plugins/`
954
+ * and the singular `.opencode/command/` dir into `.opencode/commands/`. A deploy
955
+ * cannot see a removed template, so without this a project keeps the stale V1
956
+ * files — and V2 still discovers the legacy `command/` dir, so the old command
957
+ * text would shadow the new `commands/`. Remove only the files the harness
958
+ * itself shipped (never a project-added one), then prune the dir if empty. */
959
+ const OBSOLETE_HARNESS_FILES = [
960
+ ".opencode/tools/backlog.ts",
961
+ ".opencode/tools/checkpoint.ts",
962
+ ".opencode/tools/session.ts",
963
+ ".opencode/tools/orient.ts",
964
+ ".opencode/tools/gates.ts",
965
+ ".opencode/tools/wait.ts",
966
+ ".opencode/tools/where.ts",
967
+ ".opencode/command/board.md",
968
+ ".opencode/command/checkpoint.md",
969
+ ".opencode/command/feature.md",
970
+ ".opencode/command/finish.md",
971
+ ".opencode/command/next.md",
972
+ ".opencode/command/report.md",
973
+ ".opencode/command/resume.md",
974
+ ".opencode/command/switch-model.md",
975
+ ];
976
+
977
+ function pruneObsoleteHarnessFiles(target, dryRun) {
978
+ const removed = [];
979
+ const dirs = new Set();
980
+ for (const rel of OBSOLETE_HARNESS_FILES) {
981
+ const abs = path.join(target, rel);
982
+ if (!fs.existsSync(abs)) continue;
983
+ removed.push(relKey(rel));
984
+ dirs.add(path.dirname(abs));
985
+ if (!dryRun) {
986
+ try {
987
+ fs.unlinkSync(abs);
988
+ } catch (_) {
989
+ /* best-effort */
990
+ }
991
+ }
992
+ }
993
+ if (!dryRun) {
994
+ for (const dir of dirs) {
995
+ try {
996
+ if (fs.existsSync(dir) && fs.readdirSync(dir).length === 0) fs.rmdirSync(dir);
997
+ } catch (_) {
998
+ /* leave a dir a project still uses */
999
+ }
1000
+ }
1001
+ }
1002
+ return removed;
1003
+ }
1004
+
1005
+ // ---------------------------------------------------------------- deploy
1006
+
1007
+ function backup(target, rel, content) {
1008
+ const stamp = new Date().toISOString().replace(/[:.]/g, "-");
1009
+ const dest = path.join(target, BACKUP_DIR, stamp, relKey(rel));
1010
+ fs.mkdirSync(path.dirname(dest), { recursive: true });
1011
+ fs.writeFileSync(dest, content, "utf8");
1012
+ }
1013
+
1014
+ /* Locally-modified harness-owned files a deploy WOULD overwrite:
1015
+ * `{ rel, targetAbs, prev }`. A file counts only when its content differs from
1016
+ * the incoming template (a no-op rewrite is harmless) AND its on-disk bytes no
1017
+ * longer match the checksum recorded in `.harness.json` — i.e. the project
1018
+ * edited a harness-owned file since the last deploy. Merged files
1019
+ * (`.gitattributes`, `.ignore`, `opencode.json`, `package.json`) and
1020
+ * create-if-missing project data are excluded: those never clobber. */
1021
+ /* First `init` into a repo that already has its own AGENTS.md: overwriting it
1022
+ * would destroy project instructions the harness did not create. Refuse before
1023
+ * writing anything; --accept-harness deliberately overwrites after a backup. */
1024
+ function collectInitAgentsConflict(target, variables) {
1025
+ if (fs.existsSync(path.join(target, CONFIG_FILE))) return null;
1026
+ const targetAbs = path.join(target, "AGENTS.md");
1027
+ if (!fs.existsSync(targetAbs)) return null;
1028
+ const tplAbs = path.join(TEMPLATES_DIR, "AGENTS.md");
1029
+ if (!fs.existsSync(tplAbs)) return null;
1030
+ const incoming = substitute(fs.readFileSync(tplAbs, "utf8"), variables);
1031
+ return normalizeEol(fs.readFileSync(targetAbs, "utf8")) === normalizeEol(incoming)
1032
+ ? null
1033
+ : targetAbs;
1034
+ }
1035
+
1036
+ function collectLocalHarnessDivergences(target, previousFiles, variables) {
1037
+ const divergent = [];
1038
+ for (const { abs, rel } of listFiles(TEMPLATES_DIR)) {
1039
+ const key = relKey(rel);
1040
+ if (key === ".gitattributes" || key === "package.json") continue;
1041
+ if (isIgnoreFile(rel) || isOpencodeJson(rel) || isCreateIfMissing(rel)) continue;
1042
+ const deployedHash = previousFiles[key];
1043
+ if (!deployedHash) continue; // not previously deployed: no tracked local edit
1044
+ const targetAbs = path.join(target, rel);
1045
+ if (!fs.existsSync(targetAbs)) continue;
1046
+ const prev = fs.readFileSync(targetAbs, "utf8");
1047
+ if (deployedHash === sha256(prev)) continue; // unmodified since last deploy
1048
+ const content = substitute(fs.readFileSync(abs, "utf8"), variables);
1049
+ if (prev === content) continue; // matches the incoming template: no clobber
1050
+ divergent.push({ rel: key, targetAbs, prev });
1051
+ }
1052
+ return divergent;
1053
+ }
1054
+
1055
+ /* Run the target's own mechanical gate after an accepted overwrite. A clobber
1056
+ * that breaks the project's own suite (the F-289 board-sync regression) must not
1057
+ * be committed as a `chore(harness)` commit. Returns { ran, ok, output }. */
1058
+ function runTargetQuickGate(target) {
1059
+ const pkgPath = path.join(target, "package.json");
1060
+ let scripts = {};
1061
+ try {
1062
+ scripts = JSON.parse(fs.readFileSync(pkgPath, "utf8")).scripts || {};
1063
+ } catch (_) {
1064
+ return { ran: false, ok: true, output: "" };
1065
+ }
1066
+ if (!scripts["test:quick"]) return { ran: false, ok: true, output: "" };
1067
+ const r = spawnSync("npm", ["run", "test:quick"], {
1068
+ cwd: target,
1069
+ encoding: "utf8",
1070
+ timeout: 0,
1071
+ });
1072
+ const output = String(r.stdout || "") + String(r.stderr || "");
1073
+ if (r.error || r.status == null) return { ran: false, ok: true, output };
1074
+ return { ran: true, ok: r.status === 0, output };
1075
+ }
1076
+
1077
+ async function deploy(target, opts) {
1078
+ const { name, domain, yes, dryRun, isUpdate, commit, push, allowBranch, acceptHarness } = opts || {};
1079
+ if (isWindowsMount(target)) {
1080
+ console.warn(
1081
+ ` WARNING: target "${target}" is on a Windows drive mount (/mnt/...) — file I/O is ` +
1082
+ `much slower than the WSL ext4 filesystem. Prefer a path under ~/develop.`
1083
+ );
1084
+ }
1085
+ // The deployed harness is V2-native; warn when the machine's `opencode` is V1
1086
+ // so the mismatch is visible now instead of showing up as "no tools loaded".
1087
+ warnOpencodeVersion();
1088
+ const existing = readConfig(target);
1089
+ const projectName = name || existing.projectName || path.basename(target);
1090
+ const driverName = backlogDriverName(projectName);
1091
+ let projectDomain = domain || existing.projectDomain || "";
1092
+ if (!projectDomain && !isUpdate && !yes && process.stdin.isTTY) {
1093
+ projectDomain = await ask(`Project domain (one line) for "${projectName}": `, "");
1094
+ }
1095
+ const VARIABLES = {
1096
+ PROJECT_NAME: projectName,
1097
+ PROJECT_DOMAIN: projectDomain,
1098
+ WORKSPACE_ROOT: workspaceRootFor(target),
1099
+ };
1100
+
1101
+ // All writes/commits run under a per-target deploy lock (a no-op outside a git
1102
+ // repo and on dry-run) so two updates can never interleave their read-modify-
1103
+ // write of .harness.json / the harness tree.
1104
+ const runDeploy = async () => {
1105
+ assertNoTemplateHandoffs();
1106
+ const existing = readConfig(target);
1107
+
1108
+ // First-run guard: never clobber a project's own AGENTS.md on `init`.
1109
+ if (!isUpdate && !acceptHarness) {
1110
+ const conflict = collectInitAgentsConflict(target, VARIABLES);
1111
+ if (conflict) {
1112
+ throw new Error(
1113
+ `"${projectName}" already has an AGENTS.md that this harness did not create:\n` +
1114
+ ` ${conflict}\n` +
1115
+ ` Refusing to run \`init\` and overwrite it. Move or merge that file, run in a\n` +
1116
+ ` clean directory, or re-run with --accept-harness (the existing file is\n` +
1117
+ ` backed up under ${BACKUP_DIR}/ first).`
1118
+ );
1119
+ }
1120
+ }
1121
+
1122
+ // Refuse to downgrade: the target's deployed harness is newer than this CLI.
1123
+ // This is how the "I updated from a local checkout that I never published"
1124
+ // mistake surfaces instead of silently writing older templates over a newer
1125
+ // deployment (and auto-committing that regression).
1126
+ if (isUpdate && existing.version && compareVersions(existing.version, PKG.version) > 0) {
1127
+ throw new Error(
1128
+ `"${projectName}" has harness v${existing.version} — NEWER than this CLI (v${PKG.version}). ` +
1129
+ `Not downgrading. Publish v${existing.version} (or this CLI) so \`update\` can re-sync from the registry.`
1130
+ );
1131
+ }
1132
+
1133
+ // Branch guard: never auto-commit/push harness files onto a non-default
1134
+ // branch. A deploy run from a feature branch (or a main checkout a session
1135
+ // left on a chore branch) would strand the harness commit off `main` and the
1136
+ // canonical branch would silently stay stale — the LibraryOS 2026-09-18 case
1137
+ // (harness 0.1.73 landed on `origin/chore/archive-f-244`, main stuck at
1138
+ // 0.1.72). Skipped when undeterminable (no remote) or when not committing.
1139
+ let branchGuard = null;
1140
+ if (commit) {
1141
+ const cur = currentBranch(target);
1142
+ const def = defaultBranch(target);
1143
+ const hasHead = runGit(target, ["rev-parse", "--verify", "--quiet", "HEAD"]).ok;
1144
+ if (!cur && hasHead) {
1145
+ if (!allowBranch) {
1146
+ throw new Error(
1147
+ `"${projectName}" is in detached HEAD — refusing to auto-commit/push harness files. ` +
1148
+ `Check out ${def || "the canonical branch"} (git switch ${def || "main"}) and re-run, or pass --allow-branch.`
1149
+ );
1150
+ }
1151
+ } else if (def && cur !== def) {
1152
+ if (!allowBranch) {
1153
+ throw new Error(
1154
+ `"${projectName}" is on branch \`${cur}\`, not the canonical \`${def}\` — refusing to ` +
1155
+ `auto-commit/push harness files onto a non-default branch (they would be stranded off ` +
1156
+ `\`${def}\` and its harness version would stay stale). Switch to \`${def}\` ` +
1157
+ `(git switch ${def}) and re-run \`update\`, or pass --allow-branch to override.`
1158
+ );
1159
+ }
1160
+ branchGuard = { branch: cur, defaultBranch: def, overridden: true };
1161
+ console.warn(` WARNING: deploying onto non-default branch \`${cur}\` (--allow-branch).`);
1162
+ }
1163
+ }
1164
+
1165
+ // Integrate-early: bring a stale checkout current (or refuse a diverged one)
1166
+ // BEFORE any harness file is written, so the auto-commit below can never land
1167
+ // on the stale base a worktree push left behind. Skipped when this run will
1168
+ // not commit (--no-commit) and reported-only on dry-run.
1169
+ let syncResult = null;
1170
+ if (commit) {
1171
+ syncResult = syncTargetBranch(target, !!dryRun);
1172
+ for (const note of syncResult.notes) console.log(` ${note}`);
1173
+ if (syncResult.blocked) throw new Error(`"${projectName}": ${syncResult.notes[0]}`);
1174
+ }
1175
+
1176
+ const previousFiles = existing.files || {};
1177
+ const actions = [];
1178
+ const manifest = {};
1179
+ // Harness-owned files present on disk with the correct bytes ("unchanged").
1180
+ // They are not in `changedRels`, so a present-but-untracked one would never be
1181
+ // committed by this deploy (see the untracked sweep after the loop).
1182
+ const harnessOwnedPresent = [];
1183
+
1184
+ // Fail closed on a locally-modified harness-owned file BEFORE writing anything.
1185
+ // A silent overwrite destroys a project-side fix to a harness file (F-289:
1186
+ // the 0.1.99 deploy clobbered scripts/qa/board-sync.js, breaking the target's
1187
+ // own suite). The operator must either upstream the fix into this harness's
1188
+ // `templates/` and release, or re-run with --accept-harness to overwrite
1189
+ // deliberately (the old bytes are still backed up).
1190
+ const divergent = collectLocalHarnessDivergences(target, previousFiles, VARIABLES);
1191
+ if (divergent.length && !acceptHarness) {
1192
+ const list = divergent.map((d) => ` - ${d.rel}`).join("\n");
1193
+ throw new Error(
1194
+ `"${projectName}" has locally-modified harness-owned file(s):\n${list}\n` +
1195
+ ` These diverge from the deployed checksum in .harness.json, so \`update\` would ` +
1196
+ `overwrite a hand-edit.\n` +
1197
+ ` Fix it upstream instead: port the change into this harness's \`templates/\` ` +
1198
+ `(a drift-guard test if it is a gate/QA script), bump + release the harness, then re-run \`update\`.\n` +
1199
+ ` To discard the local edit and take the template copy (a backup is written), re-run with --accept-harness.`
1200
+ );
1201
+ }
1202
+ // Snapshot for the post-overwrite gate rollback: if the accepted copy breaks the
1203
+ // target's own suite, restore these files and abort before committing.
1204
+ const configPath = path.join(target, CONFIG_FILE);
1205
+ const configPrev = fs.existsSync(configPath) ? fs.readFileSync(configPath, "utf8") : null;
1206
+
1207
+ // Auto-wire harness gate scripts into the target package.json (merged, add-only).
1208
+ // A no-op merge leaves the file byte-identical so its own formatting is never
1209
+ // rewritten/re-committed; an unparseable package.json is preserved untouched.
1210
+ {
1211
+ const { text, hadPkg, changed, unparseable } = mergePackageJson(target);
1212
+ const key = "package.json";
1213
+ const targetAbs = path.join(target, "package.json");
1214
+ if (unparseable) actions.push({ rel: key, kind: "preserve" });
1215
+ else if (!hadPkg) actions.push({ rel: key, kind: "create" });
1216
+ else if (changed) actions.push({ rel: key, kind: "merge" });
1217
+ else actions.push({ rel: key, kind: "unchanged" });
1218
+ manifest[key] = sha256(text);
1219
+ if (!dryRun && (changed || !hadPkg)) {
1220
+ fs.mkdirSync(path.dirname(targetAbs), { recursive: true });
1221
+ fs.writeFileSync(targetAbs, text, "utf8");
1222
+ }
1223
+ }
1224
+
1225
+ // Merge harness-managed .gitattributes (line-ending pins). ADR 0001 removed
1226
+ // the BACKLOG.md row-aware merge driver — the board lives in the service.
1227
+ {
1228
+ const text = mergeGitattributes(target, driverName);
1229
+ const key = ".gitattributes";
1230
+ const targetAbs = path.join(target, ".gitattributes");
1231
+ const had = fs.existsSync(targetAbs);
1232
+ const current = had ? fs.readFileSync(targetAbs, "utf8") : null;
1233
+ if (!had) actions.push({ rel: key, kind: "create" });
1234
+ else if (current !== text) actions.push({ rel: key, kind: "merge" });
1235
+ else actions.push({ rel: key, kind: "unchanged" });
1236
+ manifest[key] = sha256(text);
1237
+ if (!dryRun) {
1238
+ fs.mkdirSync(path.dirname(targetAbs), { recursive: true });
1239
+ fs.writeFileSync(targetAbs, text, "utf8");
1240
+ }
1241
+ }
1242
+
1243
+ // Merge the canonical search-ignore set (`.ignore`): idempotent begin/end
1244
+ // block, project entries preserved, replaced in place on every update. This is
1245
+ // the file ripgrep/fd read; the project's `.gitignore` stays project-owned.
1246
+ {
1247
+ const text = mergeIgnoreFile(target);
1248
+ const key = ".ignore";
1249
+ const targetAbs = path.join(target, ".ignore");
1250
+ const had = fs.existsSync(targetAbs);
1251
+ const current = had ? fs.readFileSync(targetAbs, "utf8") : null;
1252
+ if (!had) actions.push({ rel: key, kind: "create" });
1253
+ else if (current !== text) actions.push({ rel: key, kind: "merge" });
1254
+ else actions.push({ rel: key, kind: "unchanged" });
1255
+ manifest[key] = sha256(text);
1256
+ if (!dryRun) {
1257
+ fs.mkdirSync(path.dirname(targetAbs), { recursive: true });
1258
+ fs.writeFileSync(targetAbs, text, "utf8");
1259
+ }
1260
+ }
1261
+
1262
+ // ADR 0001: the BACKLOG.md merge driver is retired (the board is in the
1263
+ // service). Remove any stale per-clone registration so a leftover pointer
1264
+ // cannot dangle, and refresh the clone-local exclude file.
1265
+ if (!dryRun) {
1266
+ unregisterBacklogMergeDriver(target, projectName);
1267
+ mergeGitInfoExclude(target);
1268
+ }
1269
+
1270
+ for (const { abs, rel } of listFiles(TEMPLATES_DIR)) {
1271
+ const key = relKey(rel);
1272
+ const targetAbs = path.join(target, rel);
1273
+
1274
+ // `.ignore` is a merged file (see mergeIgnoreFile above), not a plain copy.
1275
+ if (isIgnoreFile(rel)) continue;
1276
+
1277
+ if (isOpencodeJson(rel)) {
1278
+ const merged = mergeOpencodeJson(target, VARIABLES);
1279
+ const current = fs.existsSync(targetAbs) ? fs.readFileSync(targetAbs, "utf8") : null;
1280
+ if (current == null) actions.push({ rel: key, kind: "create" });
1281
+ else if (current !== merged) actions.push({ rel: key, kind: "merge" });
1282
+ else actions.push({ rel: key, kind: "unchanged" });
1283
+ manifest[key] = sha256(merged);
1284
+ if (!dryRun) {
1285
+ fs.mkdirSync(path.dirname(targetAbs), { recursive: true });
1286
+ fs.writeFileSync(targetAbs, merged, "utf8");
1287
+ }
1288
+ continue;
1289
+ }
1290
+
1291
+ if (isCreateIfMissing(rel)) {
1292
+ // ADR 0001: a service-backed project (its `.harness.json` carries a
1293
+ // `board` block) has its board in the service, so a legacy BACKLOG.md is
1294
+ // neither scaffolded nor recreated — and a stale one is left untouched.
1295
+ if (isBacklogFile(rel) && existing.board) {
1296
+ if (fs.existsSync(targetAbs)) actions.push({ rel: key, kind: "preserve" });
1297
+ else actions.push({ rel: key, kind: "skipped (service board)" });
1298
+ continue;
1299
+ }
1300
+ if (fs.existsSync(targetAbs)) {
1301
+ actions.push({ rel: key, kind: "preserve" });
1302
+ } else {
1303
+ actions.push({ rel: key, kind: "create" });
1304
+ if (!dryRun) {
1305
+ fs.mkdirSync(path.dirname(targetAbs), { recursive: true });
1306
+ fs.writeFileSync(targetAbs, substitute(fs.readFileSync(abs, "utf8"), VARIABLES), "utf8");
1307
+ }
1308
+ }
1309
+ continue; // project data: never tracked in the manifest
1310
+ }
1311
+
1312
+ // harness-owned file
1313
+ const content = substitute(fs.readFileSync(abs, "utf8"), VARIABLES);
1314
+ if (fs.existsSync(targetAbs)) {
1315
+ const current = fs.readFileSync(targetAbs, "utf8");
1316
+ // Compare canonically so a line-ending-only difference (a CRLF `*.ps1`
1317
+ // that git checked out per `.gitattributes`) is not mistaken for a change
1318
+ // and rewritten to LF — which would leave the working tree dirty.
1319
+ if (normalizeEol(current) !== normalizeEol(content)) {
1320
+ const deployedHash = previousFiles[key];
1321
+ const locallyModified = !!deployedHash && deployedHash !== sha256(current);
1322
+ // An untracked pre-existing harness-owned file (a first `init` into a
1323
+ // repo that already has one, or a copy without .harness.json) is backed
1324
+ // up too: an overwrite must never be the only copy of project content.
1325
+ const untrackedExisting = !deployedHash;
1326
+ const backupFirst = locallyModified || untrackedExisting;
1327
+ actions.push({ rel: key, kind: backupFirst ? "overwrite (backup)" : "overwrite" });
1328
+ if (backupFirst && !dryRun) backup(target, rel, current);
1329
+ } else {
1330
+ actions.push({ rel: key, kind: "unchanged" });
1331
+ harnessOwnedPresent.push(key);
1332
+ // Record what is actually on disk (== content), not the stale hash from a
1333
+ // prior deploy: an F-289-style local restore can have left .harness.json
1334
+ // pointing at an older template, which would falsely flag the file as
1335
+ // locally-modified on the NEXT update.
1336
+ manifest[key] = sha256(content);
1337
+ continue;
1338
+ }
1339
+ } else {
1340
+ actions.push({ rel: key, kind: "create" });
1341
+ }
1342
+ manifest[key] = sha256(content);
1343
+ if (!dryRun) {
1344
+ fs.mkdirSync(path.dirname(targetAbs), { recursive: true });
1345
+ fs.writeFileSync(targetAbs, content, "utf8");
1346
+ // POSIX helper scripts must be runnable after a fresh deploy (the
1347
+ // auto-commit records the mode); `.sh` is pinned to LF via .gitattributes.
1348
+ if (key.endsWith(".sh")) {
1349
+ try {
1350
+ fs.chmodSync(targetAbs, 0o755);
1351
+ } catch (_) {
1352
+ /* best-effort */
1353
+ }
1354
+ }
1355
+ }
1356
+ }
1357
+
1358
+ // V1 -> V2 cleanup: drop the stale `.opencode/tools/*` and legacy
1359
+ // `.opencode/command/*` files the harness used to ship (now `.opencode/plugins/`
1360
+ // and `.opencode/commands/`), so an old command cannot shadow the new one.
1361
+ for (const rel of pruneObsoleteHarnessFiles(target, dryRun)) {
1362
+ actions.push({ rel, kind: "remove-obsolete" });
1363
+ }
1364
+
1365
+ // Present-but-untracked harness files. An "unchanged" file is never in
1366
+ // `changedRels`, so a deploy that left it untracked (a skipped commit, or a
1367
+ // file restored by the freshness plugin) would NEVER bring it into git — and a
1368
+ // linked worktree is a fresh checkout, so it silently misses the file. That is
1369
+ // exactly how `scripts/qa/mobile-e2e/apk-cache.js` went missing from every
1370
+ // LibraryOS worktree and disabled the APK build cache (a 7-11 min cold Gradle
1371
+ // build instead of a ~7-30 s overlay). Sweep in any untracked, non-ignored
1372
+ // harness file so the auto-commit records it. Ignored paths are left alone here
1373
+ // (the force-add below still commits them when their content actually changes).
1374
+ if (!dryRun && harnessOwnedPresent.length > 0 && isGitRepo(target)) {
1375
+ const others = runGit(target, ["ls-files", "--others", "--exclude-standard", "--", ...harnessOwnedPresent]);
1376
+ if (others.ok) {
1377
+ for (const rel of (others.out || "").split(/\r?\n/).filter(Boolean).map(relKey)) {
1378
+ actions.push({ rel, kind: "add-untracked" });
1379
+ }
1380
+ }
1381
+ }
1382
+
1383
+ // Nothing-to-update detection: an update that made no effective change to any
1384
+ // harness-owned file and was already running this exact version is a no-op —
1385
+ // report it clearly instead of printing a zero-delta "Updated", and leave the
1386
+ // target byte-for-byte untouched (no .harness.json timestamp churn, no commit).
1387
+ const changedRelsAll = actions
1388
+ .filter((a) => ["create", "overwrite", "overwrite (backup)", "merge", "add-untracked", "remove-obsolete"].includes(a.kind))
1389
+ .map((a) => a.rel);
1390
+ const nothingToUpdate =
1391
+ !!isUpdate && changedRelsAll.length === 0 && compareVersions(existing.version || "0", PKG.version) === 0;
1392
+
1393
+ const config = {
1394
+ ...existing,
1395
+ version: PKG.version,
1396
+ projectName,
1397
+ projectDomain,
1398
+ initializedAt: existing.initializedAt || new Date().toISOString(),
1399
+ updatedAt: new Date().toISOString(),
1400
+ files: manifest,
1401
+ };
1402
+ if (!dryRun && !nothingToUpdate) {
1403
+ fs.writeFileSync(path.join(target, CONFIG_FILE), JSON.stringify(config, null, 2) + "\n", "utf8");
1404
+ }
1405
+
1406
+ // Hardening for an accepted overwrite: a clobber that breaks the target's own
1407
+ // suite must never be committed. Run the target's mechanical gate BEFORE the
1408
+ // harness auto-commit; on red, restore the clobbered bytes + .harness.json and
1409
+ // abort, leaving the working tree holding the project's own content.
1410
+ if (divergent.length && acceptHarness && !dryRun && commit && !nothingToUpdate) {
1411
+ const gate = runTargetQuickGate(target);
1412
+ if (gate.ran && !gate.ok) {
1413
+ for (const d of divergent) fs.writeFileSync(d.targetAbs, d.prev, "utf8");
1414
+ if (configPrev != null) fs.writeFileSync(configPath, configPrev, "utf8");
1415
+ else if (fs.existsSync(configPath)) fs.unlinkSync(configPath);
1416
+ const tail = gate.output.split(/\r?\n/).slice(-25).join("\n");
1417
+ throw new Error(
1418
+ `"${projectName}" failed \`npm run test:quick\` after accepting the overwrite of locally-modified ` +
1419
+ `harness file(s): ${divergent.map((d) => d.rel).join(", ")}. The clobber was rolled back and the ` +
1420
+ `harness commit aborted — upstream the local fix into templates/ instead.\n${tail}`
1421
+ );
1422
+ }
1423
+ }
1424
+
1425
+ // Auto-commit the files this run created/changed so nothing the harness
1426
+ // deploys is left untracked. Runs for both `init` and `update`. Excludes only
1427
+ // rollback artifacts; freshly-scaffolded project-data files (memory/features/
1428
+ // BACKLOG) are committed so they start tracked, while pre-existing project
1429
+ // data is never touched (a "preserve" never enters `changedRelsAll`).
1430
+ let commitResult = null;
1431
+ const shouldCommit = !dryRun && (!isUpdate || !nothingToUpdate);
1432
+ if (shouldCommit) {
1433
+ const changedRels = changedRelsAll.filter((r) => !r.startsWith(".harness-backup/"));
1434
+ changedRels.push(CONFIG_FILE); // .harness.json reflects the new deployed version
1435
+ commitResult = commitHarnessChanges(target, changedRels, {
1436
+ commit,
1437
+ push,
1438
+ priorVersion: existing.version || null,
1439
+ });
1440
+ }
1441
+
1442
+ return {
1443
+ projectName,
1444
+ projectDomain,
1445
+ actions,
1446
+ dryRun: !!dryRun,
1447
+ commitResult,
1448
+ syncResult,
1449
+ branchGuard,
1450
+ isUpdate: !!isUpdate,
1451
+ nothingToUpdate,
1452
+ priorVersion: existing.version || null,
1453
+ };
1454
+ };
1455
+
1456
+ // A dry-run must write nothing — not even the lock dir.
1457
+ return dryRun ? runDeploy() : withDeployLock(target, runDeploy);
1458
+ }
1459
+
1460
+ function summarize(actions) {
1461
+ const counts = {};
1462
+ for (const a of actions) counts[a.kind] = (counts[a.kind] || 0) + 1;
1463
+ return counts;
1464
+ }
1465
+
1466
+ function printSummary(result, isUpdate) {
1467
+ const { projectName, actions, dryRun } = result;
1468
+
1469
+ if (isUpdate && result.nothingToUpdate) {
1470
+ console.log(
1471
+ `\n[Nothing-to-Update] agent-harness v${PKG.version}: "${projectName}" is already at ` +
1472
+ `v${result.priorVersion || PKG.version} and no harness-owned file changed.`
1473
+ );
1474
+ return;
1475
+ }
1476
+
1477
+ const verb = isUpdate
1478
+ ? (dryRun ? "Would update" : "Updated")
1479
+ : (dryRun ? "Would initialize" : "Initialized");
1480
+ console.log(`\nagent-harness v${PKG.version} ${verb.toLowerCase()} "${projectName}"` + (dryRun ? " (dry run)" : ""));
1481
+ if (isUpdate && result.priorVersion && result.priorVersion !== PKG.version) {
1482
+ console.log(` harness: v${result.priorVersion} -> v${PKG.version}`);
1483
+ }
1484
+ for (const a of actions) console.log(` [${a.kind}] ${a.rel}`);
1485
+ const counts = summarize(actions);
1486
+ console.log(
1487
+ `\n ${counts.create || 0} created, ${counts.overwrite || 0} overwritten, ` +
1488
+ `${counts["overwrite (backup)"] || 0} backed up (locally modified), ` +
1489
+ `${counts.merge || 0} merged, ${counts["remove-obsolete"] || 0} removed (obsolete), ` +
1490
+ `${counts.preserve || 0} preserved, ${counts.unchanged || 0} unchanged.`
1491
+ );
1492
+ }
1493
+
1494
+ /* Best-effort warning: when this CLI's version is not the latest published on
1495
+ * the registry, flag it. This catches the "bumped + ran update from a local
1496
+ * checkout, but never published" silent gap. Publish guidance stays inline so a
1497
+ * failed `npm publish` (401/404 auth/permission) never leaves the developer
1498
+ * staring at a raw npm error — it points them at `npm login`. */
1499
+ function printUnpublishedWarning() {
1500
+ // The authoritative workflow (AGENTS.md) deploys from a local git checkout of
1501
+ // this repo, where being ahead of the registry is expected and publishing is
1502
+ // optional — warning there is noise (and costs a blocking `npm view`). Only an
1503
+ // installed (npm/npx) copy is expected to match the latest published version.
1504
+ try {
1505
+ if (fs.existsSync(path.join(__dirname, "..", ".git"))) return;
1506
+ } catch (_) {
1507
+ /* treat as installed */
1508
+ }
1509
+ const published = publishedLatestVersion();
1510
+ if (published == null || published === "" || published === PKG.version) return;
1511
+ const cmp = compareVersions(PKG.version, published);
1512
+ if (cmp <= 0) return;
1513
+ console.log(
1514
+ `\n WARNING: this CLI is v${PKG.version}, but the latest version published on ` +
1515
+ `npm is v${published}. If you ran this from a local checkout, the changes were ` +
1516
+ `NOT published — Publish first, then \`update\` other projects, or they will ` +
1517
+ `branch off an older harness.`
1518
+ );
1519
+ console.log(
1520
+ ` To publish: run \`npm publish\` from the harness repo. If it fails with ` +
1521
+ `E401/E404 (auth or permission), you are not logged in as the package owner ` +
1522
+ `(\`npm owner ls ${PKG.name}\` shows who owns it) — run \`npm login\` first, ` +
1523
+ `then publish again. Login: https://www.npmjs.com/login`
1524
+ );
1525
+ }
1526
+
1527
+ function printNextSteps() {
1528
+ console.log(" Next steps:");
1529
+ console.log(" 1. Fill in `.agents/memory/domain-map.md`, `.agents/memory/stack-versions.md`,");
1530
+ console.log(" `.agents/memory/product-principles.md` (actors, product concepts, UX");
1531
+ console.log(" heuristics — the planner reads this to lead planning product-first),");
1532
+ console.log(" `.agents/memory/flow-map.md` (register cross-surface flows so");
1533
+ console.log(" test:qa-plan enforces their sibling-surface/variant closure), and");
1534
+ console.log(" `.agents/memory/environments.md` (the dev/uat/prod registry — URLs, DB");
1535
+ console.log(" env vars, deploy + seed commands; the DoD deploy-to-UAT step reads it).");
1536
+ console.log(" 2. Harness gate scripts (`test:dispatch`, `test:governance`, `test:qa-plan`,");
1537
+ console.log(" `test:backlog`, `test:product`, `test:docs`, `test:quality`, `test:wiring`,");
1538
+ console.log(" `test:linger`, `test:capacity`, `test:prefix`) were auto-wired into package.json \"scripts\".");
1539
+ console.log(" 3. Capture found items as one light row in the canonical `BACKLOG.md` (repo root);");
1540
+ console.log(" dispatch the `features` persona to author the per-feature doc chain when one is picked up.");
1541
+ console.log(" 4. The CI/CD release scaffold was seeded create-if-missing:");
1542
+ console.log(" `.github/workflows/{ci,deploy-uat,uat-health}.yml`,");
1543
+ console.log(" `.husky/pre-push`, `.vercelignore`, `docs/ci-cd-pipeline.md`. A feature");
1544
+ console.log(" lands by a direct fast-forward push to main; CI gates the landed SHA and");
1545
+ console.log(" the deploy runs after CI. Fill the repository secrets/variables it names");
1546
+ console.log(" and run `agent-harness doctor` to confirm the ship -> land -> CI cycle is ready.");
1547
+ console.log(" 5. Restart your agent CLI (config is read once at startup).\n");
1548
+ }
1549
+
1550
+ function printUsage() {
1551
+ console.log(
1552
+ `agent-harness v${PKG.version}\n\n` +
1553
+ `Usage:\n` +
1554
+ ` agent-harness init [--target <dir>] [--name <project>] [--domain <desc>] [--yes] [--dry-run] [--commit] [--push]\n` +
1555
+ ` agent-harness update [--target <dir>] [--dry-run] [--no-commit] [--no-push] [--accept-harness]\n` +
1556
+ ` agent-harness migrate-backlog [--target <dir>]\n` +
1557
+ `\n` +
1558
+ ` init writes files but does NOT commit or push by default: pass --commit to\n` +
1559
+ ` commit the harness files it creates/changes, and --push to also push. update\n` +
1560
+ ` auto-commits (chore(harness): ...) and pushes by default; use --no-commit or\n` +
1561
+ ` --no-push to opt out. Your unrelated uncommitted work is never staged. The\n` +
1562
+ ` target must be on its canonical\n` +
1563
+ ` branch (origin/HEAD, else main/master) or the commit is refused, so a\n` +
1564
+ ` harness update can never be stranded off main — pass --allow-branch to\n` +
1565
+ ` override deliberately. A locally-modified harness-owned file makes\n` +
1566
+ ` update FAIL CLOSED (port the fix into templates/ instead); pass\n` +
1567
+ ` --accept-harness to overwrite it deliberately (a backup is kept, and the\n` +
1568
+ ` target's test:quick must stay green or the clobber is rolled back).\n` +
1569
+ `\n` +
1570
+ ` migrate-backlog consolidates any live \`.agents/features/INDEX.md\` F-rows and\n` +
1571
+ ` \`.agents/memory/todo.md\` into the canonical BACKLOG.md, then rewrites those\n` +
1572
+ ` files as pointers. Idempotent: re-running never duplicates rows or deletes a\n` +
1573
+ ` source before BACKLOG.md is written and verified.\n` +
1574
+ `\n` +
1575
+ ` run chains bounded orchestration contexts for end-to-end delivery: it runs\n` +
1576
+ ` the next-item workflow, then relaunches a fresh opencode session that resumes\n` +
1577
+ ` from the checkpoint whenever a phase ends before the feature is landed. A\n` +
1578
+ ` resumed phase whose checkpoint shows implementation complete goes straight to\n` +
1579
+ ` \`npm run finalize -- --feature <id>\` (one call: archive + commit + ship, and\n` +
1580
+ ` ship lands the branch on main and confirms green CI). It stops on landed\n` +
1581
+ ` (archived / shipped outcome), the phase cap, an empty queue, or a failed phase\n` +
1582
+ ` that did not land. --dry-run prints the phase plan.\n` +
1583
+ `\n` +
1584
+ ` agent-harness list\n` +
1585
+ ` agent-harness doctor [--target <dir>] # readiness of the ship/deploy cycle\n` +
1586
+ ` agent-harness install-global [--dry-run] [--force] [--dir <dir>]\n` +
1587
+ ` # link contrib/global-plugins/* into ~/.config/opencode/plugins/\n` +
1588
+ ` # (machine-level, version-independent harness checks; restart opencode)\n` +
1589
+ ` agent-harness install-nightly [--target <dir>] [--time HH:MM] [--force] [--dry-run]\n` +
1590
+ ` # install the off-hours E2E cycle as a systemd --user timer\n` +
1591
+ ` # (scripts/setup-nightly.sh; Persistent=true, linger enabled)\n` +
1592
+ ` agent-harness dogfood [--target <dir>] [--remove] [--dry-run]\n` +
1593
+ ` # let the harness SOURCE checkout run its own guard/tools:\n` +
1594
+ ` # symlinks templates/ into the repo root; restart opencode\n` +
1595
+ ` agent-harness explain <gate> # what a gate enforces + how to satisfy/waive it\n` +
1596
+ ` agent-harness run [--target <dir>] [--feature <id>] [--prompt <text>]\n` +
1597
+ ` [--max-phases <n>] [--opencode <path>] [--dry-run]\n` +
1598
+ ` agent-harness --version | -v\n` +
1599
+ ` agent-harness --help | -h\n`
1600
+ );
1601
+ }
1602
+
1603
+ function printPersonas(templatesDir) {
1604
+ const agents = path.join(templatesDir, ".opencode", "agents");
1605
+ console.log("Personas (model routing):\n");
1606
+ for (const f of fs.readdirSync(agents).sort()) {
1607
+ const src = fs.readFileSync(path.join(agents, f), "utf8");
1608
+ const model = (src.match(/^model:\s*(.+)$/m) || [])[1] || "?";
1609
+ console.log(` ${f.replace(/\.md$/, "").padEnd(22)} -> ${model}`);
1610
+ }
1611
+ }
1612
+
1613
+ // ---------------------------------------------------------------- explain
1614
+
1615
+ /* `explain <gate>` — print the matching section of `templates/docs/gates.md`.
1616
+ * Deterministic (no LLM): agents read the contract instead of reverse-
1617
+ * engineering the check script (the 2026-09 recon: backlog.js read 45x,
1618
+ * check-qa-plan.js 16x). Returns the section body, or null when not found. */
1619
+ function explainSection(name) {
1620
+ const key = String(name || "").replace(/^npm\s+run\s+/, "").trim();
1621
+ const doc = path.join(TEMPLATES_DIR, "docs", "gates.md");
1622
+ if (!fs.existsSync(doc)) return null;
1623
+ const lines = fs.readFileSync(doc, "utf8").split(/\r?\n/);
1624
+ let start = -1;
1625
+ for (let i = 0; i < lines.length; i++) {
1626
+ const m = lines[i].match(/^##\s+`([^`]+)`/);
1627
+ if (m && m[1] === key) {
1628
+ start = i;
1629
+ break;
1630
+ }
1631
+ }
1632
+ if (start === -1) return null;
1633
+ let end = lines.length;
1634
+ for (let i = start + 1; i < lines.length; i++) {
1635
+ if (/^##\s/.test(lines[i])) {
1636
+ end = i;
1637
+ break;
1638
+ }
1639
+ }
1640
+ return lines.slice(start, end).join("\n").trim();
1641
+ }
1642
+
1643
+ function explain(name) {
1644
+ const section = explainSection(name);
1645
+ if (!section) {
1646
+ console.error(`No gate named "${name}". Run \`agent-harness explain --list\` to see the gates.`);
1647
+ process.exitCode = 1;
1648
+ return;
1649
+ }
1650
+ console.log(section);
1651
+ }
1652
+
1653
+ function explainList() {
1654
+ const doc = path.join(TEMPLATES_DIR, "docs", "gates.md");
1655
+ if (!fs.existsSync(doc)) return;
1656
+ for (const line of fs.readFileSync(doc, "utf8").split(/\r?\n/)) {
1657
+ const m = line.match(/^##\s+`([^`]+)`/);
1658
+ if (m) console.log(` ${m[1]}`);
1659
+ }
1660
+ }
1661
+
1662
+ // ---------------------------------------------------------------- doctor
1663
+
1664
+ /* Read the `name:` of each workflow file under `.github/workflows` (best-effort). */
1665
+ function workflowNamesIn(target) {
1666
+ const dir = path.join(target, ".github", "workflows");
1667
+ const names = [];
1668
+ if (!fs.existsSync(dir)) return names;
1669
+ for (const file of fs.readdirSync(dir)) {
1670
+ if (!/\.ya?ml$/i.test(file)) continue;
1671
+ try {
1672
+ const src = fs.readFileSync(path.join(dir, file), "utf8");
1673
+ const m = src.match(/^name:\s*(.+)$/m);
1674
+ names.push({ file, name: m ? m[1].trim().replace(/^["']|["']$/g, "") : file });
1675
+ } catch (_) {
1676
+ names.push({ file, name: file });
1677
+ }
1678
+ }
1679
+ return names;
1680
+ }
1681
+
1682
+ /* CI budget (advisory): estimate this repo's GitHub Actions burn from `gh` and
1683
+ * compare it to the plan's included minutes (or `.harness.json` `ciBudget`). The
1684
+ * estimate is a FLOOR (one Linux minute per completed run) so it never
1685
+ * under-reports; when usage cannot be read the honest state is `unknown`, never
1686
+ * `ok`. Never fails the doctor — the operator acts on it. See ci-usage-lib.js. */
1687
+ function ciBudgetLines(target) {
1688
+ const dir = path.join(target, ".github", "workflows");
1689
+ if (!fs.existsSync(dir)) return [];
1690
+ const cfg = safeJson(fs.readFileSync(path.join(target, ".harness.json"), "utf8"), null);
1691
+ const budgetCfg = (cfg && cfg.ciBudget) || {};
1692
+ if (budgetCfg.enabled === false) return [{ level: "ok", label: "ci budget", detail: "disabled in .harness.json" }];
1693
+ const { ghJson, has } = require(path.join(TEMPLATES_DIR, "scripts", "qa", "ci-wait-lib.js"));
1694
+ if (!has("gh")) {
1695
+ return [
1696
+ {
1697
+ level: "ok",
1698
+ label: "ci budget",
1699
+ detail: "unknown — `gh` unavailable, so Actions usage cannot be read (never assumed healthy)",
1700
+ },
1701
+ ];
1702
+ }
1703
+ const res = ghJson(target, ["run", "list", "--limit", "100", "--json", "databaseId,conclusion,createdAt,name"]);
1704
+ if (!res.ok) return [{ level: "ok", label: "ci budget", detail: `unknown — ${res.error}` }];
1705
+ const usage = require(path.join(TEMPLATES_DIR, "scripts", "qa", "ci-usage-lib.js"));
1706
+ const since = Date.now() - 30 * 24 * 60 * 60 * 1000;
1707
+ const runs = (res.data || []).filter((r) => Date.parse(r.createdAt || "") >= since);
1708
+ const est = usage.estimateUsage(runs);
1709
+ const state = usage.budgetState(est, {
1710
+ allowanceMinutes: Number(budgetCfg.includedMinutes) || undefined,
1711
+ warnAtPct: Number(budgetCfg.warnAtPct) || undefined,
1712
+ });
1713
+ const level = state.status === "fail" ? "fail" : state.status === "warn" ? "warn" : "ok";
1714
+ const limit = Number(budgetCfg.spendingLimitUsd);
1715
+ const spendNote = Number.isFinite(limit) && limit > 0 ? ` · spending limit $${limit}` : "";
1716
+ const spentNote = state.status !== "unknown" && state.remainingMinutes === 0 ? " — quota spent: workflows will bill or block" : "";
1717
+ const out = [
1718
+ {
1719
+ level,
1720
+ label: "ci budget",
1721
+ detail:
1722
+ `${state.status} — ~${state.minutes} of ${state.allowanceMinutes} included min (${state.pct}%), ` +
1723
+ `~$${Number(est.usd).toFixed(2)} floor over ${runs.length} run(s)/30d${spendNote}${spentNote}`,
1724
+ },
1725
+ ];
1726
+ if (state.status === "fail") {
1727
+ out.push({
1728
+ level: "warn",
1729
+ label: "ci budget",
1730
+ detail: "over the included allowance — trim scheduled jobs / expensive runners (`npm run test:ci-policy`) and set a spending limit",
1731
+ });
1732
+ }
1733
+ return out;
1734
+ }
1735
+
1736
+ /* Run a binary and capture its version banner (or other probe output). */
1737
+ function whichBin(cmd, args) {
1738
+ const r = spawnSync(cmd, args || ["--version"], { encoding: "utf8" });
1739
+ return { ok: r.status === 0, out: (r.stdout || "").trim(), err: (r.stderr || "").trim() };
1740
+ }
1741
+
1742
+ /* Parse the `opencode --version` banner ("opencode v2.0.29" / "2.0.29"). */
1743
+ function parseOpencodeVersion(out) {
1744
+ const m = String(out || "").match(/(\d+)\.(\d+)\.(\d+)/);
1745
+ return m ? { major: Number(m[1]), minor: Number(m[2]), patch: Number(m[3]) } : null;
1746
+ }
1747
+
1748
+ /* Judge a version banner against the harness's V2 floor. The harness is
1749
+ * OpenCode V2-only (V1 plugin implementations do not run), so a machine still on
1750
+ * V1 silently loads no plugins while everything else reports "ok". Pure so both
1751
+ * `doctor` and the unit tests can call it without a real binary. */
1752
+ function checkOpencodeVersion(out) {
1753
+ const v = parseOpencodeVersion(out);
1754
+ if (!v) {
1755
+ return {
1756
+ level: "warn",
1757
+ label: "opencode",
1758
+ detail: `unrecognized version "${String(out || "").trim() || "(empty)"}" — cannot verify the runtime`,
1759
+ };
1760
+ }
1761
+ const shown = `v${v.major}.${v.minor}.${v.patch}`;
1762
+ if (v.major < 2) {
1763
+ return {
1764
+ level: "fail",
1765
+ label: "opencode",
1766
+ detail: `${shown} — the harness requires OpenCode V2 (>= 2.0.0); V1 does not load V2 plugins`,
1767
+ };
1768
+ }
1769
+ return { level: "ok", label: "opencode", detail: shown };
1770
+ }
1771
+
1772
+ /* Warn (never fail) at deploy time when the local `opencode` is V1 — a deploy
1773
+ * target on V1 would get the V2-native harness and silently load no plugins.
1774
+ * Cached: one probe per process, since `deploy` runs many times in the suite. */
1775
+ let opencodeVersionCache = null;
1776
+ function warnOpencodeVersion() {
1777
+ if (opencodeVersionCache === null) {
1778
+ const oc = whichBin("opencode", ["--version"]);
1779
+ opencodeVersionCache = oc.ok ? checkOpencodeVersion(oc.out) : { level: "ok" };
1780
+ }
1781
+ if (opencodeVersionCache.level === "fail") {
1782
+ console.warn(
1783
+ ` WARNING: ${opencodeVersionCache.detail}. Install OpenCode V2 before starting a ` +
1784
+ "session in this target (`opencode upgrade`)."
1785
+ );
1786
+ }
1787
+ }
1788
+
1789
+ /* ------------------------------------------------------- runtime activation
1790
+ * `update` writes files, but a running opencode keeps the OLD plugins/config
1791
+ * until it restarts — so a "successful" deploy can be completely inert
1792
+ * (F-19/H-44). These helpers compare the live opencode processes for a target
1793
+ * against the last harness write (`.harness.json` mtime) and name the exact pid
1794
+ * + version to restart into. Never auto-restarts while a session is live. */
1795
+
1796
+ /* Pure: which of `procs` ({pid, startedAt}) started before the last harness
1797
+ * write. Exported for a fixture unit test. */
1798
+ function staleProcs(procs, wroteAtMs) {
1799
+ if (!wroteAtMs) return [];
1800
+ return (procs || []).filter((p) => Number(p.startedAt) < Number(wroteAtMs));
1801
+ }
1802
+
1803
+ /* Pure: the fail-loud warning naming the stale pids + the version to load. */
1804
+ function formatStaleRuntime(stale, wroteAtMs, version) {
1805
+ if (!stale || !stale.length) return null;
1806
+ const v = version ? `v${version}` : "the deployed harness";
1807
+ return (
1808
+ `opencode (pid ${stale.map((p) => p.pid).join(", ")}) started before the last harness write ` +
1809
+ `${new Date(Number(wroteAtMs)).toISOString()} — restart opencode to load ${v} ` +
1810
+ `(a deploy is inert until then).`
1811
+ );
1812
+ }
1813
+
1814
+ /* The last time this target's harness was written (the deploy's `.harness.json`). */
1815
+ function harnessWriteTime(target) {
1816
+ try {
1817
+ return fs.statSync(path.join(target, CONFIG_FILE)).mtimeMs;
1818
+ } catch {
1819
+ return null;
1820
+ }
1821
+ }
1822
+
1823
+ /* Live opencode processes whose working tree is `target`. Best-effort via Linux
1824
+ * `/proc`; [] when ps/proc is unavailable (macOS/CI). */
1825
+ function opencodeProcsFor(target) {
1826
+ const want = path.resolve(target);
1827
+ let out = "";
1828
+ try {
1829
+ const r = spawnSync("ps", ["-eo", "pid=,etimes=,args="], { encoding: "utf8" });
1830
+ if (r.status !== 0) return [];
1831
+ out = String(r.stdout || "");
1832
+ } catch (_) {
1833
+ return [];
1834
+ }
1835
+ const now = Date.now();
1836
+ const procs = [];
1837
+ for (const line of out.split(/\r?\n/)) {
1838
+ const m = line.trim().match(/^(\d+)\s+(\d+)\s+(\S.*)$/);
1839
+ if (!m) continue;
1840
+ const pid = Number(m[1]);
1841
+ const etimes = Number(m[2]);
1842
+ const args = m[3];
1843
+ if (!/(^|[\/\s])opencode(\s|$)/.test(args)) continue;
1844
+ if (/--version|--help/.test(args)) continue;
1845
+ let cwd = null;
1846
+ try {
1847
+ cwd = fs.readlinkSync("/proc/" + pid + "/cwd");
1848
+ } catch (_) {
1849
+ cwd = null;
1850
+ }
1851
+ if (cwd) {
1852
+ if (path.resolve(cwd) !== want) continue;
1853
+ } else if (!args.includes(want)) {
1854
+ continue;
1855
+ }
1856
+ procs.push({ pid, startedAt: now - etimes * 1000, args });
1857
+ }
1858
+ return procs;
1859
+ }
1860
+
1861
+ /* A warning string when a live opencode for `target` predates the last harness
1862
+ * write, else null. */
1863
+ function staleRuntimeWarning(target) {
1864
+ const wrote = harnessWriteTime(target);
1865
+ if (!wrote) return null;
1866
+ const cfg = readConfig(target);
1867
+ return formatStaleRuntime(staleProcs(opencodeProcsFor(target), wrote), wrote, cfg && cfg.version);
1868
+ }
1869
+
1870
+ /* `doctor` — a deterministic (no-LLM) readiness report for the self-contained
1871
+ * agent release cycle. It answers, before a session starts, whether the pieces
1872
+ * `ship` depends on actually exist: gh + auth, the CI/deploy workflows, the
1873
+ * pre-push gate, the Vercel link, and the local-only ignores. Missing
1874
+ * infrastructure is a `warn` (a project may not use that tier yet); missing
1875
+ * prerequisites for the cycle the harness promises are `fail`. */
1876
+
1877
+ function doctor(target) {
1878
+ const results = [];
1879
+ const add = (level, label, detail) => results.push({ level, label, detail });
1880
+
1881
+ if (!isGitRepo(target)) {
1882
+ add("fail", "git repository", "not a git repo — run this in a project checkout");
1883
+ return reportDoctor(results);
1884
+ }
1885
+ const git = whichBin("git");
1886
+ add(git.ok ? "ok" : "fail", "git", git.ok ? git.out : "git not on PATH");
1887
+
1888
+ const config = readConfig(target);
1889
+ add(
1890
+ config.version ? "ok" : "warn",
1891
+ "harness deployed",
1892
+ config.version ? `v${config.version} (${config.projectName || "?"})` : "no .harness.json — run `agent-harness init`"
1893
+ );
1894
+
1895
+ // The harness is OpenCode V2-only: on a V1 runtime every plugin/tool this
1896
+ // deploy writes is silently inert. Assert the floor rather than assume it.
1897
+ const opencode = whichBin("opencode", ["--version"]);
1898
+ if (!opencode.ok) {
1899
+ add("ok", "opencode", "not on PATH — runtime version unverified (fine in CI)");
1900
+ } else {
1901
+ const v = checkOpencodeVersion(opencode.out);
1902
+ add(v.level, v.label, v.detail);
1903
+ }
1904
+
1905
+ // deploy != activate: a live opencode started before the last harness write
1906
+ // keeps the old plugins/config (F-19/H-44). Name the pid + version to restart.
1907
+ const staleRuntime = staleRuntimeWarning(target);
1908
+ add(
1909
+ staleRuntime ? "warn" : "ok",
1910
+ "runtime activation",
1911
+ staleRuntime || "no live opencode predates the last harness write"
1912
+ );
1913
+
1914
+ const remote = runGit(target, ["remote", "get-url", "origin"]);
1915
+ add(remote.ok ? "ok" : "warn", "git remote", remote.ok ? remote.out : "no origin remote");
1916
+
1917
+ const branch = currentBranch(target);
1918
+ const def = defaultBranch(target);
1919
+ add(
1920
+ branch && (!def || branch === def) ? "ok" : "warn",
1921
+ "canonical branch",
1922
+ branch ? `${branch}${def && branch !== def ? ` (canonical is ${def})` : ""}` : "detached HEAD"
1923
+ );
1924
+
1925
+ // A checkout behind its upstream holds a stale BACKLOG.md (a row archived on
1926
+ // origin still shows Open locally) — the shape that let a mutation resurrect a
1927
+ // shipped row. Surface it so it is fixed before a session trusts the board.
1928
+ const ust = upstreamState(target);
1929
+ if (ust.known && ust.behind > 0) {
1930
+ add(
1931
+ "warn",
1932
+ "board sync",
1933
+ `checkout is ${ust.behind} behind ${ust.upstream} — the board may be stale; run: node scripts/backlog.js sync`
1934
+ );
1935
+ } else if (ust.known) {
1936
+ add("ok", "board sync", `level with ${ust.upstream}`);
1937
+ } else {
1938
+ add("ok", "board sync", "no upstream tracking branch (offline / no remote)");
1939
+ }
1940
+
1941
+ const workflows = workflowNamesIn(target);
1942
+ const ci = workflows.find((w) => /^ci$/i.test(w.name));
1943
+ const deploy = workflows.find((w) => /deploy/i.test(w.name));
1944
+ add(ci ? "ok" : "warn", "CI workflow", ci ? ci.file : "none — a landing's green CI is never confirmed");
1945
+ add(deploy ? "ok" : "warn", "deploy workflow", deploy ? deploy.file : "none — landed changes will not deploy");
1946
+
1947
+ const gh = whichBin("gh", ["--version"]);
1948
+ if (!gh.ok) {
1949
+ add("fail", "gh CLI", "not on PATH — `ship` cannot confirm CI after landing");
1950
+ } else {
1951
+ const auth = whichBin("gh", ["auth", "status"]);
1952
+ add(auth.ok ? "ok" : "warn", "gh auth", auth.ok ? "authenticated" : "not authenticated (`gh auth login`)");
1953
+ }
1954
+
1955
+ const hooksPath = runGit(target, ["config", "core.hooksPath"]);
1956
+ const hookFile = runGit(target, ["rev-parse", "--git-path", "hooks/pre-push"]);
1957
+ const hookAbs = hookFile.ok ? path.resolve(target, hookFile.out) : "";
1958
+ const hasPrePush =
1959
+ fs.existsSync(path.join(target, ".husky", "_", "pre-push")) ||
1960
+ fs.existsSync(path.join(target, ".husky", "pre-push")) ||
1961
+ (hookAbs && fs.existsSync(hookAbs));
1962
+ add(
1963
+ hasPrePush ? "ok" : "warn",
1964
+ "pre-push gate",
1965
+ hasPrePush ? (hooksPath.out || hookAbs) : "not installed — project test gates run only in CI"
1966
+ );
1967
+
1968
+ add(fs.existsSync(path.join(target, ".vercelignore")) ? "ok" : "warn", ".vercelignore", fs.existsSync(path.join(target, ".vercelignore")) ? "present" : "missing — worktree deploys can fail (ENOTDIR pruned/generated)");
1969
+ add(
1970
+ fs.existsSync(path.join(target, ".vercel", "project.json")) ? "ok" : "warn",
1971
+ "Vercel link",
1972
+ fs.existsSync(path.join(target, ".vercel", "project.json")) ? ".vercel/project.json present" : "not linked in this checkout (CI links from secrets)"
1973
+ );
1974
+
1975
+ if (config.shipCiWorkflow) add("ok", "CI workflow (ship)", String(config.shipCiWorkflow));
1976
+ add(
1977
+ fs.existsSync(path.join(target, "scripts", "finalize.js")) ? "ok" : "warn",
1978
+ "finalize command",
1979
+ fs.existsSync(path.join(target, "scripts", "finalize.js"))
1980
+ ? "`npm run finalize` available (archive + commit + land + confirm CI)"
1981
+ : "missing — re-run `agent-harness update` to deploy scripts/finalize.js"
1982
+ );
1983
+
1984
+ // Session-orientation + bounded-wait tooling (harness-shipped): `orient` collapses
1985
+ // the resume/claim prologue (measured avg 24 calls before real work), `wait-for`
1986
+ // replaces hand-rolled polling, and `docs/gates.md` documents each gate.
1987
+ add(
1988
+ fs.existsSync(path.join(target, "scripts", "orient.js")) ? "ok" : "warn",
1989
+ "orient",
1990
+ fs.existsSync(path.join(target, "scripts", "orient.js"))
1991
+ ? "one-call orientation available (`node scripts/orient.js`)"
1992
+ : "missing — re-run `agent-harness update`"
1993
+ );
1994
+ add(
1995
+ fs.existsSync(path.join(target, "scripts", "wait-for.js")) ? "ok" : "warn",
1996
+ "wait",
1997
+ fs.existsSync(path.join(target, "scripts", "wait-for.js"))
1998
+ ? "bounded waiter available (`npm run wait -- --health <url>`)"
1999
+ : "missing — re-run `agent-harness update`"
2000
+ );
2001
+ add(
2002
+ fs.existsSync(path.join(target, ".opencode", "plugins", "job-notify.ts")) ? "ok" : "warn",
2003
+ "job-notify plugin",
2004
+ fs.existsSync(path.join(target, ".opencode", "plugins", "job-notify.ts"))
2005
+ ? "detached device runs push progress/completion"
2006
+ : "missing — mobile E2E progress will not be pushed"
2007
+ );
2008
+ add(
2009
+ fs.existsSync(path.join(target, "docs", "gates.md")) ? "ok" : "warn",
2010
+ "gate reference",
2011
+ fs.existsSync(path.join(target, "docs", "gates.md"))
2012
+ ? "docs/gates.md present (`agent-harness explain <gate>`)"
2013
+ : "missing — re-run `agent-harness update`"
2014
+ );
2015
+
2016
+ // MCP per-agent gating (G1): V2 has no `tools` field, so a project still
2017
+ // declaring the V1 `tools` map (a top-level disable and/or `agents.<name>.tools`
2018
+ // enable) has that gating silently ignored — the server connects but no agent
2019
+ // can call its tools. `update` migrates both maps into ordered `permissions`.
2020
+ {
2021
+ const ocPath = path.join(target, "opencode.json");
2022
+ const doc = fs.existsSync(ocPath) ? safeJson(fs.readFileSync(ocPath, "utf8"), null) : null;
2023
+ if (doc && typeof doc === "object") {
2024
+ const top = doc.tools && typeof doc.tools === "object" ? Object.keys(doc.tools) : [];
2025
+ const perAgent = Object.entries(doc.agents && typeof doc.agents === "object" ? doc.agents : {})
2026
+ .filter(([, a]) => a && typeof a === "object" && a.tools && typeof a.tools === "object")
2027
+ .map(([n]) => n);
2028
+ if (top.length || perAgent.length) {
2029
+ const parts = [];
2030
+ if (top.length) parts.push(`top-level ${top.join(", ")}`);
2031
+ if (perAgent.length) parts.push(`per-agent ${perAgent.join(", ")}`);
2032
+ add(
2033
+ "warn",
2034
+ "MCP gating",
2035
+ `V1 \`tools\` map is ignored by V2 (${parts.join("; ")}) — run \`agent-harness update\` to migrate to \`permissions\``
2036
+ );
2037
+ }
2038
+ }
2039
+ }
2040
+
2041
+ // Session store (W1): the telemetry tooling (`report:cost`, `report:recon`,
2042
+ // `session_info`) reads the local opencode store. V2 moved the tables
2043
+ // (`session_v2`/`session_message`) and removed the `opencode db` subcommand, so
2044
+ // a stale reader silently returned empty aggregates. Assert the store resolves
2045
+ // and its table generation is readable, so the failure is visible here instead
2046
+ // of in a wrong report.
2047
+ try {
2048
+ const storeLib = require(path.join(TEMPLATES_DIR, "scripts", "qa", "store-lib.js"));
2049
+ const dbPath = storeLib.resolveDbPath();
2050
+ if (!fs.existsSync(dbPath)) {
2051
+ add("ok", "session store", "no local store yet (nothing to read)");
2052
+ } else {
2053
+ const store = storeLib.openStore();
2054
+ add("ok", "session store", `${store.flavour} tables readable (${store.dbPath})`);
2055
+ }
2056
+ } catch (err) {
2057
+ add(
2058
+ "warn",
2059
+ "session store",
2060
+ `unreadable — \`report:cost\`/\`report:recon\` would be empty (${err && err.message ? err.message : "unavailable"}); check \`opencode debug paths\``
2061
+ );
2062
+ }
2063
+
2064
+ // Nightly E2E cycle: the orchestrator + config, whether a systemd --user
2065
+ // timer is installed, and the last verdict (advisory — the day loop still
2066
+ // ships on cheap gates; nightly is the full-E2E authority).
2067
+ {
2068
+ const hasScript = fs.existsSync(path.join(target, "scripts", "nightly.js"));
2069
+ add(
2070
+ hasScript ? "ok" : "warn",
2071
+ "nightly runner",
2072
+ hasScript ? "scripts/nightly.js present (`npm run nightly`)" : "missing — re-run `agent-harness update`"
2073
+ );
2074
+ const cfg = fs.existsSync(path.join(target, ".agents", "nightly.json"));
2075
+ add(cfg ? "ok" : "warn", "nightly config", cfg ? ".agents/nightly.json present" : "missing — run `agent-harness update`");
2076
+ const unitDir = path.join(process.env.XDG_CONFIG_HOME || path.join(os.homedir(), ".config"), "systemd", "user");
2077
+ let timer = null;
2078
+ try {
2079
+ timer = fs.readdirSync(unitDir).find((f) => /^agent-nightly-.*\.timer$/.test(f)) || null;
2080
+ } catch (_) {
2081
+ timer = null;
2082
+ }
2083
+ add(
2084
+ timer ? "ok" : "warn",
2085
+ "nightly timer",
2086
+ timer ? `${timer} installed` : "not installed — run `agent-harness install-nightly --target .`"
2087
+ );
2088
+ const latestPath = path.join(target, ".agents", "qa-runs", "nightly", "latest.json");
2089
+ if (fs.existsSync(latestPath)) {
2090
+ try {
2091
+ const doc = JSON.parse(fs.readFileSync(latestPath, "utf8"));
2092
+ const failed = Array.isArray(doc.failures) ? doc.failures.length : 0;
2093
+ const reopened = Array.isArray(doc.reconcile) ? doc.reconcile.filter((a) => a.kind === "reopen").length : 0;
2094
+ add(
2095
+ doc.verdict === "pass" ? "ok" : "warn",
2096
+ "last nightly",
2097
+ `${doc.verdict || "?"} @ ${doc.stamp || "?"} — ${failed} failing, ${reopened} reopened`
2098
+ );
2099
+ } catch (_) {
2100
+ add("warn", "last nightly", "report unreadable");
2101
+ }
2102
+ } else {
2103
+ add("warn", "last nightly", "no run recorded — `npm run nightly -- run`");
2104
+ }
2105
+ }
2106
+
2107
+ // Machine capacity (advisory only): free RAM/swap/load, live `.serve/`
2108
+ // processes, the RAM-backed tmpfs, and Windows-side `.wslconfig` advice. This
2109
+ // is the preflight for the WSL2 freeze class (2026-09-29) — it never fails the
2110
+ // cycle, it tells the operator what to change before a heavy tier tips the box.
2111
+ try {
2112
+ const capacity = require(path.join(TEMPLATES_DIR, "scripts", "qa", "capacity-lib.js"));
2113
+ const s = capacity.sample(target);
2114
+ if (s.mem) {
2115
+ const ev = capacity.evaluate(s);
2116
+ add(ev.ok ? "ok" : "warn", "capacity", capacity.formatSummary(s));
2117
+ for (const r of ev.reasons) add("warn", "capacity", r);
2118
+ for (const w of ev.warnings) add("warn", "capacity", w);
2119
+ } else {
2120
+ add("ok", "capacity", "host memory not readable (non-Linux)");
2121
+ }
2122
+ if (s.psi && s.psi.mem && s.psi.mem.some10 != null) {
2123
+ add("ok", "pressure (PSI)", `memory some avg10=${s.psi.mem.some10.toFixed(2)} full avg10=${(s.psi.mem.full10 || 0).toFixed(2)}`);
2124
+ }
2125
+ const host = capacity.readHost(); // powershell, best-effort — doctor only, never the hot path
2126
+ const wsl = capacity.readWslConfig();
2127
+ if (wsl) {
2128
+ add("ok", "wslconfig", wsl.path);
2129
+ for (const a of capacity.wslConfigAdvice(wsl, host)) add("warn", "wslconfig", a);
2130
+ } else if (process.platform === "linux") {
2131
+ add("ok", "wslconfig", "no .wslconfig found (not WSL, or Windows user dir unreadable)");
2132
+ }
2133
+ // Windows-side stray dev listeners (F-13): a Metro/emulator/dev server started
2134
+ // from a Windows terminal is invisible to `.serve/` but holds the port the WSL
2135
+ // session needs. Advisory — the operator stops it on the Windows side.
2136
+ const strays = capacity.readWindowsStrays();
2137
+ if (strays.length) {
2138
+ add(
2139
+ "warn",
2140
+ "windows strays",
2141
+ `the Windows host is listening on ${strays.join(", ")} — a dev server/emulator may be running from Windows; stop it there and start it through scripts/serve.js`
2142
+ );
2143
+ }
2144
+ // One-time in-WSL tuning (scripts/wsl-tune.sh apply). Detect rather than
2145
+ // assume so doctor can point at the single command that finishes setup.
2146
+ const tuning = capacity.readTuning();
2147
+ if (tuning.swappiness != null && tuning.swappiness > 20) {
2148
+ add("warn", "wsl tuning", `vm.swappiness=${tuning.swappiness} — run \`sudo scripts/wsl-tune.sh apply\` (targets 10)`);
2149
+ }
2150
+ if (!tuning.workloadCapped && capacity.isWsl()) {
2151
+ add(
2152
+ "warn",
2153
+ "wsl tuning",
2154
+ "no MemoryHigh/MemoryMax on init.scope — the cgroup agents/emulators actually run in " +
2155
+ "(a ceiling on user.slice is inert here). Run `sudo scripts/wsl-tune.sh apply`"
2156
+ );
2157
+ } else if (!tuning.sliceApplied) {
2158
+ add("warn", "wsl tuning", "no user.slice resource ceiling — run `sudo scripts/wsl-tune.sh apply`");
2159
+ } else if (tuning.swappiness != null && tuning.swappiness <= 20) {
2160
+ add("ok", "wsl tuning", `swappiness + user.slice ceiling + init.scope backstop applied`);
2161
+ }
2162
+ // WSL GPU passthrough: /dev/dxg present but no DRM render node means the
2163
+ // `vgem` module isn't loaded, so Mesa falls back to llvmpipe and the
2164
+ // Android emulator renders several times slower than it needs to (F-296).
2165
+ try {
2166
+ if (fs.existsSync("/dev/dxg")) {
2167
+ const render = fs.existsSync("/dev/dri")
2168
+ ? fs.readdirSync("/dev/dri").some((n) => n.startsWith("renderD"))
2169
+ : false;
2170
+ if (render) add("ok", "wsl gpu", "GPU passthrough available (/dev/dri render node present)");
2171
+ else
2172
+ add(
2173
+ "warn",
2174
+ "wsl gpu",
2175
+ "GPU passthrough present but /dev/dri is missing (vgem not loaded) — run `bash scripts/wsl-gpu.sh apply`"
2176
+ );
2177
+ }
2178
+ } catch {
2179
+ /* device probing is best-effort */
2180
+ }
2181
+ } catch (err) {
2182
+ add("ok", "capacity", `not sampled (${err && err.message ? err.message : "unavailable"})`);
2183
+ }
2184
+
2185
+ // CI budget (advisory): the GitHub Actions burn vs the plan's included
2186
+ // minutes. The 2026-10 outage was a budget nobody could see; the honest state
2187
+ // is `unknown` when it cannot be read, never a silent `ok`.
2188
+ try {
2189
+ for (const line of ciBudgetLines(target)) add(line.level, line.label, line.detail);
2190
+ } catch (err) {
2191
+ add("ok", "ci budget", `not read (${err && err.message ? err.message : "unavailable"})`);
2192
+ }
2193
+
2194
+ return reportDoctor(results);
2195
+ }
2196
+
2197
+ function reportDoctor(results) {
2198
+ console.log("agent-harness doctor\n");
2199
+ const icon = { ok: "ok ", warn: "warn", fail: "FAIL" };
2200
+ for (const r of results) console.log(` [${icon[r.level]}] ${r.label}: ${r.detail}`);
2201
+ const fails = results.filter((r) => r.level === "fail").length;
2202
+ const warns = results.filter((r) => r.level === "warn").length;
2203
+ console.log(`\n ${fails} failure(s), ${warns} warning(s).`);
2204
+ process.exitCode = fails > 0 ? 1 : 0;
2205
+ return fails;
2206
+ }
2207
+
2208
+ // ---------------------------------------------------------------- backlog migration
2209
+
2210
+ /* Split a markdown table row on unescaped `|` (respects `\|` inside cells). */
2211
+ function splitCells(row) {
2212
+ const cells = [];
2213
+ let cur = "";
2214
+ let esc = false;
2215
+ for (const ch of row) {
2216
+ if (esc) {
2217
+ cur += ch;
2218
+ esc = false;
2219
+ } else if (ch === "\\") {
2220
+ esc = true;
2221
+ cur += ch;
2222
+ } else if (ch === "|") {
2223
+ cells.push(cur.trim());
2224
+ cur = "";
2225
+ } else {
2226
+ cur += ch;
2227
+ }
2228
+ }
2229
+ cells.push(cur.trim());
2230
+ return cells;
2231
+ }
2232
+
2233
+ /* Parse markdown table data rows, skipping headers and separator/empty rows. */
2234
+ function parseTableRows(src) {
2235
+ const rows = [];
2236
+ for (const raw of String(src || "").split(/\r?\n/)) {
2237
+ const line = raw.trim();
2238
+ if (!/^\|.*\|$/.test(line)) continue;
2239
+ const cells = splitCells(line.slice(1, -1));
2240
+ if (cells.every((c) => /^[-:|\s]*$/.test(c))) continue; // separator
2241
+ if (cells.every((c) => c.trim() === "")) continue; // empty row
2242
+ if (
2243
+ cells.some((c) =>
2244
+ /^(ID|[Ii]d|P|Task|Item|Priority|Context|Status|Evidence|Why frozen|Closed|Why frozen \/ reopen when|Epic|Handoff|Key|Label|Goal)$/.test(c)
2245
+ )
2246
+ )
2247
+ continue; // header
2248
+ rows.push(cells);
2249
+ }
2250
+ return rows;
2251
+ }
2252
+
2253
+ /* Parse markdown list items (bullets / checkboxes), preserving the text. */
2254
+ function parseListItems(src) {
2255
+ const items = [];
2256
+ for (const raw of String(src || "").split(/\r?\n/)) {
2257
+ const m = raw.match(/^\s*[-*]\s+(?:\[[ x]\]\s*)?(.+)$/);
2258
+ if (m && m[1].trim()) items.push(m[1].trim());
2259
+ }
2260
+ return items;
2261
+ }
2262
+
2263
+ /* Map an old INDEX.md F-row (ID | Item | Priority | Context | Status) into the
2264
+ * BACKLOG schema. Returns null for rows that carry no usable identity. */
2265
+ function mapIndexRow(cells) {
2266
+ const id = (cells[0] || "").trim();
2267
+ if (!id) return null;
2268
+ const task = (cells[1] || "").trim() || id;
2269
+ const rawPriority = (cells[2] || "").trim();
2270
+ const context = (cells[3] || "").trim();
2271
+ const status = (cells[4] || "").trim().toLowerCase();
2272
+
2273
+ // Reconcile the priority direction: old `P0` (blocking) == new `P1`.
2274
+ let priority = rawPriority;
2275
+ if (priority === "P0") priority = "P1";
2276
+ if (!/^P[1-4]$/.test(priority)) priority = "?";
2277
+
2278
+ const evidence = context || "?";
2279
+ const base = { id, task, priority, evidence };
2280
+
2281
+ if (/^(shipped|archived|done|closed)$/.test(status)) {
2282
+ return { ...base, section: "archive", closed: status };
2283
+ }
2284
+ if (status === "frozen") {
2285
+ return { ...base, section: "frozen", reopen: context || "frozen (migrated); reopen when evidence recurs" };
2286
+ }
2287
+ if (/^(in-progress|in progress|testing)$/.test(status)) {
2288
+ return { ...base, section: "inprogress", handoff: context || "?" };
2289
+ }
2290
+ return { ...base, section: "open" };
2291
+ }
2292
+
2293
+ /* Ensure the canonical BACKLOG.md exists (create-if-missing from the template),
2294
+ * then — ONLY when it is still empty — consolidate a live INDEX.md F-rows list
2295
+ * and a live todo.md list into it, and rewrite both as pointers. Idempotent:
2296
+ * a re-run finds BACKLOG.md already populated and leaves it untouched. */
2297
+ function migrateBacklog(target) {
2298
+ const backlogPath = path.join(target, "BACKLOG.md");
2299
+ const indexPath = path.join(target, ".agents", "features", "INDEX.md");
2300
+ const todoPath = path.join(target, ".agents", "memory", "todo.md");
2301
+ const templatePath = path.join(TEMPLATES_DIR, "BACKLOG.md");
2302
+
2303
+ const summary = { open: 0, inprogress: 0, frozen: 0, archived: 0, sources: [], createdBacklog: false, rewritten: [] };
2304
+
2305
+ // 1. Scaffold BACKLOG.md if missing (never overwrite an existing board).
2306
+ if (!fs.existsSync(backlogPath)) {
2307
+ if (!fs.existsSync(templatePath)) {
2308
+ throw new Error("templates/BACKLOG.md not found next to this CLI.");
2309
+ }
2310
+ fs.mkdirSync(path.dirname(backlogPath), { recursive: true });
2311
+ fs.writeFileSync(backlogPath, fs.readFileSync(templatePath, "utf8"), "utf8");
2312
+ summary.createdBacklog = true;
2313
+ }
2314
+
2315
+ // 2. Only merge into an empty board — idempotency guard against duplicates.
2316
+ const existing = fs.readFileSync(backlogPath, "utf8");
2317
+ const alreadyHasRows = parseTableRows(existing).length > 0;
2318
+ if (alreadyHasRows) {
2319
+ summary.skipped = "BACKLOG.md already has rows — nothing merged";
2320
+ return summary;
2321
+ }
2322
+
2323
+ // 3. Read the two sources.
2324
+ const open = [];
2325
+ const inProgress = [];
2326
+ const frozen = [];
2327
+ const archive = [];
2328
+ const seenIds = new Set();
2329
+
2330
+ const push = (row) => {
2331
+ if (!row || seenIds.has(row.id)) return;
2332
+ seenIds.add(row.id);
2333
+ if (row.section === "archive") archive.push(row);
2334
+ else if (row.section === "inprogress") inProgress.push(row);
2335
+ else if (row.section === "frozen") frozen.push(row);
2336
+ else open.push(row);
2337
+ };
2338
+
2339
+ if (fs.existsSync(indexPath)) {
2340
+ const indexSrc = fs.readFileSync(indexPath, "utf8");
2341
+ const isPointer = /BACKLOG\.md/.test(indexSrc);
2342
+ if (!isPointer) {
2343
+ summary.sources.push(".agents/features/INDEX.md");
2344
+ for (const row of parseTableRows(indexSrc)) push(mapIndexRow(row));
2345
+ }
2346
+ }
2347
+
2348
+ let tCounter = 0;
2349
+ if (fs.existsSync(todoPath)) {
2350
+ const todoSrc = fs.readFileSync(todoPath, "utf8");
2351
+ const isPointer = /BACKLOG\.md/.test(todoSrc);
2352
+ if (!isPointer) {
2353
+ summary.sources.push(".agents/memory/todo.md");
2354
+ for (const item of parseListItems(todoSrc)) {
2355
+ tCounter += 1;
2356
+ push({
2357
+ id: `T-${String(tCounter).padStart(3, "0")}`,
2358
+ task: item,
2359
+ priority: "?",
2360
+ evidence: ".agents/memory/todo.md",
2361
+ section: "open",
2362
+ });
2363
+ }
2364
+ }
2365
+ }
2366
+
2367
+ // 4. Emit BACKLOG.md only if there was something to migrate.
2368
+ const total = open.length + inProgress.length + frozen.length + archive.length;
2369
+ if (total === 0) {
2370
+ summary.skipped = "no live rows found in INDEX.md / todo.md";
2371
+ return summary;
2372
+ }
2373
+
2374
+ const toRow = (r) => `| ${r.id} | ${r.priority} | ? | ${r.task} | ${r.evidence} |`;
2375
+ const inProgressRow = (r) => `| ${r.id} | ? | ${r.task} | ${r.handoff || "?"} |`;
2376
+ const frozenRow = (r) => `| ${r.id} | ? | ${r.task} | ${r.reopen} |`;
2377
+ const archiveRow = (r) => `| ${r.id} | ? | ${r.task} | ${r.closed} |`;
2378
+
2379
+ const table = (headers, rows) =>
2380
+ [`| ${headers.join(" | ")} |`, `|${headers.map(() => "---").join("|")}|`, ...rows].join("\n");
2381
+
2382
+ const openBlock =
2383
+ open.length === 0
2384
+ ? ""
2385
+ : `## Open\n\nSorted by priority (P1 → P4).\n\n${table(["ID", "P", "Epic", "Task", "Evidence"], open.map(toRow))}`;
2386
+ const inProgressBlock =
2387
+ inProgress.length === 0
2388
+ ? ""
2389
+ : `## In progress\n\nActive work — picked up, not yet shipped.\n\n${table(
2390
+ ["ID", "Epic", "Task", "Handoff"],
2391
+ inProgress.map(inProgressRow)
2392
+ )}`;
2393
+ const queuedBlock =
2394
+ "## Queued\n\nSorted by priority (P1 → P4).\n\n| ID | P | Epic | Task | Evidence |\n|----|---|------|------|----------|";
2395
+ const frozenBlock =
2396
+ frozen.length === 0
2397
+ ? ""
2398
+ : `## Frozen\n\nParked, not deleted. Reopen only when the stated condition recurs.\n\n${table(
2399
+ ["ID", "Epic", "Task", "Why frozen / reopen when"],
2400
+ frozen.map(frozenRow)
2401
+ )}`;
2402
+ const archiveBlock =
2403
+ archive.length === 0
2404
+ ? ""
2405
+ : `## Archive (shipped · done)\n\n${table(["ID", "Epic", "Task", "Closed"], archive.map(archiveRow))}`;
2406
+
2407
+ // Rebuild the board: keep the template's usage header, replace the body.
2408
+ const header = existing.split(/^## Active \/ next/m)[0].trim();
2409
+ const body = [header, "## Active / next\n", inProgressBlock, queuedBlock, openBlock, frozenBlock, archiveBlock, "## Not tracking (leave-in-place, no action)\n"]
2410
+ .filter((b) => b.length > 0)
2411
+ .join("\n\n") + "\n";
2412
+
2413
+ fs.writeFileSync(backlogPath, body, "utf8");
2414
+
2415
+ // 5. Verify BACKLOG.md is written and non-empty BEFORE rewriting sources.
2416
+ const verify = fs.readFileSync(backlogPath, "utf8");
2417
+ if (parseTableRows(verify).length === 0) {
2418
+ throw new Error("refusing to rewrite sources: BACKLOG.md was not written with rows");
2419
+ }
2420
+
2421
+ // 6. Rewrite sources as pointers (never before the board is verified).
2422
+ const pointerFor = (name) =>
2423
+ `# ${name}\n\nThe backlog lives in \`BACKLOG.md\` (repo root). Per-feature docs still\nlive in \`.agents/features/<slug>/\`. This file is a pointer, not a list.\n`;
2424
+ if (fs.existsSync(indexPath) && !/BACKLOG\.md/.test(fs.readFileSync(indexPath, "utf8"))) {
2425
+ fs.writeFileSync(indexPath, pointerFor("Features"), "utf8");
2426
+ summary.rewritten.push(".agents/features/INDEX.md");
2427
+ }
2428
+ if (fs.existsSync(todoPath) && !/BACKLOG\.md/.test(fs.readFileSync(todoPath, "utf8"))) {
2429
+ fs.writeFileSync(todoPath, pointerFor("Todo"), "utf8");
2430
+ summary.rewritten.push(".agents/memory/todo.md");
2431
+ }
2432
+
2433
+ summary.open = open.length;
2434
+ summary.inprogress = inProgress.length;
2435
+ summary.frozen = frozen.length;
2436
+ summary.archived = archive.length;
2437
+ return summary;
2438
+ }
2439
+
2440
+ // ---------------------------------------------------------------- commands
2441
+
2442
+ async function init(target, flags) {
2443
+ if (!fs.existsSync(TEMPLATES_DIR)) {
2444
+ console.error("templates/ directory not found next to this CLI.");
2445
+ process.exit(1);
2446
+ }
2447
+ const result = await deploy(target, {
2448
+ name: flags["--name"],
2449
+ domain: flags["--domain"],
2450
+ yes: !!flags["--yes"],
2451
+ dryRun: !!flags["--dry-run"],
2452
+ isUpdate: false,
2453
+ // First-run safety: an `init` in someone's existing repo never commits or
2454
+ // pushes unless asked. `update` (a harness-owned maintenance step) keeps its
2455
+ // auto-commit default. --push implies --commit.
2456
+ commit: !!flags["--commit"] || !!flags["--push"],
2457
+ push: !!flags["--push"],
2458
+ allowBranch: !!flags["--allow-branch"],
2459
+ acceptHarness: !!flags["--accept-harness"],
2460
+ });
2461
+ printSummary(result, false);
2462
+ printCommitResult(result);
2463
+ if (!result.dryRun) printNextSteps();
2464
+ }
2465
+
2466
+ /* ---------------------------------------------------- worktree freshness sweep
2467
+ * `update` writes only the MAIN checkout; each linked `git worktree` is a
2468
+ * separate checkout with its own (stale) harness copy, so a resumed feature
2469
+ * silently misses the fix (F-25/H-48). Fast-forward every linked worktree to
2470
+ * `origin/main` after an update — warn, never fail (a dirty or diverged worktree
2471
+ * is the operator's to resolve). Never `update --target <worktree>`: the harness
2472
+ * rewrites `opencode.json`'s `{{WORKSPACE_ROOT}}`, which for a worktree resolves
2473
+ * to the worktree's parent and narrows the external-directory allowlist. */
2474
+
2475
+ /* Pure: the linked worktree dirs in `git worktree list --porcelain` output, the
2476
+ * main checkout excluded. Exported for a fixture test. */
2477
+ function parseWorktreeDirs(text, main) {
2478
+ const want = main ? path.resolve(main) : null;
2479
+ const out = [];
2480
+ for (const line of String(text || "").split(/\r?\n/)) {
2481
+ const m = line.match(/^worktree\s+(.+)$/);
2482
+ if (!m) continue;
2483
+ const dir = m[1].trim();
2484
+ if (want && path.resolve(dir) === want) continue;
2485
+ out.push(dir);
2486
+ }
2487
+ return out;
2488
+ }
2489
+
2490
+ /* The linked worktrees of `target` (the main checkout excluded). Best-effort:
2491
+ * [] when not a repo or git is unavailable. */
2492
+ function linkedWorktrees(target) {
2493
+ const r = runGit(target, ["worktree", "list", "--porcelain"]);
2494
+ if (!r.ok) return [];
2495
+ return parseWorktreeDirs(r.out, target);
2496
+ }
2497
+
2498
+ /* Fast-forward each linked worktree to `origin/main`; never throws. Returns
2499
+ * `[{ dir, ok, branch, reason }]`; `reason` is set only when not refreshed. */
2500
+ function refreshLinkedWorktrees(target) {
2501
+ const results = [];
2502
+ for (const wt of linkedWorktrees(target)) {
2503
+ const branch = currentBranch(wt);
2504
+ const dirty = runGit(wt, ["status", "--porcelain"]);
2505
+ if (dirty.ok && dirty.out) {
2506
+ results.push({ dir: wt, ok: false, branch, reason: "uncommitted changes" });
2507
+ continue;
2508
+ }
2509
+ runGit(wt, ["fetch", "--quiet", "origin"]);
2510
+ const r = runGit(wt, ["merge", "--ff-only", "origin/main"]);
2511
+ if (r.ok) results.push({ dir: wt, ok: true, branch });
2512
+ else
2513
+ results.push({
2514
+ dir: wt,
2515
+ ok: false,
2516
+ branch,
2517
+ reason: (r.err || r.out || "").split(/\r?\n/).filter(Boolean).pop() || "not a fast-forward",
2518
+ });
2519
+ }
2520
+ return results;
2521
+ }
2522
+
2523
+ async function update(target, flags) {
2524
+ if (!fs.existsSync(TEMPLATES_DIR)) {
2525
+ console.error("templates/ directory not found next to this CLI.");
2526
+ process.exit(1);
2527
+ }
2528
+ const result = await deploy(target, {
2529
+ yes: true,
2530
+ dryRun: !!flags["--dry-run"],
2531
+ isUpdate: true,
2532
+ commit: !flags["--no-commit"],
2533
+ push: !flags["--no-commit"] && !flags["--no-push"],
2534
+ allowBranch: !!flags["--allow-branch"],
2535
+ acceptHarness: !!flags["--accept-harness"],
2536
+ });
2537
+ printSummary(result, true);
2538
+ printUnpublishedWarning();
2539
+ printCommitResult(result);
2540
+ // deploy != activate: warn when a live opencode for this target predates the
2541
+ // write, so the operator restarts to load the new plugins/config (never
2542
+ // auto-restart while a session is live). F-19/H-44.
2543
+ const staleRuntime = staleRuntimeWarning(target);
2544
+ if (staleRuntime) console.log(`\n WARNING: ${staleRuntime}`);
2545
+ // `update` writes only the main checkout; fast-forward every linked worktree
2546
+ // so a resumed feature does not run the old harness (F-25/H-48). Warn, never
2547
+ // fail, and never `update --target <worktree>`.
2548
+ if (!flags["--dry-run"]) {
2549
+ const wts = refreshLinkedWorktrees(target);
2550
+ if (wts.length) {
2551
+ const stale = wts.filter((w) => !w.ok);
2552
+ console.log(`\n worktrees: ${wts.length - stale.length}/${wts.length} fast-forwarded to origin/main`);
2553
+ for (const w of stale) console.log(` WARNING: ${w.dir} not refreshed (${w.reason}) — merge origin/main by hand`);
2554
+ }
2555
+ }
2556
+ maybePrewarm(target);
2557
+ }
2558
+
2559
+ /* Opt-in (AGENT_HARNESS_PREWARM=1): after an update, warm the device-tier APK
2560
+ * cache in the background off the critical path, so the next `device-up.sh` is
2561
+ * a fast cache hit/overlay instead of a 7-11 min cold Gradle build. Best-effort
2562
+ * and non-blocking; a project without the mobile device tier is a no-op. */
2563
+ function maybePrewarm(target) {
2564
+ if (!process.env.AGENT_HARNESS_PREWARM) return;
2565
+ const script = path.join(target, "scripts", "qa", "mobile-e2e", "prewarm.sh");
2566
+ if (!fs.existsSync(script)) return;
2567
+ try {
2568
+ const { spawn } = require("child_process");
2569
+ const child = spawn("bash", [script, "--detach"], { cwd: target, detached: true, stdio: "ignore" });
2570
+ child.unref();
2571
+ console.log(" prewarm: device-tier APK cache warming in the background");
2572
+ } catch (_) {
2573
+ /* prewarm is an accelerator — never fail an update for it */
2574
+ }
2575
+ }
2576
+
2577
+ // ---------------------------------------------------------------- run (E2E auto-resume)
2578
+
2579
+ /* Chain bounded orchestration contexts for one work unit: run the next-item
2580
+ * workflow, and whenever a phase ends with the feature not landed, relaunch a
2581
+ * fresh opencode session that resumes from the checkpoint only — the automatic
2582
+ * half of the "prefer a fresh bounded context" policy. Stops on landed, the
2583
+ * phase cap, an empty queue, or a failed phase that did not land. The decision
2584
+ * core is pure (`templates/scripts/qa/run-loop.js`) and unit-tested; this
2585
+ * function owns only IO + the subprocess. */
2586
+ function runCommand(target, flags) {
2587
+ const loop = require(path.join(TEMPLATES_DIR, "scripts", "qa", "run-loop.js"));
2588
+ const { resolveOpencode } = require(path.join(TEMPLATES_DIR, "scripts", "qa", "provider-stats.js"));
2589
+ const backlogPath = path.join(target, "BACKLOG.md");
2590
+ const handoffDir = path.join(target, ".agents", "handoffs");
2591
+ const maxPhases = parseInt(flags["--max-phases"], 10) || 4;
2592
+ const dryRun = !!flags["--dry-run"];
2593
+ const opencode = flags["--opencode"] || resolveOpencode();
2594
+ if (!dryRun && !opencode) {
2595
+ console.error("run: opencode CLI not found — install it, or pass --opencode <path>.");
2596
+ process.exitCode = 1;
2597
+ return;
2598
+ }
2599
+ const readIf = (p) => {
2600
+ try {
2601
+ return fs.readFileSync(p, "utf8");
2602
+ } catch (_) {
2603
+ return "";
2604
+ }
2605
+ };
2606
+ const readHandoff = (feature) => (feature ? readIf(path.join(handoffDir, feature + ".md")) : "");
2607
+
2608
+ console.log(`agent-harness run — target ${target} (max ${maxPhases} phase(s))`);
2609
+ let feature = flags["--feature"] || null;
2610
+ let prompt = flags["--prompt"] || null;
2611
+ let phasesRun = 0;
2612
+ let lastExit = null;
2613
+
2614
+ while (true) {
2615
+ const decision = loop.decideRunLoop({
2616
+ backlogText: readIf(backlogPath),
2617
+ handoffText: readHandoff(feature),
2618
+ feature,
2619
+ phasesRun,
2620
+ maxPhases,
2621
+ lastExit,
2622
+ });
2623
+ if (decision.action !== "resume") {
2624
+ console.log(`\nrun: ${decision.action} — ${decision.reason}`);
2625
+ // A dry-run that reaches the phase cap is a plan, not a failure.
2626
+ if (decision.action === "stop" && !dryRun) process.exitCode = 1;
2627
+ break;
2628
+ }
2629
+ const phase = phasesRun + 1;
2630
+ // The first phase uses the explicit /next-style prompt; later phases resume.
2631
+ const message = phasesRun === 0 && prompt ? prompt : decision.prompt;
2632
+ console.log(`\n── phase ${phase}/${maxPhases}: ${decision.reason} ──`);
2633
+ if (dryRun) {
2634
+ console.log(` [dry-run] would run: ${opencode || "opencode"} run <prompt>`);
2635
+ console.log(` [dry-run] prompt: ${message}`);
2636
+ } else {
2637
+ const r = spawnSync(opencode, ["run", message], { cwd: target, stdio: "inherit" });
2638
+ lastExit = r.status == null ? 1 : r.status;
2639
+ }
2640
+ feature = decision.feature || feature;
2641
+ phasesRun = phase;
2642
+ prompt = decision.prompt;
2643
+ }
2644
+ }
2645
+
2646
+ function printCommitResult(result) {
2647
+ const c = result.commitResult;
2648
+ if (!c) return;
2649
+ console.log("");
2650
+ if (c.committed) {
2651
+ console.log(" committed harness files: " + c.staged.join(", "));
2652
+ if (c.forceAdded.length) {
2653
+ console.log(
2654
+ " force-added (gitignored in this project, but harness-owned): " +
2655
+ c.forceAdded.join(", ")
2656
+ );
2657
+ }
2658
+ console.log(
2659
+ c.pushed === true
2660
+ ? " pushed to origin."
2661
+ : c.pushed === null
2662
+ ? " push skipped (no --push / no remote)."
2663
+ : " WARNING: commit made but push FAILED."
2664
+ );
2665
+ } else {
2666
+ console.log(" no harness auto-commit: " + (c.skipped.join("; ") || "no-op"));
2667
+ }
2668
+ }
2669
+
2670
+ function parseArgs(argv) {
2671
+ const flags = {};
2672
+ const valueFlags = new Set([
2673
+ "--target",
2674
+ "--name",
2675
+ "--domain",
2676
+ "--feature",
2677
+ "--prompt",
2678
+ "--max-phases",
2679
+ "--opencode",
2680
+ "--dir",
2681
+ "--time",
2682
+ ]);
2683
+ for (let i = 0; i < argv.length; i++) {
2684
+ const a = argv[i];
2685
+ if (valueFlags.has(a)) flags[a] = argv[++i];
2686
+ else if (a === "--dry-run" || a === "--yes" || a === "-y" || a === "--force") flags[a] = true;
2687
+ else if (a === "--remove") flags[a] = true;
2688
+ else if (a === "--no-commit" || a === "--no-push" || a === "--allow-branch" || a === "--accept-harness" || a === "--commit" || a === "--push")
2689
+ flags[a] = true;
2690
+ }
2691
+ return flags;
2692
+ }
2693
+
2694
+ /* ---------------------------------------------------------------- install-global
2695
+ *
2696
+ * The global opencode plugin dir (`~/.config/opencode/plugins/`, auto-loaded for
2697
+ * EVERY project/session) is machine config, not something `update` can deploy
2698
+ * into a project. To keep it reproducible and current, the sources live here in
2699
+ * `contrib/global-plugins/`, and this command links them into that global dir.
2700
+ * A symlink means the installed plugin always reflects this checkout's latest
2701
+ * source (a copy is the fallback where symlinks are unavailable, e.g. Windows
2702
+ * without privilege — re-run `install-global` after harness updates there).
2703
+ *
2704
+ * The headline plugin is `harness-freshness.ts`: on every session start it
2705
+ * compares a checkout's `.harness.json` to the local harness and refreshes the
2706
+ * checkout ONLY when that is safe for the active branch (a fast-forward worktree,
2707
+ * or the sanctioned main-checkout `update`); otherwise it blocks and tells the
2708
+ * agent to wait. It must be global because a stale project or worktree loads its
2709
+ * OWN (stale) harness — a check shipped inside it could never fire. */
2710
+ function opencodeGlobalPluginsDir() {
2711
+ const xdg = process.env.XDG_CONFIG_HOME || path.join(os.homedir(), ".config");
2712
+ return path.join(xdg, "opencode", "plugins");
2713
+ }
2714
+
2715
+ function installGlobal(flags) {
2716
+ const dryRun = !!flags["--dry-run"];
2717
+ const force = !!flags["--force"];
2718
+ const destDir = path.resolve(flags["--dir"] || opencodeGlobalPluginsDir());
2719
+
2720
+ if (!fs.existsSync(GLOBAL_PLUGINS_SRC)) {
2721
+ console.error(`install-global: no bundled global plugins at ${GLOBAL_PLUGINS_SRC}`);
2722
+ process.exitCode = 1;
2723
+ return;
2724
+ }
2725
+ const files = fs.readdirSync(GLOBAL_PLUGINS_SRC).filter((f) => /\.(ts|js)$/.test(f));
2726
+ console.log(`install-global → ${destDir}${dryRun ? " (dry-run)" : ""}`);
2727
+
2728
+ const counts = { linked: 0, updated: 0, current: 0, skipped: 0 };
2729
+ for (const f of files) {
2730
+ const src = path.join(GLOBAL_PLUGINS_SRC, f);
2731
+ const dest = path.join(destDir, f);
2732
+ let st = null;
2733
+ try {
2734
+ st = fs.lstatSync(dest);
2735
+ } catch {
2736
+ /* not present */
2737
+ }
2738
+
2739
+ if (st && st.isSymbolicLink()) {
2740
+ const resolved = path.resolve(path.dirname(dest), fs.readlinkSync(dest));
2741
+ if (resolved === path.resolve(src)) {
2742
+ counts.current++;
2743
+ console.log(` [current] ${f}`);
2744
+ continue;
2745
+ }
2746
+ } else if (st && !force) {
2747
+ // A regular file: only treat as current if identical, else refuse.
2748
+ let same = false;
2749
+ try {
2750
+ same = fs.readFileSync(dest, "utf8") === fs.readFileSync(src, "utf8");
2751
+ } catch {
2752
+ /* unreadable */
2753
+ }
2754
+ if (same) {
2755
+ counts.current++;
2756
+ console.log(` [current] ${f}`);
2757
+ } else {
2758
+ counts.skipped++;
2759
+ console.log(` [skip] ${f} exists (not a managed link) — pass --force to replace`);
2760
+ }
2761
+ continue;
2762
+ }
2763
+
2764
+ const existed = !!st;
2765
+ if (dryRun) {
2766
+ counts[existed ? "updated" : "linked"]++;
2767
+ console.log(` [would ${existed ? "update" : "link"}] ${dest} -> ${src}`);
2768
+ continue;
2769
+ }
2770
+ fs.mkdirSync(destDir, { recursive: true });
2771
+ let linked = false;
2772
+ try {
2773
+ if (st) fs.rmSync(dest, { force: true });
2774
+ fs.symlinkSync(src, dest);
2775
+ linked = true;
2776
+ } catch {
2777
+ linked = false;
2778
+ }
2779
+ if (!linked) fs.copyFileSync(src, dest); // symlinks unavailable -> copy
2780
+ counts[existed ? "updated" : "linked"]++;
2781
+ console.log(` [${linked ? "link" : "copy"}] ${f}${linked ? "" : " (symlink unavailable — copied)"}`);
2782
+ }
2783
+
2784
+ console.log(
2785
+ `\n ${counts.linked} linked, ${counts.updated} updated, ${counts.current} current, ${counts.skipped} skipped.`
2786
+ );
2787
+ if (!dryRun && counts.linked + counts.updated > 0) {
2788
+ console.log(" Restart opencode to load the plugin(s).");
2789
+ }
2790
+ if (counts.skipped > 0) process.exitCode = 1;
2791
+ }
2792
+
2793
+ /* dogfood — make the harness's OWN source checkout run the harness it ships.
2794
+ *
2795
+ * The harness repo keeps its source under `templates/` and has no root
2796
+ * `.opencode/`, so an opencode session rooted there loads no guard, no lease and
2797
+ * none of the harness tools (`orient`, `backlog_*`, `session_info`, …) — it only
2798
+ * gets them when some deployed project's plugin instance is co-loaded in the same
2799
+ * server (F-16, harness-field-review-2026-10-16-round2). `dogfood` symlinks the
2800
+ * template tree into the repo root so the checkout dogfoods itself with NO copy
2801
+ * to drift:
2802
+ *
2803
+ * .opencode/{agents,commands,plugins,skills} -> ../templates/.opencode/*
2804
+ * scripts -> templates/scripts
2805
+ * opencode.json (template, {{WORKSPACE_ROOT}} filled)
2806
+ * .harness-dogfood marker (relaxes the main-checkout block)
2807
+ *
2808
+ * The plugins' relative imports (`../../scripts/qa/*`) resolve through the real
2809
+ * template path once `.opencode` is a directory of symlinks, and the `scripts`
2810
+ * symlink makes the runtime `scripts/...` spawns resolve too. The marker keeps
2811
+ * `templates/**` editable on main (that IS the harness workflow); every other
2812
+ * checkout is unchanged. `--remove` reverses the links; `--dry-run` prints the plan. */
2813
+ function dogfood(target, flags) {
2814
+ const dryRun = !!flags["--dry-run"];
2815
+ const remove = !!flags["--remove"];
2816
+ const src = TEMPLATES_DIR;
2817
+ const dotOpencode = path.join(src, ".opencode");
2818
+ if (!fs.existsSync(dotOpencode)) {
2819
+ console.error(`dogfood: ${dotOpencode} not found — run from (or --target) the harness source checkout.`);
2820
+ process.exitCode = 1;
2821
+ return;
2822
+ }
2823
+ const root = path.resolve(target);
2824
+ const subs = fs
2825
+ .readdirSync(dotOpencode)
2826
+ .filter((n) => fs.statSync(path.join(dotOpencode, n)).isDirectory());
2827
+ console.log(`dogfood ${remove ? "--remove " : ""}→ ${root}${dryRun ? " (dry-run)" : ""}`);
2828
+
2829
+ const sameLink = (linkPath, linkTarget) => {
2830
+ try {
2831
+ const st = fs.lstatSync(linkPath);
2832
+ if (!st.isSymbolicLink()) return false;
2833
+ return (
2834
+ path.resolve(path.dirname(linkPath), fs.readlinkSync(linkPath)) ===
2835
+ path.resolve(path.dirname(linkPath), linkTarget)
2836
+ );
2837
+ } catch {
2838
+ return false;
2839
+ }
2840
+ };
2841
+ const lstat = (p) => {
2842
+ try {
2843
+ return fs.lstatSync(p);
2844
+ } catch {
2845
+ return null;
2846
+ }
2847
+ };
2848
+ const link = (linkPath, linkTarget) => {
2849
+ const rel = path.relative(root, linkPath);
2850
+ if (remove) {
2851
+ if (lstat(linkPath)) {
2852
+ if (!dryRun) fs.rmSync(linkPath, { force: true });
2853
+ console.log(` [removed] ${rel}`);
2854
+ }
2855
+ return;
2856
+ }
2857
+ if (sameLink(linkPath, linkTarget)) {
2858
+ console.log(` [current] ${rel}`);
2859
+ return;
2860
+ }
2861
+ if (lstat(linkPath)) {
2862
+ console.error(` [skip] ${rel} exists and is not our symlink`);
2863
+ process.exitCode = 1;
2864
+ return;
2865
+ }
2866
+ if (dryRun) {
2867
+ console.log(` [link] ${rel} -> ${linkTarget}`);
2868
+ return;
2869
+ }
2870
+ fs.mkdirSync(path.dirname(linkPath), { recursive: true });
2871
+ fs.symlinkSync(linkTarget, linkPath);
2872
+ console.log(` [link] ${rel} -> ${linkTarget}`);
2873
+ };
2874
+
2875
+ const ocDir = path.join(root, ".opencode");
2876
+ for (const name of subs) link(path.join(ocDir, name), path.join("..", "templates", ".opencode", name));
2877
+ link(path.join(root, "scripts"), path.join("templates", "scripts"));
2878
+
2879
+ const marker = path.join(root, ".harness-dogfood");
2880
+ const ocJson = path.join(root, "opencode.json");
2881
+ if (remove) {
2882
+ if (lstat(marker)) {
2883
+ if (!dryRun) fs.rmSync(marker, { force: true });
2884
+ console.log(" [removed] .harness-dogfood");
2885
+ }
2886
+ if (!dryRun && lstat(ocDir) && fs.readdirSync(ocDir).length === 0) fs.rmdirSync(ocDir);
2887
+ console.log("\ndogfood removed. Restart opencode to drop the guard/tools.");
2888
+ return;
2889
+ }
2890
+ const tpl = fs.readFileSync(path.join(src, "opencode.json"), "utf8");
2891
+ const conf = substitute(tpl, { WORKSPACE_ROOT: workspaceRootFor(root) });
2892
+ if (dryRun) {
2893
+ console.log(` [write] opencode.json (template, WORKSPACE_ROOT=${workspaceRootFor(root)})`);
2894
+ console.log(" [write] .harness-dogfood");
2895
+ } else {
2896
+ fs.writeFileSync(ocJson, conf.endsWith("\n") ? conf : conf + "\n");
2897
+ fs.writeFileSync(
2898
+ marker,
2899
+ "# dogfood install — this harness source checkout runs its own guard.\n" +
2900
+ "# `templates/**` stays editable on main; remove with `agent-harness dogfood --remove`.\n"
2901
+ );
2902
+ console.log(" [write] opencode.json + .harness-dogfood");
2903
+ }
2904
+ console.log("\nRestart opencode to load the guard/tools, then edit `templates/**` as usual.");
2905
+ }
2906
+
2907
+ /* install-nightly — install the off-hours E2E cycle as a systemd --user timer by
2908
+ * delegating to the deployed project's `scripts/setup-nightly.sh` (the script
2909
+ * owns the unit contents + linger handling, so it stays correct per project and
2910
+ * is reused when run by hand). */
2911
+ function installNightly(target, flags) {
2912
+ const script = path.join(target, "scripts", "setup-nightly.sh");
2913
+ if (!fs.existsSync(script)) {
2914
+ console.error(`install-nightly: ${script} not found — run \`agent-harness update --target ${target}\` first.`);
2915
+ process.exitCode = 1;
2916
+ return;
2917
+ }
2918
+ const args = [script, "install"];
2919
+ if (flags["--time"]) args.push("--time", flags["--time"]);
2920
+ if (flags["--force"]) args.push("--force");
2921
+ if (flags["--dry-run"]) args.push("--dry-run");
2922
+ const r = spawnSync("bash", args, {
2923
+ cwd: target,
2924
+ stdio: "inherit",
2925
+ env: { ...process.env, AGENT_NIGHTLY_ROOT: target },
2926
+ });
2927
+ if (r.status !== 0) process.exitCode = r.status == null ? 1 : r.status;
2928
+ }
2929
+
2930
+ function main() {
2931
+ const args = process.argv.slice(2);
2932
+ const cmd = args[0];
2933
+ if (cmd === "--version" || cmd === "-v") return console.log(PKG.version);
2934
+ if (cmd === "--help" || cmd === "-h" || !cmd || cmd === "help") return printUsage();
2935
+
2936
+ const flags = parseArgs(args.slice(1));
2937
+ const target = path.resolve(flags["--target"] || process.cwd());
2938
+
2939
+ switch (cmd) {
2940
+ case "init":
2941
+ init(target, flags).catch((e) => {
2942
+ console.error(e);
2943
+ process.exit(1);
2944
+ });
2945
+ break;
2946
+ case "update":
2947
+ update(target, flags).catch((e) => {
2948
+ console.error(e);
2949
+ process.exit(1);
2950
+ });
2951
+ break;
2952
+ case "migrate-backlog":
2953
+ try {
2954
+ const s = migrateBacklog(target);
2955
+ if (s.skipped) {
2956
+ console.log(`\n[migrate-backlog] ${s.skipped}`);
2957
+ } else {
2958
+ console.log(
2959
+ `\n[migrate-backlog] consolidated ${s.open} open · ${s.inprogress} in progress · ${s.frozen} frozen · ${s.archived} archived`
2960
+ );
2961
+ if (s.sources.length) console.log(` read from: ${s.sources.join(", ")}`);
2962
+ if (s.rewritten.length) console.log(` rewritten as pointers: ${s.rewritten.join(", ")}`);
2963
+ if (s.createdBacklog) console.log(" created BACKLOG.md from the template");
2964
+ }
2965
+ } catch (e) {
2966
+ console.error(e);
2967
+ process.exit(1);
2968
+ }
2969
+ break;
2970
+ case "list":
2971
+ printPersonas(TEMPLATES_DIR);
2972
+ break;
2973
+ case "explain": {
2974
+ const name = args.slice(1).find((a) => !a.startsWith("-"));
2975
+ if (!name || name === "--list" || args.includes("--list")) explainList();
2976
+ else explain(name);
2977
+ break;
2978
+ }
2979
+ case "doctor":
2980
+ doctor(target);
2981
+ break;
2982
+ case "install-global":
2983
+ installGlobal(flags);
2984
+ break;
2985
+ case "install-nightly":
2986
+ installNightly(target, flags);
2987
+ break;
2988
+ case "dogfood":
2989
+ dogfood(target, flags);
2990
+ break;
2991
+ case "run":
2992
+ runCommand(target, flags);
2993
+ break;
2994
+ default:
2995
+ console.error(`Unknown command: ${cmd}\n`);
2996
+ printUsage();
2997
+ process.exitCode = 1;
2998
+ }
2999
+ }
3000
+
3001
+ if (require.main === module) main();
3002
+
3003
+ module.exports = {
3004
+ listFiles,
3005
+ substitute,
3006
+ isMemoryFile,
3007
+ isOpencodeJson,
3008
+ isWindowsMount,
3009
+ currentBranch,
3010
+ defaultBranch,
3011
+ detectIndent,
3012
+ mergePackageJson,
3013
+ mergeGitattributes,
3014
+ stripGitattributesBlock,
3015
+ stripManagedBlock,
3016
+ mergeIgnoreFile,
3017
+ isIgnoreFile,
3018
+ withDeployLock,
3019
+ sha256,
3020
+ readConfig,
3021
+ resolveVars,
3022
+ workspaceRootFor,
3023
+ mergeOpencodeJson,
3024
+ convertV1Permission,
3025
+ convertV1Tools,
3026
+ mergeMcp,
3027
+ deploy,
3028
+ assertNoTemplateHandoffs,
3029
+ parseWorktreeDirs,
3030
+ linkedWorktrees,
3031
+ refreshLinkedWorktrees,
3032
+ staleProcs,
3033
+ formatStaleRuntime,
3034
+ opencodeProcsFor,
3035
+ harnessWriteTime,
3036
+ staleRuntimeWarning,
3037
+ migrateBacklog,
3038
+ splitCells,
3039
+ parseTableRows,
3040
+ parseListItems,
3041
+ mapIndexRow,
3042
+ printPersonas,
3043
+ doctor,
3044
+ parseOpencodeVersion,
3045
+ checkOpencodeVersion,
3046
+ explain,
3047
+ explainSection,
3048
+ explainList,
3049
+ installGlobal,
3050
+ dogfood,
3051
+ opencodeGlobalPluginsDir,
3052
+ GLOBAL_PLUGINS_SRC,
3053
+ HARNESS_SCRIPTS,
3054
+ runCommand,
3055
+ TEMPLATES_DIR,
3056
+ CONFIG_FILE,
3057
+ BACKUP_DIR,
3058
+ PKG,
3059
+ };