opencode-agent-harness 0.2.0 → 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.
@@ -131,6 +131,137 @@ function dirtyEntries() {
131
131
  .filter((l) => l && !l.startsWith("!!"));
132
132
  }
133
133
 
134
+ /* Generated / machine-local paths that must never ride into a feature commit.
135
+ * `git add -A` used to sweep these up (a worktree's `prisma/generated` symlink
136
+ * broke CI on a fresh checkout), so they are blocked explicitly. */
137
+ const BLOCKED_PATTERNS = [
138
+ /(^|\/)node_modules(\/|$)/,
139
+ /(^|\/)\.next(\/|$)/,
140
+ /(^|\/)\.turbo(\/|$)/,
141
+ /(^|\/)dist(\/|$)/,
142
+ /(^|\/)build(\/|$)/,
143
+ /(^|\/)coverage(\/|$)/,
144
+ /(^|\/)prisma\/generated(\/|$)/,
145
+ /(^|\/)\.env(\..*)?$/,
146
+ /\.(log|tsbuildinfo)$/,
147
+ ];
148
+
149
+ function isBlockedPath(rel) {
150
+ return BLOCKED_PATTERNS.some((re) => re.test(rel.replace(/\\/g, "/")));
151
+ }
152
+
153
+ /* `git ls-files --others --exclude-standard` -> repo-relative untracked paths. */
154
+ function untrackedFiles() {
155
+ return out("git", ["ls-files", "--others", "--exclude-standard"], { cwd: root })
156
+ .split(/\r?\n/)
157
+ .filter(Boolean);
158
+ }
159
+
160
+ function isSymlink(rel) {
161
+ try {
162
+ return fs.lstatSync(path.join(root, rel)).isSymbolicLink();
163
+ } catch {
164
+ return false;
165
+ }
166
+ }
167
+
168
+ /* Stage the finalization tail without `git add -A`.
169
+ *
170
+ * - tracked changes (`git add -u`) are the feature's own edits;
171
+ * - untracked tail files (handoff, feature docs, QA plan, memory, docs) are added;
172
+ * - untracked generated/symlinked/machine-local paths are refused, never staged;
173
+ * - a stray `BACKLOG.md` diff is refused when the board service owns the board
174
+ * (a worktree-local row is a duplicate that would collide on merge).
175
+ *
176
+ * Returns { ok, blocked } — blocked lists the paths that need a human decision.
177
+ */
178
+ function stageTail(feature, opts = {}) {
179
+ const includeBlocked = Boolean(opts.includeBlocked);
180
+ if (!run("git", ["add", "-u"], { cwd: root })) return { ok: false, blocked: [] };
181
+
182
+ const blocked = [];
183
+ const boardService = boardServiceEnabled();
184
+ for (const rel of untrackedFiles()) {
185
+ if (rel === "BACKLOG.md" && boardService) {
186
+ blocked.push(`${rel} (board service owns the board — worktree copy is a duplicate)`);
187
+ continue;
188
+ }
189
+ if (isBlockedPath(rel) || isSymlink(rel)) {
190
+ blocked.push(rel);
191
+ continue;
192
+ }
193
+ // Another feature's handoff is never part of this landing; it is either a
194
+ // stale copy from a shared checkout or work that belongs to that session.
195
+ if (rel.startsWith(".agents/handoffs/") && rel !== `.agents/handoffs/${feature}.md`) {
196
+ blocked.push(`${rel} (another feature's handoff)`);
197
+ continue;
198
+ }
199
+ if (!run("git", ["add", "--", rel], { cwd: root })) return { ok: false, blocked };
200
+ }
201
+
202
+ // A tracked BACKLOG.md diff with the board service enabled is the same
203
+ // duplicate row, just already tracked. Never let it into the landing commit.
204
+ if (boardService) {
205
+ const blockedBoard = dirtyEntries().filter((l) => /(^|\s)BACKLOG\.md$/.test(l) || l.endsWith(" BACKLOG.md"));
206
+ if (blockedBoard.length) {
207
+ blocked.push("BACKLOG.md (board service owns the board — restore or move the row to the service)");
208
+ }
209
+ }
210
+
211
+ if (blocked.length && !includeBlocked) {
212
+ console.error(
213
+ "\n[finalize] refusing to commit these non-tail paths:\n" +
214
+ [...new Set(blocked)].map((l) => ` ${l}`).join("\n") +
215
+ "\n Move/commit/delete them first, or re-run with --include-blocked to stage them deliberately."
216
+ );
217
+ return { ok: false, blocked };
218
+ }
219
+ if (blocked.length && includeBlocked) {
220
+ console.log("\n[finalize] --include-blocked: staging the paths above.");
221
+ if (!run("git", ["add", "-A"], { cwd: root })) return { ok: false, blocked };
222
+ }
223
+ return { ok: true, blocked: [] };
224
+ }
225
+
226
+ function boardServiceEnabled() {
227
+ try {
228
+ return require(path.join(root, "scripts", "qa", "board-client.js")).enabled(root);
229
+ } catch {
230
+ return false;
231
+ }
232
+ }
233
+
234
+ /* After a landing: converge the main checkout (ff-only, only when clean) and
235
+ * print the close-out steps that used to appear as a session-ending remark. */
236
+ function closeOut(base, feature) {
237
+ let hygiene;
238
+ try {
239
+ hygiene = require(path.join(root, "scripts", "qa", "worktree-hygiene.js"));
240
+ } catch {
241
+ return;
242
+ }
243
+ spawnSync("git", ["fetch", "--quiet", "origin"], { cwd: root, stdio: "ignore", timeout: 10000 });
244
+ const h = hygiene.hygiene(root, base, process.cwd());
245
+ if (!h) return;
246
+ console.log(`\n[finalize] close-out: ${hygiene.describe(h)}`);
247
+
248
+ if (h.main.behind > 0 && h.main.dirty === 0) {
249
+ console.log(`[finalize] converging the main checkout: git -C ${h.main.path} merge --ff-only ${h.baseRef}`);
250
+ const merged = spawnSync("git", ["-C", h.main.path, "merge", "--ff-only", h.baseRef], { encoding: "utf8" });
251
+ if (merged.status === 0) console.log(`[finalize] main checkout is now up to date.`);
252
+ else console.log(`[finalize] could not fast-forward the main checkout:\n${String(merged.stderr || merged.stdout || "").trim()}`);
253
+ }
254
+
255
+ const advice = hygiene.closeOutAdvice(hygiene.hygiene(root, base, process.cwd()));
256
+ if (advice.length) {
257
+ console.log("[finalize] close-out actions still open:");
258
+ for (const a of advice) console.log(` - ${a}`);
259
+ console.log(` (the next session's orient auto-prunes merged, clean worktrees; ${feature} cannot be removed from inside it)`);
260
+ } else {
261
+ console.log("[finalize] no leftovers: main is in sync and no merged worktree remains.");
262
+ }
263
+ }
264
+
134
265
  function parseArgs(argv) {
135
266
  const args = { _: [] };
136
267
  for (let i = 0; i < argv.length; i++) {
@@ -143,6 +274,7 @@ function parseArgs(argv) {
143
274
  else if (a === "--no-rebase") args["no-rebase"] = true;
144
275
  else if (a === "--no-gate") args["no-gate"] = true;
145
276
  else if (a === "--no-ci-wait") args["no-ci-wait"] = true;
277
+ else if (a === "--include-blocked") args["include-blocked"] = true;
146
278
  else if (a === "--help" || a === "-h") args.help = true;
147
279
  else args._.push(a);
148
280
  }
@@ -239,14 +371,17 @@ function main() {
239
371
  console.log(`[finalize] ${feature} is already archived — skipping the board write.`);
240
372
  }
241
373
 
242
- // 2. Commit the tail (board + CHANGELOG + handoff + any remaining change) so
243
- // `ship`'s dirty-tree guard cannot abort the documented one-command close.
374
+ // 2. Commit the tail (board + CHANGELOG + handoff + remaining feature work)
375
+ // so `ship`'s dirty-tree guard cannot abort the documented one-command
376
+ // close. Staging is scoped: generated artifacts, symlinks and a stray
377
+ // worktree BACKLOG.md are refused instead of being swept in by `-A`.
244
378
  const dirty = dirtyEntries();
245
379
  if (dirty.length) {
246
380
  console.log(
247
381
  `\n[finalize] committing the finalization tail:\n` + dirty.map((l) => ` ${l}`).join("\n")
248
382
  );
249
- if (!run("git", ["add", "-A"], { cwd: root })) return fail("finalize: `git add -A` failed.");
383
+ const staged = stageTail(feature, { includeBlocked: args["include-blocked"] });
384
+ if (!staged.ok) return fail("finalize: the finalization tail is not safe to stage — see above.");
250
385
  if (!run("git", ["commit", "-m", `chore(${feature}): finalize — board + changelog`], { cwd: root })) {
251
386
  return fail("finalize: the finalization commit failed.");
252
387
  }
@@ -262,6 +397,10 @@ function main() {
262
397
  );
263
398
  }
264
399
 
400
+ // 4. Close the loop that used to be a session-ending remark: converge the
401
+ // main checkout and name every leftover worktree explicitly.
402
+ closeOut(base, feature);
403
+
265
404
  console.log(`\n[finalize] ${feature} landed + CI green.`);
266
405
  }
267
406
 
@@ -12,8 +12,10 @@
12
12
  *
13
13
  * Config is resolved from the project's `.harness.json` `board` block first
14
14
  * (per project, survives harness updates), then the environment:
15
- * .harness.json -> { "board": { "url", "token", "project" } }
15
+ * .harness.json -> { "board": { "url", "token", "project", "backend" } }
16
16
  * BACKLOG_API_URL / BACKLOG_API_TOKEN / BACKLOG_PROJECT (env override)
17
+ * `board.backend` pins `"file"` (deliberate legacy board) or `"service"`
18
+ * without relying on a shell export.
17
19
  *
18
20
  * The functions mirror `backlog.js` command results so `formatResult` prints the
19
21
  * same text for either backend.
@@ -33,12 +35,42 @@ function projectBoardConfig(root) {
33
35
  url: typeof b.url === "string" ? b.url : "",
34
36
  token: typeof b.token === "string" ? b.token : "",
35
37
  project: typeof b.project === "string" ? b.project : "",
38
+ backend: typeof b.backend === "string" ? b.backend.trim().toLowerCase() : "",
36
39
  };
37
40
  }
