@mmerterden/multi-agent-pipeline 20.40.0 → 20.42.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 (143) hide show
  1. package/CHANGELOG.md +94 -0
  2. package/README.md +5 -2
  3. package/README.tr.md +5 -2
  4. package/docs/adr/0019-product-tree.md +143 -0
  5. package/docs/adr/README.md +1 -0
  6. package/docs/ecosystem.md +51 -14
  7. package/docs/facts.json +7 -7
  8. package/docs/features.md +15 -4
  9. package/install/claude.mjs +45 -3
  10. package/install/templates/claude-hooks.json +23 -1
  11. package/manifest.json +146 -107
  12. package/package.json +3 -2
  13. package/pipeline/commands/multi-agent/autopilot/SKILL.md +11 -0
  14. package/pipeline/commands/multi-agent/review-analysis/SKILL.md +1 -1
  15. package/pipeline/commands/multi-agent/setup/SKILL.md +1 -1
  16. package/pipeline/contract/types/index.d.ts +53 -49
  17. package/pipeline/lib/args.mjs +131 -4
  18. package/pipeline/lib/bg-launch.mjs +5 -2
  19. package/pipeline/lib/context-budget.mjs +5 -42
  20. package/pipeline/lib/credential-store.sh +11 -1
  21. package/pipeline/lib/hook-once.mjs +134 -0
  22. package/pipeline/lib/hook-registration.mjs +5 -0
  23. package/pipeline/lib/isotonic.mjs +73 -0
  24. package/pipeline/lib/low-disk.mjs +153 -0
  25. package/pipeline/lib/mcp-schema-load.mjs +90 -0
  26. package/pipeline/lib/md2confluence-v3.py +19 -10
  27. package/pipeline/lib/model-dispatch.sh +26 -2
  28. package/pipeline/lib/normalize-text.mjs +135 -0
  29. package/pipeline/lib/outbound-gate.mjs +21 -3
  30. package/pipeline/lib/plan-todos.sh +17 -4
  31. package/pipeline/lib/redact.mjs +12 -3
  32. package/pipeline/lib/risky-settings.mjs +198 -0
  33. package/pipeline/lib/route-state.sh +1 -0
  34. package/pipeline/lib/secret-patterns.generated.mjs +6 -2
  35. package/pipeline/lib/session-usage.mjs +232 -0
  36. package/pipeline/lib/source-digest.mjs +211 -0
  37. package/pipeline/lib/tdd-evidence.mjs +250 -17
  38. package/pipeline/lib/tiered-budget.mjs +87 -0
  39. package/pipeline/lib/untrusted-fence.mjs +132 -1
  40. package/pipeline/multi-agent-refs/analysis/locked.md +1 -1
  41. package/pipeline/multi-agent-refs/analysis/review.md +23 -1
  42. package/pipeline/multi-agent-refs/features/code-graph.md +11 -1
  43. package/pipeline/multi-agent-refs/features/cost-analysis.md +37 -2
  44. package/pipeline/multi-agent-refs/features/doctor.md +82 -4
  45. package/pipeline/multi-agent-refs/features/model-fallback.md +25 -0
  46. package/pipeline/multi-agent-refs/features/plan-todos.md +4 -0
  47. package/pipeline/multi-agent-refs/features/product-tree.md +68 -0
  48. package/pipeline/multi-agent-refs/features/unattended-gates.md +5 -3
  49. package/pipeline/multi-agent-refs/features/unattended-security.md +88 -1
  50. package/pipeline/multi-agent-refs/features/usage-reporting.md +33 -0
  51. package/pipeline/multi-agent-refs/help/en.md +2 -1
  52. package/pipeline/multi-agent-refs/help/tr.md +2 -1
  53. package/pipeline/multi-agent-refs/knowledge.md +58 -0
  54. package/pipeline/multi-agent-refs/outside-the-pipeline.md +6 -0
  55. package/pipeline/multi-agent-refs/phases/phase-0-init.md +4 -0
  56. package/pipeline/multi-agent-refs/phases/phase-1-plan.md +5 -1
  57. package/pipeline/multi-agent-refs/phases/phase-2-dev.md +4 -4
  58. package/pipeline/multi-agent-refs/phases/phase-3-review.md +2 -2
  59. package/pipeline/multi-agent-refs/phases/phase-5-report.md +4 -0
  60. package/pipeline/multi-agent-refs/progress-contract.md +3 -1
  61. package/pipeline/office/index.html +13 -7
  62. package/pipeline/office/toolkit.json +1 -1
  63. package/pipeline/preferences-template.json +1 -0
  64. package/pipeline/rules/outside-the-pipeline.md +1 -1
  65. package/pipeline/schemas/doctor-report.schema.json +47 -0
  66. package/pipeline/schemas/learnings-ledger.schema.json +35 -2
  67. package/pipeline/schemas/office-archive.schema.json +225 -128
  68. package/pipeline/schemas/plan-todos.schema.json +29 -1
  69. package/pipeline/schemas/prefs.schema.json +146 -0
  70. package/pipeline/schemas/product-tree-overlay.schema.json +57 -0
  71. package/pipeline/schemas/product-tree.schema.json +136 -0
  72. package/pipeline/schemas/route-config.schema.json +51 -0
  73. package/pipeline/schemas/secret-patterns.json +17 -1
  74. package/pipeline/schemas/toolkit-path-params.json +15 -1
  75. package/pipeline/scripts/_cost-advise.mjs +357 -0
  76. package/pipeline/scripts/_cost-budget.mjs +78 -0
  77. package/pipeline/scripts/_cost.mjs +29 -0
  78. package/pipeline/scripts/_decode_text.py +107 -0
  79. package/pipeline/scripts/_eval-stats.mjs +182 -0
  80. package/pipeline/scripts/_guard-probe.mjs +406 -0
  81. package/pipeline/scripts/_guard_rules.py +336 -1
  82. package/pipeline/scripts/_learnings-promotion.mjs +229 -0
  83. package/pipeline/scripts/_locate.mjs +539 -0
  84. package/pipeline/scripts/_memory-policy.mjs +208 -33
  85. package/pipeline/scripts/_product-tree-extract.mjs +761 -0
  86. package/pipeline/scripts/_product-tree.mjs +923 -0
  87. package/pipeline/scripts/_retrieval.mjs +161 -4
  88. package/pipeline/scripts/_secret-scan.mjs +6 -1
  89. package/pipeline/scripts/_stack-routing.mjs +2 -0
  90. package/pipeline/scripts/_test-gaming.mjs +346 -0
  91. package/pipeline/scripts/_user_guard_rules.py +744 -0
  92. package/pipeline/scripts/agent-guard.py +69 -6
  93. package/pipeline/scripts/agent-guard.sh +8 -1
  94. package/pipeline/scripts/argv-secret-scan.mjs +2 -1
  95. package/pipeline/scripts/autopilot-loop.mjs +407 -0
  96. package/pipeline/scripts/autopilot-runner.mjs +38 -25
  97. package/pipeline/scripts/capture-resume.sh +9 -1
  98. package/pipeline/scripts/cost-analyze.mjs +66 -4
  99. package/pipeline/scripts/cost-budget-check.mjs +5 -13
  100. package/pipeline/scripts/disk-cleaner.mjs +1418 -0
  101. package/pipeline/scripts/doctor.mjs +324 -43
  102. package/pipeline/scripts/evidence-gate.mjs +90 -0
  103. package/pipeline/scripts/gate-ledger.mjs +76 -21
  104. package/pipeline/scripts/gc-tmp.sh +5 -0
  105. package/pipeline/scripts/graph-query.mjs +257 -17
  106. package/pipeline/scripts/guard-probe-known-holes.json +3 -0
  107. package/pipeline/scripts/learnings-ledger.mjs +680 -55
  108. package/pipeline/scripts/note-agent-event.mjs +2 -0
  109. package/pipeline/scripts/note-mcp-failure.mjs +363 -0
  110. package/pipeline/scripts/note-mcp-failure.sh +19 -0
  111. package/pipeline/scripts/note-skill-use.mjs +96 -23
  112. package/pipeline/scripts/office-archive.mjs +23 -10
  113. package/pipeline/scripts/office-memory.mjs +4 -1
  114. package/pipeline/scripts/persona-walk-anchors.mjs +443 -0
  115. package/pipeline/scripts/pre-commit-check.sh +2 -2
  116. package/pipeline/scripts/pre-push-check.sh +8 -1
  117. package/pipeline/scripts/product-tree-eval.mjs +685 -0
  118. package/pipeline/scripts/product-tree.mjs +544 -0
  119. package/pipeline/scripts/publish-staged.mjs +324 -0
  120. package/pipeline/scripts/route-learn.mjs +628 -0
  121. package/pipeline/scripts/run-scope-guard.mjs +55 -1
  122. package/pipeline/scripts/scan-agent-config.sh +1 -1
  123. package/pipeline/scripts/statusline.mjs +309 -0
  124. package/pipeline/scripts/test-integrity-gate.mjs +97 -2
  125. package/pipeline/scripts/triage-memory.mjs +12 -4
  126. package/pipeline/scripts/uninstall.mjs +1 -0
  127. package/pipeline/skills/.skill-manifest.json +15 -7
  128. package/pipeline/skills/.skills-index.json +25 -3
  129. package/pipeline/skills/shared/README.md +6 -4
  130. package/pipeline/skills/shared/core/google-play-compliance/references/examples.md +1 -1
  131. package/pipeline/skills/shared/core/multi-agent-review-analysis/SKILL.md +1 -1
  132. package/pipeline/skills/shared/external/backlog/SKILL.md +1 -1
  133. package/pipeline/skills/shared/external/disk-cleaner/SKILL.md +105 -0
  134. package/pipeline/skills/shared/external/disk-cleaner/evals/evals.json +62 -0
  135. package/pipeline/skills/shared/external/disk-cleaner/scripts/disk-cleaner.mjs +1418 -0
  136. package/pipeline/skills/shared/external/localization-reuse-map/SKILL.md +1 -1
  137. package/pipeline/skills/shared/external/spec-persona-walk/SKILL.md +118 -0
  138. package/pipeline/skills/shared/external/spec-persona-walk/evals/evals.json +50 -0
  139. package/pipeline/skills/shared/external/spec-persona-walk/scripts/persona-walk-anchors.mjs +443 -0
  140. package/pipeline/skills/shared/external/storekit/SKILL.md +1 -1
  141. package/pipeline/skills/shared/external/swiftdata/SKILL.md +1 -1
  142. package/pipeline/skills/skill-copies.json +9 -1
  143. package/pipeline/skills/skills-index.md +4 -2
