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,416 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ /*
4
+ * finalize — the deterministic finalization tail in ONE command.
5
+ *
6
+ * The problem it solves: a full dev cycle (pick → plan → implement → QA → gates →
7
+ * docs → archive → commit → land → confirm CI) needs more context than one
8
+ * bounded orchestrator transcript can hold. `finalize` collapses the whole tail
9
+ * into a single blocking command:
10
+ *
11
+ * 1. resolve root + feature (id arg, else the `f-<n>` branch);
12
+ * 2. archive the row (idempotent — an already-archived row is a no-op);
13
+ * 3. commit the tail (board + CHANGELOG + handoff + any remaining change);
14
+ * 4. shell out to `scripts/ship.js`, which rebases onto `origin/main`, runs the
15
+ * branch gates, lands `HEAD:main` with a direct fast-forward push (retrying
16
+ * after a concurrent landing), and waits (bounded) for CI to go green on the
17
+ * landed SHA. The deploy runs after CI; there is no PR, label, merge train,
18
+ * or deploy watch.
19
+ *
20
+ * The one non-deterministic bit — the CHANGELOG prose — is authored by the
21
+ * `/finish` command's single `docs` dispatch BEFORE this runs; `finalize`
22
+ * commits whatever is in the tree.
23
+ *
24
+ * Usage:
25
+ * node scripts/finalize.js --feature <id> [--closed "<note>"]
26
+ * [--base main] [--root <dir>] [--dry-run]
27
+ * [--no-rebase] [--no-gate] [--no-ci-wait]
28
+ */
29
+ const fs = require("fs");
30
+ const path = require("path");
31
+ const { spawnSync } = require("child_process");
32
+
33
+ function fail(message) {
34
+ console.error(message);
35
+ process.exitCode = 1;
36
+ }
37
+
38
+ /* Run a command, streaming its output. Returns the exit status (0 = ok). */
39
+ function run(cmd, args, opts) {
40
+ console.log(`\n$ ${[cmd, ...args].join(" ")}`);
41
+ const result = spawnSync(cmd, args, { stdio: "inherit", ...(opts || {}) });
42
+ return result.status === 0;
43
+ }
44
+
45
+ /* Run a command and capture trimmed stdout (empty string on failure). */
46
+ function out(cmd, args, opts) {
47
+ const result = spawnSync(cmd, args, { encoding: "utf8", ...(opts || {}) });
48
+ return result.status === 0 ? String(result.stdout || "").trim() : "";
49
+ }
50
+
51
+ /* Walk up from `startDir` to the repo root (the first `.git` entry). */
52
+ function findRoot(startDir) {
53
+ let dir = path.resolve(startDir || process.cwd());
54
+ for (;;) {
55
+ if (fs.existsSync(path.join(dir, ".git"))) return dir;
56
+ const parent = path.dirname(dir);
57
+ if (parent === dir) return null;
58
+ dir = parent;
59
+ }
60
+ }
61
+
62
+ function readIf(p) {
63
+ try {
64
+ return fs.readFileSync(p, "utf8");
65
+ } catch {
66
+ return "";
67
+ }
68
+ }
69
+
70
+ /* The feature id from a branch name (`f-257` -> `F-257`, `feat/F-12-x` -> `F-12`). */
71
+ function featureFromBranch(branch) {
72
+ const m = String(branch || "").match(/(?:^|\/)[fF]-?([0-9]+)/);
73
+ return m ? `F-${m[1]}` : null;
74
+ }
75
+
76
+ /* The handoff's recorded outcome, if any (`## Session metadata` -> `- outcome:`). */
77
+ function handoffOutcome(feature) {
78
+ let src = readIf(path.join(root, ".agents", "handoffs", feature + ".md"));
79
+ if (!src) {
80
+ const res = spawnSync("git", ["-C", root, "worktree", "list", "--porcelain"], { encoding: "utf8" });
81
+ for (const line of String(res.stdout || "").split(/\r?\n/)) {
82
+ if (!line.startsWith("worktree ")) continue;
83
+ const dir = line.slice("worktree ".length).trim();
84
+ const candidate = readIf(path.join(dir, ".agents", "handoffs", feature + ".md"));
85
+ if (candidate) {
86
+ src = candidate;
87
+ break;
88
+ }
89
+ }
90
+ }
91
+ const m = src.match(/^[-*]\s*outcome\s*:\s*(.+)$/im);
92
+ return m ? m[1].trim().toLowerCase() : null;
93
+ }
94
+
95
+ /* Whether the row is already archived on the board. When the board service is
96
+ * the backend (ADR 0001) the board lives in the service, so ask it; otherwise
97
+ * reuse the run-loop parser (same module the auto-resume runner trusts). */
98
+ function isArchived(feature) {
99
+ try {
100
+ const client = require(path.join(root, "scripts", "qa", "board-client.js"));
101
+ if (client.enabled(root)) {
102
+ const board = client.getBoard(root);
103
+ return (board.archive || []).some((r) => r.id === feature);
104
+ }
105
+ } catch {
106
+ /* fall back to the file parser below */
107
+ }
108
+ try {
109
+ const loop = require(path.join(root, "scripts", "qa", "run-loop.js"));
110
+ return loop.isArchived(readIf(path.join(root, "BACKLOG.md")), feature);
111
+ } catch {
112
+ return false;
113
+ }
114
+ }
115
+
116
+ /* Whether HEAD is already an ancestor of `origin/<base>` — i.e. the change is
117
+ * already landed, so a re-run is a no-op. Best-effort fetch; offline returns
118
+ * false (a re-run then re-lands idempotently). */
119
+ function landedAlready(base) {
120
+ spawnSync("git", ["fetch", "--quiet", "origin"], { cwd: root, stdio: "ignore", timeout: 10000 });
121
+ const res = spawnSync("git", ["merge-base", "--is-ancestor", "HEAD", `origin/${base}`], {
122
+ cwd: root,
123
+ stdio: "ignore",
124
+ });
125
+ return res.status === 0;
126
+ }
127
+
128
+ function dirtyEntries() {
129
+ return out("git", ["status", "--porcelain"], { cwd: root })
130
+ .split(/\r?\n/)
131
+ .filter((l) => l && !l.startsWith("!!"));
132
+ }
133
+
134
+ /* Generated / machine-local paths that must never ride into a feature commit.
135
+ * `git add -A` used to sweep these up (a worktree's `prisma/generated` symlink
136
+ * broke CI on a fresh checkout), so they are blocked explicitly. */
137
+ const BLOCKED_PATTERNS = [
138
+ /(^|\/)node_modules(\/|$)/,
139
+ /(^|\/)\.next(\/|$)/,
140
+ /(^|\/)\.turbo(\/|$)/,
141
+ /(^|\/)dist(\/|$)/,
142
+ /(^|\/)build(\/|$)/,
143
+ /(^|\/)coverage(\/|$)/,
144
+ /(^|\/)prisma\/generated(\/|$)/,
145
+ /(^|\/)\.env(\..*)?$/,
146
+ /\.(log|tsbuildinfo)$/,
147
+ ];
148
+
149
+ function isBlockedPath(rel) {
150
+ return BLOCKED_PATTERNS.some((re) => re.test(rel.replace(/\\/g, "/")));
151
+ }
152
+
153
+ /* `git ls-files --others --exclude-standard` -> repo-relative untracked paths. */
154
+ function untrackedFiles() {
155
+ return out("git", ["ls-files", "--others", "--exclude-standard"], { cwd: root })
156
+ .split(/\r?\n/)
157
+ .filter(Boolean);
158
+ }
159
+
160
+ function isSymlink(rel) {
161
+ try {
162
+ return fs.lstatSync(path.join(root, rel)).isSymbolicLink();
163
+ } catch {
164
+ return false;
165
+ }
166
+ }
167
+
168
+ /* Stage the finalization tail without `git add -A`.
169
+ *
170
+ * - tracked changes (`git add -u`) are the feature's own edits;
171
+ * - untracked tail files (handoff, feature docs, QA plan, memory, docs) are added;
172
+ * - untracked generated/symlinked/machine-local paths are refused, never staged;
173
+ * - a stray `BACKLOG.md` diff is refused when the board service owns the board
174
+ * (a worktree-local row is a duplicate that would collide on merge).
175
+ *
176
+ * Returns { ok, blocked } — blocked lists the paths that need a human decision.
177
+ */
178
+ function stageTail(feature, opts = {}) {
179
+ const includeBlocked = Boolean(opts.includeBlocked);
180
+ if (!run("git", ["add", "-u"], { cwd: root })) return { ok: false, blocked: [] };
181
+
182
+ const blocked = [];
183
+ const boardService = boardServiceEnabled();
184
+ for (const rel of untrackedFiles()) {
185
+ if (rel === "BACKLOG.md" && boardService) {
186
+ blocked.push(`${rel} (board service owns the board — worktree copy is a duplicate)`);
187
+ continue;
188
+ }
189
+ if (isBlockedPath(rel) || isSymlink(rel)) {
190
+ blocked.push(rel);
191
+ continue;
192
+ }
193
+ // Another feature's handoff is never part of this landing; it is either a
194
+ // stale copy from a shared checkout or work that belongs to that session.
195
+ if (rel.startsWith(".agents/handoffs/") && rel !== `.agents/handoffs/${feature}.md`) {
196
+ blocked.push(`${rel} (another feature's handoff)`);
197
+ continue;
198
+ }
199
+ if (!run("git", ["add", "--", rel], { cwd: root })) return { ok: false, blocked };
200
+ }
201
+
202
+ // A tracked BACKLOG.md diff with the board service enabled is the same
203
+ // duplicate row, just already tracked. Never let it into the landing commit.
204
+ if (boardService) {
205
+ const blockedBoard = dirtyEntries().filter((l) => /(^|\s)BACKLOG\.md$/.test(l) || l.endsWith(" BACKLOG.md"));
206
+ if (blockedBoard.length) {
207
+ blocked.push("BACKLOG.md (board service owns the board — restore or move the row to the service)");
208
+ }
209
+ }
210
+
211
+ if (blocked.length && !includeBlocked) {
212
+ console.error(
213
+ "\n[finalize] refusing to commit these non-tail paths:\n" +
214
+ [...new Set(blocked)].map((l) => ` ${l}`).join("\n") +
215
+ "\n Move/commit/delete them first, or re-run with --include-blocked to stage them deliberately."
216
+ );
217
+ return { ok: false, blocked };
218
+ }
219
+ if (blocked.length && includeBlocked) {
220
+ console.log("\n[finalize] --include-blocked: staging the paths above.");
221
+ if (!run("git", ["add", "-A"], { cwd: root })) return { ok: false, blocked };
222
+ }
223
+ return { ok: true, blocked: [] };
224
+ }
225
+
226
+ function boardServiceEnabled() {
227
+ try {
228
+ return require(path.join(root, "scripts", "qa", "board-client.js")).enabled(root);
229
+ } catch {
230
+ return false;
231
+ }
232
+ }
233
+
234
+ /* After a landing: converge the main checkout (ff-only, only when clean) and
235
+ * print the close-out steps that used to appear as a session-ending remark. */
236
+ function closeOut(base, feature) {
237
+ let hygiene;
238
+ try {
239
+ hygiene = require(path.join(root, "scripts", "qa", "worktree-hygiene.js"));
240
+ } catch {
241
+ return;
242
+ }
243
+ spawnSync("git", ["fetch", "--quiet", "origin"], { cwd: root, stdio: "ignore", timeout: 10000 });
244
+ const h = hygiene.hygiene(root, base, process.cwd());
245
+ if (!h) return;
246
+ console.log(`\n[finalize] close-out: ${hygiene.describe(h)}`);
247
+
248
+ if (h.main.behind > 0 && h.main.dirty === 0) {
249
+ console.log(`[finalize] converging the main checkout: git -C ${h.main.path} merge --ff-only ${h.baseRef}`);
250
+ const merged = spawnSync("git", ["-C", h.main.path, "merge", "--ff-only", h.baseRef], { encoding: "utf8" });
251
+ if (merged.status === 0) console.log(`[finalize] main checkout is now up to date.`);
252
+ else console.log(`[finalize] could not fast-forward the main checkout:\n${String(merged.stderr || merged.stdout || "").trim()}`);
253
+ }
254
+
255
+ const advice = hygiene.closeOutAdvice(hygiene.hygiene(root, base, process.cwd()));
256
+ if (advice.length) {
257
+ console.log("[finalize] close-out actions still open:");
258
+ for (const a of advice) console.log(` - ${a}`);
259
+ console.log(` (the next session's orient auto-prunes merged, clean worktrees; ${feature} cannot be removed from inside it)`);
260
+ } else {
261
+ console.log("[finalize] no leftovers: main is in sync and no merged worktree remains.");
262
+ }
263
+ }
264
+
265
+ function parseArgs(argv) {
266
+ const args = { _: [] };
267
+ for (let i = 0; i < argv.length; i++) {
268
+ const a = argv[i];
269
+ if (a === "--feature") args.feature = argv[++i];
270
+ else if (a === "--closed") args.closed = argv[++i];
271
+ else if (a === "--base") args.base = argv[++i];
272
+ else if (a === "--root") args.root = argv[++i];
273
+ else if (a === "--dry-run") args["dry-run"] = true;
274
+ else if (a === "--no-rebase") args["no-rebase"] = true;
275
+ else if (a === "--no-gate") args["no-gate"] = true;
276
+ else if (a === "--no-ci-wait") args["no-ci-wait"] = true;
277
+ else if (a === "--include-blocked") args["include-blocked"] = true;
278
+ else if (a === "--help" || a === "-h") args.help = true;
279
+ else args._.push(a);
280
+ }
281
+ return args;
282
+ }
283
+
284
+ function usage() {
285
+ console.log(
286
+ "finalize — archive + commit + land + confirm CI in one deterministic step (no LLM)\n\n" +
287
+ ' node scripts/finalize.js --feature <id> [--closed "<note>"] [--base main]\n' +
288
+ " [--root <dir>] [--dry-run]\n" +
289
+ " [--no-rebase] [--no-gate] [--no-ci-wait]\n\n" +
290
+ "Collapses the finalization tail into one blocking command: archive the row,\n" +
291
+ "commit the board + CHANGELOG + handoff, then `ship` (rebase, gates, direct\n" +
292
+ "land on the integration branch, and a bounded wait for green CI). The deploy\n" +
293
+ "runs after CI. Safe to re-run."
294
+ );
295
+ }
296
+
297
+ let root = process.cwd();
298
+
299
+ function shipArgs(args) {
300
+ const passthrough = [];
301
+ if (args.base) passthrough.push("--base", args.base);
302
+ if (args["no-rebase"]) passthrough.push("--no-rebase");
303
+ if (args["no-gate"]) passthrough.push("--no-gate");
304
+ if (args["no-ci-wait"]) passthrough.push("--no-ci-wait");
305
+ return passthrough;
306
+ }
307
+
308
+ function main() {
309
+ const args = parseArgs(process.argv.slice(2));
310
+ if (args.help) return usage();
311
+
312
+ const found = args.root ? path.resolve(args.root) : findRoot(process.cwd());
313
+ if (!found) return fail("finalize: no git repository found (no .git in this tree or its parents).");
314
+ root = found;
315
+
316
+ const base = args.base || "main";
317
+ const branch = out("git", ["rev-parse", "--abbrev-ref", "HEAD"], { cwd: root });
318
+ if (!branch) return fail("finalize: could not resolve the current branch.");
319
+ if (branch === "main" || branch === "master") {
320
+ return fail(
321
+ `finalize: refusing to finalize "${branch}" — that is the integration branch.\n` +
322
+ " Run finalize from the feature worktree."
323
+ );
324
+ }
325
+
326
+ const feature = args.feature || featureFromBranch(branch);
327
+ if (!feature) {
328
+ return fail(
329
+ `finalize: could not derive a feature id from branch "${branch}".\n` +
330
+ " Pass --feature <id> explicitly."
331
+ );
332
+ }
333
+
334
+ const shipScript = path.join(root, "scripts", "ship.js");
335
+ if (!fs.existsSync(shipScript)) {
336
+ return fail(`finalize: ${path.relative(root, shipScript)} not found — is the harness deployed in this project?`);
337
+ }
338
+
339
+ const closed = args.closed || handoffOutcome(feature) || "shipped";
340
+ const archived = isArchived(feature);
341
+
342
+ if (args["dry-run"]) {
343
+ console.log("finalize (dry run)\n");
344
+ console.log(` root: ${root}`);
345
+ console.log(` feature: ${feature}`);
346
+ console.log(` branch: ${branch}`);
347
+ console.log(` closed: ${closed}`);
348
+ console.log(` archived: ${archived ? "yes" : "no"}`);
349
+ console.log(` landed: ${landedAlready(base) ? "yes" : "no"}`);
350
+ console.log(" plan: archive -> commit -> ship (rebase, gates, land, confirm CI)");
351
+ return;
352
+ }
353
+
354
+ // Idempotence: an already-archived row whose branch is contained in
355
+ // `origin/<base>` is done.
356
+ if (archived && landedAlready(base)) {
357
+ console.log(`[finalize] ${feature} is already archived and its branch is landed on ${base} — nothing to do.`);
358
+ return;
359
+ }
360
+
361
+ const backlogScript = path.join(root, "scripts", "backlog.js");
362
+
363
+ // 1. Archive the row (idempotent). The archive runs from inside the worktree,
364
+ // so it moves the row in THIS board and skips removing this checkout.
365
+ if (!archived) {
366
+ if (!fs.existsSync(backlogScript)) return fail(`finalize: ${path.relative(root, backlogScript)} not found.`);
367
+ if (!run(process.execPath, [backlogScript, "archive", feature, "--closed", closed], { cwd: root })) {
368
+ return fail(`finalize: could not archive ${feature} — fix the board error above, then re-run.`);
369
+ }
370
+ } else {
371
+ console.log(`[finalize] ${feature} is already archived — skipping the board write.`);
372
+ }
373
+
374
+ // 2. Commit the tail (board + CHANGELOG + handoff + remaining feature work)
375
+ // so `ship`'s dirty-tree guard cannot abort the documented one-command
376
+ // close. Staging is scoped: generated artifacts, symlinks and a stray
377
+ // worktree BACKLOG.md are refused instead of being swept in by `-A`.
378
+ const dirty = dirtyEntries();
379
+ if (dirty.length) {
380
+ console.log(
381
+ `\n[finalize] committing the finalization tail:\n` + dirty.map((l) => ` ${l}`).join("\n")
382
+ );
383
+ const staged = stageTail(feature, { includeBlocked: args["include-blocked"] });
384
+ if (!staged.ok) return fail("finalize: the finalization tail is not safe to stage — see above.");
385
+ if (!run("git", ["commit", "-m", `chore(${feature}): finalize — board + changelog`], { cwd: root })) {
386
+ return fail("finalize: the finalization commit failed.");
387
+ }
388
+ } else {
389
+ console.log("\n[finalize] tree already clean — nothing to commit.");
390
+ }
391
+
392
+ // 3. Ship: rebase, gates, direct land, and a bounded CI-green wait.
393
+ if (!run(process.execPath, [shipScript, ...shipArgs(args)], { cwd: root })) {
394
+ return fail(
395
+ "finalize: ship did not complete. If the push landed but CI is unconfirmed, re-run:\n" +
396
+ ` npm run finalize -- --feature ${feature}`
397
+ );
398
+ }
399
+
400
+ // 4. Close the loop that used to be a session-ending remark: converge the
401
+ // main checkout and name every leftover worktree explicitly.
402
+ closeOut(base, feature);
403
+
404
+ console.log(`\n[finalize] ${feature} landed + CI green.`);
405
+ }
406
+
407
+ if (require.main === module) {
408
+ try {
409
+ main();
410
+ } catch (e) {
411
+ console.error("finalize: " + (e && e.message ? e.message : e));
412
+ process.exit(1);
413
+ }
414
+ }
415
+
416
+ module.exports = { featureFromBranch, handoffOutcome };