opencode-agent-harness 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (169) hide show
  1. package/CHANGELOG.md +23 -0
  2. package/LICENSE +21 -0
  3. package/README.md +590 -2
  4. package/bin/agent-harness.js +3059 -0
  5. package/contrib/global-plugins/README.md +49 -0
  6. package/contrib/global-plugins/harness-freshness.ts +355 -0
  7. package/package.json +48 -4
  8. package/templates/.agents/AGENTS.md +204 -0
  9. package/templates/.agents/features/INDEX.md +10 -0
  10. package/templates/.agents/handoffs/README.md +87 -0
  11. package/templates/.agents/memory/dev-loop.md +59 -0
  12. package/templates/.agents/memory/domain-map.md +29 -0
  13. package/templates/.agents/memory/environments.md +35 -0
  14. package/templates/.agents/memory/flow-map.md +23 -0
  15. package/templates/.agents/memory/history.md +7 -0
  16. package/templates/.agents/memory/locations.md +14 -0
  17. package/templates/.agents/memory/model-routing.md +261 -0
  18. package/templates/.agents/memory/orchestration.md +183 -0
  19. package/templates/.agents/memory/owned-files.md +19 -0
  20. package/templates/.agents/memory/product-principles.md +37 -0
  21. package/templates/.agents/memory/quality-parameters.md +37 -0
  22. package/templates/.agents/memory/stack-versions.md +35 -0
  23. package/templates/.agents/memory/test-design-parameters.md +36 -0
  24. package/templates/.agents/nightly.json +17 -0
  25. package/templates/.agents/qa-plans/README.md +70 -0
  26. package/templates/.agents/qa-runs/README.md +21 -0
  27. package/templates/.agents/reviews/README.md +47 -0
  28. package/templates/.agents/rules/00-operating.md +199 -0
  29. package/templates/.agents/skills/data-engineer/SKILL.md +31 -0
  30. package/templates/.agents/skills/devops-engineer/SKILL.md +50 -0
  31. package/templates/.agents/skills/diagnostics-expert/SKILL.md +44 -0
  32. package/templates/.agents/skills/docs/SKILL.md +140 -0
  33. package/templates/.agents/skills/features/SKILL.md +187 -0
  34. package/templates/.agents/skills/frontend-engineer/SKILL.md +81 -0
  35. package/templates/.agents/skills/handoff/SKILL.md +85 -0
  36. package/templates/.agents/skills/mobile-engineer/SKILL.md +101 -0
  37. package/templates/.agents/skills/planner/SKILL.md +112 -0
  38. package/templates/.agents/skills/product-manager/SKILL.md +115 -0
  39. package/templates/.agents/skills/qa-architect/SKILL.md +224 -0
  40. package/templates/.agents/skills/qa-runner/SKILL.md +64 -0
  41. package/templates/.agents/skills/security-engineer/SKILL.md +53 -0
  42. package/templates/.agents/skills/system-architect/SKILL.md +42 -0
  43. package/templates/.agents/skills/ui-designer/SKILL.md +71 -0
  44. package/templates/.github/workflows/ci.yml +148 -0
  45. package/templates/.github/workflows/deploy-uat.yml +95 -0
  46. package/templates/.github/workflows/nightly.yml +83 -0
  47. package/templates/.github/workflows/uat-health.yml +41 -0
  48. package/templates/.husky/pre-push +23 -0
  49. package/templates/.ignore +28 -0
  50. package/templates/.opencode/agents/data-engineer.md +37 -0
  51. package/templates/.opencode/agents/devops-engineer.md +37 -0
  52. package/templates/.opencode/agents/diagnostics-expert.md +37 -0
  53. package/templates/.opencode/agents/docs.md +37 -0
  54. package/templates/.opencode/agents/features.md +21 -0
  55. package/templates/.opencode/agents/frontend-engineer.md +37 -0
  56. package/templates/.opencode/agents/handoff.md +21 -0
  57. package/templates/.opencode/agents/mobile-engineer.md +37 -0
  58. package/templates/.opencode/agents/planner.md +34 -0
  59. package/templates/.opencode/agents/product-manager.md +29 -0
  60. package/templates/.opencode/agents/qa-architect.md +27 -0
  61. package/templates/.opencode/agents/qa-runner.md +17 -0
  62. package/templates/.opencode/agents/security-engineer.md +37 -0
  63. package/templates/.opencode/agents/system-architect.md +37 -0
  64. package/templates/.opencode/agents/ui-designer.md +37 -0
  65. package/templates/.opencode/commands/board.md +15 -0
  66. package/templates/.opencode/commands/checkpoint.md +25 -0
  67. package/templates/.opencode/commands/feature.md +56 -0
  68. package/templates/.opencode/commands/finish.md +36 -0
  69. package/templates/.opencode/commands/next.md +49 -0
  70. package/templates/.opencode/commands/report.md +55 -0
  71. package/templates/.opencode/commands/resume.md +39 -0
  72. package/templates/.opencode/commands/switch-model.md +34 -0
  73. package/templates/.opencode/commands/tidy.md +49 -0
  74. package/templates/.opencode/plugins/backlog-notify.ts +57 -0
  75. package/templates/.opencode/plugins/backlog.ts +272 -0
  76. package/templates/.opencode/plugins/checkpoint.ts +160 -0
  77. package/templates/.opencode/plugins/context-guard.ts +1164 -0
  78. package/templates/.opencode/plugins/diff.ts +85 -0
  79. package/templates/.opencode/plugins/gates.ts +71 -0
  80. package/templates/.opencode/plugins/job-notify.ts +241 -0
  81. package/templates/.opencode/plugins/orient.ts +67 -0
  82. package/templates/.opencode/plugins/session.ts +89 -0
  83. package/templates/.opencode/plugins/wait.ts +101 -0
  84. package/templates/.opencode/plugins/where.ts +70 -0
  85. package/templates/.opencode/skills/bounded-explore/SKILL.md +38 -0
  86. package/templates/.opencode/skills/dev-loop/SKILL.md +87 -0
  87. package/templates/.vercelignore +16 -0
  88. package/templates/AGENTS.md +27 -0
  89. package/templates/BACKLOG.md +95 -0
  90. package/templates/docs/ci-cd-pipeline.md +81 -0
  91. package/templates/docs/gates.md +128 -0
  92. package/templates/docs/mcp-integrations.md +97 -0
  93. package/templates/docs/mobile-testing.md +555 -0
  94. package/templates/docs/nightly-testing.md +106 -0
  95. package/templates/docs/wsl-optimizations.md +290 -0
  96. package/templates/opencode.json +188 -0
  97. package/templates/scripts/agent-report.js +541 -0
  98. package/templates/scripts/agent-search.sh +117 -0
  99. package/templates/scripts/backlog.js +1864 -0
  100. package/templates/scripts/board-service.sh +207 -0
  101. package/templates/scripts/checkpoint.js +290 -0
  102. package/templates/scripts/finalize.js +277 -0
  103. package/templates/scripts/nightly.js +913 -0
  104. package/templates/scripts/orient.js +514 -0
  105. package/templates/scripts/qa/board-client.js +260 -0
  106. package/templates/scripts/qa/board-lib.js +96 -0
  107. package/templates/scripts/qa/board-sync.js +469 -0
  108. package/templates/scripts/qa/capacity-lib.js +916 -0
  109. package/templates/scripts/qa/check-backlog.js +427 -0
  110. package/templates/scripts/qa/check-capacity.js +85 -0
  111. package/templates/scripts/qa/check-ci-policy.js +164 -0
  112. package/templates/scripts/qa/check-concurrency.js +344 -0
  113. package/templates/scripts/qa/check-dispatch-config.js +296 -0
  114. package/templates/scripts/qa/check-docs.js +284 -0
  115. package/templates/scripts/qa/check-integrate.js +98 -0
  116. package/templates/scripts/qa/check-linger.js +160 -0
  117. package/templates/scripts/qa/check-prefix-stability.js +183 -0
  118. package/templates/scripts/qa/check-product.js +177 -0
  119. package/templates/scripts/qa/check-qa-plan.js +378 -0
  120. package/templates/scripts/qa/check-qa-scripts.js +85 -0
  121. package/templates/scripts/qa/check-quality.js +249 -0
  122. package/templates/scripts/qa/check-test-wiring.js +253 -0
  123. package/templates/scripts/qa/ci-triage.js +346 -0
  124. package/templates/scripts/qa/ci-usage-lib.js +185 -0
  125. package/templates/scripts/qa/ci-wait-lib.js +294 -0
  126. package/templates/scripts/qa/command-classifier.js +552 -0
  127. package/templates/scripts/qa/context-guard-core.js +1618 -0
  128. package/templates/scripts/qa/diff.js +174 -0
  129. package/templates/scripts/qa/feature-scaffold.js +224 -0
  130. package/templates/scripts/qa/fixtures/backlog.md +104 -0
  131. package/templates/scripts/qa/governance.js +174 -0
  132. package/templates/scripts/qa/hash-file.js +32 -0
  133. package/templates/scripts/qa/lease-lib.js +263 -0
  134. package/templates/scripts/qa/merge-backlog.js +324 -0
  135. package/templates/scripts/qa/mobile-e2e/analyze-timings.js +300 -0
  136. package/templates/scripts/qa/mobile-e2e/apk-cache.js +420 -0
  137. package/templates/scripts/qa/mobile-e2e/backend-build-cache.js +203 -0
  138. package/templates/scripts/qa/mobile-e2e/boot-emulator.sh +432 -0
  139. package/templates/scripts/qa/mobile-e2e/build-apk.sh +210 -0
  140. package/templates/scripts/qa/mobile-e2e/check-flows.js +453 -0
  141. package/templates/scripts/qa/mobile-e2e/config.yaml +18 -0
  142. package/templates/scripts/qa/mobile-e2e/device-down.sh +88 -0
  143. package/templates/scripts/qa/mobile-e2e/device-up.sh +258 -0
  144. package/templates/scripts/qa/mobile-e2e/ios-simulator-down.sh +72 -0
  145. package/templates/scripts/qa/mobile-e2e/ios-simulator-up.sh +153 -0
  146. package/templates/scripts/qa/mobile-e2e/job-events.js +181 -0
  147. package/templates/scripts/qa/mobile-e2e/prewarm.sh +56 -0
  148. package/templates/scripts/qa/mobile-e2e/run-detached.sh +222 -0
  149. package/templates/scripts/qa/mobile-e2e/run-maestro.js +1543 -0
  150. package/templates/scripts/qa/mobile-e2e/ui-dump.js +327 -0
  151. package/templates/scripts/qa/models.allowlist.txt +32 -0
  152. package/templates/scripts/qa/provider-stats.js +878 -0
  153. package/templates/scripts/qa/run-clean.js +83 -0
  154. package/templates/scripts/qa/run-gates.js +212 -0
  155. package/templates/scripts/qa/run-loop.js +220 -0
  156. package/templates/scripts/qa/session-recon.js +512 -0
  157. package/templates/scripts/qa/store-lib.js +324 -0
  158. package/templates/scripts/qa/tool-lib.js +134 -0
  159. package/templates/scripts/qa/where.js +214 -0
  160. package/templates/scripts/qa/wslconfig-merge.js +157 -0
  161. package/templates/scripts/serve.js +1328 -0
  162. package/templates/scripts/setup-nightly.sh +185 -0
  163. package/templates/scripts/setup-tmpfs.sh +374 -0
  164. package/templates/scripts/ship.js +586 -0
  165. package/templates/scripts/switch-reasoning-model.ps1 +101 -0
  166. package/templates/scripts/switch-reasoning-model.sh +104 -0
  167. package/templates/scripts/wait-for.js +342 -0
  168. package/templates/scripts/wsl-gpu.sh +180 -0
  169. package/templates/scripts/wsl-tune.sh +261 -0
