muse-crew 0.14.4 → 0.14.6

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.
@@ -1,140 +0,0 @@
1
- #!/usr/bin/env node
2
- // build-readback-request.js — deterministic builder for the parent publish
3
- // content read-back inspection request.
4
- //
5
- // The parent (tick worker) never hand-writes the inspection prompt: this
6
- // script builds the EXACT request from the merge commit's diff, so the
7
- // read-back asks about the real expected change, not an LLM's paraphrase.
8
- // Output is JSON on stdout: { verbatim_request }.
9
- //
10
- // Usage:
11
- // node build-readback-request.js --repo-path <path> --commit <sha>
12
- // --base <sha> --task-id <uuid> --slug <artifact-slug>
13
- // [--build-agent-id <uuid>]
14
- //
15
- // --base is the previously-stamped provenance source_commit (the tree the
16
- // last verification certified), or the empty-tree sha
17
- // 4b825dc642cb6eb9a060e54bf8d69288fbee4904 for a first publish with no
18
- // prior stamp. It is REQUIRED because the merge commit's first parent is
19
- // NOT necessarily the previously-published tree: push-time reconcile
20
- // merges (2026-09-14, task 0c53af4e) put the task's own changes behind an
21
- // intermediate merge, so `commit^1..commit` covers only the reconcile
22
- // delta and the request would certify content it never checked.
23
- //
24
- // Exit codes: 0 ok · 2 usage/validation · 1 git/diff failure.
25
-
26
- import { execFileSync } from "node:child_process";
27
-
28
- // --help: before required-arg parsing (shebang⇔CLI contract).
29
- if (process.argv.slice(2).includes("--help")) {
30
- console.log(
31
- "usage: node build-readback-request.js --repo-path <path> --commit <sha>\n" +
32
- " --base <sha> --task-id <uuid> --slug <artifact-slug> [--build-agent-id <uuid>]\n" +
33
- "builds the read-back inspection request from the merge commit's diff"
34
- );
35
- process.exit(0);
36
- }
37
-
38
- const EMPTY_TREE = "4b825dc642cb6eb9a060e54bf8d69288fbee4904";
39
-
40
- function arg(name) {
41
- const i = process.argv.indexOf(name);
42
- if (i < 0 || i + 1 >= process.argv.length) {
43
- process.stderr.write(JSON.stringify({ ok: false, error: "usage", message: `${name} is required.` }) + "\n");
44
- process.exit(2);
45
- }
46
- return process.argv[i + 1];
47
- }
48
-
49
- const repoPath = arg("--repo-path");
50
- const commit = arg("--commit");
51
- const base = arg("--base");
52
- const taskId = arg("--task-id");
53
- const slug = arg("--slug");
54
- const buildAgentId = process.argv.includes("--build-agent-id")
55
- ? arg("--build-agent-id") : null;
56
-
57
- if (!/^[0-9a-f]{40}$/.test(commit)) {
58
- process.stderr.write(JSON.stringify({ ok: false, error: "usage", message: "commit must be a 40-char hex sha." }) + "\n");
59
- process.exit(2);
60
- }
61
- if (!/^[0-9a-f]{40}$/.test(base)) {
62
- process.stderr.write(JSON.stringify({ ok: false, error: "usage", message: "base must be a 40-char hex sha." }) + "\n");
63
- process.exit(2);
64
- }
65
- // The publish delta is base..commit. Refuse a base that is not an ancestor:
66
- // certifying a diff against an unrelated tree is worse than no request.
67
- if (base !== EMPTY_TREE) {
68
- try {
69
- execFileSync("git", ["-C", repoPath, "merge-base", "--is-ancestor", base, commit], { stdio: "ignore" });
70
- } catch (e) {
71
- process.stderr.write(JSON.stringify({ ok: false, error: "usage", message: `base ${base} is not an ancestor of commit ${commit} — refusing to build a request that could certify an unrelated tree.` }) + "\n");
72
- process.exit(2);
73
- }
74
- }
75
-
76
- let diff;
77
- try {
78
- diff = execFileSync("git", ["-C", repoPath, "diff", base, commit, "--"], {
79
- encoding: "utf8", maxBuffer: 4 * 1024 * 1024,
80
- });
81
- } catch (e) {
82
- process.stderr.write(JSON.stringify({ ok: false, error: "git", message: `git diff failed: ${e.message}` }) + "\n");
83
- process.exit(1);
84
- }
85
- if (!diff.trim()) {
86
- process.stderr.write(JSON.stringify({ ok: false, error: "git", message: "empty diff for commit." }) + "\n");
87
- process.exit(1);
88
- }
89
-
90
- // Parse the diff into per-file added/removed lines (the contract the
91
- // verifier will check the inspector's findings against).
92
- const files = [];
93
- let current = null;
94
- for (const line of diff.split("\n")) {
95
- if (line.startsWith("diff --git")) {
96
- const m = line.match(/^diff --git a\/(.+) b\/(.+)$/);
97
- current = { path: m ? m[2] : "unknown", added: [], removed: [] };
98
- files.push(current);
99
- } else if (current && line.startsWith("+") && !line.startsWith("+++")) {
100
- current.added.push(line.slice(1));
101
- } else if (current && line.startsWith("-") && !line.startsWith("---")) {
102
- current.removed.push(line.slice(1));
103
- }
104
- }
105
-
106
- const buildIdLine = buildAgentId
107
- ? `Expected builder build agent_id: ${buildAgentId} (the artifact system's in-flight correlation ID for this publish attempt — not a durable post-completion identifier).\nReport the live build's agent_id as seen in artifact_status (or state explicitly that no build/agent_id is visible). If an expected agent_id is given above and the live one differs, say so exactly — the read-back may be inspecting a different build's output.\n\n`
108
- : "";
109
-
110
- const verbatim_request =
111
- `Publish content read-back for task ${taskId}, merge commit ${commit}.
112
- Expected change: the publish delta ${base}..${commit} (base = previously-stamped source commit, or the empty tree for a first publish).
113
- The unified diff below was supposed to be applied to this artifact's source tree and deployed. Do NOT modify anything.
114
- Do NOT rely on the builder's applied-changes report — it is derived from this same diff, so it cannot confirm the content. Read the artifact's CURRENT source directly.
115
-
116
- ${buildIdLine}UNIFIED DIFF (expected change):
117
- \`\`\`diff
118
- ${diff}\`\`\`
119
-
120
- For each file in the diff:
121
- 1. Read the file's CURRENT content in the artifact source tree.
122
- 2. Quote the exact current text of the regions around the changed lines.
123
- 3. For every added (+) line in the diff, state whether that exact line is PRESENT in the current source.
124
- 4. For every removed (-) line in the diff, state whether that exact line is ABSENT from the current source.
125
- 5. Report build/deploy health and the console error count.
126
-
127
- MACHINE-READABLE FINDINGS (REQUIRED — the parent parses this block mechanically; if it is missing or malformed the verification FAILS CLOSED as blocked):
128
- For each file, emit exactly these lines, one per changed line, with the verdict at the end of the line:
129
- FILE: <path>
130
- ADDED: <exact added line from the diff> :: PRESENT
131
- ADDED: <exact added line from the diff> :: ABSENT
132
- REMOVED: <exact removed line from the diff> :: PRESENT
133
- REMOVED: <exact removed line from the diff> :: ABSENT
134
- END_FILE
135
- Emit one ADDED line per (+) diff line and one REMOVED line per (-) diff line — no more, no fewer. The verdict is PRESENT if that exact line occurs in the file's current source, ABSENT otherwise.
136
-
137
- Return the per-file present/absent findings with the quoted observed lines. Do not modify anything.
138
- This read-back feeds the parent content-verification protocol (docs/publish-verification.md): the parent stamps provenance only when every added line is present and every removed line is absent.`;
139
-
140
- process.stdout.write(JSON.stringify({ verbatim_request, files_changed: files.map((f) => f.path) }, null, 2) + "\n");
@@ -1,462 +0,0 @@
1
- #!/usr/bin/env node
2
- // classify-publish-absence.js — deterministic classifier for publish attempts
3
- // parked with an UNKNOWN outcome (blocker 15, Phase 1, 2026-09-18).
4
- //
5
- // The workflow's fire-and-forget trigger returns no receipt, so a parked
6
- // unknown means "the edit may or may not have gone through and the build
7
- // may or may not have run." This unit decides mechanically from durable
8
- // signals only — never from timing windows or audit-dir counting:
9
- //
10
- // sensor findings (lib/readback-disk.js — the on-disk source read-back)
11
- // × manifest (.space-build/manifest.json — built_at + content_sha256)
12
- // × repo state (git diff base..commit, HEAD)
13
- //
14
- // Decisions (design-room19.md §1.4):
15
- // verified — manifest built_at advanced past the trigger AND
16
- // every discriminating added line PRESENT / removed
17
- // ABSENT (the build landed; route to parent
18
- // verification, which stamps).
19
- // provably-dropped — (a) every discriminating added line ABSENT,
20
- // (b) every discriminating removed line PRESENT,
21
- // (c) manifest built_at NOT advanced past trigger,
22
- // (d) no build in flight (checked twice, bracketing
23
- // the content read), (e) decision time ≥ park +
24
- // quiesce, (f) HEAD == commit. One safe retry.
25
- // applied-not-built — source PRESENT but manifest stale: the platform
26
- // started something but no build completed.
27
- // → ambiguous, park with the diagnosis, NO retry
28
- // (re-applying a possibly mid-apply diff is the
29
- // 2026-09-12 hazard in a new coat).
30
- // ambiguous — partial-apply, binary/mode-only/rename diffs,
31
- // unreadable sensor, manifest-advanced-but-mismatched,
32
- // zero discriminating lines. Terminal, no retry.
33
- // deferred — trigger age < quiesce, or build in flight. No
34
- // budget consumed. Still in flight at park+2h → the
35
- // caller treats it as terminal (pathological).
36
- // superseded — HEAD != commit. Terminal, no retry (a retry would
37
- // regress a newer publish).
38
- //
39
- // "Discriminating" reuses lib/publish-content.js — the verifier's own
40
- // collision-exemption logic. Lines already in the old tree are
41
- // non-discriminating and ignored.
42
- //
43
- // Usage:
44
- // node classify-publish-absence.js --repo-path <path> --commit <sha>
45
- // --base <sha> --slug <slug> --trigger-ts <ISO> --park-ts <ISO>
46
- // [--spaces-root <dir>] [--task-id <uuid>]
47
- // [--quiesce-mins <n>] [--in-flight-window-mins <n>]
48
- //
49
- // --manifest-before is the workflow's pre-trigger manifest snapshot
50
- // (JSON {"built_at":<ISO|null>,"content_sha256":<hex|null>}, design §1.9).
51
- // The verified path requires the current manifest's content_sha256 to
52
- // differ from the baseline (a new build identity, not a replayed
53
- // manifest). When the baseline is unavailable the classifier falls back
54
- // to the time-based advance check and notes it; the Step 4.5 verifier
55
- // (lib/verify-publish.js) is the strict gate and fails closed without a
56
- // baseline before stamping.
57
- //
58
- // Exit 0 with the decision JSON on stdout for every decision (a decision
59
- // is data, not a failure). Exit 2 on usage/validation. Nothing is printed
60
- // to stdout on failure.
61
-
62
- import { execFileSync } from "node:child_process";
63
- import { readdirSync, readFileSync, realpathSync, statSync } from "node:fs";
64
- import { homedir } from "node:os";
65
- import { join, resolve } from "node:path";
66
- import {
67
- EMPTY_TREE,
68
- parseDiff,
69
- parseFindings,
70
- makeOldCounter,
71
- discriminatingLines,
72
- } from "./publish-content.js";
73
-
74
- // --help: before required-arg parsing (shebang⇔CLI contract).
75
- if (process.argv.slice(2).includes("--help")) {
76
- console.log(
77
- "usage: node classify-publish-absence.js --repo-path <path> --commit <sha>\n" +
78
- " --base <sha> --slug <slug> --trigger-ts <ISO> --park-ts <ISO>\n" +
79
- " [--spaces-root <dir>] [--task-id <uuid>] [--quiesce-mins <n>] [--in-flight-window-mins <n>] [--manifest-before <json>]\n" +
80
- "six-way classifier for publish attempts parked with an UNKNOWN outcome; prints the decision JSON on stdout"
81
- );
82
- process.exit(0);
83
- }
84
-
85
- function arg(name, required = true, def = null) {
86
- const i = process.argv.lastIndexOf(name); // last occurrence wins
87
- if (i < 0 || i + 1 >= process.argv.length) {
88
- if (required && def === null) fail("usage", `${name} is required.`);
89
- return def;
90
- }
91
- return process.argv[i + 1];
92
- }
93
- function fail(code, message) {
94
- process.stderr.write(JSON.stringify({ ok: false, error: code, message }) + "\n");
95
- process.exit(2);
96
- }
97
-
98
- const repoPath = arg("--repo-path");
99
- const commit = arg("--commit");
100
- const base = arg("--base");
101
- const slug = arg("--slug");
102
- const triggerTs = arg("--trigger-ts");
103
- const parkTs = arg("--park-ts");
104
- const spacesRoot = arg("--spaces-root", false, join(homedir(), "workspace", "ts-spaces"));
105
- const taskId = arg("--task-id", false, "classify");
106
- const quiesceMins = parseInt(arg("--quiesce-mins", false, "30"), 10);
107
- const inFlightWindowMins = parseInt(arg("--in-flight-window-mins", false, "15"), 10);
108
- // Pre-trigger manifest baseline (design §1.9), JSON-encoded. Optional —
109
- // the classifier falls back to the time-based check when absent.
110
- // 2026-09-18, should-fix 1: distinguish absent (legacy, no baseline) from
111
- // malformed (supplied but invalid) — malformed is ambiguous, not absent.
112
- // A valid baseline requires a parseable built_at timestamp and a 64-hex
113
- // content_sha256.
114
- let manifestBefore = null;
115
- let manifestBeforeMalformed = false;
116
- const manifestBeforeRaw = arg("--manifest-before", false, null);
117
- if (manifestBeforeRaw) {
118
- try {
119
- const parsed = JSON.parse(manifestBeforeRaw);
120
- const builtAt = parsed && typeof parsed.built_at === "string" ? parsed.built_at : null;
121
- const sha = parsed && typeof parsed.content_sha256 === "string" ? parsed.content_sha256 : null;
122
- const builtAtMs = builtAt ? Date.parse(builtAt) : NaN;
123
- const shaOk = sha && /^[0-9a-f]{64}$/.test(sha);
124
- if (parsed && typeof parsed === "object" && builtAtMs > 0 && shaOk) {
125
- manifestBefore = { built_at: builtAt, content_sha256: sha };
126
- } else {
127
- // Supplied but invalid: fail closed as ambiguous, not absent.
128
- manifestBeforeMalformed = true;
129
- }
130
- } catch {
131
- // Supplied but unparsable: fail closed as ambiguous, not absent.
132
- manifestBeforeMalformed = true;
133
- }
134
- }
135
-
136
- if (!/^[0-9a-f]{40}$/.test(commit)) fail("usage", "commit must be a 40-char hex sha.");
137
- if (!/^[0-9a-f]{40}$/.test(base)) fail("usage", "base must be a 40-char hex sha.");
138
- if (!/^[A-Za-z0-9][A-Za-z0-9_.-]*$/.test(slug)) fail("usage", "slug is not a safe artifact slug.");
139
- const triggerMs = Date.parse(triggerTs);
140
- const parkMs = Date.parse(parkTs);
141
- if (!(triggerMs > 0)) fail("usage", "trigger-ts is not a valid timestamp.");
142
- if (!(parkMs > 0)) fail("usage", "park-ts is not a valid timestamp.");
143
- if (!(quiesceMins > 0)) fail("usage", "quiesce-mins must be positive.");
144
- if (!(inFlightWindowMins > 0)) fail("usage", "in-flight-window-mins must be positive.");
145
-
146
- function decide(decision, reasons, details = {}) {
147
- process.stdout.write(JSON.stringify({ ok: true, decision, reasons, details }) + "\n");
148
- process.exit(0);
149
- }
150
-
151
- // Resolve the space dir with realpath containment (same rule as
152
- // readback-disk.js — the slug must not escape the spaces root).
153
- function resolveSpaceDir() {
154
- try {
155
- const rootReal = realpathSync(spacesRoot);
156
- const candReal = realpathSync(join(spacesRoot, slug));
157
- if (candReal !== rootReal && !candReal.startsWith(rootReal + "/")) return null;
158
- return statSync(candReal).isDirectory() ? candReal : null;
159
- } catch {
160
- return null;
161
- }
162
- }
163
-
164
- // (d) No build in flight. Signals, both heuristic but conservative:
165
- // - manifest built_at within the window: a build just landed, the
166
- // deployment may still be propagating;
167
- // - any file under .space-build with mtime within the window: the
168
- // platform is actively writing build output.
169
- // A build running longer than the window without touching .space-build is
170
- // pathological; the caller escalates to terminal at park+2h.
171
- // (d) Build-in-flight detection: the manifest is the platform's build
172
- // record. A build is "in flight" for our purposes if the manifest state
173
- // changes during the content read (a build landed mid-read — the read may
174
- // be torn) or if the manifest's built_at is within the settle window (a
175
- // build just completed; the working copy may still be settling). Checked
176
- // twice bracketing the content read (design §1.4d); the double check
177
- // bounds the residual window to the local disk-read duration. Directory
178
- // mtimes are NOT used — they cannot distinguish a running build from a
179
- // recently completed one, and the manifest is the honest record.
180
- function manifestState(spaceDir) {
181
- const m = readManifest(spaceDir);
182
- if (!m) return null;
183
- return { built_at: m.built_at, content_sha256: m.content_sha256 };
184
- }
185
- function buildInFlight(spaceDir, nowMs, beforeState) {
186
- const afterState = manifestState(spaceDir);
187
- // State changed during the read → a build landed mid-read.
188
- if (beforeState && afterState &&
189
- (beforeState.built_at !== afterState.built_at ||
190
- beforeState.content_sha256 !== afterState.content_sha256)) {
191
- return { inFlight: true, afterState, reason: `manifest changed during the content read (before built_at=${beforeState.built_at}, after built_at=${afterState.built_at}) — the read may be torn` };
192
- }
193
- // Manifest built very recently → a build just completed; let it settle.
194
- // 2026-09-18, should-fix 2: enforce 0 <= age < settleMs. A future built_at
195
- // (negative age) is pathological — clock skew or corruption — and must not
196
- // defer forever. It is ambiguous, not in-flight.
197
- const settleMs = inFlightWindowMins * 60 * 1000;
198
- const builtAtMs = afterState && afterState.built_at ? Date.parse(afterState.built_at) : NaN;
199
- if (Number.isFinite(builtAtMs)) {
200
- const ageMs = nowMs - builtAtMs;
201
- if (ageMs < 0) {
202
- return { inFlight: false, afterState, pathological: true, reason: `manifest built_at ${afterState.built_at} is in the future (age ${ageMs}ms) — pathological, not in-flight` };
203
- }
204
- if (ageMs < settleMs) {
205
- return { inFlight: true, afterState, reason: `manifest built_at ${afterState.built_at} is within the ${inFlightWindowMins}min settle window — a build just completed` };
206
- }
207
- }
208
- return { inFlight: false, afterState };
209
- }
210
-
211
- function readManifest(spaceDir) {
212
- if (!spaceDir) return null;
213
- try {
214
- const m = JSON.parse(readFileSync(join(spaceDir, ".space-build", "manifest.json"), "utf8"));
215
- return {
216
- built_at: typeof m.built_at === "string" ? m.built_at : null,
217
- content_sha256: typeof m.content_sha256 === "string" ? m.content_sha256 : null,
218
- };
219
- } catch {
220
- return null;
221
- }
222
- }
223
-
224
- const nowMs = Date.now();
225
- const spaceDir = resolveSpaceDir();
226
-
227
- // (should-fix 1) Malformed supplied baseline → ambiguous, not absent.
228
- // A supplied --manifest-before that fails validation is evidence corruption,
229
- // not a legacy absent baseline. Fail closed.
230
- if (manifestBeforeMalformed) {
231
- decide("ambiguous",
232
- [`supplied --manifest-before failed validation (must be JSON with a parseable built_at and a 64-hex content_sha256)`],
233
- { manifest_before_malformed: true });
234
- }
235
-
236
- // (e) Decision time ≥ park + quiesce. Too young → deferred, no budget
237
- // consumed, no timer advanced.
238
- if (nowMs < parkMs + quiesceMins * 60 * 1000) {
239
- decide("deferred",
240
- [`trigger age below quiesce: park ${parkTs}, quiesce ${quiesceMins}min`],
241
- { park_ts: parkTs, quiesce_mins: quiesceMins });
242
- }
243
-
244
- // (d) First in-flight check, before the content read. Captures the
245
- // manifest state; the second check compares against it.
246
- const manifestBeforeRead = manifestState(spaceDir);
247
- let flight = buildInFlight(spaceDir, nowMs, null);
248
- // Pathological future timestamp → ambiguous, not deferred (should-fix 2).
249
- if (flight.pathological) {
250
- decide("ambiguous",
251
- [`manifest built_at is in the future (pathological): ${flight.reason}`],
252
- { pathological_future_built_at: true, in_flight_reason: flight.reason });
253
- }
254
- if (flight.inFlight) {
255
- if (nowMs > parkMs + 2 * 60 * 60 * 1000) {
256
- decide("ambiguous",
257
- [`build still in flight at park+2h (pathological): ${flight.reason}`],
258
- { in_flight_reason: flight.reason });
259
- }
260
- decide("deferred", [`build in flight (pre-read check): ${flight.reason}`],
261
- { in_flight_reason: flight.reason });
262
- }
263
-
264
- // The content read: the deterministic sensor on the platform's working copy.
265
- const sensorPath = join(new URL(".", import.meta.url).pathname, "readback-disk.js");
266
- let findingsText;
267
- try {
268
- findingsText = execFileSync("node", [
269
- sensorPath,
270
- "--repo-path", repoPath,
271
- "--commit", commit,
272
- "--base", base,
273
- "--slug", slug,
274
- "--task-id", taskId,
275
- "--spaces-root", spacesRoot,
276
- ], { encoding: "utf8", maxBuffer: 8 * 1024 * 1024 });
277
- } catch (e) {
278
- decide("ambiguous",
279
- [`sensor unreadable: ${(e.stderr || e.message || "").toString().slice(0, 200)}`],
280
- { sensor_failed: true });
281
- }
282
-
283
- // (d) Second in-flight check, bracketing the content read. Compares the
284
- // manifest state against the pre-read baseline; a change means a build
285
- // landed mid-read (the read may be torn). The double check bounds the
286
- // residual window to the local disk-read duration.
287
- flight = buildInFlight(spaceDir, Date.now(), manifestBeforeRead);
288
- // Pathological future timestamp → ambiguous, not deferred (should-fix 2).
289
- if (flight.pathological) {
290
- decide("ambiguous",
291
- [`manifest built_at is in the future (pathological, post-read): ${flight.reason}`],
292
- { pathological_future_built_at: true, in_flight_reason: flight.reason });
293
- }
294
- if (flight.inFlight) {
295
- decide("deferred", [`build in flight (post-read check): ${flight.reason}`],
296
- { in_flight_reason: flight.reason });
297
- }
298
-
299
- // 2026-09-18, should-fix 3: use the manifest state already checked by the
300
- // post-read in-flight check (flight.afterState) — do NOT re-read the manifest
301
- // here. A third read reopens the TOCTOU window the double-check just closed.
302
- const manifest = flight.afterState;
303
- const manifestBuiltAtMs = manifest && manifest.built_at ? Date.parse(manifest.built_at) : NaN;
304
- const manifestAdvanced = Number.isFinite(manifestBuiltAtMs) && manifestBuiltAtMs > triggerMs;
305
-
306
- // The expected change, from git (never from anyone's report).
307
- if (base !== EMPTY_TREE) {
308
- try {
309
- execFileSync("git", ["-C", repoPath, "merge-base", "--is-ancestor", base, commit], { stdio: "ignore" });
310
- } catch {
311
- decide("ambiguous", [`base ${base} is not an ancestor of commit ${commit}`], {});
312
- }
313
- }
314
- let diff;
315
- try {
316
- diff = execFileSync("git", ["-C", repoPath, "diff", base, commit, "--"], {
317
- encoding: "utf8", maxBuffer: 4 * 1024 * 1024,
318
- });
319
- } catch (e) {
320
- decide("ambiguous", [`git diff failed: ${e.message.slice(0, 200)}`], {});
321
- }
322
- if (!diff.trim()) {
323
- decide("ambiguous", ["empty diff for commit — nothing to judge"], {});
324
- }
325
- const diffMap = parseDiff(diff);
326
- const oldCount = makeOldCounter(repoPath, base);
327
- const disc = discriminatingLines(diffMap, oldCount);
328
-
329
- // Files the line-based judge cannot certify at all → ambiguous, never a
330
- // retry on zero signal.
331
- for (const [path, d] of disc) {
332
- if (d.unjudgeable) {
333
- decide("ambiguous",
334
- [`unverifiable-content ${path}: ${d.unjudgeable} — the diff carries no discriminating lines for this file`],
335
- { file: path, unjudgeable: d.unjudgeable });
336
- }
337
- }
338
-
339
- // (f) Supersession re-check: a retry against a moved HEAD would regress a
340
- // newer publish.
341
- let head;
342
- try {
343
- head = execFileSync("git", ["-C", repoPath, "rev-parse", "HEAD"], { encoding: "utf8" }).trim();
344
- } catch (e) {
345
- decide("ambiguous", [`git rev-parse HEAD failed: ${e.message.slice(0, 200)}`], {});
346
- }
347
- if (head !== commit) {
348
- decide("superseded",
349
- [`HEAD is ${head}, not ${commit} — a newer publish supersedes this one; no retry`],
350
- { head, commit });
351
- }
352
-
353
- // The findings must cover every discriminating line, or the read is not a
354
- // read of this diff.
355
- const { findings, malformed } = parseFindings(findingsText);
356
- if (malformed) {
357
- decide("ambiguous", [`unreadable findings: ${malformed}`], {});
358
- }
359
- let totalDisc = 0;
360
- let addedPresent = 0, addedAbsent = 0, removedPresent = 0, removedAbsent = 0;
361
- for (const [path, d] of disc) {
362
- const found = findings.get(path);
363
- if (!found) {
364
- decide("ambiguous", [`no findings for changed file ${path}`], { file: path });
365
- }
366
- for (const line of d.addedDisc) {
367
- totalDisc++;
368
- const v = found.added.get(line);
369
- if (v === undefined) decide("ambiguous", [`no ADDED finding for line in ${path}`], { file: path });
370
- if (v === "PRESENT") addedPresent++; else addedAbsent++;
371
- }
372
- for (const line of d.removedDisc) {
373
- totalDisc++;
374
- const v = found.removed.get(line);
375
- if (v === undefined) decide("ambiguous", [`no REMOVED finding for line in ${path}`], { file: path });
376
- if (v === "PRESENT") removedPresent++; else removedAbsent++;
377
- }
378
- }
379
- if (totalDisc === 0) {
380
- decide("ambiguous",
381
- ["zero discriminating lines across the diff — no signal to judge; refusing to decide on vacuous truth"],
382
- {});
383
- }
384
-
385
- const details = {
386
- manifest_built_at: manifest ? manifest.built_at : null,
387
- manifest_advanced: manifestAdvanced,
388
- head,
389
- discriminating_added: addedPresent + addedAbsent,
390
- discriminating_removed: removedPresent + removedAbsent,
391
- added_present: addedPresent,
392
- added_absent: addedAbsent,
393
- removed_present: removedPresent,
394
- removed_absent: removedAbsent,
395
- };
396
-
397
- // Manifest advanced past the trigger: a build ran for this attempt.
398
- if (manifestAdvanced) {
399
- // Verified ⟺ the source shows the full post-edit state. A side with no
400
- // discriminating lines is vacuously satisfied; totalDisc > 0 (checked
401
- // above) guarantees at least one side carries signal.
402
- const addedOk = addedPresent + addedAbsent === 0 || (addedPresent > 0 && addedAbsent === 0);
403
- const removedOk = removedPresent + removedAbsent === 0 || (removedAbsent > 0 && removedPresent === 0);
404
- if (addedOk && removedOk) {
405
- // Design §1.9: the manifest must be a NEW build identity, not a
406
- // replayed manifest with a bumped built_at. When the pre-trigger
407
- // baseline is available, require the content_sha256 to differ; when
408
- // unavailable, fall back to the time-based advance (noted) — the Step
409
- // 4.5 verifier is the strict gate and fails closed without a baseline
410
- // before stamping.
411
- const beforeHash = manifestBefore ? manifestBefore.content_sha256 : null;
412
- const currentHash = manifest ? manifest.content_sha256 : null;
413
- if (manifestBefore && beforeHash && currentHash) {
414
- if (beforeHash === currentHash) {
415
- decide("ambiguous",
416
- [`manifest built_at advanced past trigger but content_sha256 is unchanged from the pre-trigger baseline — a replayed manifest, not a new build; refusing to verify`],
417
- { ...details, manifest_before: manifestBefore });
418
- }
419
- decide("verified",
420
- [`manifest built_at ${manifest.built_at} advanced past trigger ${triggerTs} with a new content_sha256 (differs from pre-trigger baseline); content matches the diff`],
421
- { ...details, manifest_before: manifestBefore });
422
- }
423
- decide("verified",
424
- [`manifest built_at ${manifest.built_at} advanced past trigger ${triggerTs}; content matches the diff (no pre-trigger baseline — freshness by time only; the Step 4.5 verifier fails closed without a baseline)`],
425
- { ...details, manifest_before: null, baseline_absent: true });
426
- }
427
- // A build ran but the content does not match: not ours to claim.
428
- decide("ambiguous",
429
- [`manifest advanced past trigger but content mismatched (added PRESENT ${addedPresent}/${addedPresent + addedAbsent}, removed ABSENT ${removedAbsent}/${removedPresent + removedAbsent}) — a build ran that is not this diff`],
430
- details);
431
- }
432
-
433
- // Manifest stale: no build for this attempt. Judge the source state.
434
- const addedDropped = addedPresent + addedAbsent === 0 || (addedAbsent > 0 && addedPresent === 0);
435
- const removedDropped = removedPresent + removedAbsent === 0 || (removedPresent > 0 && removedAbsent === 0);
436
- const addedApplied = addedPresent + addedAbsent === 0 || (addedPresent > 0 && addedAbsent === 0);
437
- const removedApplied = removedPresent + removedAbsent === 0 || (removedAbsent > 0 && removedPresent === 0);
438
- if (addedDropped && removedDropped) {
439
- decide("provably-dropped",
440
- [
441
- "(a) every discriminating added line ABSENT",
442
- "(b) every discriminating removed line PRESENT",
443
- `(c) manifest built_at ${manifest ? manifest.built_at : "missing"} NOT advanced past trigger ${triggerTs}`,
444
- "(d) no build in flight (checked twice, bracketing the read)",
445
- `(e) decision time past park+${quiesceMins}min quiesce`,
446
- "(f) HEAD == commit",
447
- ],
448
- details);
449
- }
450
- if (addedApplied && removedApplied) {
451
- // J1's shape: the platform started something (the phantom) but no build
452
- // completed — "platform build-emission failure." No retry: re-applying a
453
- // possibly mid-apply diff is the 2026-09-12 hazard in a new coat.
454
- decide("applied-not-built",
455
- [
456
- `source shows the full post-edit state but manifest stale (built_at ${manifest ? manifest.built_at : "missing"}) — platform build-emission failure; no retry`,
457
- ],
458
- details);
459
- }
460
- decide("ambiguous",
461
- [`partial-apply or indeterminate (added PRESENT ${addedPresent}/${addedPresent + addedAbsent}, removed PRESENT ${removedPresent}/${removedPresent + removedAbsent}) with a stale manifest`],
462
- details);