38
41
  } catch {
39
42
  /* no .harness.json / no board block */
40
43
  }
41
- return { url: "", token: "", project: "" };
44
+ return { url: "", token: "", project: "", backend: "" };
45
+ }
46
+
47
+ /* Machine-level client config. `board-service.sh install` writes
48
+ * `~/.config/agent-harness/board.env` and sources it from `~/.bashrc`; an
49
+ * opencode server launched outside that shell (systemd, a desktop launcher, a
50
+ * resumed session) never inherits those exports. Read the file directly so a
51
+ * board-configured project still reaches its service instead of silently
52
+ * falling back to a checkout-local file. */
53
+ function boardEnvFile() {
54
+ const base = process.env.XDG_CONFIG_HOME || path.join(require("os").homedir(), ".config");
55
+ try {
56
+ const src = fs.readFileSync(path.join(base, "agent-harness", "board.env"), "utf8");
57
+ const out = {};
58
+ for (const raw of src.split(/\r?\n/)) {
59
+ const m = /^\s*(?:export\s+)?([A-Z0-9_]+)\s*=\s*(.*?)\s*$/.exec(raw);
60
+ if (!m) continue;
61
+ let value = m[2];
62
+ if (
63
+ (value.startsWith('"') && value.endsWith('"')) ||
64
+ (value.startsWith("'") && value.endsWith("'"))
65
+ ) {
66
+ value = value.slice(1, -1);
67
+ }
68
+ out[m[1]] = value;
69
+ }
70
+ return out;
71
+ } catch {
72
+ return {};
73
+ }
42
74
  }