@@ -0,0 +1,211 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * source-digest.mjs - one sha256 over the source a working tree holds right
4
+ * now, committed or not.
5
+ *
6
+ * Build and test evidence is recorded before Phase 4 commits anything, so the
7
+ * HEAD a gate records says nothing about an edit made after the build. This
8
+ * digest does: it covers every tracked file as it is on disk and every
9
+ * untracked file git does not ignore, so an edit, a new file or a deletion
10
+ * after the evidence changes it, and undoing the edit brings it back.
11
+ * Committing the same content leaves it unchanged, so a checkpoint commit does
12
+ * not age the evidence.
13
+ *
14
+ * How it stays cheap on a large repository:
15
+ * - unchanged tracked files are named by the blob id the index already holds
16
+ * (`git ls-files -s`); nothing is read for them;
17
+ * - only modified and untracked files are hashed, by `git hash-object
18
+ * --stdin-paths`, which streams each file and applies the same clean
19
+ * filters the index used, so an unmodified file and a re-saved one agree;
20
+ * - hashing stops at `maxFiles` files or `maxBytes` bytes; past the cap a
21
+ * file is named by its size and mtime, which still changes on an edit,
22
+ * and the result says `capped: true`;
23
+ * - every git call has `timeoutMs`; a call that fails or times out makes the
24
+ * digest null, which callers read as "cannot tell", never as a match.
25
+ *
26
+ * Ignore rules are git's own (`--exclude-standard`). The pipeline's own
27
+ * output inside a worktree is left out too, because it is written after the
28
+ * build it describes: untracked `*.log` files, `*.xcresult` bundles and the
29
+ * `.pipeline/`, `.multi-agent/` and `.claude/` directories.
30
+ *
31
+ * A submodule is named by the commit its checkout is on, plus `dirty` when
32
+ * its own tree has changes.
33
+ *
34
+ * CLI: source-digest.mjs [--repo <dir>] [--json]
35
+ * prints the digest (or the whole result with --json); exit 3 when <dir> is
36
+ * not in a git work tree or git could not answer.
37
+ *
38
+ * Zero runtime dependencies (ADR-0004).
39
+ *
40
+ * @module pipeline/lib/source-digest
41
+ */
42
+
43
+ import { spawnSync } from "node:child_process";
44
+ import { createHash } from "node:crypto";
45
+ import { lstatSync, readlinkSync } from "node:fs";
46
+ import { join } from "node:path";
47
+
48
+ import { invokedDirectly } from "./invoked-directly.mjs";
49
+ import { parseArgs } from "./args.mjs";
50
+
51
+ export const DIGEST_LIMITS = Object.freeze({
52
+ maxFiles: 5000,
53
+ maxBytes: 256 * 1024 * 1024,
54
+ timeoutMs: 20000,
55
+ });
56
+
57
+ const ARTEFACT = /(?:^|\/)(?:\.pipeline|\.multi-agent|\.claude)\/|\.log$|\.xcresult(?:\/|$)/;
58
+
59
+ /** Whether an untracked path is the pipeline's own output rather than source. */
60
+ export function isPipelineArtefact(path) {
61
+ return ARTEFACT.test(path);
62
+ }
63
+
64
+ function git(cwd, args, { timeoutMs, input } = {}) {
65
+ const r = spawnSync("git", ["-C", cwd, ...args], {
66
+ encoding: "utf8",
67
+ timeout: timeoutMs,
68
+ maxBuffer: 1024 * 1024 * 1024,
69
+ input,
70
+ });
71
+ if (r.status !== 0 || r.error) return null;
72
+ return r.stdout;
73
+ }
74
+
75
+ const nulList = (out) => (out ? out.split("\0").filter(Boolean) : []);
76
+
77
+ function statOf(path) {
78
+ try {
79
+ return lstatSync(path);
80
+ } catch {
81
+ return null;
82
+ }
83
+ }
84
+
85
+ function submoduleToken(root, path, timeoutMs) {
86
+ const dir = join(root, path);
87
+ const head = git(dir, ["rev-parse", "HEAD"], { timeoutMs });
88
+ if (head === null) return "gitlink:absent";
89
+ const dirty = git(dir, ["status", "--porcelain", "--untracked-files=no"], { timeoutMs });
90
+ return `gitlink:${head.trim()}${dirty && dirty.trim() ? ":dirty" : ""}`;
91
+ }
92
+
93
+ /**
94
+ * The digest of the working tree `dir` is in, or null when it is not in one
95
+ * or git could not answer in time.
96
+ *
97
+ * @param {string} dir
98
+ * @param {{maxFiles?: number, maxBytes?: number, timeoutMs?: number}} [opts]
99
+ * @returns {null | {digest: string, root: string, files: number, hashed: number,
100
+ * statOnly: number, capped: boolean, newestEditMs: number, ms: number}}
101
+ */
102
+ export function sourceDigest(dir, opts = {}) {
103
+ const { maxFiles, maxBytes, timeoutMs } = { ...DIGEST_LIMITS, ...opts };
104
+ const started = Date.now();
105
+ const top = git(dir, ["rev-parse", "--show-toplevel"], { timeoutMs });
106
+ if (top === null) return null;
107
+ const root = top.trim();
108
+
109
+ const staged = git(root, ["ls-files", "-s", "-z"], { timeoutMs });
110
+ const modifiedOut = git(root, ["ls-files", "-m", "-z"], { timeoutMs });
111
+ const deletedOut = git(root, ["ls-files", "-d", "-z"], { timeoutMs });
112
+ const untrackedOut = git(root, ["ls-files", "-o", "--exclude-standard", "-z"], { timeoutMs });
113
+ if (staged === null || modifiedOut === null || deletedOut === null || untrackedOut === null) {
114
+ return null;
115
+ }
116
+
117
+ const tokens = new Map();
118
+ const gitlinks = new Set();
119
+ for (const rec of nulList(staged)) {
120
+ const tab = rec.indexOf("\t");
121
+ const [mode, sha, stage] = rec.slice(0, tab).split(" ");
122
+ const path = rec.slice(tab + 1);
123
+ if (stage !== "0" && tokens.has(path)) continue;
124
+ if (mode === "160000") gitlinks.add(path);
125
+ tokens.set(path, `${mode}:${sha}`);
126
+ }
127
+ const deleted = new Set(nulList(deletedOut));
128
+ const toHash = [];
129
+ for (const path of nulList(modifiedOut)) {
130
+ if (deleted.has(path)) continue;
131
+ if (gitlinks.has(path)) tokens.set(path, submoduleToken(root, path, timeoutMs));
132
+ else toHash.push(path);
133
+ }
134
+ for (const path of deleted) tokens.set(path, "deleted");
135
+ for (const path of nulList(untrackedOut)) {
136
+ if (!isPipelineArtefact(path)) toHash.push(path);
137
+ }
138
+
139
+ let hashedBytes = 0;
140
+ let newestEditMs = 0;
141
+ let capped = false;
142
+ const hashList = [];
143
+ for (const path of toHash) {
144
+ const st = statOf(join(root, path));
145
+ if (!st) {
146
+ tokens.set(path, "deleted");
147
+ continue;
148
+ }
149
+ newestEditMs = Math.max(newestEditMs, st.mtimeMs);
150
+ if (st.isSymbolicLink()) {
151
+ let target;
152
+ try {
153
+ target = readlinkSync(join(root, path));
154
+ } catch {
155
+ target = "?";
156
+ }
157
+ tokens.set(path, `link:${target}`);
158
+ continue;
159
+ }
160
+ if (!st.isFile()) {
161
+ tokens.set(path, `other:${st.mode}`);
162
+ continue;
163
+ }
164
+ const fits = hashList.length < maxFiles && hashedBytes + st.size <= maxBytes;
165
+ if (!fits || path.includes("\n")) {
166
+ if (!path.includes("\n")) capped = true;
167
+ tokens.set(path, `stat:${st.size}:${Math.trunc(st.mtimeMs)}`);
168
+ continue;
169
+ }
170
+ hashedBytes += st.size;
171
+ hashList.push(path);
172
+ }
173
+ if (hashList.length) {
174
+ const out = git(root, ["hash-object", "--stdin-paths"], {
175
+ timeoutMs,
176
+ input: `${hashList.join("\n")}\n`,
177
+ });
178
+ if (out === null) return null;
179
+ const shas = out.trim().split("\n");
180
+ if (shas.length !== hashList.length) return null;
181
+ hashList.forEach((path, i) => tokens.set(path, `blob:${shas[i]}`));
182
+ }
183
+
184
+ const hash = createHash("sha256");
185
+ let statOnly = 0;
186
+ for (const path of [...tokens.keys()].sort()) {
187
+ const token = tokens.get(path);
188
+ if (token.startsWith("stat:")) statOnly++;
189
+ hash.update(`${path}\0${token.replace(/^(?:100644|100755):/, "blob:")}\n`);
190
+ }
191
+ return {
192
+ digest: `sha256:${hash.digest("hex")}`,
193
+ root,
194
+ files: tokens.size,
195
+ hashed: hashList.length,
196
+ statOnly,
197
+ capped,
198
+ newestEditMs,
199
+ ms: Date.now() - started,
200
+ };
201
+ }
202
+
203
+ if (invokedDirectly(import.meta.url)) {
204
+ const { flags } = parseArgs(process.argv.slice(2), { booleans: ["json"] });
205
+ const r = sourceDigest(typeof flags.repo === "string" ? flags.repo : process.cwd());
206
+ if (!r) {
207
+ process.stderr.write("source-digest: not a git work tree, or git did not answer in time\n");
208
+ process.exit(3);
209
+ }
210
+ process.stdout.write(flags.json ? `${JSON.stringify(r)}\n` : `${r.digest}\n`);
211
+ }
@@ -40,10 +40,25 @@
40
40
  * mode without the evidence). Phase 3 notes the unverified todos and the