@@ -0,0 +1,586 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ /*
4
+ * ship — deterministic branch lander (no LLM).
5
+ *
6
+ * Direct-land flow (the bootstrap-simple cycle for a one-person shop): a session
7
+ * ends by rebasing its gated branch onto the integration branch and pushing it
8
+ * straight to `main`, then waiting only for CI to go green on the landed SHA.
9
+ * There is no PR, no landing label, no merge train, and no deploy watch — the
10
+ * deploy workflow is triggered by CI success on `main` (workflow_run), so the
11
+ * session never has to babysit a 10–20 minute asynchronous tail.
12
+ *
13
+ * 1. refuse `main` (never ship the integration branch) or a dirty tree;
14
+ * a `.agents/handoffs/*` checkpoint left by a budget pause is the one
15
+ * exception — it is auto-committed so the documented resume can run;
16
+ * 2. integrate early — `git fetch origin` + `git rebase origin/<base>`;
17
+ * 3. run the branch gates (default: `test:integrate`, else `test:backlog` +
18
+ * `test:concurrency` when the project defines them);
19
+ * 4. land: `git push origin HEAD:<base>` (a fast-forward). If another session
20
+ * landed first, the push is rejected non-fast-forward — re-fetch + rebase
21
+ * and retry, up to `maxLandAttempts`;
22
+ * 5. wait (bounded) for CI to go green on the landed SHA. The deploy runs
23
+ * after CI, so an unconfirmed CI is the only blocker ship reports.
24
+ *
25
+ * Usage:
26
+ * node scripts/ship.js [--base main] [--gate "cmd"]... [--root dir]
27
+ * [--no-rebase] [--no-gate] [--no-ci-wait]
28
+ * [--ci-timeout <min>] [--ci-poll <sec>]
29
+ *
30
+ * CI watch is on by default. `--no-ci-wait` stops after landing (a deliberate
31
+ * pause — verify with `gh run list`), it is NOT a completion. `.harness.json`
32
+ * overrides: `shipCiWorkflow` (default: the workflow named `CI`),
33
+ * `shipCiTimeoutMinutes` (default 20), `shipCiPollSeconds` (default 15).
34
+ *
35
+ * Test seams (never set in normal use): `HARNESS_SHIP_GH_BIN` (alternate `gh`),
36
+ * `HARNESS_SHIP_CI_NO_SLEEP=1` (skip the poll sleeps),
37
+ * `HARNESS_SHIP_CI_TIMEOUT_MS` / `HARNESS_SHIP_CI_POLL_MS` (timings).
38
+ */
39
+ const fs = require("fs");
40
+ const os = require("os");
41
+ const path = require("path");
42
+ const { spawnSync } = require("child_process");
43
+ const boardSync = require("./qa/board-sync.js");
44
+ const { withLock } = require("./backlog.js");
45
+ const ciWait = require("./qa/ci-wait-lib.js");
46
+
47
+ function fail(message) {
48
+ console.error(message);
49
+ process.exitCode = 1;
50
+ }
51
+
52
+ /* Run a command, streaming its output. Returns the exit status (0 = ok). */
53
+ function run(cmd, args, opts) {
54
+ console.log(`\n$ ${[cmd, ...args].join(" ")}`);
55
+ const result = spawnSync(cmd, args, { stdio: "inherit", ...(opts || {}) });
56
+ return result.status === 0;
57
+ }
58
+
59
+ /* Run a command and capture trimmed stdout (empty string on failure). */
60
+ function out(cmd, args, opts) {
61
+ const result = spawnSync(cmd, args, {
62
+ encoding: "utf8",
63
+ ...(opts || {}),
64
+ });
65
+ return result.status === 0 ? String(result.stdout || "").trim() : "";
66
+ }
67
+
68
+ function has(cmd) {
69
+ return spawnSync(cmd, ["--version"], { stdio: "ignore" }).status === 0;
70
+ }
71
+
72
+ /* The path in a `git status --porcelain` line (`XY <path>`). Robust to the
73
+ * leading space `out()` trims off the FIRST line of a captured status: match the
74
+ * status code(s) + separator rather than assuming a fixed column. */
75
+ function porcelainPath(line) {
76
+ const m = line.match(/^\s*[A-Z?!]{1,2}\s+(.*)$/);
77
+ return (m ? m[1] : line).trim().replace(/^"|"$/g, "");
78
+ }
79
+
80
+ /* The machine-written session handoff a budget-paused checkpoint leaves
81
+ * uncommitted. It is the one path `ship` auto-commits: leaving it dirty makes
82
+ * the documented resume (`npm run ship`) abort at the dirty-tree guard before it
83
+ * can land — the re-engagement loop (code committed, checkpoint dirty, ship
84
+ * refuses). Any other dirty tracked file still fails. */
85
+ function isHandoffPath(p) {
86
+ return /^\.agents\/handoffs\//.test(p);
87
+ }
88
+
89
+ /* Stage + commit handoff-only dirt so the branch lands clean. */
90
+ function commitSessionHandoffs(root, entries, branch) {
91
+ const paths = entries.map(porcelainPath);
92
+ console.log(
93
+ `\n[handoff] committing the session handoff checkpoint so the branch is clean: ${paths.join(", ")}`
94
+ );
95
+ if (!run("git", ["add", "--", ...paths], { cwd: root })) return false;
96
+ return run("git", ["commit", "-m", `docs(${branch}): session checkpoint`], { cwd: root });
97
+ }
98
+
99
+ /* Append-only files whose conflicts are safe to auto-resolve during the landing
100
+ * rebase: two sessions that each appended an entry at the top (CHANGELOG) or a
101
+ * line (owned-files) collide on the same hunk. A union merge keeps every line
102
+ * from both sides, so the one-call `finalize` contract survives a concurrent
103
+ * landing — F-303 and F-305 both hit `UU CHANGELOG.md` and had to resolve by
104
+ * hand. Any other conflict is still left to the operator. */
105
+ const APPEND_ONLY_CONFLICTS = ["CHANGELOG.md", ".agents/memory/owned-files.md"];
106
+
107
+ function conflictedPaths(root) {
108
+ return out("git", ["diff", "--name-only", "--diff-filter=U"], { cwd: root })
109
+ .split(/\r?\n/)
110
+ .filter(Boolean);
111
+ }
112
+
113
+ /* Union-merge one conflicted append-only file (drop exact duplicate lines,
114
+ * preserve order + the rest of both sides) and stage it. */
115
+ function unionResolveFile(root, rel) {
116
+ const stage = (n) => {
117
+ const r = spawnSync("git", ["show", `:${n}:${rel}`], { cwd: root, encoding: "utf8" });
118
+ return r.status === 0 ? String(r.stdout || "") : "";
119
+ };
120
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "ship-union-"));
121
+ const write = (name, text) => {
122
+ const p = path.join(dir, name);
123
+ fs.writeFileSync(p, text, "utf8");
124
+ return p;
125
+ };
126
+ const r = spawnSync(
127
+ "git",
128
+ ["merge-file", "-p", "--union", write("ours", stage(2)), write("base", stage(1)), write("theirs", stage(3))],
129
+ { encoding: "utf8" }
130
+ );
131
+ const mergedRaw = String(r.stdout || "");
132
+ if (!mergedRaw || /^<{7}|^={7}|^>{7}/m.test(mergedRaw)) {
133
+ console.error(`[ship] could not union-resolve ${rel} (unexpected merge output).`);
134
+ return false;
135
+ }
136
+ const seen = new Set();
137
+ const merged = mergedRaw
138
+ .split("\n")
139
+ .filter((line) => {
140
+ if (line.trim() === "") return true;
141
+ if (seen.has(line)) return false;
142
+ seen.add(line);
143
+ return true;
144
+ })
145
+ .join("\n");
146
+ fs.writeFileSync(path.join(root, rel), merged.endsWith("\n") ? merged : merged + "\n", "utf8");
147
+ run("git", ["add", "--", rel], { cwd: root });
148
+ console.log(`[ship] auto-resolved append-only conflict: ${rel}`);
149
+ return true;
150
+ }
151
+
152
+ /* Rebase onto origin/<base>, auto-resolving append-only conflicts and
153
+ * continuing. Returns true when the rebase completed. */
154
+ function rebaseOntoMain(root, base) {
155
+ if (run("git", ["rebase", `origin/${base}`], { cwd: root })) return true;
156
+ for (let guard = 0; guard < 20; guard++) {
157
+ const conflicted = conflictedPaths(root);
158
+ if (conflicted.length === 0) {
159
+ fail(
160
+ `ship: rebase onto origin/${base} did not complete — inspect \`git status\` and run \`git rebase --continue\`.`
161
+ );
162
+ return false;
163
+ }
164
+ const unresolved = conflicted.filter((p) => !APPEND_ONLY_CONFLICTS.includes(p));
165
+ if (unresolved.length > 0) {
166
+ fail(
167
+ `ship: rebase onto origin/${base} has conflicts in ${unresolved.join(", ")}.\n` +
168
+ " Resolve them, `git rebase --continue`, then re-run `npm run ship`."
169
+ );
170
+ return false;
171
+ }
172
+ for (const rel of conflicted) if (!unionResolveFile(root, rel)) return false;
173
+ const cont = spawnSync("git", ["rebase", "--continue"], {
174
+ cwd: root,
175
+ encoding: "utf8",
176
+ env: Object.assign({}, process.env, { GIT_EDITOR: "true" }),
177
+ });
178
+ if (cont.status === 0) return true;
179
+ }
180
+ fail(`ship: rebase onto origin/${base} could not be auto-resolved.`);
181
+ return false;
182
+ }
183
+
184
+ /* The `gh` binary (overridable for tests). */
185
+ function ghBin() { return ciWait.ghBin();
186
+ }
187
+
188
+ /* Synchronous sleep — a poll loop must not need async/await. `Atomics.wait` is
189
+ * a real blocking wait (setTimeout would not block the event loop). The test
190
+ * seam skips it so the watch tests run instantly. */
191
+ function sleepSync(ms) {
192
+ return ciWait.sleepSync(ms);
193
+ }
194
+
195
+ /* Run a `gh` command and parse its JSON stdout. Returns `{ ok, data, error }`:
196
+ * `ok: false` on any failure (dead cwd, non-zero exit, no gh, malformed JSON)
197
+ * with `error` carrying the real reason — the caller decides whether that is
198
+ * fatal. Never prints, so poll loops stay quiet. The cwd is checked explicitly
199
+ * because a deleted working directory (a feature worktree pruned mid-watch)
200
+ * makes `spawnSync` fail with an opaque error and every poll silently return
201
+ * nothing — the F-252 phantom CI timeout. */
202
+ function ghJson(cwd, args) {
203
+ return ciWait.ghJson(cwd, args);
204
+ }
205
+
206
+ /* Read the `name:` of each workflow file under `.github/workflows`. Used to
207
+ * find the CI workflow whose green run confirms the landing. Best-effort:
208
+ * a file without a `name:` is skipped. */
209
+ function workflowNames(root) {
210
+ return ciWait.workflowNames(root);
211
+ }
212
+
213
+ /* The CI workflow whose green run on the landed SHA is the completion signal:
214
+ * `.harness.json` `shipCiWorkflow` when set, else the workflow named `CI`. */
215
+ function ciWorkflow(root) {
216
+ const config = readJson(path.join(root, ".harness.json"));
217
+ if (config && config.shipCiWorkflow) return String(config.shipCiWorkflow);
218
+ return workflowNames(root).find((n) => /^ci$/i.test(n)) || null;
219
+ }
220
+
221
+ function ciConfig(root, args) {
222
+ return ciWait.ciConfig(root, args);
223
+ }
224
+
225
+ /* Consecutive `gh` failures tolerated before the watch says why it is stuck.
226
+ * `gh` can hiccup transiently, so a single failed poll is not news; a run of
227
+ * them means the watch is blind and the operator should know. */
228
+ const CI_GH_FAILURE_WARN = ciWait.CI_GH_FAILURE_WARN;
229
+
230
+ /* Wait for the CI workflow's run on the landed SHA to complete. Returns 0 when
231
+ * green (success/skipped/neutral), 1 otherwise (failed, timeout, or a watch
232
+ * that went blind — an unobserved gate is not a passed gate).
233
+ *
234
+ * Delegates to the shared `scripts/qa/ci-wait-lib.js` (one implementation for
235
+ * ship and `wait-for.js`); kept as a named `function waitCi` so the ship
236
+ * behavior contract — and the drift guard that asserts it — stay in this file. */
237
+ function waitCi(root, sha, opts) {
238
+ return ciWait.waitCi(root, sha, opts);
239
+ }
240
+
241
+ /* Walk up from `startDir` to the repo root (the first `.git` entry). */
242
+ function findRoot(startDir) {
243
+ let dir = path.resolve(startDir || process.cwd());
244
+ for (;;) {
245
+ if (fs.existsSync(path.join(dir, ".git"))) return dir;
246
+ const parent = path.dirname(dir);
247
+ if (parent === dir) return null;
248
+ dir = parent;
249
+ }
250
+ }
251
+
252
+ function readJson(p) {
253
+ try {
254
+ return JSON.parse(fs.readFileSync(p, "utf8"));
255
+ } catch {
256
+ return null;
257
+ }
258
+ }
259
+
260
+ /* The MAIN worktree's path (first entry of `git worktree list --porcelain`), or
261
+ * null. `ship` runs in the feature worktree, so converging the board means
262
+ * acting on the main checkout's working tree. */
263
+ function mainWorktreeRoot(root) {
264
+ const res = spawnSync("git", ["-C", root, "worktree", "list", "--porcelain"], { encoding: "utf8" });
265
+ if (res.status !== 0) return null;
266
+ const first = String(res.stdout || "").split(/\r?\n/).find((l) => l.startsWith("worktree "));
267
+ return first ? first.slice("worktree ".length).trim() : null;
268
+ }
269
+
270
+ /* After a confirmed landing, bring the MAIN checkout level with origin/<base> so
271
+ * its BACKLOG.md reflects the archived row. The shared board-sync module owns
272
+ * the logic — reconcile the board row-aware (an archived-upstream row wins over
273
+ * a stale local take; local-only rows survive), clear redundant non-board dirt,
274
+ * fast-forward, and publish local-only rows so a later `git checkout --` cannot
275
+ * wipe them (the F-147 incident). The short read-modify-write is serialized with
276
+ * the board lock so it cannot race a concurrent `backlog` command. Any OTHER
277
+ * dirty/detached/diverged main is reported with the exact manual fix, never
278
+ * force-resolved. */
279
+ function convergeMainCheckout(root, base, cachedMain) {
280
+ // Accept the main path resolved before landing: if the feature worktree was
281
+ // pruned mid-watch, walking it again here would fail and lose the reconcile.
282
+ const main = cachedMain || mainWorktreeRoot(root);
283
+ if (!main) return;
284
+ const upstream = `origin/${base}`;
285
+ try {
286
+ withLock(main, () => {
287
+ const conv = boardSync.convergeCanonical(main, upstream, { fetch: true });
288
+ for (const note of conv.notes) console.log(`[ship] ${note}`);
289
+ if (!conv.ok) {
290
+ console.warn(
291
+ `[ship] landed, but the main checkout could not be converged — resolve it, then: git -C ${main} merge --ff-only ${upstream}`
292
+ );
293
+ return;
294
+ }
295
+ if (conv.canPublish === false) {
296
+ console.warn(`[ship] main checkout board reconciled but main is diverged — not publishing`);
297
+ return;
298
+ }
299
+ const pub = boardSync.publishBoard(
300
+ main,
301
+ upstream,
302
+ "chore(board): publish local-only rows reconciled from the main checkout"
303
+ );
304
+ if (pub.published && pub.committed) {
305
+ console.log(`\n[ship] fast-forwarded the main checkout and published its local-only board rows.`);
306
+ } else if (!pub.published) {
307
+ console.warn(
308
+ `[ship] the main checkout board carries local-only rows that could not be pushed — publish them when the remote is reachable: git -C ${main} push origin HEAD:${base}`
309
+ );
310
+ } else {
311
+ console.log(`\n[ship] fast-forwarded the main checkout — its board now reflects the landed row.`);
312
+ }
313
+ });
314
+ } catch (e) {
315
+ console.warn(`[ship] could not lock the main checkout to converge its board: ${e.message}`);
316
+ }
317
+ }
318
+
319
+ function projectScripts(root) {
320
+ const pkg = readJson(path.join(root, "package.json"));
321
+ return (pkg && pkg.scripts) || {};
322
+ }
323
+
324
+ /* Process gates that must run on every ship regardless of whether the project's
325
+ * pre-push hook is installed. A missing hook (fresh worktree, `--no-verify`)
326
+ * must never silently drop the board/QA/docs gates — `ship` is the deterministic
327
+ * finalizer, so it owns them itself. */
328
+ const PROCESS_GATES = [
329
+ "test:dispatch",
330
+ "test:governance",
331
+ "test:concurrency",
332
+ "test:capacity",
333
+ "test:backlog",
334
+ "test:wiring",
335
+ "test:product",
336
+ "test:docs",
337
+ "test:quality",
338
+ ];
339
+
340
+ /* Default gate commands. `test:integrate` is the harness one-shot. The process
341
+ * gates are run by `ship` ONLY when no pre-push hook is installed: when a hook
342
+ * exists, `git push` runs the project's own battery (which may deliberately
343
+ * exclude a gate that is red pending another fix), and duplicating it would both
344
+ * double the cost and impose a gate the project chose not to enforce yet. With no
345
+ * hook, `ship` owns the process gates so a missing hook cannot silently drop
346
+ * them. `test:qa-plan` is diff-scoped and must compare against the integration
347
+ * base — `--base=HEAD` would be a trivially empty diff. */
348
+ function defaultGates(root, base) {
349
+ const scripts = projectScripts(root);
350
+ const gates = [];
351
+ if (scripts["test:integrate"]) gates.push("npm run test:integrate");
352
+ if (!prePushInstalled(root)) {
353
+ for (const name of PROCESS_GATES) {
354
+ if (scripts[name]) gates.push(`npm run ${name}`);
355
+ }
356
+ if (scripts["test:qa-plan"]) gates.push(`npm run test:qa-plan -- --base=origin/${base}`);
357
+ }
358
+ return gates;
359
+ }
360
+
361
+ /* Whether a pre-push hook is installed (husky via core.hooksPath, or the
362
+ * default hooks dir). Only used for an advisory: project test gates stay in the
363
+ * hook/CI, while the process gates above never depend on it. */
364
+ function prePushInstalled(root) {
365
+ if (fs.existsSync(path.join(root, ".husky", "_", "pre-push"))) return true;
366
+ if (fs.existsSync(path.join(root, ".husky", "pre-push"))) return true;
367
+ const hooksPath = out("git", ["config", "core.hooksPath"], { cwd: root });
368
+ if (hooksPath) return true;
369
+ const p = out("git", ["rev-parse", "--git-path", "hooks/pre-push"], { cwd: root });
370
+ return !!(p && fs.existsSync(path.resolve(root, p)));
371
+ }
372
+
373
+ /* How many times to re-fetch/rebase-and-retry a non-fast-forward land when a
374
+ * concurrent session pushed to the integration branch first. */
375
+ const MAX_LAND_ATTEMPTS = 3;
376
+
377
+ /* Land HEAD on `origin/<base>` by fast-forward push. Re-fetches + rebases on a
378
+ * non-fast-forward rejection (another session landed first) and retries.
379
+ * Returns the landed SHA, or null on failure. */
380
+ function landOnMain(root, base, args) {
381
+ for (let attempt = 1; attempt <= MAX_LAND_ATTEMPTS; attempt++) {
382
+ if (!args["no-rebase"] && attempt > 1) {
383
+ if (!run("git", ["fetch", "origin"], { cwd: root })) return null;
384
+ const counts = out("git", ["rev-list", "--left-right", "--count", `HEAD...origin/${base}`], { cwd: root });
385
+ const behind = counts ? parseInt(counts.trim().split(/\s+/)[1], 10) || 0 : 0;
386
+ if (behind > 0) {
387
+ if (!rebaseOntoMain(root, base)) return null;
388
+ }
389
+ }
390
+ const res = spawnSync("git", ["push", "origin", `HEAD:${base}`], {
391
+ cwd: root,
392
+ encoding: "utf8",
393
+ });
394
+ if (res.status === 0) {
395
+ if (res.stdout) process.stdout.write(String(res.stdout));
396
+ if (res.stderr) process.stderr.write(String(res.stderr));
397
+ return out("git", ["rev-parse", "HEAD"], { cwd: root });
398
+ }
399
+ const text = `${res.stdout || ""}\n${res.stderr || ""}`;
400
+ const raced = /non-fast-forward|fetch first|tip of your current branch is behind|\[rejected\]/i.test(text);
401
+ if (raced && !args["no-rebase"] && attempt < MAX_LAND_ATTEMPTS) {
402
+ console.log(
403
+ `\n[land] ${base} moved (another session landed first) — re-fetching and retrying (attempt ${attempt + 1}/${MAX_LAND_ATTEMPTS})...`
404
+ );
405
+ continue;
406
+ }
407
+ fail(
408
+ `ship: \`git push origin HEAD:${base}\` failed:\n` +
409
+ text
410
+ .split(/\r?\n/)
411
+ .filter(Boolean)
412
+ .map((l) => ` ${l}`)
413
+ .join("\n")
414
+ );
415
+ return null;
416
+ }
417
+ return null;
418
+ }
419
+
420
+ function parseArgs(argv) {
421
+ const args = { gates: [] };
422
+ for (let i = 0; i < argv.length; i++) {
423
+ const a = argv[i];
424
+ if (a === "--base") args.base = argv[++i];
425
+ else if (a === "--gate") args.gates.push(argv[++i]);
426
+ else if (a === "--root") args.root = argv[++i];
427
+ else if (a === "--no-ci-wait") args["no-ci-wait"] = true;
428
+ else if (a === "--ci-timeout") args["ci-timeout"] = argv[++i];
429
+ else if (a === "--ci-poll") args["ci-poll"] = argv[++i];
430
+ else if (a === "--no-rebase") args["no-rebase"] = true;
431
+ else if (a === "--no-gate") args["no-gate"] = true;
432
+ else if (a === "--help" || a === "-h") args.help = true;
433
+ else args._.push(a);
434
+ }
435
+ return args;
436
+ }
437
+
438
+ function usage() {
439
+ console.log(
440
+ "ship — integrate, gate, and land the feature branch directly on the integration branch (no LLM)\n\n" +
441
+ " node scripts/ship.js [--base main] [--gate \"<cmd>\"]... [--root <dir>]\n" +
442
+ " [--no-rebase] [--no-gate] [--no-ci-wait]\n" +
443
+ " [--ci-timeout <min>] [--ci-poll <sec>]\n\n" +
444
+ "Never runs on main. Rebases on origin/<base>, runs the branch gates, then lands\n" +
445
+ "`HEAD:<base>` with a fast-forward push (retrying after a concurrent landing).\n" +
446
+ "Then waits (bounded) for CI to go green on the landed SHA; the deploy runs\n" +
447
+ "after CI succeeds. `--no-ci-wait` stops after landing — a deliberate pause, not\n" +
448
+ "a completed task. Resume by re-running `npm run ship` (it is idempotent)."
449
+ );
450
+ }
451
+
452
+ function main() {
453
+ const args = parseArgs(process.argv.slice(2));
454
+ if (args.help) {
455
+ usage();
456
+ return;
457
+ }
458
+ const root = args.root ? path.resolve(args.root) : findRoot(process.cwd());
459
+ if (!root) return fail("ship: no git repository found (no .git in this tree or its parents).");
460
+
461
+ // Resolve the main worktree NOW, while the feature checkout still exists: the
462
+ // CI watch and the board reconcile both run from main, so they survive the
463
+ // feature worktree being pruned mid-watch (the F-252 race).
464
+ const mainRoot = mainWorktreeRoot(root) || root;
465
+
466
+ const base = args.base || "main";
467
+ const branch = out("git", ["rev-parse", "--abbrev-ref", "HEAD"], { cwd: root });
468
+ if (!branch) return fail("ship: could not resolve the current branch.");
469
+
470
+ if (branch === base || branch === "main" || branch === "master") {
471
+ return fail(
472
+ `ship: refusing to ship "${branch}" — that is the integration branch.\n` +
473
+ " Work and ship a feature branch."
474
+ );
475
+ }
476
+
477
+ const entries = out("git", ["status", "--porcelain"], { cwd: root })
478
+ .split(/\r?\n/)
479
+ .filter((l) => l && !l.startsWith("!!"));
480
+ // A budget pause writes the checkpoint into `.agents/handoffs/<id>.md`; commit
481
+ // that machine-written artifact here so the documented resume path works. Any
482
+ // other dirty tracked file is still a hard stop (never ship WIP).
483
+ const foreignTracked = entries.filter((l) => !l.startsWith("??") && !isHandoffPath(porcelainPath(l)));
484
+ if (foreignTracked.length > 0) {
485
+ return fail(
486
+ "ship: uncommitted tracked changes — commit first (the tests belong in the tree you ship):\n" +
487
+ foreignTracked.map((l) => ` ${l}`).join("\n")
488
+ );
489
+ }
490
+ const handoffs = entries.filter((l) => isHandoffPath(porcelainPath(l)));
491
+ if (handoffs.length > 0 && !commitSessionHandoffs(root, handoffs, branch)) {
492
+ return fail("ship: could not commit the session handoff checkpoint — commit it by hand, then re-run.");
493
+ }
494
+
495
+ if (!args["no-rebase"]) {
496
+ if (!run("git", ["fetch", "origin"], { cwd: root })) return fail("ship: `git fetch origin` failed.");
497
+ if (!rebaseOntoMain(root, base)) return;
498
+ }
499
+
500
+ if (!args["no-gate"]) {
501
+ const gates = args.gates.length ? args.gates : defaultGates(root, base);
502
+ if (gates.length === 0) {
503
+ console.warn("ship: no branch gates found (set --gate or define test:integrate) — skipping.");
504
+ }
505
+ for (const gate of gates) {
506
+ if (!run(gate, [], { cwd: root, shell: true })) return fail(`ship: gate failed: ${gate}`);
507
+ }
508
+ if (!prePushInstalled(root)) {
509
+ console.warn(
510
+ "ship: no pre-push hook detected — project test gates (e.g. test:quick) will run in CI only.\n" +
511
+ " Install the hook (husky) or rely on CI as the backstop."
512
+ );
513
+ }
514
+ }
515
+
516
+ const sha = landOnMain(root, base, args);
517
+ if (!sha) return; // landOnMain set the process exit code
518
+
519
+ console.log(`\n[land] landed ${branch} -> origin/${base} (${sha.slice(0, 7)}).`);
520
+
521
+ if (args["no-ci-wait"]) {
522
+ console.log(
523
+ " CI is NOT confirmed (deliberate --no-ci-wait pause). Verify with:\n" +
524
+ ` gh run list --workflow "${ciWorkflow(root) || "CI"}" --commit ${sha}`
525
+ );
526
+ convergeMainCheckout(root, base, mainRoot);
527
+ return;
528
+ }
529
+
530
+ const { timeoutMs, pollMs } = ciConfig(root, args);
531
+ const code = waitCi(root, sha, {
532
+ timeoutMs,
533
+ pollMs,
534
+ workflow: ciWorkflow(root),
535
+ cwd: mainRoot,
536
+ });
537
+ // Converge the main checkout even when CI is red: a failed/flaky run must not
538
+ // strand main's board behind (that is how it silently drifts stale).
539
+ convergeMainCheckout(root, base, mainRoot);
540
+ if (code !== 0) {
541
+ process.exitCode = code;
542
+ return;
543
+ }
544
+ console.log("\n[ship] landed + CI green.");
545
+ pruneShippedWorktree(mainRoot, branch, root);
546
+ }
547
+
548
+ /* Remove the just-shipped feature's worktree now that its branch is landed and
549
+ * CI is green, so a session can clean up after itself instead of leaving the
550
+ * checkout behind for a later `worktree-prune` (the 0.1.90 regression: the live
551
+ * session's own pointer made the cleanup command keep the finished worktree
552
+ * until the session closed). `backlog worktree-prune` owns every safety rule
553
+ * (clean checkout, landed/merged branch, never a worktree a DIFFERENT live
554
+ * session owns, never a session's own `--open` root), so ship merely asks it to
555
+ * prune this branch from the MAIN checkout. `--self` authorizes THIS session to
556
+ * release its own pointer; that is safe here because ship passes it only after
557
+ * the CI watch is over, so there is no mid-watch checkout to blind (F-252). A
558
+ * no-op with the manual fallback when the worktree cannot be removed safely.
559
+ * Runs from `mainRoot` so it survives this process's cwd being the worktree:
560
+ * removing the cwd would break any later relative-path work. `--dir` pins the
561
+ * prune to THIS checkout, so a `--self` run never converges a sibling session's
562
+ * worktree. */
563
+ function pruneShippedWorktree(mainRoot, branch, worktreeDir) {
564
+ const backlog = path.join(mainRoot, "scripts", "backlog.js");
565
+ if (!fs.existsSync(backlog)) {
566
+ console.log("\n[ship] feature worktree left in place (scripts/backlog.js not found in main).");
567
+ return;
568
+ }
569
+ const res = spawnSync(
570
+ process.execPath,
571
+ [backlog, "worktree-prune", branch, "--self", "--dir", worktreeDir, "--no-fetch"],
572
+ { cwd: mainRoot, encoding: "utf8" }
573
+ );
574
+ if (/pruned /.test(res.stdout || "")) {
575
+ console.log("\n[ship] pruned the feature worktree (branch landed + CI green).");
576
+ } else {
577
+ console.log(
578
+ "\n[ship] feature worktree left in place. Clean up when this session ends:\n" +
579
+ " node scripts/backlog.js worktree-prune"
580
+ );
581
+ }
582
+ const text = `${res.stdout || ""}${res.stderr || ""}`.trim();
583
+ for (const line of text.split(/\r?\n/).filter(Boolean)) console.log(` ${line}`);
584
+ }
585
+
586
+ main();
@@ -0,0 +1,101 @@
1
+ param(
2
+ [Parameter(Mandatory = $true)][string]$Target
3
+ )
4
+
5
+ $ErrorActionPreference = "Stop"
6
+
7
+ $root = Split-Path -Parent $PSScriptRoot
8
+
9
+ $aliases = @{
10
+ "go" = "opencode-go/deepseek-v4.1-flash"
11
+ "go-flash" = "opencode-go/deepseek-v4.1-flash"
12
+ "go-deepseek" = "opencode-go/deepseek-v4.1-flash"
13
+ "go-pro" = "opencode-go/deepseek-v4-pro"
14
+ "deepseek" = "deepseek/deepseek-flash"
15
+ "flash" = "deepseek/deepseek-flash"
16
+ "deepseek-flash" = "deepseek/deepseek-flash"
17
+ "direct" = "deepseek/deepseek-flash"
18
+ "deepseek-pro" = "deepseek/deepseek-v4-pro"
19
+ "deepseek-v4-pro" = "deepseek/deepseek-v4-pro"
20
+ "pro" = "deepseek/deepseek-v4-pro"
21
+ "nvidia" = "nvidia/moonshotai/kimi-k3"
22
+ "kimi" = "nvidia/moonshotai/kimi-k3"
23
+ "kimi-k3" = "nvidia/moonshotai/kimi-k3"
24
+ "nemotron" = "nvidia/nemotron-3-ultra-550b-a55b:free"
25
+ "nemotron-ultra" = "nvidia/nemotron-3-ultra-550b-a55b:free"
26
+ "openrouter" = "openrouter/minimax/minimax-m3"
27
+ "or" = "openrouter/minimax/minimax-m3"
28
+ "minimax-m3" = "openrouter/minimax/minimax-m3"
29
+ "m3" = "openrouter/minimax/minimax-m3"
30
+ }
31
+
32
+ $targetModel = $Target
33
+ if ($aliases.ContainsKey($Target.ToLowerInvariant())) {
34
+ $targetModel = $aliases[$Target.ToLowerInvariant()]
35
+ }
36
+ elseif (-not ($targetModel -match "^[a-zA-Z0-9._-]+/")) {
37
+ $targetModel = "deepseek/$targetModel"
38
+ }
39
+
40
+ # The replace list is derived from the alias map so any model the script can
41
+ # switch TO is also a model it can switch FROM. Without this, a value the user
42
+ # hand-set (or set via a previous alias) but that is not in the find list is
43
+ # invisible to the regex and the script silently reports "already set".
44
+ $reasoningModels = @($aliases.Values | Sort-Object -Unique)
45
+
46
+ $files = @(
47
+ "opencode.json",
48
+ ".opencode/agents/planner.md",
49
+ ".opencode/agents/system-architect.md",
50
+ ".opencode/agents/security-engineer.md",
51
+ ".opencode/agents/diagnostics-expert.md",
52
+ ".opencode/agents/product-manager.md",
53
+ ".opencode/agents/qa-architect.md"
54
+ )
55
+
56
+ $changed = @()
57
+ $skipped = @()
58
+ foreach ($rel in $files) {
59
+ $path = Join-Path $root $rel
60
+ if (-not (Test-Path -LiteralPath $path)) {
61
+ Write-Warning "missing: $rel"
62
+ continue
63
+ }
64
+ $content = Get-Content -LiteralPath $path -Raw
65
+ $new = $content
66
+ $findHits = $false
67
+ foreach ($m in $reasoningModels) {
68
+ if ($m -eq $targetModel) { continue }
69
+ if ($new -match [regex]::Escape($m)) { $findHits = $true }
70
+ $new = $new -replace [regex]::Escape($m), $targetModel
71
+ }
72
+ if ($new -ne $content) {
73
+ Set-Content -LiteralPath $path -Value $new -NoNewline
74
+ $changed += $rel
75
+ }
76
+ elseif (-not $findHits -and $content -notmatch ([regex]::Escape($targetModel))) {
77
+ # content != target, but the regex never matched — the current value is a
78
+ # model id the script doesn't know how to replace. Surface it instead of
79
+ # printing a misleading "already set".
80
+ $current = ($content | Select-String -Pattern 'model:\s*"?([A-Za-z0-9._:\-/]+)"?' -AllMatches).Matches |
81
+ ForEach-Object { $_.Groups[1].Value } |
82
+ Where-Object { $_ -ne $targetModel -and $_ -notin $reasoningModels } |
83
+ Select-Object -First 1
84
+ $skipped += "$rel (current value `"$current`" not in replace list; edit by hand or add an alias)"
85
+ }
86
+ }
87
+
88
+ Write-Output ("Switched reasoning-tier model -> {0}" -f $targetModel)
89
+ if ($changed.Count -gt 0) {
90
+ Write-Output "Updated:"
91
+ $changed | ForEach-Object { Write-Output " - $_" }
92
+ }
93
+ if ($skipped.Count -gt 0) {
94
+ Write-Warning "Skipped (current value not in replace list):"
95
+ $skipped | ForEach-Object { Write-Warning " - $_" }
96
+ Write-Warning "Add an alias to scripts/switch-reasoning-model.ps1 (or edit the file by hand)."
97
+ }
98
+ if ($changed.Count -eq 0 -and $skipped.Count -eq 0) {
99
+ Write-Output "No files changed (already set)."
100
+ }
101
+ Write-Output "Restart opencode for the change to take effect."