@gtrabanco/agentic-workflow-schema 3.3.0 → 3.5.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.
- package/README.es.md +549 -3
- package/README.md +539 -3
- package/dist/canonical-json.d.ts +60 -0
- package/dist/canonical-json.js +119 -0
- package/dist/index.d.ts +263 -2
- package/dist/index.js +587 -52
- package/dist/pre-execution-contract.d.ts +175 -0
- package/dist/pre-execution-contract.js +676 -0
- package/dist/pre-execution-vectors.d.ts +19 -0
- package/dist/pre-execution-vectors.js +35 -0
- package/dist/pre-execution.d.ts +363 -0
- package/dist/pre-execution.js +838 -0
- package/dist/sha256.d.ts +43 -0
- package/dist/sha256.js +189 -0
- package/dist/verification-contract.d.ts +294 -0
- package/dist/verification-contract.js +1229 -0
- package/package.json +21 -3
- package/pre-execution-artifact-snapshot.schema.json +383 -0
- package/pre-execution-review-receipt.schema.json +457 -0
- package/verification-plan.schema.json +197 -0
- package/verification-receipt.schema.json +309 -0
|
@@ -0,0 +1,838 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pre-execution evidence contracts — the feature 28 runtime surface.
|
|
3
|
+
*
|
|
4
|
+
* `PreExecutionArtifactSnapshot v1` records the EXACT artifact set, authoritative
|
|
5
|
+
* contexts, source revision and authoring revision an independent reviewer read;
|
|
6
|
+
* `PreExecutionReviewReceipt v1` records that reviewer's content-bound verdict on
|
|
7
|
+
* one snapshot. Together they make "the Product was reviewed before the Plan was
|
|
8
|
+
* written" a checkable claim instead of a hopeful sentence in a progress log.
|
|
9
|
+
*
|
|
10
|
+
* What lives here, and what deliberately does not:
|
|
11
|
+
* - Every structural rule is declared once in `pre-execution-contract.ts` and
|
|
12
|
+
* enforced by the ONE package-wide structural engine (`validateStructure`),
|
|
13
|
+
* so this module adds semantics, not a second walker.
|
|
14
|
+
* - The package never reads the filesystem or Git. The selector and the builder
|
|
15
|
+
* consume caller-supplied text and caller-supplied revisions, so a reviewer can
|
|
16
|
+
* bind a document from any source (forge API, shallow clone, editor buffer) and
|
|
17
|
+
* a digest can never describe bytes other than the ones it was handed.
|
|
18
|
+
* - These contracts are not the candidate review receipt (feature 25) and not the
|
|
19
|
+
* staged verification receipt (feature 26): a pre-execution PASS authorizes
|
|
20
|
+
* WRITING code, never merging it. A substitute from either family is refused by
|
|
21
|
+
* contract-id mismatch before any content is compared.
|
|
22
|
+
*
|
|
23
|
+
* Feature 28, phase P1. Diagnostics follow the package's D16 rule: a frozen code
|
|
24
|
+
* plus an RFC 6901 pointer, never the submitted value.
|
|
25
|
+
*/
|
|
26
|
+
import { VERIFICATION_DIAGNOSTIC_CODES, applyCrossRule, assertCrossRuleVocabulary, captureVerificationInput, createVerificationDiagnosticSink, validateStructure, } from "./verification-contract.js";
|
|
27
|
+
import { PRE_EXECUTION_ARTIFACT_KINDS, PRE_EXECUTION_AUTHOR_EXCLUSIONS, PRE_EXECUTION_CONTEXT_KINDS, PRE_EXECUTION_CONTEXT_PRESENCE, PRE_EXECUTION_CONTRACT, PRE_EXECUTION_FINDING_CLASSES, PRE_EXECUTION_FINDING_RESOLUTIONS, PRE_EXECUTION_FINDING_SEVERITIES, PRE_EXECUTION_FINDING_VERIFICATION, PRE_EXECUTION_LIMITS, PRE_EXECUTION_MODEL_DIVERSITY, PRE_EXECUTION_PARENT_ROLES, PRE_EXECUTION_RECEIPT_CONTRACT_ID, PRE_EXECUTION_REVIEW_ROLES, PRE_EXECUTION_SELECTORS, PRE_EXECUTION_STAGES, PRE_EXECUTION_SNAPSHOT_CONTRACT_ID, PRE_EXECUTION_UNIT_KINDS, PRE_EXECUTION_VERDICTS, } from "./pre-execution-contract.js";
|
|
28
|
+
import { PRE_EXECUTION_CANONICAL_VECTORS, } from "./pre-execution-vectors.js";
|
|
29
|
+
import { canonicalizeContractInput, canonicalJSONValue, utf8Bytes, utf8ByteCompare, } from "./canonical-json.js";
|
|
30
|
+
import { sha256HexSync } from "./sha256.js";
|
|
31
|
+
// ---------------------------------------------------------------------------
|
|
32
|
+
// Published identities, vocabularies, and types
|
|
33
|
+
// ---------------------------------------------------------------------------
|
|
34
|
+
export { PRE_EXECUTION_SNAPSHOT_CONTRACT_ID, PRE_EXECUTION_RECEIPT_CONTRACT_ID, PRE_EXECUTION_STAGES, PRE_EXECUTION_UNIT_KINDS, PRE_EXECUTION_SELECTORS, PRE_EXECUTION_ARTIFACT_KINDS, PRE_EXECUTION_CONTEXT_KINDS, PRE_EXECUTION_CONTEXT_PRESENCE, PRE_EXECUTION_VERDICTS, PRE_EXECUTION_FINDING_SEVERITIES, PRE_EXECUTION_FINDING_CLASSES, PRE_EXECUTION_FINDING_VERIFICATION, PRE_EXECUTION_FINDING_RESOLUTIONS, PRE_EXECUTION_REVIEW_ROLES, PRE_EXECUTION_PARENT_ROLES, PRE_EXECUTION_AUTHOR_EXCLUSIONS, PRE_EXECUTION_MODEL_DIVERSITY, PRE_EXECUTION_LIMITS, PRE_EXECUTION_CANONICAL_VECTORS, };
|
|
35
|
+
export { PRE_EXECUTION_RUNTIME_RULES } from "./pre-execution-contract.js";
|
|
36
|
+
/** The one selector a SPEC-stage snapshot may bind: the Product projection (D2). */
|
|
37
|
+
export const PRE_EXECUTION_SNAPSHOT_SELECTOR = "spec-product-v1";
|
|
38
|
+
/**
|
|
39
|
+
* The closed diagnostic vocabulary of this contract family: the package-wide D16
|
|
40
|
+
* codes (so a driver that already routes on them keeps working unchanged) plus the
|
|
41
|
+
* pre-execution refusals no existing code describes. Adding a member is a reviewed,
|
|
42
|
+
* versioned change, and no code ever names a submitted value.
|
|
43
|
+
*/
|
|
44
|
+
export const PRE_EXECUTION_DIAGNOSTIC_CODES = Object.freeze([
|
|
45
|
+
...VERIFICATION_DIAGNOSTIC_CODES,
|
|
46
|
+
"missing-artifact-kind",
|
|
47
|
+
"invalid-artifact-set",
|
|
48
|
+
"invalid-selector",
|
|
49
|
+
"invalid-author",
|
|
50
|
+
"invalid-context",
|
|
51
|
+
"invalid-topology",
|
|
52
|
+
"stale-snapshot",
|
|
53
|
+
"stale-policy",
|
|
54
|
+
]);
|
|
55
|
+
// The widened `code` field on a cross rule exists for THIS family's own codes, so the
|
|
56
|
+
// family is the one that has to prove every pin is published (F71). At load: a rule
|
|
57
|
+
// that mistypes `invalid-topology`, or borrows a code from another contract, breaks
|
|
58
|
+
// the import instead of answering a reviewer with a diagnostic no consumer knows.
|
|
59
|
+
assertCrossRuleVocabulary(PRE_EXECUTION_CONTRACT, PRE_EXECUTION_DIAGNOSTIC_CODES, "pre-execution");
|
|
60
|
+
/**
|
|
61
|
+
* The freshness/authority answers of `comparePreExecutionReceiptToSnapshot`.
|
|
62
|
+
* Exactly one fires per call, in the documented precedence, and the comparison
|
|
63
|
+
* never throws: an input it cannot read is answered with a code.
|
|
64
|
+
*/
|
|
65
|
+
export const PRE_EXECUTION_FRESHNESS_CODES = Object.freeze([
|
|
66
|
+
"invalid-stage",
|
|
67
|
+
"invalid-unit",
|
|
68
|
+
"stale-policy",
|
|
69
|
+
"stale-context",
|
|
70
|
+
"stale-source-revision",
|
|
71
|
+
"stale-parent",
|
|
72
|
+
"stale-artifact-revision",
|
|
73
|
+
"stale-artifact-content",
|
|
74
|
+
"missing-receipt-snapshot",
|
|
75
|
+
]);
|
|
76
|
+
/** The Product-half headings the selector binds, in required order. */
|
|
77
|
+
export const SPEC_PRODUCT_REQUIRED_HEADINGS = Object.freeze([
|
|
78
|
+
"Goal",
|
|
79
|
+
"Branch",
|
|
80
|
+
"Size",
|
|
81
|
+
"Dependencies",
|
|
82
|
+
"Product half",
|
|
83
|
+
"Design status",
|
|
84
|
+
]);
|
|
85
|
+
// ---------------------------------------------------------------------------
|
|
86
|
+
// Shared plumbing: one sink, one capture, one structural engine
|
|
87
|
+
// ---------------------------------------------------------------------------
|
|
88
|
+
const DIGEST_PATTERN = /^[a-f0-9]{64}$/;
|
|
89
|
+
/**
|
|
90
|
+
* The bounded row collector shared by every entry point below.
|
|
91
|
+
*
|
|
92
|
+
* Structural rows come from the package-wide engine sink (which only ever emits
|
|
93
|
+
* the shared D16 codes); the semantic layer adds this family's refusals. One
|
|
94
|
+
* ceiling covers both, so an oversized document can never spend more than
|
|
95
|
+
* `PRE_EXECUTION_LIMITS.diagnostics` allocations, and `truncated` reports the
|
|
96
|
+
* truth across the whole run rather than per stage.
|
|
97
|
+
*/
|
|
98
|
+
function createCollector(limit = PRE_EXECUTION_LIMITS.diagnostics) {
|
|
99
|
+
const rows = [];
|
|
100
|
+
let dropped = 0;
|
|
101
|
+
const add = (code, path) => {
|
|
102
|
+
if (rows.length < limit)
|
|
103
|
+
rows.push({ code, path });
|
|
104
|
+
else
|
|
105
|
+
dropped += 1;
|
|
106
|
+
};
|
|
107
|
+
return {
|
|
108
|
+
add,
|
|
109
|
+
/** Fold one engine pass in, keeping the dropped-row count exact. */
|
|
110
|
+
addEngine(sink) {
|
|
111
|
+
const total = sink.count();
|
|
112
|
+
const held = sink.finish();
|
|
113
|
+
for (const row of held.diagnostics)
|
|
114
|
+
add(row.code, row.path);
|
|
115
|
+
dropped += total - held.diagnostics.length;
|
|
116
|
+
},
|
|
117
|
+
failed() {
|
|
118
|
+
return rows.length + dropped > 0;
|
|
119
|
+
},
|
|
120
|
+
finish() {
|
|
121
|
+
return {
|
|
122
|
+
diagnostics: Object.freeze(rows.map((row) => Object.freeze({ code: row.code, path: row.path }))),
|
|
123
|
+
truncated: dropped > 0,
|
|
124
|
+
};
|
|
125
|
+
},
|
|
126
|
+
};
|
|
127
|
+
}
|
|
128
|
+
function refused(collector) {
|
|
129
|
+
const { diagnostics, truncated } = collector.finish();
|
|
130
|
+
return { ok: false, diagnostics, truncated };
|
|
131
|
+
}
|
|
132
|
+
function accepted(label, value) {
|
|
133
|
+
return {
|
|
134
|
+
ok: true,
|
|
135
|
+
[label]: value,
|
|
136
|
+
diagnostics: Object.freeze([]),
|
|
137
|
+
truncated: false,
|
|
138
|
+
};
|
|
139
|
+
}
|
|
140
|
+
/**
|
|
141
|
+
* One bounded structural run: capture under the payload budget, then walk the
|
|
142
|
+
* captured snapshot (never the submission), so the budget, the walk, and the
|
|
143
|
+
* semantics below all decide on one document. Returns the normalized DTO or
|
|
144
|
+
* `null` with every refusal row already in the collector.
|
|
145
|
+
*/
|
|
146
|
+
function structuralRun(contract, value, budgetBytes, collector) {
|
|
147
|
+
const captured = captureVerificationInput(value, budgetBytes);
|
|
148
|
+
if (!captured.ok) {
|
|
149
|
+
collector.add(captured.code, captured.pointer);
|
|
150
|
+
return null;
|
|
151
|
+
}
|
|
152
|
+
if (!captured.measureExact) {
|
|
153
|
+
let canonical = null;
|
|
154
|
+
try {
|
|
155
|
+
canonical = canonicalJSONValue(captured.value);
|
|
156
|
+
}
|
|
157
|
+
catch {
|
|
158
|
+
canonical = null; // an unserializable leaf is the walk's `invalid-type` answer
|
|
159
|
+
}
|
|
160
|
+
if (canonical !== null && utf8Bytes(canonical) > budgetBytes) {
|
|
161
|
+
collector.add("limit-exceeded", "");
|
|
162
|
+
return null;
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
const sink = createVerificationDiagnosticSink();
|
|
166
|
+
const document = validateStructure(contract, contract.root, captured.value, "", sink);
|
|
167
|
+
collector.addEngine(sink);
|
|
168
|
+
if (sink.count() > 0 || document === undefined)
|
|
169
|
+
return null;
|
|
170
|
+
return document;
|
|
171
|
+
}
|
|
172
|
+
const LEVEL_TWO_HEADING = /^## (.*)$/;
|
|
173
|
+
const LEVEL_ONE_HEADING = /^# (.*)$/;
|
|
174
|
+
const FENCE_LINE = /^ {0,3}(`{3,}|~{3,})(.*)$/;
|
|
175
|
+
/**
|
|
176
|
+
* Advance the fence state over one fence-looking line (finding F64). A block closes
|
|
177
|
+
* only on a run of the character that OPENED it, at least as long, with nothing but
|
|
178
|
+
* spaces after it — CommonMark's rule, and the reason a `~~~` line inside a ``` block
|
|
179
|
+
* is content rather than a terminator. Both selector passes decide through this one
|
|
180
|
+
* function, so the heading scan and the boundary scan can never track differently.
|
|
181
|
+
*/
|
|
182
|
+
function advanceFence(run, open) {
|
|
183
|
+
const marker = run[1][0];
|
|
184
|
+
const length = run[1].length;
|
|
185
|
+
if (open === null)
|
|
186
|
+
return { marker, length };
|
|
187
|
+
return marker === open.marker && length >= open.length && run[2].trim() === "" ? null : open;
|
|
188
|
+
}
|
|
189
|
+
function selectionError(code, heading) {
|
|
190
|
+
return { ok: false, errors: Object.freeze([Object.freeze({ code, heading })]) };
|
|
191
|
+
}
|
|
192
|
+
/**
|
|
193
|
+
* Cut the Product projection out of a SPEC document.
|
|
194
|
+
*
|
|
195
|
+
* The selection is byte-exact and total: the level-1 title and the required
|
|
196
|
+
* level-2 sections (Goal, Branch, Size, Dependencies, Product half, Design
|
|
197
|
+
* status), ending at the first boundary heading after Design status, with trailing
|
|
198
|
+
* blank lines removed and exactly one final newline. Everything the selector does
|
|
199
|
+
* NOT take — Amendments, the Engineering half, later appendices — stays outside
|
|
200
|
+
* Product authority, so a Plan-phase write can never rotate a Product digest and
|
|
201
|
+
* silently erase a recorded review (the property AC2 and S6 test).
|
|
202
|
+
*
|
|
203
|
+
* Determinism rules that make the digest trustworthy:
|
|
204
|
+
* - line endings normalize to LF first, so a CRLF checkout and an LF editor
|
|
205
|
+
* select identical bytes;
|
|
206
|
+
* - fenced blocks are inert: a `## Goal` inside a template is neither a duplicate
|
|
207
|
+
* heading nor a section boundary, and fenced content still belongs to the
|
|
208
|
+
* section containing it (under-binding would leave edits unchecked); a block ends
|
|
209
|
+
* only on a run of its own fence character, at least as long and with no info
|
|
210
|
+
* string, so a mixed-character fence cannot end it early;
|
|
211
|
+
* - heading text is compared EXACTLY — no trimming, no case folding, no
|
|
212
|
+
* substring — so `## Goals`, `### Goal` and `## Goal ` all fail closed;
|
|
213
|
+
* - the FIRST defect in the fixed order title → missing → duplicate → order is
|
|
214
|
+
* reported alone, because every later position is already suspect.
|
|
215
|
+
*
|
|
216
|
+
* No I/O: the caller supplies the text it read.
|
|
217
|
+
*/
|
|
218
|
+
export function selectSpecProduct(text) {
|
|
219
|
+
if (typeof text !== "string")
|
|
220
|
+
return selectionError("selector-title-missing", "<title>");
|
|
221
|
+
const lines = text.replace(/\r\n?/g, "\n").split("\n");
|
|
222
|
+
const headings = [];
|
|
223
|
+
let titleLine = -1;
|
|
224
|
+
let openFence = null;
|
|
225
|
+
for (let i = 0; i < lines.length; i++) {
|
|
226
|
+
const line = lines[i];
|
|
227
|
+
const fence = FENCE_LINE.exec(line);
|
|
228
|
+
if (fence !== null) {
|
|
229
|
+
openFence = advanceFence(fence, openFence);
|
|
230
|
+
continue;
|
|
231
|
+
}
|
|
232
|
+
if (openFence !== null)
|
|
233
|
+
continue;
|
|
234
|
+
const two = LEVEL_TWO_HEADING.exec(line);
|
|
235
|
+
if (two !== null) {
|
|
236
|
+
headings.push({ name: two[1], line: i });
|
|
237
|
+
continue;
|
|
238
|
+
}
|
|
239
|
+
if (titleLine === -1) {
|
|
240
|
+
const one = LEVEL_ONE_HEADING.exec(line);
|
|
241
|
+
if (one !== null && one[1].length > 0)
|
|
242
|
+
titleLine = i;
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
if (titleLine === -1)
|
|
246
|
+
return selectionError("selector-title-missing", "<title>");
|
|
247
|
+
for (const required of SPEC_PRODUCT_REQUIRED_HEADINGS) {
|
|
248
|
+
if (!headings.some((heading) => heading.name === required)) {
|
|
249
|
+
return selectionError("selector-heading-missing", required);
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
const seen = new Set();
|
|
253
|
+
for (const heading of headings) {
|
|
254
|
+
if (!SPEC_PRODUCT_REQUIRED_HEADINGS.includes(heading.name))
|
|
255
|
+
continue;
|
|
256
|
+
if (seen.has(heading.name))
|
|
257
|
+
return selectionError("selector-heading-duplicate", heading.name);
|
|
258
|
+
seen.add(heading.name);
|
|
259
|
+
}
|
|
260
|
+
let highest = -1;
|
|
261
|
+
for (const heading of headings) {
|
|
262
|
+
const index = SPEC_PRODUCT_REQUIRED_HEADINGS.indexOf(heading.name);
|
|
263
|
+
if (index === -1)
|
|
264
|
+
continue;
|
|
265
|
+
if (index < highest)
|
|
266
|
+
return selectionError("selector-heading-order", heading.name);
|
|
267
|
+
highest = index;
|
|
268
|
+
}
|
|
269
|
+
// The projection ends at the first boundary heading (level 1 or 2) after the
|
|
270
|
+
// Design-status section opens — never inside a fence.
|
|
271
|
+
let designLine = -1;
|
|
272
|
+
for (const heading of headings)
|
|
273
|
+
if (heading.name === "Design status")
|
|
274
|
+
designLine = heading.line;
|
|
275
|
+
let end = lines.length;
|
|
276
|
+
openFence = null;
|
|
277
|
+
for (let i = 0; i < lines.length; i++) {
|
|
278
|
+
const fence = FENCE_LINE.exec(lines[i]);
|
|
279
|
+
if (fence !== null) {
|
|
280
|
+
openFence = advanceFence(fence, openFence);
|
|
281
|
+
continue;
|
|
282
|
+
}
|
|
283
|
+
if (openFence !== null || i <= designLine)
|
|
284
|
+
continue;
|
|
285
|
+
if (LEVEL_TWO_HEADING.test(lines[i]) || LEVEL_ONE_HEADING.test(lines[i])) {
|
|
286
|
+
end = i;
|
|
287
|
+
break;
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
const selected = lines.slice(0, end);
|
|
291
|
+
while (selected.length > 0 && selected[selected.length - 1].trim() === "")
|
|
292
|
+
selected.pop();
|
|
293
|
+
const content = `${selected.join("\n")}\n`;
|
|
294
|
+
return Object.freeze({
|
|
295
|
+
ok: true,
|
|
296
|
+
content,
|
|
297
|
+
byteLength: utf8Bytes(content),
|
|
298
|
+
digest: sha256HexSync(content),
|
|
299
|
+
});
|
|
300
|
+
}
|
|
301
|
+
// ---------------------------------------------------------------------------
|
|
302
|
+
// PreExecutionArtifactSnapshot v1 — semantics the projection cannot state
|
|
303
|
+
// ---------------------------------------------------------------------------
|
|
304
|
+
/** The rows each stage REQUIRES. A fix unit has no Product half (D6). */
|
|
305
|
+
const REQUIRED_ARTIFACTS = Object.freeze({ spec: ["spec"], plan: ["spec", "acceptance"] });
|
|
306
|
+
function snapshotSemantics(document, collector) {
|
|
307
|
+
const stage = document.stage;
|
|
308
|
+
const rows = document.artifacts;
|
|
309
|
+
const contexts = document.contexts;
|
|
310
|
+
if (stage === "spec" && document.unitKind === "fix") {
|
|
311
|
+
// D6: a fix unit has no Product half to review, so `spec` is not a valid stage
|
|
312
|
+
// for it — the same bytes at the plan stage ARE the fix path.
|
|
313
|
+
collector.add("invalid-value", "/stage");
|
|
314
|
+
}
|
|
315
|
+
const kinds = new Set();
|
|
316
|
+
let previousPath = null;
|
|
317
|
+
for (let i = 0; i < rows.length; i++) {
|
|
318
|
+
const row = rows[i];
|
|
319
|
+
const at = `/artifacts/${i}`;
|
|
320
|
+
if (kinds.has(row.kind))
|
|
321
|
+
collector.add("duplicate-id", `${at}/kind`);
|
|
322
|
+
kinds.add(row.kind);
|
|
323
|
+
if (previousPath !== null && utf8ByteCompare(previousPath, row.path) >= 0) {
|
|
324
|
+
collector.add("invalid-order", `${at}/path`);
|
|
325
|
+
}
|
|
326
|
+
previousPath = row.path;
|
|
327
|
+
if (stage === "spec") {
|
|
328
|
+
// The SPEC stage binds exactly one row: the Product projection of the SPEC
|
|
329
|
+
// file. Binding the whole file would put the Engineering half — which the
|
|
330
|
+
// plan phase is about to rewrite — under a review that only authorized it.
|
|
331
|
+
if (row.kind !== "spec") {
|
|
332
|
+
// Name the member that is actually wrong: a driver repairs what the pointer
|
|
333
|
+
// points at, and this row's selector may well be the sanctioned one (F65).
|
|
334
|
+
collector.add("invalid-value", `${at}/kind`);
|
|
335
|
+
}
|
|
336
|
+
else if (row.selector !== PRE_EXECUTION_SNAPSHOT_SELECTOR) {
|
|
337
|
+
collector.add("invalid-value", `${at}/selector`);
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
else if (row.selector === PRE_EXECUTION_SNAPSHOT_SELECTOR) {
|
|
341
|
+
// A projection is a Product authority; the Plan stage binds whole files.
|
|
342
|
+
collector.add("invalid-value", `${at}/selector`);
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
if (stage === "spec" && rows.length !== 1)
|
|
346
|
+
collector.add("invalid-artifact-set", "/artifacts");
|
|
347
|
+
for (const required of REQUIRED_ARTIFACTS[stage]) {
|
|
348
|
+
if (!kinds.has(required))
|
|
349
|
+
collector.add("missing-artifact-kind", "/artifacts");
|
|
350
|
+
}
|
|
351
|
+
const identities = new Set();
|
|
352
|
+
let previousContext = null;
|
|
353
|
+
for (let i = 0; i < contexts.length; i++) {
|
|
354
|
+
const context = contexts[i];
|
|
355
|
+
const identity = `${context.kind}\u0000${context.identifier}`;
|
|
356
|
+
if (identities.has(identity))
|
|
357
|
+
collector.add("duplicate-id", `/contexts/${i}/identifier`);
|
|
358
|
+
identities.add(identity);
|
|
359
|
+
if (previousContext !== null && utf8ByteCompare(previousContext, identity) >= 0) {
|
|
360
|
+
collector.add("invalid-order", `/contexts/${i}`);
|
|
361
|
+
}
|
|
362
|
+
previousContext = identity;
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
/**
|
|
366
|
+
* The authoritative snapshot validator (feature 28 AC1).
|
|
367
|
+
*
|
|
368
|
+
* Enforces, in one pass and from the canonical definition: the contract id, the
|
|
369
|
+
* closed stage/unit/artifact/selector/context vocabularies, the exact 40- or
|
|
370
|
+
* 64-hex source revision and 64-hex digest shapes, normalized repository-relative
|
|
371
|
+
* paths, the declared-field-only DTO at every level (prototype and undeclared keys
|
|
372
|
+
* are never contract data), the published cardinality and length ceilings, the
|
|
373
|
+
* payload budget, and the stage matrix Draft-07 cannot express: `spec` binds one
|
|
374
|
+
* Product-projection row and no parent, `plan` binds at least the whole SPEC and
|
|
375
|
+
* ACCEPTANCE and its parent snapshot digest, a fix unit has no `spec` stage, rows
|
|
376
|
+
* are unique per kind and byte-ordered by path, and context identities are unique
|
|
377
|
+
* and byte-ordered.
|
|
378
|
+
*
|
|
379
|
+
* The input domain is JSON documents. A value outside it (a throwing getter, say)
|
|
380
|
+
* is refused as one redacted `invalid-type` row rather than escaping as an
|
|
381
|
+
* exception, and no diagnostic ever carries a submitted value.
|
|
382
|
+
*/
|
|
383
|
+
export function validatePreExecutionArtifactSnapshotV1(value) {
|
|
384
|
+
const collector = createCollector();
|
|
385
|
+
const document = structuralRun(PRE_EXECUTION_CONTRACT.snapshot, value, PRE_EXECUTION_LIMITS.snapshotBytes, collector);
|
|
386
|
+
if (document === null)
|
|
387
|
+
return refused(collector);
|
|
388
|
+
snapshotSemantics(document, collector);
|
|
389
|
+
if (collector.failed())
|
|
390
|
+
return refused(collector);
|
|
391
|
+
return accepted("snapshot", document);
|
|
392
|
+
}
|
|
393
|
+
/**
|
|
394
|
+
* True when `value` is a valid snapshot. The freshness comparator needs the yes/no
|
|
395
|
+
* answer for two documents per call and never their DTOs, so it uses this instead
|
|
396
|
+
* of copying fields it will not read.
|
|
397
|
+
*/
|
|
398
|
+
function isValidSnapshot(value) {
|
|
399
|
+
const collector = createCollector();
|
|
400
|
+
const document = structuralRun(PRE_EXECUTION_CONTRACT.snapshot, value, PRE_EXECUTION_LIMITS.snapshotBytes, collector);
|
|
401
|
+
if (document === null)
|
|
402
|
+
return false;
|
|
403
|
+
snapshotSemantics(document, collector);
|
|
404
|
+
return !collector.failed();
|
|
405
|
+
}
|
|
406
|
+
function defaultSelector(stage, kind) {
|
|
407
|
+
return stage === "spec" && kind === "spec" ? PRE_EXECUTION_SNAPSHOT_SELECTOR : "whole-file";
|
|
408
|
+
}
|
|
409
|
+
/**
|
|
410
|
+
* Build the canonical artifact set for a stage from bytes the caller supplied.
|
|
411
|
+
*
|
|
412
|
+
* This is the only sanctioned way to produce a snapshot: it derives every digest
|
|
413
|
+
* and `byteLength` from the text it is handed, orders artifact rows by UTF-8 path
|
|
414
|
+
* bytes and context rows by (kind, identifier), defaults the parent binding to
|
|
415
|
+
* `null` at the SPEC stage, and then feeds the result through
|
|
416
|
+
* `validatePreExecutionArtifactSnapshotV1`. That last step is the guarantee: a
|
|
417
|
+
* builder can never return a snapshot its own validator would refuse, and a
|
|
418
|
+
* hand-assembled object is not how a reviewer gets one.
|
|
419
|
+
*
|
|
420
|
+
* A `spec-product-v1` row binds the PROJECTION, so Engineering-half and Amendments
|
|
421
|
+
* writes do not move its digest; a `whole-file` row binds the exact bytes. A
|
|
422
|
+
* rejected selection fails the build under `invalid-selector` at the row's content
|
|
423
|
+
* pointer rather than producing a partial binding. Diagnostics in this family are
|
|
424
|
+
* bounded (code, path) pairs, so WHICH heading failed and how is not carried here —
|
|
425
|
+
* `selectSpecProduct` is the only entry that reports the selector's own reason.
|
|
426
|
+
*/
|
|
427
|
+
export function buildPreExecutionArtifactSnapshot(input) {
|
|
428
|
+
const collector = createCollector();
|
|
429
|
+
if (input === null || typeof input !== "object" || !Array.isArray(input.files)) {
|
|
430
|
+
collector.add("invalid-type", "");
|
|
431
|
+
return refused(collector);
|
|
432
|
+
}
|
|
433
|
+
const stage = input.stage;
|
|
434
|
+
const artifacts = [];
|
|
435
|
+
for (let i = 0; i < input.files.length; i++) {
|
|
436
|
+
const file = input.files[i];
|
|
437
|
+
const at = `/files/${i}`;
|
|
438
|
+
if (file === null || typeof file !== "object") {
|
|
439
|
+
collector.add("invalid-type", at);
|
|
440
|
+
continue;
|
|
441
|
+
}
|
|
442
|
+
if (typeof file.content !== "string") {
|
|
443
|
+
// The builder binds bytes it was given; there is no read behind it.
|
|
444
|
+
collector.add("missing-field", `${at}/content`);
|
|
445
|
+
continue;
|
|
446
|
+
}
|
|
447
|
+
if (typeof file.path !== "string" || file.path.length === 0) {
|
|
448
|
+
collector.add("invalid-value", `${at}/path`);
|
|
449
|
+
continue;
|
|
450
|
+
}
|
|
451
|
+
if (!PRE_EXECUTION_ARTIFACT_KINDS.includes(file.kind)) {
|
|
452
|
+
collector.add("invalid-value", `${at}/kind`);
|
|
453
|
+
continue;
|
|
454
|
+
}
|
|
455
|
+
const selector = file.selector ?? defaultSelector(stage, file.kind);
|
|
456
|
+
if (!PRE_EXECUTION_SELECTORS.includes(selector)) {
|
|
457
|
+
collector.add("invalid-selector", `${at}/selector`);
|
|
458
|
+
continue;
|
|
459
|
+
}
|
|
460
|
+
let content = file.content;
|
|
461
|
+
if (selector === PRE_EXECUTION_SNAPSHOT_SELECTOR) {
|
|
462
|
+
const selected = selectSpecProduct(content);
|
|
463
|
+
if (!selected.ok) {
|
|
464
|
+
collector.add("invalid-selector", `${at}/content`);
|
|
465
|
+
continue;
|
|
466
|
+
}
|
|
467
|
+
content = selected.content;
|
|
468
|
+
}
|
|
469
|
+
artifacts.push(Object.freeze({
|
|
470
|
+
kind: file.kind,
|
|
471
|
+
path: file.path,
|
|
472
|
+
selector,
|
|
473
|
+
byteLength: utf8Bytes(content),
|
|
474
|
+
digest: sha256HexSync(content),
|
|
475
|
+
}));
|
|
476
|
+
}
|
|
477
|
+
const contexts = [];
|
|
478
|
+
const suppliedContexts = input.contexts ?? [];
|
|
479
|
+
if (!Array.isArray(suppliedContexts)) {
|
|
480
|
+
collector.add("invalid-type", "/contexts");
|
|
481
|
+
}
|
|
482
|
+
else {
|
|
483
|
+
for (let i = 0; i < suppliedContexts.length; i++) {
|
|
484
|
+
const context = suppliedContexts[i];
|
|
485
|
+
const at = `/contexts/${i}`;
|
|
486
|
+
if (context === null || typeof context !== "object") {
|
|
487
|
+
collector.add("invalid-type", at);
|
|
488
|
+
continue;
|
|
489
|
+
}
|
|
490
|
+
if (!PRE_EXECUTION_CONTEXT_KINDS.includes(context.kind)) {
|
|
491
|
+
collector.add("invalid-value", `${at}/kind`);
|
|
492
|
+
continue;
|
|
493
|
+
}
|
|
494
|
+
if (typeof context.identifier !== "string" || context.identifier.length === 0) {
|
|
495
|
+
collector.add("invalid-value", `${at}/identifier`);
|
|
496
|
+
continue;
|
|
497
|
+
}
|
|
498
|
+
const hasContent = typeof context.content === "string";
|
|
499
|
+
if (hasContent && context.presence === "absent") {
|
|
500
|
+
// A row cannot claim an authority is missing and bind its bytes at once.
|
|
501
|
+
collector.add("invalid-context", at);
|
|
502
|
+
continue;
|
|
503
|
+
}
|
|
504
|
+
if (!hasContent && context.presence !== "absent") {
|
|
505
|
+
collector.add("missing-field", `${at}/content`);
|
|
506
|
+
continue;
|
|
507
|
+
}
|
|
508
|
+
contexts.push(Object.freeze({
|
|
509
|
+
kind: context.kind,
|
|
510
|
+
identifier: context.identifier,
|
|
511
|
+
presence: hasContent ? "present" : "absent",
|
|
512
|
+
digest: hasContent ? sha256HexSync(context.content) : null,
|
|
513
|
+
}));
|
|
514
|
+
}
|
|
515
|
+
}
|
|
516
|
+
if (collector.failed())
|
|
517
|
+
return refused(collector);
|
|
518
|
+
artifacts.sort((a, b) => utf8ByteCompare(a.path, b.path));
|
|
519
|
+
contexts.sort((a, b) => utf8ByteCompare(a.kind, b.kind) || utf8ByteCompare(a.identifier, b.identifier));
|
|
520
|
+
return validatePreExecutionArtifactSnapshotV1({
|
|
521
|
+
contract: PRE_EXECUTION_SNAPSHOT_CONTRACT_ID,
|
|
522
|
+
stage,
|
|
523
|
+
unitKind: input.unitKind,
|
|
524
|
+
unitId: input.unitId,
|
|
525
|
+
sourceRevision: input.sourceRevision,
|
|
526
|
+
artifactRevisionId: input.artifactRevisionId,
|
|
527
|
+
artifacts,
|
|
528
|
+
contexts,
|
|
529
|
+
parentSpecSnapshotDigest: stage === "spec" ? null : input.parentSpecSnapshotDigest ?? null,
|
|
530
|
+
});
|
|
531
|
+
}
|
|
532
|
+
// ---------------------------------------------------------------------------
|
|
533
|
+
// Canonical form and digests
|
|
534
|
+
// ---------------------------------------------------------------------------
|
|
535
|
+
/**
|
|
536
|
+
* D6 — canonical serialization of a validated `PreExecutionArtifactSnapshot v1`.
|
|
537
|
+
*
|
|
538
|
+
* Sorted keys, compact separators, declared own-properties only, and the input
|
|
539
|
+
* domain is the JSON data model: an undeclared field, a prototype value, or a leaf
|
|
540
|
+
* no validator would accept (a function, a BigInt, `NaN`) is a named refusal, so a
|
|
541
|
+
* digest can never describe bytes the contract would reject. Artifact and context
|
|
542
|
+
* order is PRESERVED, never re-sorted here: the canonical order is a contract rule
|
|
543
|
+
* the validator enforces, so the serializer stays a pure projection.
|
|
544
|
+
*/
|
|
545
|
+
export function canonicalizePreExecutionArtifactSnapshot(snapshot) {
|
|
546
|
+
return canonicalizeContractInput(snapshot, PRE_EXECUTION_CONTRACT.snapshot, {
|
|
547
|
+
collectionField: "artifacts",
|
|
548
|
+
maxItems: PRE_EXECUTION_LIMITS.artifacts,
|
|
549
|
+
budgetBytes: PRE_EXECUTION_LIMITS.snapshotBytes,
|
|
550
|
+
family: "pre-execution",
|
|
551
|
+
label: "snapshot",
|
|
552
|
+
});
|
|
553
|
+
}
|
|
554
|
+
/**
|
|
555
|
+
* D6 — canonical serialization of a validated `PreExecutionReviewReceipt v1`.
|
|
556
|
+
*
|
|
557
|
+
* Findings are re-emitted in UTF-8 byte order of their stable ids and parent
|
|
558
|
+
* receipts in byte order of their digests: the ORDER two independent reviewers
|
|
559
|
+
* happened to append them in carries no meaning, so it must not change a digest
|
|
560
|
+
* either. (Artifact and context rows are the opposite case — their order IS a
|
|
561
|
+
* contract rule the validator enforces — so the snapshot serializer preserves it.)
|
|
562
|
+
*/
|
|
563
|
+
export function canonicalizePreExecutionReviewReceipt(receipt) {
|
|
564
|
+
const findings = Array.isArray(receipt?.findings)
|
|
565
|
+
? [...receipt.findings].sort((a, b) => utf8ByteCompare(String(a?.id ?? ""), String(b?.id ?? "")))
|
|
566
|
+
: receipt?.findings;
|
|
567
|
+
const parentReceipts = Array.isArray(receipt?.parentReceipts)
|
|
568
|
+
? [...receipt.parentReceipts].sort((a, b) => utf8ByteCompare(String(a?.receiptDigest ?? ""), String(b?.receiptDigest ?? "")))
|
|
569
|
+
: receipt?.parentReceipts;
|
|
570
|
+
return canonicalizeContractInput({ ...receipt, findings, parentReceipts }, PRE_EXECUTION_CONTRACT.receipt, {
|
|
571
|
+
collectionField: "findings",
|
|
572
|
+
maxItems: PRE_EXECUTION_LIMITS.findings,
|
|
573
|
+
budgetBytes: PRE_EXECUTION_LIMITS.receiptBytes,
|
|
574
|
+
family: "pre-execution",
|
|
575
|
+
label: "receipt",
|
|
576
|
+
});
|
|
577
|
+
}
|
|
578
|
+
/** D6 — digest of a validated snapshot (inherits the canonical-input guards). Sync, like the family that produces it (F67). */
|
|
579
|
+
export function digestPreExecutionArtifactSnapshot(snapshot) {
|
|
580
|
+
return sha256HexSync(canonicalizePreExecutionArtifactSnapshot(snapshot));
|
|
581
|
+
}
|
|
582
|
+
/** D6 — digest of a validated receipt (inherits the canonical-input guards). Sync, like the family that produces it (F67). */
|
|
583
|
+
export function digestPreExecutionReviewReceipt(receipt) {
|
|
584
|
+
return sha256HexSync(canonicalizePreExecutionReviewReceipt(receipt));
|
|
585
|
+
}
|
|
586
|
+
// ---------------------------------------------------------------------------
|
|
587
|
+
// PreExecutionReviewReceipt v1 — semantics
|
|
588
|
+
// ---------------------------------------------------------------------------
|
|
589
|
+
/** A PASS verdict of either stage. Everything else may report freely. */
|
|
590
|
+
function isPassVerdict(verdict) {
|
|
591
|
+
return verdict === "spec-review-pass" || verdict === "plan-review-pass";
|
|
592
|
+
}
|
|
593
|
+
/**
|
|
594
|
+
* The receipt rules that run with or without a snapshot in hand: the finding rows
|
|
595
|
+
* whose meaning Draft-07 cannot carry.
|
|
596
|
+
*
|
|
597
|
+
* A finding with no evidence reference is an opinion, so the contract refuses it
|
|
598
|
+
* (`invalid-evidence`); the engine already refuses a duplicate finding id, a
|
|
599
|
+
* reversal of the review window, a timestamp that names a non-existent instant, and
|
|
600
|
+
* a verdict from the wrong stage — the matrix is declared once, in
|
|
601
|
+
* `PRE_EXECUTION_RECEIPT_CONTRACT.rules`, and applied by the shared structural pass.
|
|
602
|
+
*/
|
|
603
|
+
function receiptSemantics(document, collector) {
|
|
604
|
+
const findings = document.findings;
|
|
605
|
+
for (let i = 0; i < findings.length; i++) {
|
|
606
|
+
if (findings[i].evidenceRefs.length === 0) {
|
|
607
|
+
collector.add("invalid-evidence", `/findings/${i}/evidenceRefs`);
|
|
608
|
+
}
|
|
609
|
+
}
|
|
610
|
+
}
|
|
611
|
+
/**
|
|
612
|
+
* The authoritative receipt validator that does NOT bind a snapshot (feature 28
|
|
613
|
+
* AC1): the contract id, the closed verdict/severity/class/verification/resolution/
|
|
614
|
+
* role vocabularies, the stage/verdict matrix, opaque bounded identities, UTC
|
|
615
|
+
* calendar-valid ordered timestamps, the bounded finding and parent-receipt sets
|
|
616
|
+
* with unique ids, digests, and rows, and the payload budget.
|
|
617
|
+
*
|
|
618
|
+
* It proves a receipt is WELL-FORMED. The parent topology is deliberately not
|
|
619
|
+
* part of that answer — a plain reviewer may record a critique lineage — and
|
|
620
|
+
* cannot prove the claim a PASS makes — that the bound snapshot is the current
|
|
621
|
+
* one and nothing material is still open — so it is never the gate;
|
|
622
|
+
* `validatePreExecutionReceiptAgainstSnapshot` is.
|
|
623
|
+
*/
|
|
624
|
+
export function validatePreExecutionReviewReceiptV1(value) {
|
|
625
|
+
const collector = createCollector();
|
|
626
|
+
const document = structuralRun(PRE_EXECUTION_CONTRACT.receipt, value, PRE_EXECUTION_LIMITS.receiptBytes, collector);
|
|
627
|
+
if (document === null)
|
|
628
|
+
return refused(collector);
|
|
629
|
+
receiptSemantics(document, collector);
|
|
630
|
+
if (collector.failed())
|
|
631
|
+
return refused(collector);
|
|
632
|
+
return accepted("receipt", document);
|
|
633
|
+
}
|
|
634
|
+
/**
|
|
635
|
+
* The ONLY authority that blesses a pre-execution verdict (feature 28 AC1/AC2).
|
|
636
|
+
*
|
|
637
|
+
* On top of the structural pass it binds the receipt to a snapshot and to the
|
|
638
|
+
* policy it was reviewed under, then enforces what a PASS actually claims:
|
|
639
|
+
*
|
|
640
|
+
* 1. the receipt must bind THIS snapshot — same stage, current `policyVersion`,
|
|
641
|
+
* and a `snapshotDigest` equal to the digest of the snapshot (`stale-snapshot`
|
|
642
|
+
* otherwise, so a rotated document cannot be blessed by an older reading);
|
|
643
|
+
* 2. when the runtime can observe authorship, a reviewer cannot be its own author
|
|
644
|
+
* (`invalid-author`); where it cannot, the receipt says so in
|
|
645
|
+
* `authorExclusion: "not-enforceable"` and the limit stays visible instead of
|
|
646
|
+
* being laundered into a PASS;
|
|
647
|
+
* 3. `contextClean` is mandatory for a PASS and never for a FAIL: a contaminated
|
|
648
|
+
* reviewer may still report what it found;
|
|
649
|
+
* 4. a PASS may not carry a material finding that is still open or unverified
|
|
650
|
+
* (`verdict-mismatch`) — `info` severity is the only immaterial row.
|
|
651
|
+
*
|
|
652
|
+
* The parent-topology rule (parents require a critic/synthesizer/arbiter role,
|
|
653
|
+
* `invalid-topology`) is part of the canonical definition itself — the shared
|
|
654
|
+
* structural walk enforces it for the standalone validator too, so there is no
|
|
655
|
+
* second, binding-only copy. `modelDiversity` is deliberately absent from this
|
|
656
|
+
* list: it is reported truthfully and never converted into a threshold, because
|
|
657
|
+
* plurality of identical models is not independence. There is no quorum to
|
|
658
|
+
* satisfy, and no numeric approval model to reverse-engineer from a parent list.
|
|
659
|
+
*/
|
|
660
|
+
export function validatePreExecutionReceiptAgainstSnapshot(receipt, snapshot, policyVersion) {
|
|
661
|
+
const collector = createCollector();
|
|
662
|
+
const document = structuralRun(PRE_EXECUTION_CONTRACT.receipt, receipt, PRE_EXECUTION_LIMITS.receiptBytes, collector);
|
|
663
|
+
if (document === null)
|
|
664
|
+
return refused(collector);
|
|
665
|
+
// The parent topology is a definition rule with `binding` enforcement: the
|
|
666
|
+
// plain structural walk skipped it (a well-formed receipt may record the
|
|
667
|
+
// topology), and THIS authority — the only one that blesses a verdict —
|
|
668
|
+
// applies it here over the same captured document.
|
|
669
|
+
const bindingSink = createVerificationDiagnosticSink();
|
|
670
|
+
for (const rule of PRE_EXECUTION_CONTRACT.receipt.root.rules) {
|
|
671
|
+
if (rule.enforcement === "binding") {
|
|
672
|
+
applyCrossRule(PRE_EXECUTION_CONTRACT.receipt.root, rule, document, "", bindingSink);
|
|
673
|
+
}
|
|
674
|
+
}
|
|
675
|
+
collector.addEngine(bindingSink);
|
|
676
|
+
receiptSemantics(document, collector);
|
|
677
|
+
if (collector.failed())
|
|
678
|
+
return refused(collector);
|
|
679
|
+
if (!isValidSnapshot(snapshot)) {
|
|
680
|
+
// Nothing verifiable was reviewed: the binding, not the artifact fields, is
|
|
681
|
+
// what failed, so the answer is one row on the receipt's own pointer.
|
|
682
|
+
collector.add("stale-snapshot", "/snapshotDigest");
|
|
683
|
+
return refused(collector);
|
|
684
|
+
}
|
|
685
|
+
const bound = document;
|
|
686
|
+
const reviewed = snapshot;
|
|
687
|
+
if (bound.stage !== reviewed.stage)
|
|
688
|
+
collector.add("invalid-stage", "/stage");
|
|
689
|
+
if (bound.policyVersion !== policyVersion)
|
|
690
|
+
collector.add("stale-policy", "/policyVersion");
|
|
691
|
+
else if (digestPreExecutionArtifactSnapshot(reviewed) !== bound.snapshotDigest) {
|
|
692
|
+
collector.add("stale-snapshot", "/snapshotDigest");
|
|
693
|
+
}
|
|
694
|
+
if (bound.authorExclusion === "enforced" && bound.authorId === bound.reviewer) {
|
|
695
|
+
collector.add("invalid-author", "/authorId");
|
|
696
|
+
}
|
|
697
|
+
if (isPassVerdict(bound.verdict) && !bound.contextClean) {
|
|
698
|
+
collector.add("invalid-context", "/contextClean");
|
|
699
|
+
}
|
|
700
|
+
if (isPassVerdict(bound.verdict)) {
|
|
701
|
+
for (let i = 0; i < bound.findings.length; i++) {
|
|
702
|
+
const finding = bound.findings[i];
|
|
703
|
+
const material = finding.severity !== "info";
|
|
704
|
+
if (material && (finding.resolution === "open" || finding.verification === "unverified")) {
|
|
705
|
+
collector.add("verdict-mismatch", `/findings/${i}`);
|
|
706
|
+
}
|
|
707
|
+
}
|
|
708
|
+
}
|
|
709
|
+
if (collector.failed())
|
|
710
|
+
return refused(collector);
|
|
711
|
+
return accepted("receipt", bound);
|
|
712
|
+
}
|
|
713
|
+
// ---------------------------------------------------------------------------
|
|
714
|
+
// Freshness — one deterministic answer per comparison
|
|
715
|
+
// ---------------------------------------------------------------------------
|
|
716
|
+
const FRESH = Object.freeze({ fresh: true });
|
|
717
|
+
function stale(reasonCode) {
|
|
718
|
+
return Object.freeze({ fresh: false, reasonCode });
|
|
719
|
+
}
|
|
720
|
+
/**
|
|
721
|
+
* Is the approval recorded in `receipt` still the approval of the CURRENT document?
|
|
722
|
+
*
|
|
723
|
+
* Pure, deterministic, and total: it throws nothing and returns exactly one verdict
|
|
724
|
+
* in this fixed precedence —
|
|
725
|
+
*
|
|
726
|
+
* 1. `missing-receipt-snapshot` — the receipt does not bind the reviewed snapshot
|
|
727
|
+
* (including a receipt or snapshot it cannot read at all);
|
|
728
|
+
* 2. `invalid-stage` / `invalid-unit` — the two snapshots are not the same review
|
|
729
|
+
* target, which no content comparison can repair;
|
|
730
|
+
* 3. `stale-policy` — the review policy moved under the approval;
|
|
731
|
+
* 4. `stale-context` — an authority the reviewer relied on changed;
|
|
732
|
+
* 5. `stale-source-revision` — the repository revision the artifacts were read at
|
|
733
|
+
* changed;
|
|
734
|
+
* 6. `stale-parent` — the Product snapshot a Plan approval descends from changed
|
|
735
|
+
* (lineage, so a Product rewrite erases the descendant approval);
|
|
736
|
+
* 7. `stale-artifact-content` — a bound artifact's bytes changed;
|
|
737
|
+
* 8. `stale-artifact-revision` — the authoring revision rotated with identical
|
|
738
|
+
* bytes, which is why content is checked first: a mutate-then-revert with a
|
|
739
|
+
* rotated `artifactRevisionId` still lands here and an older PASS never
|
|
740
|
+
* resurrects (S6);
|
|
741
|
+
* 9. otherwise `{ fresh: true }`.
|
|
742
|
+
*
|
|
743
|
+
* Every dimension is reported alone because a caller routes on it: a stale context
|
|
744
|
+
* asks a sensor to re-read, a stale artifact asks the reviewer to re-read, and a
|
|
745
|
+
* rotated revision asks the author for a new review. Collapsing them into "stale"
|
|
746
|
+
* would leave a driver guessing which is why the codes are named per dimension.
|
|
747
|
+
*/
|
|
748
|
+
export function comparePreExecutionReceiptToSnapshot(receipt, reviewedSnapshot, currentSnapshot, policyVersion) {
|
|
749
|
+
if (!isValidSnapshot(reviewedSnapshot) || !isValidSnapshot(currentSnapshot)) {
|
|
750
|
+
// An input the comparator cannot read at all is precedence 1: the receipt
|
|
751
|
+
// does not bind a snapshot (reviewed side) or the document is not the thing
|
|
752
|
+
// that was approved (current side). There is no content comparison to make,
|
|
753
|
+
// so a failed validation can never read as content drift — even for an
|
|
754
|
+
// invalid object or an array (arrays are objects).
|
|
755
|
+
return stale("missing-receipt-snapshot");
|
|
756
|
+
}
|
|
757
|
+
const reviewed = reviewedSnapshot;
|
|
758
|
+
const current = currentSnapshot;
|
|
759
|
+
let reviewedDigest;
|
|
760
|
+
try {
|
|
761
|
+
reviewedDigest = digestPreExecutionArtifactSnapshot(reviewed);
|
|
762
|
+
}
|
|
763
|
+
catch {
|
|
764
|
+
return stale("missing-receipt-snapshot");
|
|
765
|
+
}
|
|
766
|
+
const record = readReceiptBinding(receipt);
|
|
767
|
+
if (record === null || record.snapshotDigest !== reviewedDigest)
|
|
768
|
+
return stale("missing-receipt-snapshot");
|
|
769
|
+
if (reviewed.stage !== current.stage)
|
|
770
|
+
return stale("invalid-stage");
|
|
771
|
+
if (reviewed.unitKind !== current.unitKind || reviewed.unitId !== current.unitId) {
|
|
772
|
+
return stale("invalid-unit");
|
|
773
|
+
}
|
|
774
|
+
if (record.policyVersion !== policyVersion)
|
|
775
|
+
return stale("stale-policy");
|
|
776
|
+
if (!sameContexts(reviewed.contexts, current.contexts))
|
|
777
|
+
return stale("stale-context");
|
|
778
|
+
if (reviewed.sourceRevision !== current.sourceRevision)
|
|
779
|
+
return stale("stale-source-revision");
|
|
780
|
+
if (reviewed.parentSpecSnapshotDigest !== current.parentSpecSnapshotDigest)
|
|
781
|
+
return stale("stale-parent");
|
|
782
|
+
if (!sameArtifacts(reviewed.artifacts, current.artifacts))
|
|
783
|
+
return stale("stale-artifact-content");
|
|
784
|
+
if (reviewed.artifactRevisionId !== current.artifactRevisionId)
|
|
785
|
+
return stale("stale-artifact-revision");
|
|
786
|
+
return FRESH;
|
|
787
|
+
}
|
|
788
|
+
/**
|
|
789
|
+
* The two receipt fields the comparison needs, read defensively.
|
|
790
|
+
*
|
|
791
|
+
* A malformed receipt is not an error here: it is a receipt that binds no snapshot,
|
|
792
|
+
* which is exactly `missing-receipt-snapshot`. Field names are the only thing read,
|
|
793
|
+
* and no submitted value is carried out of the answer.
|
|
794
|
+
*/
|
|
795
|
+
function readReceiptBinding(receipt) {
|
|
796
|
+
if (receipt === null || typeof receipt !== "object" || Array.isArray(receipt))
|
|
797
|
+
return null;
|
|
798
|
+
const candidate = receipt;
|
|
799
|
+
if (candidate.contract !== PRE_EXECUTION_RECEIPT_CONTRACT_ID)
|
|
800
|
+
return null;
|
|
801
|
+
if (typeof candidate.snapshotDigest !== "string" || !DIGEST_PATTERN.test(candidate.snapshotDigest)) {
|
|
802
|
+
return null;
|
|
803
|
+
}
|
|
804
|
+
if (typeof candidate.policyVersion !== "string")
|
|
805
|
+
return null;
|
|
806
|
+
return { snapshotDigest: candidate.snapshotDigest, policyVersion: candidate.policyVersion };
|
|
807
|
+
}
|
|
808
|
+
function sameArtifacts(a, b) {
|
|
809
|
+
if (a.length !== b.length)
|
|
810
|
+
return false;
|
|
811
|
+
for (let i = 0; i < a.length; i++) {
|
|
812
|
+
const left = a[i];
|
|
813
|
+
const right = b[i];
|
|
814
|
+
if (left.kind !== right.kind
|
|
815
|
+
|| left.path !== right.path
|
|
816
|
+
|| left.selector !== right.selector
|
|
817
|
+
|| left.byteLength !== right.byteLength
|
|
818
|
+
|| left.digest !== right.digest) {
|
|
819
|
+
return false;
|
|
820
|
+
}
|
|
821
|
+
}
|
|
822
|
+
return true;
|
|
823
|
+
}
|
|
824
|
+
function sameContexts(a, b) {
|
|
825
|
+
if (a.length !== b.length)
|
|
826
|
+
return false;
|
|
827
|
+
for (let i = 0; i < a.length; i++) {
|
|
828
|
+
const left = a[i];
|
|
829
|
+
const right = b[i];
|
|
830
|
+
if (left.kind !== right.kind
|
|
831
|
+
|| left.identifier !== right.identifier
|
|
832
|
+
|| left.presence !== right.presence
|
|
833
|
+
|| left.digest !== right.digest) {
|
|
834
|
+
return false;
|
|
835
|
+
}
|
|
836
|
+
}
|
|
837
|
+
return true;
|
|
838
|
+
}
|