41
41
  * exemptions a todo declared for itself (`--no-tests`, `selfDeclared`).
42
42
  *
43
+ * The tests RED wrote are kept. RED records `red.testFiles[]`: every test file
44
+ * of the run's work tree (state.worktreePath, or --repo) committed since the
45
+ * run base (state.baseSha, else MA_RUN_BASE_SHA; HEAD when neither is set)
46
+ * or new or changed in the work tree, as {path, blob}, so a failing test
47
+ * committed before RED is kept too. The blob is written into that
48
+ * repository's object store so the bytes can come back. Under
49
+ * MULTI_AGENT_UNATTENDED=1 test-integrity-gate reports even a recorded edit
50
+ * as blocking. GREEN refuses (exit 1) when one of those files was
51
+ * modified or deleted since, because a suite made green by weakening its own
52
+ * new test proves nothing; `restore` writes the RED bytes back. A legitimate
53
+ * fix to the test passes with `--test-edit-reason <why>` and is kept as
54
+ * `green.testEdits[]`, which test-integrity-gate --state reports for review.
55
+ * Outside a git work tree no files are recorded and nothing is refused.
56
+ *
43
57
  * CLI (exit 0 ok, 1 the evidence does not hold, 2 usage or unreadable input):
44
58
  * tdd-evidence.mjs parse <results>
