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,469 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ /*
4
+ * board-sync — the single home for bringing the canonical checkout's BACKLOG.md
5
+ * into agreement with `origin/<base>`, and for publishing board edits back.
6
+ *
7
+ * The board is a single markdown file duplicated in every checkout. Feature work
8
+ * lands on `origin/main` from its own worktree, so the main checkout's copy
9
+ * drifts. Two failure modes recur under concurrent work:
10
+ *
11
+ * 1. A board mutation read a stale working copy and "resurrected" a row that
12
+ * had already been archived upstream (it still showed Open locally).
13
+ * 2. The post-landing fast-forward bailed on ANY tracked dirty file other than
14
+ * BACKLOG.md — even one whose working content was already identical to
15
+ * upstream — so main silently drifted further behind every landing.
16
+ *
17
+ * This module provides the primitives both `backlog.js` (mutations) and
18
+ * `ship.js` (post-landing convergence) share, so they can never disagree:
19
+ *
20
+ * - classifyDirty(): split tracked dirt into board / redundant / genuine.
21
+ * - reconcileWorkingBoard(): row-aware 3-way merge of the working board
22
+ * against the upstream board (an archived-upstream row wins; local-only
23
+ * rows survive). Delegates to merge-backlog.js.
24
+ * - convergeCanonical(): fetch, clear redundant dirt, reconcile, fast-forward.
25
+ * Fails closed on genuine local changes rather than skipping silently.
26
+ * - publishBoard(): commit the reconciled board and fast-forward push it with
27
+ * a bounded fetch+rebase retry, so the board is never left as working-tree
28
+ * dirt that a later `git checkout --` could wipe.
29
+ *
30
+ * No locking here: `withLock` lives in backlog.js (the board write path owner);
31
+ * callers wrap convergeCanonical/publishBoard in it.
32
+ */
33
+ const fs = require("fs");
34
+ const path = require("path");
35
+ const { spawnSync } = require("child_process");
36
+
37
+ const MAX_PUBLISH_ATTEMPTS = 3;
38
+
39
+ // Repo-scoping GIT_* vars can leak in from a parent git hook (husky's pre-push
40
+ // exports GIT_DIR); `git -C <root>` must always target `root`, so drop them.
41
+ const REPO_SCOPING_GIT_VARS = [
42
+ "GIT_DIR",
43
+ "GIT_WORK_TREE",
44
+ "GIT_INDEX_FILE",
45
+ "GIT_COMMON_DIR",
46
+ "GIT_PREFIX",
47
+ "GIT_OBJECT_DIRECTORY",
48
+ "GIT_ALTERNATE_OBJECT_DIRECTORIES",
49
+ "GIT_CEILING_DIRECTORIES",
50
+ ];
51
+
52
+ function hermeticGitEnv() {
53
+ const env = { ...process.env };
54
+ for (const k of REPO_SCOPING_GIT_VARS) delete env[k];
55
+ return env;
56
+ }
57
+
58
+ function gitCmd(root, args, opts) {
59
+ return spawnSync("git", ["-C", root, ...args], {
60
+ encoding: "utf8",
61
+ timeout: (opts && opts.timeout) || 0,
62
+ env: hermeticGitEnv(),
63
+ });
64
+ }
65
+
66
+ function gitOut(root, args, opts) {
67
+ const r = gitCmd(root, args, opts);
68
+ return r.status === 0 ? String(r.stdout || "").trim() : "";
69
+ }
70
+
71
+ /* The MAIN worktree's path (first entry of `git worktree list --porcelain`), or
72
+ * null. A feature session runs in a linked worktree, so canonical-board logic
73
+ * (`convergeCanonical` / `publishBoard`) applies only to the main checkout. */
74
+ function mainWorktreeRoot(root) {
75
+ const r = gitCmd(root, ["worktree", "list", "--porcelain"]);
76
+ if (r.status !== 0) return null;
77
+ const first = String(r.stdout || "").split(/\r?\n/).find((l) => l.startsWith("worktree "));
78
+ return first ? first.slice("worktree ".length).trim() : null;
79
+ }
80
+
81
+ function isCanonicalCheckout(root) {
82
+ const main = mainWorktreeRoot(root);
83
+ return !!main && path.resolve(main) === path.resolve(root);
84
+ }
85
+
86
+ function currentUpstream(root) {
87
+ return gitOut(root, ["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{u}"]);
88
+ }
89
+
90
+ /* `<tree-ish>:<path>` as text, or "" when the ref/path does not exist. */
91
+ function gitShow(root, spec) {
92
+ const r = gitCmd(root, ["show", spec]);
93
+ return r.status === 0 ? String(r.stdout || "") : "";
94
+ }
95
+
96
+ function readWorkingBoard(root) {
97
+ try {
98
+ return fs.readFileSync(path.join(root, "BACKLOG.md"), "utf8");
99
+ } catch {
100
+ return "";
101
+ }
102
+ }
103
+
104
+ /* A porcelain v2-ish path from a `git status --porcelain` line: strips the XY
105
+ * status, any rename arrow, and surrounding quotes. */
106
+ function porcelainPath(line) {
107
+ let p = line.slice(3);
108
+ const arrow = p.indexOf(" -> ");
109
+ if (arrow !== -1) p = p.slice(arrow + 4);
110
+ p = p.trim();
111
+ if (p.startsWith('"') && p.endsWith('"')) {
112
+ p = p
113
+ .slice(1, -1)
114
+ .replace(/\\([0-7]{3})/g, (_, o) => String.fromCharCode(parseInt(o, 8)))
115
+ .replace(/\\(.)/g, "$1");
116
+ }
117
+ return p;
118
+ }
119
+
120
+ function dirtyTracked(root) {
121
+ const r = gitCmd(root, ["status", "--porcelain", "--untracked-files=no"]);
122
+ if (r.status !== 0) return [];
123
+ return String(r.stdout || "")
124
+ .split(/\r?\n/)
125
+ .filter(Boolean)
126
+ .map((line) => ({ line, path: porcelainPath(line) }));
127
+ }
128
+
129
+ /* 3-way reconcile of the working board against the upstream board. `base` is the
130
+ * checkout's committed board, `ours` the working board, `theirs` the landed
131
+ * upstream board. Returns merge-backlog's `{ ok, board, dropped, conflicts }`;
132
+ * when there is no upstream board (or no merge module) it degrades to `ours`. */
133
+ function reconcileWorkingBoard(root, upstream) {
134
+ const ours = readWorkingBoard(root);
135
+ const theirs = gitShow(root, `${upstream}:BACKLOG.md`);
136
+ const base = gitShow(root, "HEAD:BACKLOG.md");
137
+ if (!theirs) return { ok: true, board: ours, dropped: [], conflicts: [] };
138
+ let rec;
139
+ try {
140
+ rec = require("./merge-backlog.js").reconcileBoard(base, ours, theirs);
141
+ } catch (e) {
142
+ return { ok: false, board: ours, dropped: [], conflicts: [], error: e.message };
143
+ }
144
+ return rec;
145
+ }
146
+
147
+ /* Split the canonical checkout's tracked dirt: the board, non-board paths whose
148
+ * working content is byte-identical to upstream (safe to discard), and genuine
149
+ * local edits (which must never be force-resolved). */
150
+ function classifyDirty(root, upstream) {
151
+ const entries = dirtyTracked(root);
152
+ const board = [];
153
+ const redundant = [];
154
+ const genuine = [];
155
+ for (const e of entries) {
156
+ if (e.path === "BACKLOG.md") {
157
+ board.push(e.path);
158
+ continue;
159
+ }
160
+ const diff = gitCmd(root, ["diff", "--quiet", upstream, "--", e.path]);
161
+ if (diff.status === 0) redundant.push(e.path);
162
+ else genuine.push(e.path);
163
+ }
164
+ return { board, redundant, genuine, entries };
165
+ }
166
+
167
+ function clearRedundant(root, upstream, paths) {
168
+ if (!paths || !paths.length) return true;
169
+ const r = gitCmd(root, ["checkout", upstream, "--", ...paths]);
170
+ return r.status === 0;
171
+ }
172
+
173
+ /* True when every commit HEAD carries over `upstream` touches only BACKLOG.md —
174
+ * i.e. the checkout is ahead solely because of unpublished board commits, which
175
+ * can be replayed onto upstream automatically. Any other commit means genuine
176
+ * divergence and must not be silently rewritten. */
177
+ function aheadOnlyBoard(root, upstream) {
178
+ const r = gitCmd(root, ["rev-list", `${upstream}..HEAD`]);
179
+ if (r.status !== 0) return false;
180
+ const commits = String(r.stdout || "").split(/\r?\n/).filter(Boolean);
181
+ for (const c of commits) {
182
+ const files = gitCmd(root, ["show", "--name-only", "--format=", c]);
183
+ if (files.status !== 0) return false;
184
+ const paths = String(files.stdout || "")
185
+ .split(/\r?\n/)
186
+ .map((s) => s.trim())
187
+ .filter(Boolean);
188
+ if (paths.some((p) => p !== "BACKLOG.md")) return false;
189
+ }
190
+ return true;
191
+ }
192
+
193
+ /* True when every commit HEAD carries over `upstream` is a local harness deploy
194
+ * commit (`chore(harness): …`). Those are safe to replay onto upstream with a
195
+ * plain rebase — the object was a deploy that committed but never pushed while
196
+ * upstream advanced with feature landings (the F-303/F-304 "not publishing"
197
+ * drift). Arbitrary local work is NOT replayed: it keeps the report-only path. */
198
+ function aheadOnlyHarness(root, upstream) {
199
+ const r = gitCmd(root, ["log", "--format=%s", `${upstream}..HEAD`]);
200
+ if (r.status !== 0) return false;
201
+ const subjects = String(r.stdout || "").split(/\r?\n/).filter(Boolean);
202
+ return subjects.length > 0 && subjects.every((s) => /^chore\(harness\)/.test(s));
203
+ }
204
+
205
+ /* Replay local board-only commits onto `upstream` using the same row-aware
206
+ * reconcile as the rest of the module — NOT `git rebase`, which depends on the
207
+ * per-clone merge driver being registered (a fresh clone that never ran
208
+ * `agent-harness update` has no driver, so a textual rebase conflicts on the
209
+ * board). The checkout is advanced with `reset --hard` so HEAD, the index, and
210
+ * the working tree move together: a `reset --soft` left the index/worktree
211
+ * stale, turning every landed upstream non-board commit into a permanent staged
212
+ * reverse-diff that corrupted the canonical checkout. Genuine uncommitted
213
+ * non-board changes fail the replay closed (never silently discarded). Returns
214
+ * `{ ok, changed, blockedBy }`. Idempotent: when HEAD already descends from
215
+ * `upstream` and its board already equals the reconciled board, the local board
216
+ * commits are already replayed, so the reset+recommit is skipped (otherwise it
217
+ * would mint a fresh SHA — same tree, new committer timestamp — on every call,
218
+ * churning a new board commit per mutation). */
219
+ function replayBoardOnly(root, upstream) {
220
+ const ours = readWorkingBoard(root);
221
+ const mb = gitCmd(root, ["merge-base", upstream, "HEAD"]);
222
+ const baseRef = mb.status === 0 ? String(mb.stdout || "").trim() : "";
223
+ const base = baseRef ? gitShow(root, `${baseRef}:BACKLOG.md`) : gitShow(root, "HEAD:BACKLOG.md");
224
+ const theirs = gitShow(root, `${upstream}:BACKLOG.md`);
225
+ const rec = require("./merge-backlog.js").reconcileBoard(base, ours, theirs);
226
+ if (!rec.ok) return { ok: false, conflicts: rec.conflicts || [] };
227
+
228
+ // A hard reset must never discard uncommitted work: the only tracked dirt we
229
+ // may clear is the board itself (already reconciled into `rec.board` above).
230
+ // Any other dirty path is genuine local state — fail closed so the caller
231
+ // cannot move the checkout and silently lose it.
232
+ const blockedBy = dirtyTracked(root)
233
+ .map((e) => e.path)
234
+ .filter((p) => p !== "BACKLOG.md");
235
+ if (blockedBy.length) return { ok: false, conflicts: [], blockedBy };
236
+
237
+ // Idempotency short-circuit: if HEAD already descends from `upstream` and its
238
+ // board already equals the reconciled board, the local board-only commits are
239
+ // already replayed. Reset+recommit would only mint a fresh SHA (identical tree,
240
+ // new committer timestamp) on every call, so `backlog.js sync`/every mutation
241
+ // would churn a new board commit. Nothing to do — leave HEAD untouched.
242
+ const upstreamSha = gitOut(root, ["rev-parse", upstream]);
243
+ const mergeBase = gitOut(root, ["merge-base", upstream, "HEAD"]);
244
+ if (upstreamSha && mergeBase === upstreamSha && gitShow(root, "HEAD:BACKLOG.md") === rec.board) {
245
+ return { ok: true, changed: false };
246
+ }
247
+
248
+ const reset = gitCmd(root, ["reset", "--hard", upstream]);
249
+ if (reset.status !== 0) return { ok: false, conflicts: [], blockedBy: [] };
250
+ fs.writeFileSync(path.join(root, "BACKLOG.md"), rec.board, "utf8");
251
+ gitCmd(root, ["add", "--", "BACKLOG.md"]);
252
+ const staged = gitCmd(root, ["diff", "--cached", "--quiet", "--", "BACKLOG.md"]);
253
+ if (staged.status === 0) return { ok: true, changed: false };
254
+ const c = gitCmd(root, ["commit", "-q", "-m", "chore(board): replay local board rows", "--", "BACKLOG.md"]);
255
+ return { ok: c.status === 0, changed: c.status === 0 };
256
+ }
257
+
258
+ /* Bring the canonical checkout level with `upstream`, reconciling the board
259
+ * row-aware. Returns `{ ok, behind, ahead, board, dropped, notes, blockedBy,
260
+ * canPublish }`:
261
+ *
262
+ * - `ok:false` — the board cannot be made safe (genuine uncommitted non-board
263
+ * changes block the fast-forward, or the board itself has an unresolvable
264
+ * row conflict). The caller must NOT mutate.
265
+ * - `canPublish:false` — the board was reconciled but the checkout is diverged
266
+ * (local non-board commits), so pushing would land unrelated work. The
267
+ * caller mutates locally and skips the publish.
268
+ *
269
+ * Reconcile runs BEFORE any fast-forward and does not need a clean tree, so a
270
+ * mutation never reads a stale board even when the checkout can't move. */
271
+ function convergeCanonical(root, upstream, opts) {
272
+ const notes = [];
273
+ if (!opts || opts.fetch !== false) {
274
+ gitCmd(root, ["fetch", "--quiet", "origin"], { timeout: 10000 });
275
+ }
276
+ const counts = gitCmd(root, ["rev-list", "--left-right", "--count", `HEAD...${upstream}`]);
277
+ if (counts.status !== 0) {
278
+ return { ok: true, behind: 0, ahead: 0, notes, board: readWorkingBoard(root), canPublish: false };
279
+ }
280
+ const [ahead, behind] = String(counts.stdout || "")
281
+ .trim()
282
+ .split(/\s+/)
283
+ .map((n) => parseInt(n, 10) || 0);
284
+
285
+ if (ahead > 0) {
286
+ if (aheadOnlyBoard(root, upstream)) {
287
+ const replay = replayBoardOnly(root, upstream);
288
+ if (!replay.ok) {
289
+ if (replay.blockedBy && replay.blockedBy.length) {
290
+ notes.push(
291
+ `main is ${behind} behind ${upstream} but has uncommitted changes to ${replay.blockedBy.join(", ")} — ` +
292
+ `commit or discard them, then run: node scripts/backlog.js sync`
293
+ );
294
+ } else {
295
+ notes.push(
296
+ `main has local board commits that could not be replayed onto ${upstream} — reconcile manually: git pull --rebase`
297
+ );
298
+ }
299
+ return {
300
+ ok: false,
301
+ behind,
302
+ ahead,
303
+ blockedBy: replay.blockedBy || replay.conflicts || [],
304
+ notes,
305
+ board: readWorkingBoard(root),
306
+ };
307
+ }
308
+ notes.push(`replayed ${ahead} local board commit(s) onto ${upstream}`);
309
+ return { ok: true, behind: 0, ahead: 0, notes, board: readWorkingBoard(root), canPublish: true };
310
+ }
311
+ // Diverged: local non-board commits. The common case is a local harness
312
+ // deploy commit that was never pushed while upstream advanced with feature
313
+ // landings — the note below already names `git pull --rebase` as the remedy,
314
+ // so do exactly that automatically when the tree is otherwise clean (board
315
+ // dirt is reconciled into `rec.board` first). A conflicting replay is
316
+ // aborted and stays manual, so genuine divergence is never silently
317
+ // rewritten. Without this, every board mutation skipped the publish and main
318
+ // drifted stale ("board: not published (main is diverged)", F-303/F-304).
319
+ const dirty = classifyDirty(root, upstream);
320
+ const rec = reconcileWorkingBoard(root, upstream);
321
+ if (!rec.ok) {
322
+ notes.push(`main checkout board has conflicting rows (${(rec.conflicts || []).join(", ") || "unknown"}) — resolve manually`);
323
+ return { ok: false, behind, ahead, blockedBy: rec.conflicts || [], notes, board: readWorkingBoard(root) };
324
+ }
325
+ let rebased = false;
326
+ if (dirty.genuine.length === 0 && aheadOnlyHarness(root, upstream)) {
327
+ const saved = readWorkingBoard(root);
328
+ gitCmd(root, ["checkout", "--", "BACKLOG.md"]);
329
+ const rebase = gitCmd(root, ["rebase", upstream]);
330
+ if (rebase.status === 0) {
331
+ rebased = true;
332
+ } else {
333
+ gitCmd(root, ["rebase", "--abort"]);
334
+ fs.writeFileSync(path.join(root, "BACKLOG.md"), saved, "utf8");
335
+ }
336
+ }
337
+ fs.writeFileSync(path.join(root, "BACKLOG.md"), rec.board, "utf8");
338
+ if (rebased) {
339
+ notes.push(`rebased ${ahead} local commit(s) onto ${upstream}`);
340
+ if (rec.dropped.length) notes.push(`reconciled its board (archived upstream: ${rec.dropped.join(", ")})`);
341
+ return { ok: true, behind: 0, ahead: 0, notes, board: rec.board, dropped: rec.dropped, canPublish: true };
342
+ }
343
+ if (rec.dropped.length) notes.push(`reconciled its board (archived upstream: ${rec.dropped.join(", ")})`);
344
+ notes.push(
345
+ `main is ${behind} behind and ${ahead} ahead of ${upstream} — local commits touch non-board files; ` +
346
+ `not publishing (reconcile manually: git pull --rebase)`
347
+ );
348
+ return { ok: true, behind, ahead, notes, board: rec.board, canPublish: false };
349
+ }
350
+
351
+ if (behind === 0) {
352
+ return { ok: true, behind: 0, ahead: 0, notes, board: readWorkingBoard(root), canPublish: true };
353
+ }
354
+
355
+ const dirty = classifyDirty(root, upstream);
356
+ if (dirty.genuine.length) {
357
+ notes.push(
358
+ `main is ${behind} behind ${upstream} but has local changes to ${dirty.genuine.join(", ")} — ` +
359
+ `commit or discard them, then run: node scripts/backlog.js sync`
360
+ );
361
+ return { ok: false, behind, ahead: 0, blockedBy: dirty.genuine, notes, board: readWorkingBoard(root) };
362
+ }
363
+ const rec = reconcileWorkingBoard(root, upstream);
364
+ if (!rec.ok) {
365
+ notes.push(`main checkout board has conflicting rows (${(rec.conflicts || []).join(", ") || "unknown"}) — resolve manually`);
366
+ return { ok: false, behind, ahead: 0, blockedBy: rec.conflicts || [], notes, board: readWorkingBoard(root) };
367
+ }
368
+ const saved = readWorkingBoard(root);
369
+ if (dirty.redundant.length) clearRedundant(root, upstream, dirty.redundant);
370
+ gitCmd(root, ["checkout", "--", "BACKLOG.md"]);
371
+ const ff = gitCmd(root, ["merge", "--ff-only", upstream]);
372
+ if (ff.status !== 0) {
373
+ fs.writeFileSync(path.join(root, "BACKLOG.md"), saved, "utf8");
374
+ notes.push(`main is ${behind} behind ${upstream} — could not fast-forward: ${(ff.stderr || ff.stdout || "").trim()}`);
375
+ return { ok: false, behind, ahead: 0, blockedBy: [], notes, board: saved };
376
+ }
377
+ fs.writeFileSync(path.join(root, "BACKLOG.md"), rec.board, "utf8");
378
+ notes.push(`fast-forwarded main to ${upstream} (${behind} commit(s))`);
379
+ if (rec.dropped.length) notes.push(`reconciled its board (archived upstream: ${rec.dropped.join(", ")})`);
380
+ return { ok: true, behind: 0, ahead: 0, notes, board: rec.board, dropped: rec.dropped, canPublish: true };
381
+ }
382
+
383
+ /* Paths publishBoard stages alongside the board (when tracked) so the owned-
384
+ * files registry never lingers as canonical dirt either. */
385
+ const PUBLISH_EXTRA_PATHS = [".agents/memory/owned-files.md"];
386
+
387
+ function trackedPath(root, rel) {
388
+ const r = gitCmd(root, ["ls-files", "--error-unmatch", "--", rel]);
389
+ return r.status === 0;
390
+ }
391
+
392
+ /* Commit the board (and any changed owned-files registry) and fast-forward push
393
+ * it, re-fetching + rebasing after a concurrent landing. Returns
394
+ * `{ published, committed, reason }`: `published:true` with reason "no change"
395
+ * when nothing needed committing; `published:false` when the commit/push could
396
+ * not complete (the commit may still exist locally — durable, just unpublished).
397
+ * `opts.deferPush` commits locally but skips the network push (reason
398
+ * "deferred"): the request path stays fast and a later `sync` publishes. */
399
+ function publishBoard(root, upstream, message, opts) {
400
+ const rels = ["BACKLOG.md", ...PUBLISH_EXTRA_PATHS.filter((p) => trackedPath(root, p))];
401
+ const add = gitCmd(root, ["add", "--", ...rels]);
402
+ if (add.status !== 0) return { published: false, committed: false, reason: "add-failed" };
403
+ const staged = gitCmd(root, ["diff", "--cached", "--quiet", "--", ...rels]);
404
+ let committed = false;
405
+ if (staged.status !== 0) {
406
+ const commit = gitCmd(root, ["commit", "-q", "-m", message, "--", ...rels]);
407
+ if (commit.status !== 0) return { published: false, committed: false, reason: "commit-failed" };
408
+ committed = true;
409
+ }
410
+ // Push whenever HEAD carries anything upstream does not — a rebase in
411
+ // convergeCanonical can leave a local board commit with a clean index, and it
412
+ // must still be published.
413
+ const counts = gitCmd(root, ["rev-list", "--left-right", "--count", `HEAD...${upstream}`]);
414
+ const ahead = counts.status === 0 ? parseInt(String(counts.stdout || "").trim().split(/\s+/)[0], 10) || 0 : 0;
415
+ if (ahead === 0) return { published: true, committed, reason: "no change" };
416
+ if (opts && opts.deferPush) return { published: false, committed, reason: "deferred" };
417
+
418
+ const base = upstream.includes("/") ? upstream.slice(upstream.indexOf("/") + 1) : upstream;
419
+ for (let attempt = 1; attempt <= MAX_PUBLISH_ATTEMPTS; attempt++) {
420
+ const push = gitCmd(root, ["push", "origin", `HEAD:${base}`]);
421
+ if (push.status === 0) return { published: true, committed, reason: "pushed" };
422
+ const text = `${push.stdout || ""}\n${push.stderr || ""}`;
423
+ if (
424
+ attempt < MAX_PUBLISH_ATTEMPTS &&
425
+ /non-fast-forward|fetch first|tip of your current branch is behind|\[rejected\]/i.test(text)
426
+ ) {
427
+ gitCmd(root, ["fetch", "--quiet", "origin"], { timeout: 10000 });
428
+ const replay = aheadOnlyBoard(root, upstream) ? replayBoardOnly(root, upstream) : { ok: false };
429
+ if (!replay.ok) return { published: false, committed, reason: "replay-conflict" };
430
+ continue;
431
+ }
432
+ return { published: false, committed, reason: "push-failed" };
433
+ }
434
+ return { published: false, committed, reason: "retries-exhausted" };
435
+ }
436
+
437
+ /* Read-only view for `list` / `next`: the working board reconciled against the
438
+ * last-known upstream, so an agent never decides from a stale board. Never
439
+ * writes. Returns `{ board, behind, ok }`. */
440
+ function displayBoard(root, upstream) {
441
+ const working = readWorkingBoard(root);
442
+ if (!upstream) return { board: working, behind: 0, ok: true };
443
+ const counts = gitCmd(root, ["rev-list", "--left-right", "--count", `HEAD...${upstream}`]);
444
+ if (counts.status !== 0) return { board: working, behind: 0, ok: true };
445
+ const [ahead, behind] = String(counts.stdout || "")
446
+ .trim()
447
+ .split(/\s+/)
448
+ .map((n) => parseInt(n, 10) || 0);
449
+ if (behind <= 0) return { board: working, behind, ok: true };
450
+ const rec = reconcileWorkingBoard(root, upstream);
451
+ return { board: rec.ok ? rec.board : working, behind, ok: rec.ok };
452
+ }
453
+
454
+ module.exports = {
455
+ gitCmd,
456
+ gitOut,
457
+ mainWorktreeRoot,
458
+ isCanonicalCheckout,
459
+ currentUpstream,
460
+ gitShow,
461
+ readWorkingBoard,
462
+ porcelainPath,
463
+ reconcileWorkingBoard,
464
+ classifyDirty,
465
+ clearRedundant,
466
+ convergeCanonical,
467
+ publishBoard,
468
+ displayBoard,
469
+ };