43
75
 
44
76
  /* Machine-level token store: `~/.config/agent-harness/tokens.json` maps a
@@ -56,9 +88,20 @@ function tokenStore(project) {
56
88
 
57
89
  function config(root) {
58
90
  const file = root ? projectBoardConfig(root) : { url: "", token: "", project: "" };
59
- const project = process.env.BACKLOG_PROJECT || file.project || "";
60
- const url = (process.env.BACKLOG_API_URL || file.url || "").replace(/\/+$/, "");
61
- const token = process.env.BACKLOG_API_TOKEN || file.token || tokenStore(project) || "";
91
+ const machine = boardEnvFile();
92
+ const project = process.env.BACKLOG_PROJECT || file.project || machine.BACKLOG_PROJECT || "";
93
+ const url = (
94
+ process.env.BACKLOG_API_URL ||
95
+ file.url ||
96
+ machine.BACKLOG_API_URL ||
97
+ ""
98
+ ).replace(/\/+$/, "");
99
+ const token =
100
+ process.env.BACKLOG_API_TOKEN ||
101
+ file.token ||
102
+ machine.BACKLOG_API_TOKEN ||
103
+ tokenStore(project) ||
104
+ "";
62
105
  return { url, token, project };
63
106
  }
64
107
 
@@ -79,14 +122,25 @@ function config(root) {
79
122
  * board-configured shell (e.g. `npm test` in the harness) writes its local
80
123
  * fixtures into the live shared board — the F-339 fixture-row leak. An
81
124
  * env-only setup opts in explicitly with `BACKLOG_BACKEND=service`.
125
+ *
126
+ * A declared board is MANDATORY: once the project itself declares `board.url`,
127
+ * the service backend wins even when the token is not configured yet. The
128
+ * request then fails loudly in `httpSync` ("token missing") instead of quietly
129
+ * writing the checkout's local `BACKLOG.md` — the split-board defect where a
130
+ * feature worktree filed a row that never reached the main board. The legacy
131
+ * file backend remains available only through an explicit opt-out
132
+ * (`BACKLOG_BACKEND=file`, `--root`, or the durable `.harness.json`
133
+ * `board.backend: "file"` — a project choice that also beats ambient env).
82
134
  */