45
- * tdd-evidence.mjs red --state <f> --todo <id> --results <r> [--tests a,b] [--already-passing <reason>] [--mode off|warn|enforce]
46
- * tdd-evidence.mjs green --state <f> --todo <id> --results <r>
59
+ * tdd-evidence.mjs red --state <f> --todo <id> --results <r> [--tests a,b] [--already-passing <reason>] [--mode off|warn|enforce] [--repo <dir>]
60
+ * tdd-evidence.mjs green --state <f> --todo <id> --results <r> [--test-edit-reason <why>] [--repo <dir>]
61
+ * tdd-evidence.mjs restore --state <f> --todo <id> [--repo <dir>]
47
62
  * tdd-evidence.mjs check --state <f> --todo <id> --mode off|warn|enforce [--no-tests <reason>]
48
63
  * tdd-evidence.mjs unverified --state <f>
49
64
  *
@@ -56,10 +71,12 @@
56
71
  */
57
72
 
58
73
  import { spawnSync } from "node:child_process";
59
- import { readdirSync, readFileSync, statSync } from "node:fs";
60
- import { basename, join } from "node:path";
74
+ import { existsSync, lstatSync, readdirSync, readFileSync, statSync } from "node:fs";
75
+ import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
61
76
 
77
+ import { isTestPath } from "../scripts/_handle-patterns.mjs";
62
78
  import { fromXcresultJson, summarize } from "../scripts/test-summary.mjs";
