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,499 @@
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
+ /* First non-empty line of a git command's error output, for the publish
67
+ * failure note. A bare `reason` code ("add-failed") hid the real cause for
68
+ * weeks (F-004): the operator saw "remote unreachable" for a local `git add`
69
+ * rejection. */
70
+ function firstLine(r) {
71
+ return String((r && (r.stderr || r.stdout)) || "")
72
+ .split(/\r?\n/)
73
+ .find((l) => l.trim()) || "";
74
+ }
75
+
76
+ function gitOut(root, args, opts) {
77
+ const r = gitCmd(root, args, opts);
78
+ return r.status === 0 ? String(r.stdout || "").trim() : "";
79
+ }
80
+
81
+ /* The MAIN worktree's path (first entry of `git worktree list --porcelain`), or
82
+ * null. A feature session runs in a linked worktree, so canonical-board logic
83
+ * (`convergeCanonical` / `publishBoard`) applies only to the main checkout. */
84
+ function mainWorktreeRoot(root) {
85
+ const r = gitCmd(root, ["worktree", "list", "--porcelain"]);
86
+ if (r.status !== 0) return null;
87
+ const first = String(r.stdout || "").split(/\r?\n/).find((l) => l.startsWith("worktree "));
88
+ return first ? first.slice("worktree ".length).trim() : null;
89
+ }
90
+
91
+ function isCanonicalCheckout(root) {
92
+ const main = mainWorktreeRoot(root);
93
+ return !!main && path.resolve(main) === path.resolve(root);
94
+ }
95
+
96
+ function currentUpstream(root) {
97
+ return gitOut(root, ["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{u}"]);
98
+ }
99
+
100
+ /* `<tree-ish>:<path>` as text, or "" when the ref/path does not exist. */
101
+ function gitShow(root, spec) {
102
+ const r = gitCmd(root, ["show", spec]);
103
+ return r.status === 0 ? String(r.stdout || "") : "";
104
+ }
105
+
106
+ function readWorkingBoard(root) {
107
+ try {
108
+ return fs.readFileSync(path.join(root, "BACKLOG.md"), "utf8");
109
+ } catch {
110
+ return "";
111
+ }
112
+ }
113
+
114
+ /* A porcelain v2-ish path from a `git status --porcelain` line: strips the XY
115
+ * status, any rename arrow, and surrounding quotes. */
116
+ function porcelainPath(line) {
117
+ let p = line.slice(3);
118
+ const arrow = p.indexOf(" -> ");
119
+ if (arrow !== -1) p = p.slice(arrow + 4);
120
+ p = p.trim();
121
+ if (p.startsWith('"') && p.endsWith('"')) {
122
+ p = p
123
+ .slice(1, -1)
124
+ .replace(/\\([0-7]{3})/g, (_, o) => String.fromCharCode(parseInt(o, 8)))
125
+ .replace(/\\(.)/g, "$1");
126
+ }
127
+ return p;
128
+ }
129
+
130
+ function dirtyTracked(root) {
131
+ const r = gitCmd(root, ["status", "--porcelain", "--untracked-files=no"]);
132
+ if (r.status !== 0) return [];
133
+ return String(r.stdout || "")
134
+ .split(/\r?\n/)
135
+ .filter(Boolean)
136
+ .map((line) => ({ line, path: porcelainPath(line) }));
137
+ }
138
+
139
+ /* 3-way reconcile of the working board against the upstream board. `base` is the
140
+ * checkout's committed board, `ours` the working board, `theirs` the landed
141
+ * upstream board. Returns merge-backlog's `{ ok, board, dropped, conflicts }`;
142
+ * when there is no upstream board (or no merge module) it degrades to `ours`. */
143
+ function reconcileWorkingBoard(root, upstream) {
144
+ const ours = readWorkingBoard(root);
145
+ const theirs = gitShow(root, `${upstream}:BACKLOG.md`);
146
+ const base = gitShow(root, "HEAD:BACKLOG.md");
147
+ if (!theirs) return { ok: true, board: ours, dropped: [], conflicts: [] };
148
+ let rec;
149
+ try {
150
+ rec = require("./merge-backlog.js").reconcileBoard(base, ours, theirs);
151
+ } catch (e) {
152
+ return { ok: false, board: ours, dropped: [], conflicts: [], error: e.message };
153
+ }
154
+ return rec;
155
+ }
156
+
157
+ /* Split the canonical checkout's tracked dirt: the board, non-board paths whose
158
+ * working content is byte-identical to upstream (safe to discard), and genuine
159
+ * local edits (which must never be force-resolved). */
160
+ function classifyDirty(root, upstream) {
161
+ const entries = dirtyTracked(root);
162
+ const board = [];
163
+ const redundant = [];
164
+ const genuine = [];
165
+ for (const e of entries) {
166
+ if (e.path === "BACKLOG.md") {
167
+ board.push(e.path);
168
+ continue;
169
+ }
170
+ const diff = gitCmd(root, ["diff", "--quiet", upstream, "--", e.path]);
171
+ if (diff.status === 0) redundant.push(e.path);
172
+ else genuine.push(e.path);
173
+ }
174
+ return { board, redundant, genuine, entries };
175
+ }
176
+
177
+ function clearRedundant(root, upstream, paths) {
178
+ if (!paths || !paths.length) return true;
179
+ const r = gitCmd(root, ["checkout", upstream, "--", ...paths]);
180
+ return r.status === 0;
181
+ }
182
+
183
+ /* True when every commit HEAD carries over `upstream` touches only BACKLOG.md —
184
+ * i.e. the checkout is ahead solely because of unpublished board commits, which
185
+ * can be replayed onto upstream automatically. Any other commit means genuine
186
+ * divergence and must not be silently rewritten. */
187
+ function aheadOnlyBoard(root, upstream) {
188
+ const r = gitCmd(root, ["rev-list", `${upstream}..HEAD`]);
189
+ if (r.status !== 0) return false;
190
+ const commits = String(r.stdout || "").split(/\r?\n/).filter(Boolean);
191
+ for (const c of commits) {
192
+ const files = gitCmd(root, ["show", "--name-only", "--format=", c]);
193
+ if (files.status !== 0) return false;
194
+ const paths = String(files.stdout || "")
195
+ .split(/\r?\n/)
196
+ .map((s) => s.trim())
197
+ .filter(Boolean);
198
+ if (paths.some((p) => p !== "BACKLOG.md")) return false;
199
+ }
200
+ return true;
201
+ }
202
+
203
+ /* True when every commit HEAD carries over `upstream` is a local harness deploy
204
+ * commit (`chore(harness): …`). Those are safe to replay onto upstream with a
205
+ * plain rebase — the object was a deploy that committed but never pushed while
206
+ * upstream advanced with feature landings (the F-303/F-304 "not publishing"
207
+ * drift). Arbitrary local work is NOT replayed: it keeps the report-only path. */
208
+ function aheadOnlyHarness(root, upstream) {
209
+ const r = gitCmd(root, ["log", "--format=%s", `${upstream}..HEAD`]);
210
+ if (r.status !== 0) return false;
211
+ const subjects = String(r.stdout || "").split(/\r?\n/).filter(Boolean);
212
+ return subjects.length > 0 && subjects.every((s) => /^chore\(harness\)/.test(s));
213
+ }
214
+
215
+ /* Replay local board-only commits onto `upstream` using the same row-aware
216
+ * reconcile as the rest of the module — NOT `git rebase`, which depends on the
217
+ * per-clone merge driver being registered (a fresh clone that never ran
218
+ * `agent-harness update` has no driver, so a textual rebase conflicts on the
219
+ * board). The checkout is advanced with `reset --hard` so HEAD, the index, and
220
+ * the working tree move together: a `reset --soft` left the index/worktree
221
+ * stale, turning every landed upstream non-board commit into a permanent staged
222
+ * reverse-diff that corrupted the canonical checkout. Genuine uncommitted
223
+ * non-board changes fail the replay closed (never silently discarded). Returns
224
+ * `{ ok, changed, blockedBy }`. Idempotent: when HEAD already descends from
225
+ * `upstream` and its board already equals the reconciled board, the local board
226
+ * commits are already replayed, so the reset+recommit is skipped (otherwise it
227
+ * would mint a fresh SHA — same tree, new committer timestamp — on every call,
228
+ * churning a new board commit per mutation). */
229
+ function replayBoardOnly(root, upstream) {
230
+ const ours = readWorkingBoard(root);
231
+ const mb = gitCmd(root, ["merge-base", upstream, "HEAD"]);
232
+ const baseRef = mb.status === 0 ? String(mb.stdout || "").trim() : "";
233
+ const base = baseRef ? gitShow(root, `${baseRef}:BACKLOG.md`) : gitShow(root, "HEAD:BACKLOG.md");
234
+ const theirs = gitShow(root, `${upstream}:BACKLOG.md`);
235
+ const rec = require("./merge-backlog.js").reconcileBoard(base, ours, theirs);
236
+ if (!rec.ok) return { ok: false, conflicts: rec.conflicts || [] };
237
+
238
+ // A hard reset must never discard uncommitted work: the only tracked dirt we
239
+ // may clear is the board itself (already reconciled into `rec.board` above).
240
+ // Any other dirty path is genuine local state — fail closed so the caller
241
+ // cannot move the checkout and silently lose it.
242
+ const blockedBy = dirtyTracked(root)
243
+ .map((e) => e.path)
244
+ .filter((p) => p !== "BACKLOG.md");
245
+ if (blockedBy.length) return { ok: false, conflicts: [], blockedBy };
246
+
247
+ // Idempotency short-circuit: if HEAD already descends from `upstream` and its
248
+ // board already equals the reconciled board, the local board-only commits are
249
+ // already replayed. Reset+recommit would only mint a fresh SHA (identical tree,
250
+ // new committer timestamp) on every call, so `backlog.js sync`/every mutation
251
+ // would churn a new board commit. Nothing to do — leave HEAD untouched.
252
+ const upstreamSha = gitOut(root, ["rev-parse", upstream]);
253
+ const mergeBase = gitOut(root, ["merge-base", upstream, "HEAD"]);
254
+ if (upstreamSha && mergeBase === upstreamSha && gitShow(root, "HEAD:BACKLOG.md") === rec.board) {
255
+ return { ok: true, changed: false };
256
+ }
257
+
258
+ const reset = gitCmd(root, ["reset", "--hard", upstream]);
259
+ if (reset.status !== 0) return { ok: false, conflicts: [], blockedBy: [] };
260
+ fs.writeFileSync(path.join(root, "BACKLOG.md"), rec.board, "utf8");
261
+ gitCmd(root, ["add", "--", "BACKLOG.md"]);
262
+ const staged = gitCmd(root, ["diff", "--cached", "--quiet", "--", "BACKLOG.md"]);
263
+ if (staged.status === 0) return { ok: true, changed: false };
264
+ const c = gitCmd(root, ["commit", "-q", "-m", "chore(board): replay local board rows", "--", "BACKLOG.md"]);
265
+ return { ok: c.status === 0, changed: c.status === 0 };
266
+ }
267
+
268
+ /* Bring the canonical checkout level with `upstream`, reconciling the board
269
+ * row-aware. Returns `{ ok, behind, ahead, board, dropped, notes, blockedBy,
270
+ * canPublish }`:
271
+ *
272
+ * - `ok:false` — the board cannot be made safe (genuine uncommitted non-board
273
+ * changes block the fast-forward, or the board itself has an unresolvable
274
+ * row conflict). The caller must NOT mutate.
275
+ * - `canPublish:false` — the board was reconciled but the checkout is diverged
276
+ * (local non-board commits), so pushing would land unrelated work. The
277
+ * caller mutates locally and skips the publish.
278
+ *
279
+ * Reconcile runs BEFORE any fast-forward and does not need a clean tree, so a
280
+ * mutation never reads a stale board even when the checkout can't move. */
281
+ function convergeCanonical(root, upstream, opts) {
282
+ const notes = [];
283
+ if (!opts || opts.fetch !== false) {
284
+ gitCmd(root, ["fetch", "--quiet", "origin"], { timeout: 10000 });
285
+ }
286
+ const counts = gitCmd(root, ["rev-list", "--left-right", "--count", `HEAD...${upstream}`]);
287
+ if (counts.status !== 0) {
288
+ return { ok: true, behind: 0, ahead: 0, notes, board: readWorkingBoard(root), canPublish: false };
289
+ }
290
+ const [ahead, behind] = String(counts.stdout || "")
291
+ .trim()
292
+ .split(/\s+/)
293
+ .map((n) => parseInt(n, 10) || 0);
294
+
295
+ if (ahead > 0) {
296
+ if (aheadOnlyBoard(root, upstream)) {
297
+ const replay = replayBoardOnly(root, upstream);
298
+ if (!replay.ok) {
299
+ if (replay.blockedBy && replay.blockedBy.length) {
300
+ notes.push(
301
+ `main is ${behind} behind ${upstream} but has uncommitted changes to ${replay.blockedBy.join(", ")} — ` +
302
+ `commit or discard them, then run: node scripts/backlog.js sync`
303
+ );
304
+ } else {
305
+ notes.push(
306
+ `main has local board commits that could not be replayed onto ${upstream} — reconcile manually: git pull --rebase`
307
+ );
308
+ }
309
+ return {
310
+ ok: false,
311
+ behind,
312
+ ahead,
313
+ blockedBy: replay.blockedBy || replay.conflicts || [],
314
+ notes,
315
+ board: readWorkingBoard(root),
316
+ };
317
+ }
318
+ notes.push(`replayed ${ahead} local board commit(s) onto ${upstream}`);
319
+ return { ok: true, behind: 0, ahead: 0, notes, board: readWorkingBoard(root), canPublish: true };
320
+ }
321
+ // Diverged: local non-board commits. The common case is a local harness
322
+ // deploy commit that was never pushed while upstream advanced with feature
323
+ // landings — the note below already names `git pull --rebase` as the remedy,
324
+ // so do exactly that automatically when the tree is otherwise clean (board
325
+ // dirt is reconciled into `rec.board` first). A conflicting replay is
326
+ // aborted and stays manual, so genuine divergence is never silently
327
+ // rewritten. Without this, every board mutation skipped the publish and main
328
+ // drifted stale ("board: not published (main is diverged)", F-303/F-304).
329
+ const dirty = classifyDirty(root, upstream);
330
+ const rec = reconcileWorkingBoard(root, upstream);
331
+ if (!rec.ok) {
332
+ notes.push(`main checkout board has conflicting rows (${(rec.conflicts || []).join(", ") || "unknown"}) — resolve manually`);
333
+ return { ok: false, behind, ahead, blockedBy: rec.conflicts || [], notes, board: readWorkingBoard(root) };
334
+ }
335
+ let rebased = false;
336
+ if (dirty.genuine.length === 0 && aheadOnlyHarness(root, upstream)) {
337
+ const saved = readWorkingBoard(root);
338
+ gitCmd(root, ["checkout", "--", "BACKLOG.md"]);
339
+ const rebase = gitCmd(root, ["rebase", upstream]);
340
+ if (rebase.status === 0) {
341
+ rebased = true;
342
+ } else {
343
+ gitCmd(root, ["rebase", "--abort"]);
344
+ fs.writeFileSync(path.join(root, "BACKLOG.md"), saved, "utf8");
345
+ }
346
+ }
347
+ fs.writeFileSync(path.join(root, "BACKLOG.md"), rec.board, "utf8");
348
+ if (rebased) {
349
+ notes.push(`rebased ${ahead} local commit(s) onto ${upstream}`);
350
+ if (rec.dropped.length) notes.push(`reconciled its board (archived upstream: ${rec.dropped.join(", ")})`);
351
+ return { ok: true, behind: 0, ahead: 0, notes, board: rec.board, dropped: rec.dropped, canPublish: true };
352
+ }
353
+ if (rec.dropped.length) notes.push(`reconciled its board (archived upstream: ${rec.dropped.join(", ")})`);
354
+ notes.push(
355
+ `main is ${behind} behind and ${ahead} ahead of ${upstream} — local commits touch non-board files; ` +
356
+ `not publishing (reconcile manually: git pull --rebase)`
357
+ );
358
+ return { ok: true, behind, ahead, notes, board: rec.board, canPublish: false };
359
+ }
360
+
361
+ if (behind === 0) {
362
+ return { ok: true, behind: 0, ahead: 0, notes, board: readWorkingBoard(root), canPublish: true };
363
+ }
364
+
365
+ const dirty = classifyDirty(root, upstream);
366
+ const rec = reconcileWorkingBoard(root, upstream);
367
+ if (!rec.ok) {
368
+ notes.push(`main checkout board has conflicting rows (${(rec.conflicts || []).join(", ") || "unknown"}) — resolve manually`);
369
+ return { ok: false, behind, ahead: 0, blockedBy: rec.conflicts || [], notes, board: readWorkingBoard(root) };
370
+ }
371
+ const saved = readWorkingBoard(root);
372
+ if (dirty.redundant.length) clearRedundant(root, upstream, dirty.redundant);
373
+ gitCmd(root, ["checkout", "--", "BACKLOG.md"]);
374
+ const ff = gitCmd(root, ["merge", "--ff-only", upstream]);
375
+ if (ff.status !== 0) {
376
+ fs.writeFileSync(path.join(root, "BACKLOG.md"), saved, "utf8");
377
+ // Unrelated dirt is carried across a fast-forward (git preserves files the
378
+ // landing does not touch); only a file the landing WOULD overwrite makes git
379
+ // refuse. Pre-refusing every behind checkout with unrelated dirt stranded
380
+ // main 1 behind on an uncommitted config toggle the landing never touched
381
+ // (F-008). Attempt the merge and report the real blocker.
382
+ notes.push(
383
+ dirty.genuine.length
384
+ ? `main is ${behind} behind ${upstream} but has local changes to ${dirty.genuine.join(", ")} that the fast-forward would overwrite — commit or discard them, then run: node scripts/backlog.js sync (git: ${firstLine(ff)})`
385
+ : `main is ${behind} behind ${upstream} — could not fast-forward: ${(ff.stderr || ff.stdout || "").trim()}`
386
+ );
387
+ return { ok: false, behind, ahead: 0, blockedBy: dirty.genuine, notes, board: saved };
388
+ }
389
+ fs.writeFileSync(path.join(root, "BACKLOG.md"), rec.board, "utf8");
390
+ notes.push(`fast-forwarded main to ${upstream} (${behind} commit(s))`);
391
+ if (rec.dropped.length) notes.push(`reconciled its board (archived upstream: ${rec.dropped.join(", ")})`);
392
+ return { ok: true, behind: 0, ahead: 0, notes, board: rec.board, dropped: rec.dropped, canPublish: true };
393
+ }
394
+
395
+ /* Paths publishBoard stages alongside the board (when tracked) so the owned-
396
+ * files registry never lingers as canonical dirt either. */
397
+ const PUBLISH_EXTRA_PATHS = [".agents/memory/owned-files.md"];
398
+
399
+ function trackedPath(root, rel) {
400
+ const r = gitCmd(root, ["ls-files", "--error-unmatch", "--", rel]);
401
+ return r.status === 0;
402
+ }
403
+
404
+ /* Commit the board (and any changed owned-files registry) and fast-forward push
405
+ * it, re-fetching + rebasing after a concurrent landing. Returns
406
+ * `{ published, committed, reason, detail }`: `published:true` with reason "no
407
+ * change" when nothing needed committing; `published:false` when the commit/push
408
+ * could not complete (the commit may still exist locally — durable, just
409
+ * unpublished). `detail` is git's own first error line, so a caller can name the
410
+ * real cause instead of guessing "remote unreachable". `opts.deferPush` commits
411
+ * locally but skips the network push (reason "deferred"): the request path stays
412
+ * fast and a later `sync` publishes. */
413
+ function publishBoard(root, upstream, message, opts) {
414
+ const rels = ["BACKLOG.md", ...PUBLISH_EXTRA_PATHS.filter((p) => trackedPath(root, p))];
415
+ // `-f`: the extras are tracked-only (filtered by trackedPath above), but a
416
+ // tracked path can still be ignored by .gitignore (`.agents/memory/`), and a
417
+ // plain `git add` then aborts the whole publish with "paths are ignored" —
418
+ // aborting every board mutation until the operator hit `sync` from a terminal
419
+ // (F-004). -f cannot stage unrelated ignored files: only these paths ride along.
420
+ const add = gitCmd(root, ["add", "-f", "--", ...rels]);
421
+ if (add.status !== 0) {
422
+ return { published: false, committed: false, reason: "add-failed", detail: firstLine(add) };
423
+ }
424
+ const staged = gitCmd(root, ["diff", "--cached", "--quiet", "--", ...rels]);
425
+ let committed = false;
426
+ if (staged.status !== 0) {
427
+ const commit = gitCmd(root, ["commit", "-q", "-m", message, "--", ...rels]);
428
+ if (commit.status !== 0) {
429
+ return { published: false, committed: false, reason: "commit-failed", detail: firstLine(commit) };
430
+ }
431
+ committed = true;
432
+ }
433
+ // Push whenever HEAD carries anything upstream does not — a rebase in
434
+ // convergeCanonical can leave a local board commit with a clean index, and it
435
+ // must still be published.
436
+ const counts = gitCmd(root, ["rev-list", "--left-right", "--count", `HEAD...${upstream}`]);
437
+ const ahead = counts.status === 0 ? parseInt(String(counts.stdout || "").trim().split(/\s+/)[0], 10) || 0 : 0;
438
+ if (ahead === 0) return { published: true, committed, reason: "no change" };
439
+ if (opts && opts.deferPush) return { published: false, committed, reason: "deferred" };
440
+
441
+ const base = upstream.includes("/") ? upstream.slice(upstream.indexOf("/") + 1) : upstream;
442
+ for (let attempt = 1; attempt <= MAX_PUBLISH_ATTEMPTS; attempt++) {
443
+ const push = gitCmd(root, ["push", "origin", `HEAD:${base}`]);
444
+ if (push.status === 0) return { published: true, committed, reason: "pushed" };
445
+ const text = `${push.stdout || ""}\n${push.stderr || ""}`;
446
+ if (
447
+ attempt < MAX_PUBLISH_ATTEMPTS &&
448
+ /non-fast-forward|fetch first|tip of your current branch is behind|\[rejected\]/i.test(text)
449
+ ) {
450
+ gitCmd(root, ["fetch", "--quiet", "origin"], { timeout: 10000 });
451
+ const replay = aheadOnlyBoard(root, upstream) ? replayBoardOnly(root, upstream) : { ok: false };
452
+ if (!replay.ok) {
453
+ return {
454
+ published: false,
455
+ committed,
456
+ reason: "replay-conflict",
457
+ detail: (replay.conflicts || []).join(", ") || firstLine(push),
458
+ };
459
+ }
460
+ continue;
461
+ }
462
+ return { published: false, committed, reason: "push-failed", detail: firstLine(push) };
463
+ }
464
+ return { published: false, committed, reason: "retries-exhausted", detail: "push rejected after retries" };
465
+ }
466
+
467
+ /* Read-only view for `list` / `next`: the working board reconciled against the
468
+ * last-known upstream, so an agent never decides from a stale board. Never
469
+ * writes. Returns `{ board, behind, ok }`. */
470
+ function displayBoard(root, upstream) {
471
+ const working = readWorkingBoard(root);
472
+ if (!upstream) return { board: working, behind: 0, ok: true };
473
+ const counts = gitCmd(root, ["rev-list", "--left-right", "--count", `HEAD...${upstream}`]);
474
+ if (counts.status !== 0) return { board: working, behind: 0, ok: true };
475
+ const [ahead, behind] = String(counts.stdout || "")
476
+ .trim()
477
+ .split(/\s+/)
478
+ .map((n) => parseInt(n, 10) || 0);
479
+ if (behind <= 0) return { board: working, behind, ok: true };
480
+ const rec = reconcileWorkingBoard(root, upstream);
481
+ return { board: rec.ok ? rec.board : working, behind, ok: rec.ok };
482
+ }
483
+
484
+ module.exports = {
485
+ gitCmd,
486
+ gitOut,
487
+ mainWorktreeRoot,
488
+ isCanonicalCheckout,
489
+ currentUpstream,
490
+ gitShow,
491
+ readWorkingBoard,
492
+ porcelainPath,
493
+ reconcileWorkingBoard,
494
+ classifyDirty,
495
+ clearRedundant,
496
+ convergeCanonical,
497
+ publishBoard,
498
+ displayBoard,
499
+ };