83
135
  function enabled(root, opts) {
84
136
  if (opts && opts.forceFile) return false;
137
+ const declared = projectBoardConfig(root);
138
+ if (declared.backend === "file") return false;
85
139
  if (process.env.BACKLOG_BACKEND === "file") return false;
86
140
  if (process.env.BACKLOG_BACKEND === "service") return true;
87
- if (!projectBoardConfig(root).url) return false;
88
- const c = config(root);
89
- return Boolean(c.url && c.token);
141
+ if (declared.backend === "service") return true;
142
+ if (!declared.url) return false;
143
+ return Boolean(config(root).url);
90
144
  }
91
145
 
92
146
  function projectKey(root) {
@@ -109,7 +163,16 @@ function projectKey(root) {
109
163
  function httpSync(root, method, endpoint, body) {
110
164
  const c = config(root);
111
165
  if (!c.url) throw new Error("board service not configured: set BACKLOG_API_URL");
112
- if (!c.token) throw new Error("board service token missing: set BACKLOG_API_TOKEN");
166
+ if (!c.token) {
167
+ const base = process.env.XDG_CONFIG_HOME || path.join(require("os").homedir(), ".config");
168
+ throw new Error(
169
+ `board service token missing for project "${projectKey(root)}": set BACKLOG_API_TOKEN, ` +
170
+ `add it to ${path.join(base, "agent-harness", "tokens.json")} or ` +
171
+ `${path.join(base, "agent-harness", "board.env")}.\n` +
172
+ "This project declares a board service, so the CLI will not fall back to a checkout-local " +
173
+ "BACKLOG.md (set BACKLOG_BACKEND=file only to opt into the legacy board deliberately)."
174
+ );
175
+ }
113
176
 
114
177
  const payload = JSON.stringify({
115
178
  url: `${c.url}${endpoint}`,
@@ -63,6 +63,16 @@ function gitCmd(root, args, opts) {
63
63
  });
64
64
  }
65
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
+
66
76
  function gitOut(root, args, opts) {
67
77
  const r = gitCmd(root, args, opts);
68
78
  return r.status === 0 ? String(r.stdout || "").trim() : "";
@@ -353,13 +363,6 @@ function convergeCanonical(root, upstream, opts) {
353
363
  }
354
364
 
355
365
  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
366
  const rec = reconcileWorkingBoard(root, upstream);
364
367
  if (!rec.ok) {
365
368
  notes.push(`main checkout board has conflicting rows (${(rec.conflicts || []).join(", ") || "unknown"}) — resolve manually`);
@@ -371,8 +374,17 @@ function convergeCanonical(root, upstream, opts) {
371
374
  const ff = gitCmd(root, ["merge", "--ff-only", upstream]);
372
375
  if (ff.status !== 0) {
373
376
  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 };
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 };
376
388
  }
377
389
  fs.writeFileSync(path.join(root, "BACKLOG.md"), rec.board, "utf8");
378
390
  notes.push(`fast-forwarded main to ${upstream} (${behind} commit(s))`);
@@ -391,20 +403,31 @@ function trackedPath(root, rel) {
391
403
 
392
404
  /* Commit the board (and any changed owned-files registry) and fast-forward push
393
405
  * 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. */
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. */
399
413
  function publishBoard(root, upstream, message, opts) {
400
414
  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" };
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
+ }
403
424
  const staged = gitCmd(root, ["diff", "--cached", "--quiet", "--", ...rels]);
404
425
  let committed = false;
405
426
  if (staged.status !== 0) {
406
427
  const commit = gitCmd(root, ["commit", "-q", "-m", message, "--", ...rels]);
407
- if (commit.status !== 0) return { published: false, committed: false, reason: "commit-failed" };
428
+ if (commit.status !== 0) {
429
+ return { published: false, committed: false, reason: "commit-failed", detail: firstLine(commit) };
430
+ }
408
431
  committed = true;
409
432
  }
410
433
  // Push whenever HEAD carries anything upstream does not — a rebase in
@@ -426,12 +449,19 @@ function publishBoard(root, upstream, message, opts) {
426
449
  ) {
427
450
  gitCmd(root, ["fetch", "--quiet", "origin"], { timeout: 10000 });
428
451
  const replay = aheadOnlyBoard(root, upstream) ? replayBoardOnly(root, upstream) : { ok: false };
429
- if (!replay.ok) return { published: false, committed, reason: "replay-conflict" };
452
+ if (!replay.ok) {
453
+ return {
454
+ published: false,
455
+ committed,
456
+ reason: "replay-conflict",
457
+ detail: (replay.conflicts || []).join(", ") || firstLine(push),
458
+ };
459
+ }
430
460
  continue;
431
461
  }
432
- return { published: false, committed, reason: "push-failed" };
462
+ return { published: false, committed, reason: "push-failed", detail: firstLine(push) };
433
463
  }
434
- return { published: false, committed, reason: "retries-exhausted" };
464
+ return { published: false, committed, reason: "retries-exhausted", detail: "push rejected after retries" };
435
465
  }
436
466
 
437
467
  /* Read-only view for `list` / `next`: the working board reconciled against the
@@ -128,7 +128,12 @@ if (useService) {
128
128
  // The service enforces uniqueness/priority/evidence/cycles on write; the gate
129
129
  // still re-verifies structure so a corrupt row can never slip through.
130
130
  check(true, "board service reachable (BACKLOG_BACKEND=service)");
131
- const strays = insideGitRepo() ? gitLsFiles("*BACKLOG.md").filter((f) => f !== "BACKLOG.md") : [];
131
+ // The stray scan must not count the harness's own template board: every
132
+ // project repo ships `templates/BACKLOG.md` as a scaffold source, never as a
133
+ // live board. Only a stray *project* board is a defect.
134
+ const strays = insideGitRepo()
135
+ ? gitLsFiles("*BACKLOG.md").filter((f) => f !== "BACKLOG.md" && !f.startsWith("templates/"))
136
+ : [];
132
137
  check(strays.length === 0, `no stray BACKLOG.md boards (found: ${strays.join(", ") || "none"})`);
133
138
  lines = serviceBoardToLines(snapshot);
134
139
  } else {
@@ -142,7 +147,9 @@ if (useService) {
142
147
 
143
148
  // No stray/secondary boards: the root file is the ONLY canonical board.
144
149
  if (insideGitRepo()) {
145
- const strays = gitLsFiles("*BACKLOG.md").filter((f) => f !== "BACKLOG.md");
150
+ const strays = gitLsFiles("*BACKLOG.md").filter(
151
+ (f) => f !== "BACKLOG.md" && !f.startsWith("templates/")
152
+ );
146
153
  check(strays.length === 0, `no stray BACKLOG.md boards (found: ${strays.join(", ") || "none"})`);
147
154
  } else {
148
155
  check(true, "not a git repo \u2014 skipping stray BACKLOG.md check");
@@ -91,11 +91,15 @@ for (const { abs, rel } of docFiles) {
91
91
  }
92
92
 
93
93
  // ---- 2. no dangling relative links ------------------------------------------
94
+ // Links are a prose construct: a `plugin["tool.execute.before"](...)` example
95
+ // inside a code span is API notation, not a markdown link (the F-004 false
96
+ // positive). Strip fenced blocks + inline code spans before scanning.
94
97
  function relativeLinks(src) {
95
98
  const links = [];
96
99
  const re = /(?<!\!)\[[^\]]*\]\(([^)\s]+)(?:\s+"[^"]*")?\)/g;
100
+ const prose = stripCode(src);
97
101
  let m;
98
- while ((m = re.exec(src)) !== null) links.push(m[1]);
102
+ while ((m = re.exec(prose)) !== null) links.push(m[1]);
99
103
  return links;
100
104
  }
101
105
  function isExternal(target) {
@@ -44,14 +44,18 @@ const strict = process.env.AGENT_PREFIX_STRICT !== "0";
44
44
  * above the shipped size so a real growth must be a deliberate bump, not a
45
45
  * quiet accumulation. Memory files are project-owned and deliberately absent.
46
46
  * 0.1.164: raised the AGENTS.md ceiling 10 -> 11 KiB for the "prefer the
47
- * harness tools over the shell" rule (W4 discoverability). */
47
+ * harness tools over the shell" rule (W4 discoverability).
48
+ * 0.3.5: trimmed the rulebook to standards-only (47 -> 27 KiB) by replacing
49
+ * duplicated operating mechanics with pointers; lowered its ceiling to match so
50
+ * the dedupe cannot silently regrow. */
48
51
  const SIZE_BUDGET = {
49
52
  "AGENTS.md": 11264,
50
- ".agents/AGENTS.md": 48128,
53
+ ".agents/AGENTS.md": 28672,
51
54
  ".agents/rules/00-operating.md": 30720,
52
55
  };
53
- /* Combined harness-owned ceiling; `AGENT_PREFIX_MAX_BYTES` overrides. */
54
- const DEFAULT_TOTAL_BUDGET = 89088; // ≈ 87 KB
56
+ /* Combined harness-owned ceiling (the sum of the per-file ceilings);
57
+ * `AGENT_PREFIX_MAX_BYTES` overrides. */
58
+ const DEFAULT_TOTAL_BUDGET = 70656; // ≈ 69 KB
55
59
  const totalBudget = (() => {
56
60
  const n = Number(process.env.AGENT_PREFIX_MAX_BYTES);
57
61
  return Number.isFinite(n) && n > 0 ? n : DEFAULT_TOTAL_BUDGET;
@@ -0,0 +1,93 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ /*
4
+ * check-worktrees — fail the gate battery when a landing left the repo open.
5
+ *
6
+ * This is the enforcement half of worktree-hygiene. `finalize`/`ship` now
7
+ * converge the main checkout and print the close-out, but a session can still
8
+ * end without those (hand-run ship, interrupted finalize, a crashed agent).
9
+ * The leftovers were invisible until a human read the session summary:
10
+ *
11
+ * - the main checkout drifts N commits behind origin/main and accumulates
12
+ * unrelated uncommitted work, so the next feature lands on top of it and
13
+ * two sessions collide in CHANGELOG.md / package.json / AGENTS.md;
14
+ * - merged, clean feature worktrees stay on disk forever ("prune later").
15
+ *
16
+ * Policy (local only — CI has no developer worktrees):
17
+ * FAIL main checkout behind origin/<base>
18
+ * FAIL merged + clean linked worktree left on disk
19
+ * FAIL merged worktree with uncommitted work (cannot be pruned safely)
20
+ * WARN main checkout dirty (unrelated WIP still present)
21
+ *
22
+ * Usage:
23
+ * node scripts/qa/check-worktrees.js [--root <dir>] [--base main] [--json]
24
+ */
25
+ const path = require("path");
26
+ const hygiene = require("./worktree-hygiene.js");
27
+
28
+ function main() {
29
+ const argv = process.argv.slice(2);
30
+ const args = { root: process.cwd(), base: "main", json: false, force: false };
31
+ for (let i = 0; i < argv.length; i++) {
32
+ const a = argv[i];
33
+ if (a === "--root") args.root = path.resolve(argv[++i]);
34
+ else if (a === "--base") args.base = argv[++i];
35
+ else if (a === "--json") args.json = true;
36
+ else if (a === "--force") args.force = true;
37
+ else if (a === "--help" || a === "-h") {
38
+ console.log("check-worktrees — fail when main is stale or a merged worktree is left behind\n\n node scripts/qa/check-worktrees.js [--root <dir>] [--base main] [--json]");
39
+ return;
40
+ }
41
+ }
42
+
43
+ // CI runners are fresh clones with no developer worktrees or local drift.
44
+ if (process.env.CI && !args.force) {
45
+ console.log("check-worktrees: skipped in CI (no developer worktrees)");
46
+ return;
47
+ }
48
+
49
+ const h = hygiene.hygiene(args.root, args.base);
50
+ if (!h) {
51
+ console.log("check-worktrees: not a git repository — skipped");
52
+ return;
53
+ }
54
+ if (!h.hasBase) {
55
+ console.log(`check-worktrees: no ${h.baseRef} — skipped (nothing to compare)`);
56
+ return;
57
+ }
58
+
59
+ if (args.json) console.log(JSON.stringify(h, null, 2));
60
+
61
+ const failures = [];
62
+ if (h.main.behind > 0) {
63
+ failures.push(
64
+ `main checkout is ${h.main.behind} commit(s) behind ${h.baseRef} — converge it: git -C ${h.main.path} merge --ff-only ${h.baseRef}`
65
+ );
66
+ }
67
+ for (const w of h.stale) {
68
+ failures.push(`merged worktree left behind: ${w.path} (${w.branch || "detached"}) — node scripts/backlog.js worktree-prune`);
69
+ }
70
+ for (const w of h.mergedDirty) {
71
+ failures.push(
72
+ `merged worktree still dirty (${w.dirty} entr${w.dirty === 1 ? "y" : "ies"}): ${w.path} (${w.branch || "detached"}) — commit or discard, then prune`
73
+ );
74
+ }
75
+
76
+ console.log(`check-worktrees: ${hygiene.describe(h)}`);
77
+ if (h.main.dirty) {
78
+ console.warn(`\ncheck-worktrees: WARN — main checkout has ${h.main.dirty} uncommitted entr${h.main.dirty === 1 ? "y" : "ies"}:`);
79
+ for (const l of h.main.dirtyEntries) console.warn(` ${l}`);
80
+ console.warn(" Land features from their worktree; keep main clean so it can fast-forward.");
81
+ }
82
+ if (failures.length) {
83
+ console.error("\ncheck-worktrees: FAIL");
84
+ for (const f of failures) console.error(` - ${f}`);
85
+ process.exitCode = 1;
86
+ return;
87
+ }
88
+ console.log("check-worktrees: OK — main is current and no merged worktree remains");
89
+ }
90
+
91
+ if (require.main === module) main();
92
+
93
+ module.exports = { main };