79
+ import { mkdirSafe, writeFileSafe } from "./safe-write.mjs";
63
80
  import { invokedDirectly } from "./invoked-directly.mjs";
64
81
  import { ArgsError, parseArgs } from "./args.mjs";
65
82
 
@@ -327,6 +344,191 @@ export function resultsFresh(path, startedAt) {
327
344
  }
328
345
  }
329
346
 
347
+ // ---------------------------------------------------------------------------
348
+ // Test files written in RED
349
+
350
+ const MAX_TEST_FILES = 200;
351
+ const GIT_TIMEOUT_MS = 20000;
352
+
353
+ function gitRun(dir, args, { input, buffer = false } = {}) {
354
+ const r = spawnSync("git", ["-C", dir, ...args], {
355
+ encoding: buffer ? null : "utf8",
356
+ timeout: GIT_TIMEOUT_MS,
357
+ maxBuffer: 256 * 1024 * 1024,
358
+ input,
359
+ });
360
+ return r.status === 0 && !r.error ? r.stdout : null;
361
+ }
362
+
363
+ /** The root of the git work tree `dir` is in, or null. */
364
+ export function workTreeRoot(dir) {
365
+ if (!dir || !existsSync(dir)) return null;
366
+ const out = gitRun(dir, ["rev-parse", "--show-toplevel"]);
367
+ return out ? out.trim() : null;
368
+ }
369
+
370
+ /** A repository-relative path that stays inside the work tree. */
371
+ function insideRoot(root, path) {
372
+ if (typeof path !== "string" || !path || isAbsolute(path) || path.includes("\0")) return null;
373
+ const abs = resolve(root, path);
374
+ const rel = relative(root, abs);
375
+ if (!rel || rel === ".." || rel.startsWith(`..${sep}`) || isAbsolute(rel)) return null;
376
+ return abs;
377
+ }
378
+
379
+ /** The commit `ref` names in the work tree at root, or null. */
380
+ function commitOf(root, ref) {
381
+ if (typeof ref !== "string" || !/^[0-9a-f]{7,64}$/i.test(ref)) return null;
382
+ const out = gitRun(root, [
383
+ "rev-parse",
384
+ "--verify",
385
+ "--quiet",
386
+ "--end-of-options",
387
+ `${ref}^{commit}`,
388
+ ]);
389
+ return out ? out.trim() || null : null;
390
+ }
391
+
392
+ /**
393
+ * The test files the run wrote: those committed since the run base
394
+ * (`git diff <base>...HEAD`, deletions left out), and the work tree's new,
395
+ * changed and renamed-to ones, untracked included. Without a base, or with
396
+ * one that names no commit here, the run starts at HEAD and only the work
397
+ * tree counts.
398
+ */
399
+ function changedTestFiles(root, base = null) {
400
+ const paths = [];
401
+ const since = commitOf(root, base);
402
+ if (since) {
403
+ const committed = gitRun(root, [
404
+ "diff",
405
+ "--name-only",
406
+ "-z",
407
+ "--diff-filter=d",
408
+ `${since}...HEAD`,
409
+ ]);
410
+ for (const path of (committed ?? "").split("\0"))
411
+ if (path && isTestPath(path)) paths.push(path);
412
+ }
413
+ const out = gitRun(root, ["status", "--porcelain=v1", "-z", "--untracked-files=all"]);
414
+ if (out === null) return paths;
415
+ const recs = out.split("\0");
416
+ for (let i = 0; i < recs.length; i++) {
417
+ const rec = recs[i];
418
+ if (rec.length < 4) continue;
419
+ const xy = rec.slice(0, 2);
420
+ if (xy[0] === "R" || xy[0] === "C") i++;
421
+ if (xy.includes("D")) continue;
422
+ const path = rec.slice(3);
423
+ if (isTestPath(path)) paths.push(path);
424
+ }
425
+ return paths;
426
+ }
427
+
428
+ /** The run base: the state's baseSha, else MA_RUN_BASE_SHA, else none (HEAD). */
429
+ export function runBase(state, env = process.env) {
430
+ const fromState = typeof state?.baseSha === "string" ? state.baseSha.trim() : "";
431
+ return fromState || String(env.MA_RUN_BASE_SHA || "").trim() || null;
432
+ }
433
+
434
+ function hashFiles(root, paths, write) {
435
+ if (!paths.length) return [];
436
+ const args = write ? ["hash-object", "-w", "--stdin-paths"] : ["hash-object", "--stdin-paths"];
437
+ const out = gitRun(root, args, { input: `${paths.join("\n")}\n` });
438
+ const shas = out ? out.trim().split("\n") : [];
439
+ if (shas.length !== paths.length) throw new Unreadable(`git could not hash ${paths.join(", ")}`);
440
+ return shas;
441
+ }
442
+
443
+ /**
444
+ * Keep the test files a RED run stands on: each file's bytes go into the
445
+ * repository's object store and its blob id is returned. `paths` defaults to
446
+ * the test files the run wrote since `base` (changedTestFiles).
447
+ *
448
+ * @param {string} repo
449
+ * @param {string[]|null} [paths]
450
+ * @param {{base?: string|null}} [opts]
451
+ * @returns {{path: string, blob: string}[]}
452
+ */
453
+ export function snapshotTestFiles(repo, paths = null, { base = null } = {}) {
454
+ const root = workTreeRoot(repo);
455
+ if (!root) return [];
456
+ const wanted = [...new Set(paths ?? changedTestFiles(root, base))]
457
+ .filter((p) => {
458
+ const abs = insideRoot(root, p);
459
+ return abs && !p.includes("\n") && existsSync(abs) && lstatSync(abs).isFile();
460
+ })
461
+ .sort()
462
+ .slice(0, MAX_TEST_FILES);
463
+ const blobs = hashFiles(root, wanted, true);
464
+ return wanted.map((path, i) => ({ path, blob: blobs[i] }));
465
+ }
466
+
467
+ /**
468
+ * Which kept test files no longer hold their RED bytes.
469
+ *
470
+ * @param {string} repo
471
+ * @param {{path: string, blob: string}[]} testFiles
472
+ * @returns {{path: string, change: "modified"|"deleted"}[]}
473
+ */
474
+ export function testFileChanges(repo, testFiles) {
475
+ const root = workTreeRoot(repo);
476
+ if (!root || !Array.isArray(testFiles) || !testFiles.length) return [];
477
+ const present = [];
478
+ const changes = [];
479
+ for (const f of testFiles) {
480
+ const abs = insideRoot(root, f?.path);
481
+ if (!abs) continue;
482
+ if (!existsSync(abs)) changes.push({ path: f.path, change: "deleted" });
483
+ else present.push(f);
484
+ }
485
+ const now = hashFiles(
486
+ root,
487
+ present.map((f) => f.path),
488
+ false,
489
+ );
490
+ present.forEach((f, i) => {
491
+ if (now[i] !== f.blob) changes.push({ path: f.path, change: "modified" });
492
+ });
493
+ return changes.sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
494
+ }
495
+
496
+ /**
497
+ * Write the RED bytes of every kept test file that changed back into the work
498
+ * tree. A path that leaves the work tree, or a link on the way, is refused.
499
+ *
500
+ * @param {string} repo
501
+ * @param {{path: string, blob: string}[]} testFiles
502
+ * @returns {string[]} the restored paths
503
+ */
504
+ export function restoreTestFiles(repo, testFiles) {
505
+ const root = workTreeRoot(repo);
506
+ if (!root) throw new Unreadable(`${repo} is not in a git work tree`);
507
+ for (const f of testFiles ?? []) {
508
+ if (!insideRoot(root, f?.path)) {
509
+ throw new Refused(`refusing to restore ${f?.path}: outside the work tree`);
510
+ }
511
+ }
512
+ const changed = new Set(testFileChanges(root, testFiles).map((c) => c.path));
513
+ const restored = [];
514
+ for (const f of testFiles ?? []) {
515
+ if (!changed.has(f.path)) continue;
516
+ const bytes = gitRun(root, ["cat-file", "blob", f.blob], { buffer: true });
517
+ if (bytes === null) throw new Unreadable(`blob ${f.blob} for ${f.path} is gone`);
518
+ const abs = insideRoot(root, f.path);
519
+ try {
520
+ mkdirSafe(dirname(abs), { mode: 0o755, anchors: [root] });
521
+ writeFileSafe(abs, bytes, { mode: 0o644, anchors: [root] });
522
+ } catch (err) {
523
+ if (err?.code === "ELINKED")
524
+ throw new Refused(`refusing to restore ${f.path}: ${err.message}`);
525
+ throw err;
526
+ }
527
+ restored.push(f.path);
528
+ }
529
+ return restored;
530
+ }
531
+
330
532
  // ---------------------------------------------------------------------------
