opencode-agent-harness 0.0.0-stage → 0.3.14

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