331
533
  // Decisions
332
534
 
@@ -407,9 +609,19 @@ export function redRecord(summary, { tests = [], alreadyPassing = "", mode = "wa
407
609
  * The GREEN record, on top of the todo's RED record.
408
610
  *
409
611
  * @param {object} summary
410
- * @param {{prior: object|null, testPolicy?: string, now: string}} opts
612
+ * @param {{prior: object|null, testPolicy?: string, now: string,
613
+ * testChanges?: {path: string, change: string}[], testEditReason?: string}} opts
411
614
  */
412
- export function greenRecord(summary, { prior, testPolicy, now }) {
615
+ export function greenRecord(
616
+ summary,
617
+ { prior, testPolicy, now, testChanges = [], testEditReason = "" },
618
+ ) {
619
+ if (testChanges.length && !testEditReason) {
620
+ const list = testChanges.map((c) => `${c.path} (${c.change})`).join(", ");
621
+ throw new Refused(
622
+ `test file(s) written in RED changed before GREEN: ${list}. A suite made green by weakening its own new test proves nothing: restore them (tdd-evidence.mjs restore, plan-todos.sh tdd-restore), or, when the test itself was wrong, record why with --test-edit-reason <why>`,
623
+ );
624
+ }
413
625
  if (!prior?.red && testPolicy !== "tests-after") {
414
626
  throw new Refused("no RED run recorded for this todo; record RED first");
415
627
  }
@@ -436,7 +648,10 @@ export function greenRecord(summary, { prior, testPolicy, now }) {
436
648
  base.outcome = "verified";
437
649
  delete base.reason;
438
650
  }
439
- return { ...base, green: { at: now, failed: 0, total: summary.total } };
651
+ const green = { at: now, failed: 0, total: summary.total };
652
+ if (testChanges.length)
653
+ green.testEdits = testChanges.map((c) => ({ ...c, reason: testEditReason }));
654
+ return { ...base, green };
440
655
  }
441
656
 
442
657
  function exemption(todo, { taskType, testPolicy, noTests }) {
@@ -532,21 +747,39 @@ function main(argv) {
532
747
  if (!f.results) throw new Unreadable("--results is required");
533
748
  const summary = parseResults(f.results);
534
749
  resultsFresh(f.results, todo.startedAt);
535
- const record =
536
- cmd === "red"
537
- ? redRecord(summary, {
538
- tests: (f.tests ?? "").split(",").filter(Boolean),
539
- alreadyPassing: f["already-passing"] ?? "",
540
- mode: f.mode,
541
- now,
542
- })
543
- : greenRecord(summary, { prior: todo.tdd ?? null, testPolicy: state.testPolicy, now });
750
+ const repo = typeof f.repo === "string" ? f.repo : state.worktreePath;
751
+ let record;
752
+ if (cmd === "red") {
753
+ record = redRecord(summary, {
754
+ tests: (f.tests ?? "").split(",").filter(Boolean),
755
+ alreadyPassing: f["already-passing"] ?? "",
756
+ mode: f.mode,
757
+ now,
758
+ });
759
+ const testFiles =
760
+ record.outcome === "red"
761
+ ? snapshotTestFiles(repo, null, { base: runBase(state, process.env) })
762
+ : [];
763
+ if (testFiles.length) record.red.testFiles = testFiles;
764
+ } else {
765
+ record = greenRecord(summary, {
766
+ prior: todo.tdd ?? null,
767
+ testPolicy: state.testPolicy,
768
+ now,
769
+ testChanges: testFileChanges(repo, todo.tdd?.red?.testFiles),
770
+ testEditReason: typeof f["test-edit-reason"] === "string" ? f["test-edit-reason"] : "",
771
+ });
772
+ }
544
773
  if (record.red?.testsUnverifiable) {
545
774
  process.stderr.write(
546
775
  `tdd-evidence: warning: ${f.results} names no failing test, so --tests ${f.tests} is recorded unchecked (red.testsUnverifiable); JUnit XML names them\n`,
547
776
  );
548
777
  }
549
778
  print(record);
779
+ } else if (cmd === "restore") {
780
+ const { state, todo } = loadTodo(f);
781
+ const repo = typeof f.repo === "string" ? f.repo : state.worktreePath;
782
+ print({ restored: restoreTestFiles(repo, todo.tdd?.red?.testFiles ?? []) });
550
783
  } else if (cmd === "check") {
551
784
  const { state, todo } = loadTodo(f);
552
785
  print(
@@ -566,7 +799,7 @@ function main(argv) {
566
799
  }
567
800
  } else {
568
801
  throw new Unreadable(
569
- `unknown subcommand '${cmd ?? ""}' (parse | red | green | check | unverified)`,
802
+ `unknown subcommand '${cmd ?? ""}' (parse | red | green | restore | check | unverified)`,
570
803
  );
571
804
  }
572
805
  return 0;
@@ -0,0 +1,87 @@
1
+ /**
2
+ * @file tiered-budget.mjs - fit a block of whole items under a character
3
+ * budget, and the three budgets a tiered query answers in.
4
+ *
5
+ * fitToBudget(items, { maxChars, render, measure, note })
6
+ * items [{ id, priority, ... }]; higher priority survives longer, and
7
+ * among equal priorities the later item is dropped first. An
8
+ * item too large to fit even alone is dropped before any other.
9
+ * render (keptItems) => string, called with the kept items in their
10
+ * original order
11
+ * measure (text) => number, default text.length
12
+ * note (droppedCount) => string, the line appended when anything was
13
+ * dropped; default omittedNote (the hook limit wording)
14
+ * returns { text, dropped: [ids in the order they were dropped] }
15
+ *
16
+ * The appended line is counted against the budget too. An item is never cut
17
+ * in half: a clipped fact reads as a different fact.
18
+ *
19
+ * QUERY_TIERS are the answer sizes for a graph or learnings query:
20
+ * quick top hits only
21
+ * panorama hubs, clusters and neighbours around the hits
22
+ * deep paths and full node detail
23
+ * deep is larger than the hook limit on purpose: a tiered answer goes to a
24
+ * caller that asked for it, never into a hook's output.
25
+ *
26
+ * Imports nothing, so the toolkit can carry a byte-identical copy
27
+ * (scripts/vendor-sync.mjs there).
28
+ *
29
+ * @module pipeline/lib/tiered-budget
30
+ */
31
+
32
+ export const HOOK_OUTPUT_LIMIT = 10000;
33
+
34
+ export const QUERY_TIERS = Object.freeze({ quick: 1500, panorama: 6000, deep: 12000 });
35
+
36
+ export const TIER_NAMES = Object.freeze(Object.keys(QUERY_TIERS));
37
+
38
+ /** The character budget of a tier, or null for a name that is not one. */
39
+ export function tierChars(name) {
40
+ return Object.hasOwn(QUERY_TIERS, String(name)) ? QUERY_TIERS[name] : null;
41
+ }
42
+
43
+ /** The line appended when items were dropped to fit a hook's output. */
44
+ export function omittedNote(n, maxChars) {
45
+ return `(${n} ${n === 1 ? "item" : "items"} left out to stay under the ${maxChars}-character hook limit)`;
46
+ }
47
+
48
+ /** The line appended when items were dropped to fit a query tier. */
49
+ export function tierNote(tier, maxChars) {
50
+ return (n) =>
51
+ `(${n} ${n === 1 ? "item" : "items"} left out to fit the ${tier} tier's ${maxChars} characters)`;
52
+ }
53
+
54
+ /**
55
+ * @param {Array<{id?: string, priority?: number}>} items
56
+ * @param {{maxChars?: number, render: (items: object[]) => string, measure?: (s: string) => number, note?: (n: number) => string}} opts
57
+ * @returns {{text: string, dropped: string[]}}
58
+ */
59
+ export function fitToBudget(items, { maxChars = HOOK_OUTPUT_LIMIT, render, measure, note } = {}) {
60
+ const size = measure || ((s) => s.length);
61
+ const noteFor = note || ((n) => omittedNote(n, maxChars));
62
+ const list = Array.isArray(items) ? items : [];
63
+ // An item that cannot fit even alone is never kept, so it goes first and
64
+ // does not take the smaller items below it down with it.
65
+ const dropOrder = list
66
+ .map((it, index) => ({
67
+ index,
68
+ priority: Number(it?.priority) || 0,
69
+ oversize: size(String(render([it]) ?? "")) > maxChars,
70
+ }))
71
+ .sort((a, b) => b.oversize - a.oversize || a.priority - b.priority || b.index - a.index)
72
+ .map((x) => x.index);
73
+ const gone = new Set();
74
+ const dropped = [];
75
+ for (let step = 0; step <= dropOrder.length; step++) {
76
+ const kept = list.filter((_, i) => !gone.has(i));
77
+ const body = kept.length ? String(render(kept) ?? "") : "";
78
+ const text = dropped.length ? `${body}${body ? "\n" : ""}${noteFor(dropped.length)}` : body;
79
+ if (size(text) <= maxChars) return { text, dropped };
80
+ if (step === dropOrder.length) break;
81
+ const i = dropOrder[step];
82
+ gone.add(i);
83
+ dropped.push(String(list[i]?.id ?? i));
84
+ }
85
+ const last = noteFor(dropped.length);
86
+ return { text: size(last) <= maxChars ? last : "", dropped };
87
+ }