@gtrabanco/agentic-workflow-schema 3.2.0 → 3.4.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 +300 -3
- package/README.md +292 -3
- package/candidate-snapshot.schema.json +129 -0
- package/dist/index.d.ts +410 -0
- package/dist/index.js +1116 -1
- package/dist/verification-contract.d.ts +227 -0
- package/dist/verification-contract.js +1111 -0
- package/package.json +17 -3
- package/review-receipt.schema.json +130 -0
- package/verification-plan.schema.json +197 -0
- package/verification-receipt.schema.json +309 -0
package/dist/index.js
CHANGED
|
@@ -8,6 +8,7 @@
|
|
|
8
8
|
* take the LAST fenced ```json block of the assistant's final message;
|
|
9
9
|
* exactly one envelope per turn; all top-level keys always present.
|
|
10
10
|
*/
|
|
11
|
+
import { VERIFICATION_COMMAND_STATUSES, VERIFICATION_CONTRACT, VERIFICATION_COST_CLASSES, VERIFICATION_DIAGNOSTIC_CODES, VERIFICATION_LIMITS, VERIFICATION_PLAN_CONTRACT_ID, VERIFICATION_RECEIPT_CONTRACT_ID, VERIFICATION_STAGES, VERIFICATION_VERDICTS, createVerificationDiagnosticSink, captureVerificationInput, projectStructure, validateStructure, } from "./verification-contract.js";
|
|
11
12
|
// ---------------------------------------------------------------------------
|
|
12
13
|
// Types (source of truth: this package; the internal skill carries policy only)
|
|
13
14
|
// ---------------------------------------------------------------------------
|
|
@@ -341,10 +342,26 @@ export function isRunHalt(envelope) {
|
|
|
341
342
|
// ---------------------------------------------------------------------------
|
|
342
343
|
/** The strict, driver-facing interpretation of the legacy envelope. */
|
|
343
344
|
const STRICT_V2_KEYS = [...REQUIRED_KEYS, "detail"];
|
|
345
|
+
/**
|
|
346
|
+
* Memo for the key vocabularies below: they are static contract data repeated
|
|
347
|
+
* per parsed envelope, so the `Set` is built once per distinct vocabulary
|
|
348
|
+
* instead of once per call. The key joins on NUL, which no JSON member name can
|
|
349
|
+
* contain here, so two vocabularies can never alias each other.
|
|
350
|
+
*/
|
|
351
|
+
const _vocabularyKeys = new Map();
|
|
352
|
+
function vocabularyKeys(keys) {
|
|
353
|
+
const memo = keys.join("\0");
|
|
354
|
+
let allowed = _vocabularyKeys.get(memo);
|
|
355
|
+
if (allowed === undefined) {
|
|
356
|
+
allowed = new Set(keys);
|
|
357
|
+
_vocabularyKeys.set(memo, allowed);
|
|
358
|
+
}
|
|
359
|
+
return allowed;
|
|
360
|
+
}
|
|
344
361
|
function rejectUnexpectedKeys(value, path, keys, errors) {
|
|
345
362
|
if (!isObj(value))
|
|
346
363
|
return;
|
|
347
|
-
const allowed =
|
|
364
|
+
const allowed = vocabularyKeys(keys);
|
|
348
365
|
for (const key of Object.keys(value)) {
|
|
349
366
|
if (!allowed.has(key))
|
|
350
367
|
errors.push(`unexpected key: ${path}.${key}`);
|
|
@@ -1817,3 +1834,1101 @@ export function compileWorkflowSnapshot(input) {
|
|
|
1817
1834
|
? { ok: true, snapshot: validation.snapshot }
|
|
1818
1835
|
: { ok: false, errors: validation.errors };
|
|
1819
1836
|
}
|
|
1837
|
+
// ===========================================================================
|
|
1838
|
+
// Content-bound review receipts — CandidateSnapshot v1
|
|
1839
|
+
// ===========================================================================
|
|
1840
|
+
/** Contract identifier for CandidateSnapshot v1. */
|
|
1841
|
+
export const CANDIDATE_SNAPSHOT_CONTRACT_ID = "agentic-workflow/candidate-snapshot@1";
|
|
1842
|
+
// ---------------------------------------------------------------------------
|
|
1843
|
+
// Internal helpers
|
|
1844
|
+
// ---------------------------------------------------------------------------
|
|
1845
|
+
const SHA1_RE = /^[a-f0-9]{40}$/;
|
|
1846
|
+
const SHA256_RE = /^[a-f0-9]{64}$/;
|
|
1847
|
+
const FP_RE = /^[a-f0-9]{64}$/;
|
|
1848
|
+
const VALID_MODES = new Set(["100644", "100755", "120000", "160000"]);
|
|
1849
|
+
const VALID_STATUSES = new Set(["added", "modified", "deleted", "renamed", "copied", "type-changed"]);
|
|
1850
|
+
function isGitObjectId(v) {
|
|
1851
|
+
if (!isObj(v))
|
|
1852
|
+
return false;
|
|
1853
|
+
const keys = Object.keys(v);
|
|
1854
|
+
if (keys.length !== 2)
|
|
1855
|
+
return false;
|
|
1856
|
+
if (v.algorithm !== "sha1" && v.algorithm !== "sha256")
|
|
1857
|
+
return false;
|
|
1858
|
+
if (v.hex === undefined || typeof v.hex !== "string")
|
|
1859
|
+
return false;
|
|
1860
|
+
if (v.algorithm === "sha1" && !SHA1_RE.test(v.hex))
|
|
1861
|
+
return false;
|
|
1862
|
+
if (v.algorithm === "sha256" && !SHA256_RE.test(v.hex))
|
|
1863
|
+
return false;
|
|
1864
|
+
return true;
|
|
1865
|
+
}
|
|
1866
|
+
function hasUndeclaredKeys(actual, known) {
|
|
1867
|
+
return Object.keys(actual).filter((k) => !known.includes(k));
|
|
1868
|
+
}
|
|
1869
|
+
/**
|
|
1870
|
+
* Compare two UTF-8 strings in ascending unsigned-byte order.
|
|
1871
|
+
* Returns < 0 if a < b, > 0 if a > b, 0 if equal.
|
|
1872
|
+
*/
|
|
1873
|
+
const _utf8Encoder = new TextEncoder();
|
|
1874
|
+
function utf8ByteCompare(a, b) {
|
|
1875
|
+
const ba = _utf8Encoder.encode(a);
|
|
1876
|
+
const bb = _utf8Encoder.encode(b);
|
|
1877
|
+
const len = Math.min(ba.length, bb.length);
|
|
1878
|
+
for (let i = 0; i < len; i++) {
|
|
1879
|
+
const diff = ba[i] - bb[i];
|
|
1880
|
+
if (diff !== 0)
|
|
1881
|
+
return diff;
|
|
1882
|
+
}
|
|
1883
|
+
return ba.length - bb.length;
|
|
1884
|
+
}
|
|
1885
|
+
/**
|
|
1886
|
+
* Structural validation of a CandidateSnapshot v1.
|
|
1887
|
+
* Rejects undeclared fields, enforces GitObjectId format, path-byte ordering,
|
|
1888
|
+
* null-applicability matrix, and the empty-diff rule.
|
|
1889
|
+
*/
|
|
1890
|
+
export function validateCandidateSnapshotV1(value) {
|
|
1891
|
+
const errors = [];
|
|
1892
|
+
if (!isObj(value)) {
|
|
1893
|
+
return { ok: false, errors: ["candidate snapshot is not a JSON object"] };
|
|
1894
|
+
}
|
|
1895
|
+
// --- contract id ---
|
|
1896
|
+
if (value.contract !== CANDIDATE_SNAPSHOT_CONTRACT_ID) {
|
|
1897
|
+
errors.push(`contract must be "${CANDIDATE_SNAPSHOT_CONTRACT_ID}" (got: ${String(value.contract)})`);
|
|
1898
|
+
}
|
|
1899
|
+
// --- top-level undeclared keys ---
|
|
1900
|
+
const knownTopKeys = [
|
|
1901
|
+
"contract", "objectFormat", "baseCommit", "candidateCommit",
|
|
1902
|
+
"baseTree", "candidateTree", "acceptanceFingerprint", "changedPaths",
|
|
1903
|
+
];
|
|
1904
|
+
const topExtra = hasUndeclaredKeys(value, knownTopKeys);
|
|
1905
|
+
for (const k of topExtra) {
|
|
1906
|
+
errors.push(`${k} is not a valid candidate-snapshot field`);
|
|
1907
|
+
}
|
|
1908
|
+
// --- objectFormat ---
|
|
1909
|
+
const objectFormat = value.objectFormat;
|
|
1910
|
+
if (objectFormat !== "sha1" && objectFormat !== "sha256") {
|
|
1911
|
+
errors.push(`objectFormat must be "sha1" | "sha256" (got: ${String(objectFormat)})`);
|
|
1912
|
+
}
|
|
1913
|
+
// --- GitObjectId fields (baseCommit, candidateCommit, baseTree, candidateTree) ---
|
|
1914
|
+
for (const key of ["baseCommit", "candidateCommit", "baseTree", "candidateTree"]) {
|
|
1915
|
+
if (!isGitObjectId(value[key])) {
|
|
1916
|
+
errors.push(`${key} must be a GitObjectId {algorithm:"${objectFormat}", hex:/^[a-f0-9]{${objectFormat === "sha1" ? 40 : 64}}$/}`);
|
|
1917
|
+
}
|
|
1918
|
+
else if (value[key].algorithm !== objectFormat) {
|
|
1919
|
+
errors.push(`${key}.algorithm must match objectFormat "${objectFormat}" (got: ${value[key].algorithm})`);
|
|
1920
|
+
}
|
|
1921
|
+
}
|
|
1922
|
+
// --- acceptanceFingerprint ---
|
|
1923
|
+
if (typeof value.acceptanceFingerprint !== "string" || !FP_RE.test(value.acceptanceFingerprint)) {
|
|
1924
|
+
errors.push("acceptanceFingerprint must be a lowercase SHA-256 hex string (64 chars)");
|
|
1925
|
+
}
|
|
1926
|
+
// --- changedPaths ---
|
|
1927
|
+
if (!Array.isArray(value.changedPaths)) {
|
|
1928
|
+
errors.push("changedPaths must be an array");
|
|
1929
|
+
}
|
|
1930
|
+
else {
|
|
1931
|
+
const entries = value.changedPaths;
|
|
1932
|
+
let seenPaths = new Set();
|
|
1933
|
+
let prevPath = "";
|
|
1934
|
+
for (let i = 0; i < entries.length; i++) {
|
|
1935
|
+
const entry = entries[i];
|
|
1936
|
+
const prefix = `changedPaths[${i}]`;
|
|
1937
|
+
if (!isObj(entry)) {
|
|
1938
|
+
errors.push(`${prefix} must be an object`);
|
|
1939
|
+
continue;
|
|
1940
|
+
}
|
|
1941
|
+
// Unknown keys
|
|
1942
|
+
const knownEntryKeys = ["path", "status", "oldPath", "mode", "objectSha", "sizeBytes", "binary"];
|
|
1943
|
+
const extra = hasUndeclaredKeys(entry, knownEntryKeys);
|
|
1944
|
+
for (const k of extra) {
|
|
1945
|
+
errors.push(`${prefix}.${k} is not a valid field`);
|
|
1946
|
+
}
|
|
1947
|
+
// path
|
|
1948
|
+
if (typeof entry.path !== "string") {
|
|
1949
|
+
errors.push(`${prefix}.path must be a string`);
|
|
1950
|
+
}
|
|
1951
|
+
else {
|
|
1952
|
+
if (entry.path.includes("\0")) {
|
|
1953
|
+
errors.push(`${prefix}.path must not contain NUL`);
|
|
1954
|
+
}
|
|
1955
|
+
if (entry.path.startsWith("/")) {
|
|
1956
|
+
errors.push(`${prefix}.path must not be absolute`);
|
|
1957
|
+
}
|
|
1958
|
+
const segments = entry.path.split("/");
|
|
1959
|
+
if (segments.some((s) => s === ".." || s.startsWith(".."))) {
|
|
1960
|
+
errors.push(`${prefix}.path must not contain a ".." segment`);
|
|
1961
|
+
}
|
|
1962
|
+
// Byte-order check
|
|
1963
|
+
if (utf8ByteCompare(entry.path, prevPath) < 0) {
|
|
1964
|
+
errors.push(`${prefix}.path is not in ascending byte order`);
|
|
1965
|
+
}
|
|
1966
|
+
prevPath = entry.path;
|
|
1967
|
+
// Duplicate check
|
|
1968
|
+
if (seenPaths.has(entry.path)) {
|
|
1969
|
+
errors.push(`${prefix}.path is a duplicate`);
|
|
1970
|
+
}
|
|
1971
|
+
seenPaths.add(entry.path);
|
|
1972
|
+
}
|
|
1973
|
+
// status
|
|
1974
|
+
if (typeof entry.status !== "string" || !VALID_STATUSES.has(entry.status)) {
|
|
1975
|
+
errors.push(`${prefix}.status must be one of added|modified|deleted|renamed|copied|type-changed (got: ${String(entry.status)})`);
|
|
1976
|
+
}
|
|
1977
|
+
// oldPath
|
|
1978
|
+
const status = entry.status;
|
|
1979
|
+
if ((status === "renamed" || status === "copied") && entry.oldPath === null) {
|
|
1980
|
+
errors.push(`${prefix}.renamed/copied entries require a non-null oldPath`);
|
|
1981
|
+
}
|
|
1982
|
+
else if ((status !== "renamed" && status !== "copied") && entry.oldPath !== null) {
|
|
1983
|
+
errors.push(`${prefix}.oldPath must be null when status is ${status}`);
|
|
1984
|
+
}
|
|
1985
|
+
// objectSha
|
|
1986
|
+
if (status === "deleted" && entry.objectSha !== null) {
|
|
1987
|
+
errors.push(`${prefix}.objectSha must be null for deleted entries`);
|
|
1988
|
+
}
|
|
1989
|
+
else if (status !== "deleted" && !isGitObjectId(entry.objectSha)) {
|
|
1990
|
+
// For non-deleted, objectSha should be a GitObjectId
|
|
1991
|
+
if (entry.objectSha !== null && !isGitObjectId(entry.objectSha)) {
|
|
1992
|
+
errors.push(`${prefix}.objectSha must be a GitObjectId or null`);
|
|
1993
|
+
}
|
|
1994
|
+
}
|
|
1995
|
+
// mode
|
|
1996
|
+
if (entry.mode !== null && !VALID_MODES.has(entry.mode)) {
|
|
1997
|
+
errors.push(`${prefix}.mode must be one of 100644|100755|120000|160000 or null (got: ${String(entry.mode)})`);
|
|
1998
|
+
}
|
|
1999
|
+
// sizeBytes
|
|
2000
|
+
if (entry.sizeBytes !== null) {
|
|
2001
|
+
if (typeof entry.sizeBytes !== "number" || entry.sizeBytes < 0 || !Number.isInteger(entry.sizeBytes)) {
|
|
2002
|
+
errors.push(`${prefix}.sizeBytes must be a non-negative integer or null`);
|
|
2003
|
+
}
|
|
2004
|
+
else if (entry.mode === "160000") {
|
|
2005
|
+
errors.push(`${prefix}.sizeBytes must be null for gitlinks (mode 160000)`);
|
|
2006
|
+
}
|
|
2007
|
+
}
|
|
2008
|
+
// binary
|
|
2009
|
+
if (entry.binary !== null && typeof entry.binary !== "boolean") {
|
|
2010
|
+
errors.push(`${prefix}.binary must be a boolean or null`);
|
|
2011
|
+
}
|
|
2012
|
+
else if (entry.mode === "160000" && entry.binary !== null) {
|
|
2013
|
+
errors.push(`${prefix}.binary must be null for gitlinks (mode 160000)`);
|
|
2014
|
+
}
|
|
2015
|
+
}
|
|
2016
|
+
}
|
|
2017
|
+
// --- Empty-diff rule ---
|
|
2018
|
+
if (Array.isArray(value.changedPaths) && value.changedPaths.length === 0) {
|
|
2019
|
+
// Check if baseTree equals candidateTree
|
|
2020
|
+
if (isGitObjectId(value.baseTree) && isGitObjectId(value.candidateTree)) {
|
|
2021
|
+
if (value.baseTree.hex !== value.candidateTree.hex) {
|
|
2022
|
+
errors.push("empty changedPaths requires baseTree and candidateTree to be identical (empty diff rule)");
|
|
2023
|
+
}
|
|
2024
|
+
}
|
|
2025
|
+
}
|
|
2026
|
+
if (errors.length > 0) {
|
|
2027
|
+
return { ok: false, errors };
|
|
2028
|
+
}
|
|
2029
|
+
return { ok: true, snapshot: value };
|
|
2030
|
+
}
|
|
2031
|
+
// ===========================================================================
|
|
2032
|
+
// Content-bound review receipts — ReviewReceipt v1
|
|
2033
|
+
// ===========================================================================
|
|
2034
|
+
/** Contract identifier for ReviewReceipt v1. */
|
|
2035
|
+
export const REVIEW_RECEIPT_CONTRACT_ID = "agentic-workflow/review-receipt@1";
|
|
2036
|
+
/** All review kinds supported by the workflow. */
|
|
2037
|
+
export const REVIEW_KINDS = [
|
|
2038
|
+
"implementation", "security", "verification", "debt",
|
|
2039
|
+
"design", "accessibility", "brand", "performance", "seo", "audit",
|
|
2040
|
+
];
|
|
2041
|
+
/** Finding severity levels. */
|
|
2042
|
+
export const FINDING_SEVERITIES = [
|
|
2043
|
+
"info", "low", "medium", "high", "critical",
|
|
2044
|
+
];
|
|
2045
|
+
const REVIEW_KINDS_SET = new Set(REVIEW_KINDS);
|
|
2046
|
+
const FINDING_SEVERITIES_SET = new Set(FINDING_SEVERITIES);
|
|
2047
|
+
// ---------------------------------------------------------------------------
|
|
2048
|
+
// Validator: validateReviewReceiptV1
|
|
2049
|
+
// ---------------------------------------------------------------------------
|
|
2050
|
+
const DIGEST_RE = /^[a-f0-9]{64}$/;
|
|
2051
|
+
const ISO_8601_RE = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?Z$/;
|
|
2052
|
+
/**
|
|
2053
|
+
* Structural validation of a ReviewReceipt v1.
|
|
2054
|
+
* Rejects undeclared fields, enforces closed vocabularies, format rules,
|
|
2055
|
+
* and constraints on timestamps and finding structure.
|
|
2056
|
+
*/
|
|
2057
|
+
export function validateReviewReceiptV1(value) {
|
|
2058
|
+
const errors = [];
|
|
2059
|
+
if (!isObj(value)) {
|
|
2060
|
+
return { ok: false, errors: ["review receipt is not a JSON object"] };
|
|
2061
|
+
}
|
|
2062
|
+
// --- contract id ---
|
|
2063
|
+
if (value.contract !== REVIEW_RECEIPT_CONTRACT_ID) {
|
|
2064
|
+
errors.push(`contract must be "${REVIEW_RECEIPT_CONTRACT_ID}" (got: ${String(value.contract)})`);
|
|
2065
|
+
}
|
|
2066
|
+
// --- top-level undeclared keys ---
|
|
2067
|
+
const knownReceiptKeys = [
|
|
2068
|
+
"contract", "id", "candidateSnapshotDigest", "kind", "verdict",
|
|
2069
|
+
"findings", "reviewer", "sessionId", "startedAt", "finishedAt",
|
|
2070
|
+
"diagnostics", "policyVersion",
|
|
2071
|
+
];
|
|
2072
|
+
const topExtra = hasUndeclaredKeys(value, knownReceiptKeys);
|
|
2073
|
+
for (const k of topExtra) {
|
|
2074
|
+
errors.push(`${k} is not a valid review-receipt field`);
|
|
2075
|
+
}
|
|
2076
|
+
// --- id ---
|
|
2077
|
+
if (typeof value.id !== "string" || value.id.length === 0) {
|
|
2078
|
+
errors.push("id must be a non-empty string");
|
|
2079
|
+
}
|
|
2080
|
+
// --- candidateSnapshotDigest ---
|
|
2081
|
+
if (typeof value.candidateSnapshotDigest !== "string" || !DIGEST_RE.test(value.candidateSnapshotDigest)) {
|
|
2082
|
+
errors.push("candidateSnapshotDigest must be a lowercase SHA-256 hex string (64 chars)");
|
|
2083
|
+
}
|
|
2084
|
+
// --- kind ---
|
|
2085
|
+
if (typeof value.kind !== "string" || !REVIEW_KINDS_SET.has(value.kind)) {
|
|
2086
|
+
errors.push(`kind must be one of ${REVIEW_KINDS.join("|")} (got: ${String(value.kind)})`);
|
|
2087
|
+
}
|
|
2088
|
+
// --- verdict ---
|
|
2089
|
+
if (value.verdict !== "pass" && value.verdict !== "fail") {
|
|
2090
|
+
errors.push(`verdict must be "pass" | "fail" (got: ${String(value.verdict)})`);
|
|
2091
|
+
}
|
|
2092
|
+
// --- findings ---
|
|
2093
|
+
if (!Array.isArray(value.findings)) {
|
|
2094
|
+
errors.push("findings must be an array");
|
|
2095
|
+
}
|
|
2096
|
+
else {
|
|
2097
|
+
const findings = value.findings;
|
|
2098
|
+
let seenFindingIds = new Set();
|
|
2099
|
+
for (let i = 0; i < findings.length; i++) {
|
|
2100
|
+
const f = findings[i];
|
|
2101
|
+
const prefix = `findings[${i}]`;
|
|
2102
|
+
if (!isObj(f)) {
|
|
2103
|
+
errors.push(`${prefix} must be an object`);
|
|
2104
|
+
continue;
|
|
2105
|
+
}
|
|
2106
|
+
// Unknown keys on finding
|
|
2107
|
+
const knownFindingKeys = ["id", "severity", "summary", "evidence", "refs"];
|
|
2108
|
+
const findingExtra = hasUndeclaredKeys(f, knownFindingKeys);
|
|
2109
|
+
for (const k of findingExtra) {
|
|
2110
|
+
errors.push(`${prefix}.${k} is not a valid field`);
|
|
2111
|
+
}
|
|
2112
|
+
// id
|
|
2113
|
+
if (typeof f.id !== "string" || f.id.length === 0) {
|
|
2114
|
+
errors.push(`${prefix}.id must be a non-empty string`);
|
|
2115
|
+
}
|
|
2116
|
+
else {
|
|
2117
|
+
if (seenFindingIds.has(f.id)) {
|
|
2118
|
+
errors.push(`${prefix}.id is a duplicate`);
|
|
2119
|
+
}
|
|
2120
|
+
seenFindingIds.add(f.id);
|
|
2121
|
+
}
|
|
2122
|
+
// severity
|
|
2123
|
+
if (typeof f.severity !== "string" || !FINDING_SEVERITIES_SET.has(f.severity)) {
|
|
2124
|
+
errors.push(`${prefix}.severity must be one of ${FINDING_SEVERITIES.join("|")} (got: ${String(f.severity)})`);
|
|
2125
|
+
}
|
|
2126
|
+
// summary
|
|
2127
|
+
if (typeof f.summary !== "string" || f.summary.length === 0) {
|
|
2128
|
+
errors.push(`${prefix}.summary must be a non-empty string`);
|
|
2129
|
+
}
|
|
2130
|
+
// evidence
|
|
2131
|
+
if (f.evidence !== undefined && f.evidence !== null) {
|
|
2132
|
+
if (isObj(f.evidence)) {
|
|
2133
|
+
const evidenceKeys = Object.keys(f.evidence);
|
|
2134
|
+
const knownEvidenceKeys = ["path", "line"];
|
|
2135
|
+
const evidenceExtra = hasUndeclaredKeys(f.evidence, knownEvidenceKeys);
|
|
2136
|
+
for (const k of evidenceExtra) {
|
|
2137
|
+
errors.push(`${prefix}.evidence.${k} is not a valid field`);
|
|
2138
|
+
}
|
|
2139
|
+
if (typeof f.evidence.path !== "string") {
|
|
2140
|
+
errors.push(`${prefix}.evidence.path must be a string`);
|
|
2141
|
+
}
|
|
2142
|
+
if (f.evidence.line !== undefined && f.evidence.line !== null) {
|
|
2143
|
+
if (typeof f.evidence.line !== "number" || !Number.isInteger(f.evidence.line) || f.evidence.line < 1) {
|
|
2144
|
+
errors.push(`${prefix}.evidence.line must be an integer >= 1`);
|
|
2145
|
+
}
|
|
2146
|
+
}
|
|
2147
|
+
}
|
|
2148
|
+
else {
|
|
2149
|
+
errors.push(`${prefix}.evidence must be an object or null`);
|
|
2150
|
+
}
|
|
2151
|
+
}
|
|
2152
|
+
// refs
|
|
2153
|
+
if (!Array.isArray(f.refs)) {
|
|
2154
|
+
errors.push(`${prefix}.refs must be an array`);
|
|
2155
|
+
}
|
|
2156
|
+
else {
|
|
2157
|
+
for (let j = 0; j < f.refs.length; j++) {
|
|
2158
|
+
if (typeof f.refs[j] !== "string") {
|
|
2159
|
+
errors.push(`${prefix}.refs[${j}] must be a string`);
|
|
2160
|
+
break;
|
|
2161
|
+
}
|
|
2162
|
+
}
|
|
2163
|
+
}
|
|
2164
|
+
}
|
|
2165
|
+
}
|
|
2166
|
+
// --- reviewer ---
|
|
2167
|
+
if (typeof value.reviewer !== "string" || value.reviewer.length === 0) {
|
|
2168
|
+
errors.push("reviewer must be a non-empty string");
|
|
2169
|
+
}
|
|
2170
|
+
// --- sessionId ---
|
|
2171
|
+
if (typeof value.sessionId !== "string" || value.sessionId.length === 0) {
|
|
2172
|
+
errors.push("sessionId must be a non-empty string");
|
|
2173
|
+
}
|
|
2174
|
+
// --- startedAt / finishedAt (ISO-8601 UTC) ---
|
|
2175
|
+
if (typeof value.startedAt !== "string" || !ISO_8601_RE.test(value.startedAt)) {
|
|
2176
|
+
errors.push("startedAt must be an ISO-8601 UTC timestamp");
|
|
2177
|
+
}
|
|
2178
|
+
if (typeof value.finishedAt !== "string" || !ISO_8601_RE.test(value.finishedAt)) {
|
|
2179
|
+
errors.push("finishedAt must be an ISO-8601 UTC timestamp");
|
|
2180
|
+
}
|
|
2181
|
+
// finishedAt >= startedAt — Date.parse is safe because the regex only
|
|
2182
|
+
// accepts Z-suffix (UTC) so no mixed-offset ambiguity remains.
|
|
2183
|
+
if (typeof value.startedAt === "string" && typeof value.finishedAt === "string" &&
|
|
2184
|
+
ISO_8601_RE.test(value.startedAt) && ISO_8601_RE.test(value.finishedAt)) {
|
|
2185
|
+
if (Date.parse(value.finishedAt) < Date.parse(value.startedAt)) {
|
|
2186
|
+
errors.push("finishedAt must be >= startedAt");
|
|
2187
|
+
}
|
|
2188
|
+
}
|
|
2189
|
+
// --- diagnostics ---
|
|
2190
|
+
if (!Array.isArray(value.diagnostics)) {
|
|
2191
|
+
errors.push("diagnostics must be an array");
|
|
2192
|
+
}
|
|
2193
|
+
else {
|
|
2194
|
+
for (let i = 0; i < value.diagnostics.length; i++) {
|
|
2195
|
+
if (typeof value.diagnostics[i] !== "string") {
|
|
2196
|
+
errors.push(`diagnostics[${i}] must be a string`);
|
|
2197
|
+
break;
|
|
2198
|
+
}
|
|
2199
|
+
}
|
|
2200
|
+
}
|
|
2201
|
+
// --- policyVersion ---
|
|
2202
|
+
if (typeof value.policyVersion !== "string" || value.policyVersion.length === 0) {
|
|
2203
|
+
errors.push("policyVersion must be a non-empty string");
|
|
2204
|
+
}
|
|
2205
|
+
if (errors.length > 0) {
|
|
2206
|
+
return { ok: false, errors };
|
|
2207
|
+
}
|
|
2208
|
+
return { ok: true, receipt: value };
|
|
2209
|
+
}
|
|
2210
|
+
// ===========================================================================
|
|
2211
|
+
// Canonical content-binding core (D2, D4, D1)
|
|
2212
|
+
// ===========================================================================
|
|
2213
|
+
/** Staleness reason codes — one per detectable dimension. */
|
|
2214
|
+
export const STALE_REASON_CODES = [
|
|
2215
|
+
"stale-base-tree",
|
|
2216
|
+
"stale-candidate-tree",
|
|
2217
|
+
"stale-manifest",
|
|
2218
|
+
"stale-acceptance-fingerprint",
|
|
2219
|
+
"stale-review-policy",
|
|
2220
|
+
];
|
|
2221
|
+
/**
|
|
2222
|
+
* D4/D6 — Canonical serialization of one value.
|
|
2223
|
+
*
|
|
2224
|
+
* The domain is the JSON data model: `null`, string, finite number, boolean, array
|
|
2225
|
+
* and plain object. What happens *outside* it is the `domain` argument above — a
|
|
2226
|
+
* named refusal for the verification contracts, the 3.3.0 fallback for the legacy
|
|
2227
|
+
* ones. This function is the byte-level authority behind every digest in the
|
|
2228
|
+
* package, so the two domains are pinned by golden vectors
|
|
2229
|
+
* (`test/fixtures/canonical-legacy-vectors.mjs`) and by the AC5 verification
|
|
2230
|
+
* vectors, never by prose.
|
|
2231
|
+
*/
|
|
2232
|
+
function canonicalJSONValue(v, domain = "verification") {
|
|
2233
|
+
if (v === null)
|
|
2234
|
+
return "null";
|
|
2235
|
+
const kind = typeof v;
|
|
2236
|
+
if (kind === "string")
|
|
2237
|
+
return JSON.stringify(v);
|
|
2238
|
+
if (kind === "number") {
|
|
2239
|
+
if (!Number.isFinite(v)) {
|
|
2240
|
+
if (domain === "verification") {
|
|
2241
|
+
throw new TypeError(`canonical JSON: unsupported leaf (non-finite ${kind})`);
|
|
2242
|
+
}
|
|
2243
|
+
return JSON.stringify(v); // 3.3.0: NaN / ±Infinity serialize as `null`
|
|
2244
|
+
}
|
|
2245
|
+
return JSON.stringify(v);
|
|
2246
|
+
}
|
|
2247
|
+
if (kind === "boolean")
|
|
2248
|
+
return JSON.stringify(v);
|
|
2249
|
+
if (Array.isArray(v)) {
|
|
2250
|
+
// An explicit arrow, never `.map(canonicalJSONValue)`: `map` would pass the
|
|
2251
|
+
// element INDEX as the domain, silently selecting the legacy fallback for
|
|
2252
|
+
// every array leaf.
|
|
2253
|
+
return "[" + v.map((item) => canonicalJSONValue(item, domain)).join(",") + "]";
|
|
2254
|
+
}
|
|
2255
|
+
if (kind === "object") {
|
|
2256
|
+
const keys = Object.keys(v).sort();
|
|
2257
|
+
return "{" + keys.map(k => JSON.stringify(k) + ":" + canonicalJSONValue(v[k], domain)).join(",") + "}";
|
|
2258
|
+
}
|
|
2259
|
+
if (domain === "verification") {
|
|
2260
|
+
throw new TypeError(`canonical JSON: unsupported leaf (${kind})`);
|
|
2261
|
+
}
|
|
2262
|
+
return JSON.stringify(v);
|
|
2263
|
+
}
|
|
2264
|
+
/**
|
|
2265
|
+
* D4 — Canonicalize a CandidateSnapshotV1.
|
|
2266
|
+
* Produces deterministic JSON with declaration-order keys and sorted changedPaths.
|
|
2267
|
+
*/
|
|
2268
|
+
export function canonicalizeCandidateSnapshot(snapshot) {
|
|
2269
|
+
const sortedPaths = [...snapshot.changedPaths].sort((a, b) => utf8ByteCompare(a.path, b.path));
|
|
2270
|
+
const obj = {
|
|
2271
|
+
contract: snapshot.contract,
|
|
2272
|
+
objectFormat: snapshot.objectFormat,
|
|
2273
|
+
baseCommit: snapshot.baseCommit,
|
|
2274
|
+
candidateCommit: snapshot.candidateCommit,
|
|
2275
|
+
baseTree: snapshot.baseTree,
|
|
2276
|
+
candidateTree: snapshot.candidateTree,
|
|
2277
|
+
acceptanceFingerprint: snapshot.acceptanceFingerprint,
|
|
2278
|
+
changedPaths: sortedPaths,
|
|
2279
|
+
};
|
|
2280
|
+
return canonicalJSONValue(obj, "legacy");
|
|
2281
|
+
}
|
|
2282
|
+
/**
|
|
2283
|
+
* D4 — Canonicalize a ReviewReceiptV1.
|
|
2284
|
+
* Findings are sorted by ascending byte order of their stable ids.
|
|
2285
|
+
*/
|
|
2286
|
+
export function canonicalizeReviewReceipt(receipt) {
|
|
2287
|
+
const sortedFindings = [...receipt.findings].sort((a, b) => utf8ByteCompare(a.id, b.id));
|
|
2288
|
+
const obj = {
|
|
2289
|
+
contract: receipt.contract,
|
|
2290
|
+
id: receipt.id,
|
|
2291
|
+
candidateSnapshotDigest: receipt.candidateSnapshotDigest,
|
|
2292
|
+
kind: receipt.kind,
|
|
2293
|
+
verdict: receipt.verdict,
|
|
2294
|
+
findings: sortedFindings,
|
|
2295
|
+
reviewer: receipt.reviewer,
|
|
2296
|
+
sessionId: receipt.sessionId,
|
|
2297
|
+
startedAt: receipt.startedAt,
|
|
2298
|
+
finishedAt: receipt.finishedAt,
|
|
2299
|
+
diagnostics: receipt.diagnostics,
|
|
2300
|
+
policyVersion: receipt.policyVersion,
|
|
2301
|
+
};
|
|
2302
|
+
return canonicalJSONValue(obj, "legacy");
|
|
2303
|
+
}
|
|
2304
|
+
// ---------------------------------------------------------------------------
|
|
2305
|
+
// SHA-256 hashing
|
|
2306
|
+
// ---------------------------------------------------------------------------
|
|
2307
|
+
/** D4 — SHA-256 hex digest (async via Web Crypto). */
|
|
2308
|
+
async function sha256Hex(data) {
|
|
2309
|
+
const buf = _utf8Encoder.encode(data);
|
|
2310
|
+
const hashBuffer = await crypto.subtle.digest("SHA-256", buf);
|
|
2311
|
+
const hashArray = new Uint8Array(hashBuffer);
|
|
2312
|
+
return Array.from(hashArray).map(b => b.toString(16).padStart(2, "0")).join("");
|
|
2313
|
+
}
|
|
2314
|
+
/** D4 — Digest a CandidateSnapshotV1 via canonical serialization. */
|
|
2315
|
+
export async function digestCandidateSnapshot(snapshot) {
|
|
2316
|
+
return sha256Hex(canonicalizeCandidateSnapshot(snapshot));
|
|
2317
|
+
}
|
|
2318
|
+
/** D4 — Digest a ReviewReceiptV1 via canonical serialization. */
|
|
2319
|
+
export async function digestReviewReceipt(receipt) {
|
|
2320
|
+
return sha256Hex(canonicalizeReviewReceipt(receipt));
|
|
2321
|
+
}
|
|
2322
|
+
// ---------------------------------------------------------------------------
|
|
2323
|
+
// D2 — Acceptance fingerprint
|
|
2324
|
+
// ---------------------------------------------------------------------------
|
|
2325
|
+
/**
|
|
2326
|
+
* D2 — Compute the acceptance fingerprint from an ordered array of
|
|
2327
|
+
* {id, blobSha256} entries. Returns lowercase hex SHA-256 over their
|
|
2328
|
+
* canonical serialization (sorted by byte-order of id).
|
|
2329
|
+
*/
|
|
2330
|
+
export async function computeAcceptanceFingerprint(inputs) {
|
|
2331
|
+
const sorted = [...inputs].sort((a, b) => utf8ByteCompare(a.id, b.id));
|
|
2332
|
+
const obj = {
|
|
2333
|
+
inputs: sorted,
|
|
2334
|
+
};
|
|
2335
|
+
return sha256Hex(canonicalJSONValue(obj, "legacy"));
|
|
2336
|
+
}
|
|
2337
|
+
// ---------------------------------------------------------------------------
|
|
2338
|
+
// D1 — Freshness predicate
|
|
2339
|
+
// ---------------------------------------------------------------------------
|
|
2340
|
+
/** Deep- equality for two JSON values. */
|
|
2341
|
+
function deepEqual(a, b) {
|
|
2342
|
+
if (a === b)
|
|
2343
|
+
return true;
|
|
2344
|
+
if (typeof a !== typeof b)
|
|
2345
|
+
return false;
|
|
2346
|
+
if (a === null || b === null)
|
|
2347
|
+
return a === b;
|
|
2348
|
+
if (typeof a !== "object")
|
|
2349
|
+
return false;
|
|
2350
|
+
if (Array.isArray(a) !== Array.isArray(b))
|
|
2351
|
+
return false;
|
|
2352
|
+
if (Array.isArray(a)) {
|
|
2353
|
+
const bArr = b;
|
|
2354
|
+
if (a.length !== bArr.length)
|
|
2355
|
+
return false;
|
|
2356
|
+
for (let i = 0; i < a.length; i++) {
|
|
2357
|
+
if (!deepEqual(a[i], bArr[i]))
|
|
2358
|
+
return false;
|
|
2359
|
+
}
|
|
2360
|
+
return true;
|
|
2361
|
+
}
|
|
2362
|
+
const aObj = a;
|
|
2363
|
+
const bObj = b;
|
|
2364
|
+
const ka = Object.keys(aObj);
|
|
2365
|
+
const kb = Object.keys(bObj);
|
|
2366
|
+
if (ka.length !== kb.length)
|
|
2367
|
+
return false;
|
|
2368
|
+
ka.sort();
|
|
2369
|
+
kb.sort();
|
|
2370
|
+
for (let i = 0; i < ka.length; i++) {
|
|
2371
|
+
if (ka[i] !== kb[i])
|
|
2372
|
+
return false;
|
|
2373
|
+
if (!deepEqual(aObj[ka[i]], bObj[kb[i]]))
|
|
2374
|
+
return false;
|
|
2375
|
+
}
|
|
2376
|
+
return true;
|
|
2377
|
+
}
|
|
2378
|
+
/**
|
|
2379
|
+
* D1 — Compare a receipt against the current candidate snapshot and
|
|
2380
|
+
* acceptance fingerprint. Returns exactly one stable reason code per stale
|
|
2381
|
+
* dimension, or `{fresh: true}` when everything matches.
|
|
2382
|
+
*
|
|
2383
|
+
* Comparison order (per spec): baseCommit → candidateCommit → changedPaths
|
|
2384
|
+
* (canonical equality) → acceptanceFingerprint → policyVersion.
|
|
2385
|
+
* Everything equal AND snapshot digest === receipt.candidateSnapshotDigest → fresh.
|
|
2386
|
+
*/
|
|
2387
|
+
export async function compareReceiptToCurrentSnapshot(receipt, snapshot, acceptanceInputs, policyVersion) {
|
|
2388
|
+
// 1. policyVersion — O(1) short-circuit (per comparison order: baseCommit →
|
|
2389
|
+
// candidateCommit → changedPaths → acceptanceFingerprint → policyVersion;
|
|
2390
|
+
// policyVersion is checked last in order but is the cheapest so we
|
|
2391
|
+
// short-circuit first; the remaining base/candidate/manifest dimensions
|
|
2392
|
+
// are conflated into stale-base-tree because the receipt only stores the
|
|
2393
|
+
// single candidateSnapshotDigest and cannot carry individual field values).
|
|
2394
|
+
if (policyVersion !== receipt.policyVersion) {
|
|
2395
|
+
return { fresh: false, reasonCode: "stale-review-policy" };
|
|
2396
|
+
}
|
|
2397
|
+
// 2. acceptance fingerprint — compare computed from current inputs against
|
|
2398
|
+
// the snapshot's stored fingerprint.
|
|
2399
|
+
const currentFP = await computeAcceptanceFingerprint(acceptanceInputs);
|
|
2400
|
+
if (currentFP !== snapshot.acceptanceFingerprint) {
|
|
2401
|
+
return { fresh: false, reasonCode: "stale-acceptance-fingerprint" };
|
|
2402
|
+
}
|
|
2403
|
+
// 3. digest — baseCommit / candidateCommit / changedPaths dimension.
|
|
2404
|
+
// The receipt carries only the single candidateSnapshotDigest so we
|
|
2405
|
+
// cannot distinguish which sub-field changed; return the first dimension
|
|
2406
|
+
// in the canonical comparison order.
|
|
2407
|
+
const currentDigest = await digestCandidateSnapshot(snapshot);
|
|
2408
|
+
if (currentDigest !== receipt.candidateSnapshotDigest) {
|
|
2409
|
+
return { fresh: false, reasonCode: "stale-base-tree" };
|
|
2410
|
+
}
|
|
2411
|
+
return { fresh: true };
|
|
2412
|
+
}
|
|
2413
|
+
/**
|
|
2414
|
+
* Published frozen canonical vectors. Each vector is a minimal valid value
|
|
2415
|
+
* whose canonical digest is deterministic and reproducible.
|
|
2416
|
+
*
|
|
2417
|
+
* These vectors lock the canonicalization rules (D4) in place.
|
|
2418
|
+
* Changing any vector's expected digest would be a reviewed contract change.
|
|
2419
|
+
*/
|
|
2420
|
+
export const CANONICAL_VECTORS = Object.freeze([
|
|
2421
|
+
{
|
|
2422
|
+
contract: "agentic-workflow/candidate-snapshot@1",
|
|
2423
|
+
digest: "d85671a09c73836fea421013c0d2537dfc233988083d981f7daca869af55ec7a",
|
|
2424
|
+
description: "minimal valid snapshot (empty diff, sha1)",
|
|
2425
|
+
},
|
|
2426
|
+
{
|
|
2427
|
+
contract: "agentic-workflow/review-receipt@1",
|
|
2428
|
+
digest: "8ae86246d83da2611380098910920b8850779a77613897e5d8efa4dd197d16e6",
|
|
2429
|
+
description: "minimal valid receipt (single finding)",
|
|
2430
|
+
},
|
|
2431
|
+
]);
|
|
2432
|
+
// ---------------------------------------------------------------------------
|
|
2433
|
+
// VerificationPlan v1 — staged verification contracts
|
|
2434
|
+
// ---------------------------------------------------------------------------
|
|
2435
|
+
/** Contract identifier for VerificationPlan v1 (re-exported from the canonical definition). */
|
|
2436
|
+
export { VERIFICATION_PLAN_CONTRACT_ID };
|
|
2437
|
+
/** Verification stages: fast and full (re-exported from the canonical definition). */
|
|
2438
|
+
export { VERIFICATION_STAGES };
|
|
2439
|
+
/** Cost classes declared by the project, not measured by the package. */
|
|
2440
|
+
export { VERIFICATION_COST_CLASSES };
|
|
2441
|
+
/**
|
|
2442
|
+
* D14 bounded usability — the published ceilings of the v1 contracts
|
|
2443
|
+
* (re-exported from the canonical definition, which is where they are enforced).
|
|
2444
|
+
*/
|
|
2445
|
+
export { VERIFICATION_LIMITS };
|
|
2446
|
+
/**
|
|
2447
|
+
* D16 closed diagnostic result (re-exported from the canonical definition).
|
|
2448
|
+
*
|
|
2449
|
+
* A failure never carries a message or a submitted value — only the frozen code
|
|
2450
|
+
* and the RFC 6901 pointer to the offending location, capped at
|
|
2451
|
+
* `VERIFICATION_LIMITS.diagnostics` rows with `truncated` telling the consumer
|
|
2452
|
+
* the list is not the whole story.
|
|
2453
|
+
*/
|
|
2454
|
+
export { VERIFICATION_DIAGNOSTIC_CODES };
|
|
2455
|
+
/** UTF-8 byte length of a canonical form — the unit D14 payload budgets use. */
|
|
2456
|
+
function utf8Bytes(text) {
|
|
2457
|
+
return _utf8Encoder.encode(text).length;
|
|
2458
|
+
}
|
|
2459
|
+
/**
|
|
2460
|
+
* D14 canonical payload budget (F77), measured BEFORE any diagnostic is
|
|
2461
|
+
* allocated, so a wide document is refused by the budget alone instead of
|
|
2462
|
+
* spending the diagnostic ceiling on its individual disliked fields.
|
|
2463
|
+
*
|
|
2464
|
+
* The measurement uses the same canonical serializer the canonicalizers use
|
|
2465
|
+
* (`canonicalJSONValue`: sorted keys, compact separators), so it is byte-identical
|
|
2466
|
+
* to the canonical payload size for every document the structural pass would
|
|
2467
|
+
* accept: undeclared keys are the only thing a submitted object can carry that a
|
|
2468
|
+
* normalized DTO drops, and the structural pass rejects those (F71 `unknown-field`).
|
|
2469
|
+
* Returns the refusal rows, or `null` when the payload fits (or cannot be
|
|
2470
|
+
* serialized at all, which the structural pass then rejects on type grounds).
|
|
2471
|
+
*/
|
|
2472
|
+
function canonicalBudgetRefusal(value, limit) {
|
|
2473
|
+
let canonical;
|
|
2474
|
+
try {
|
|
2475
|
+
canonical = canonicalJSONValue(value);
|
|
2476
|
+
}
|
|
2477
|
+
catch {
|
|
2478
|
+
return null;
|
|
2479
|
+
}
|
|
2480
|
+
return utf8Bytes(canonical) > limit
|
|
2481
|
+
? [Object.freeze({ code: "limit-exceeded", path: "" })]
|
|
2482
|
+
: null;
|
|
2483
|
+
}
|
|
2484
|
+
/**
|
|
2485
|
+
* F97/F99 — one captured observation of a submitted document, bounded by the
|
|
2486
|
+
* canonical byte budget.
|
|
2487
|
+
*
|
|
2488
|
+
* Every authority below runs on the snapshot, never on the submission: the byte
|
|
2489
|
+
* budget, the structural walk, the cross-rules and the DTO would otherwise read the
|
|
2490
|
+
* same accessor again and could decide on a document other than the one it blesses.
|
|
2491
|
+
* The capture aborts on the budget before the payload is fully copied (F99), and an
|
|
2492
|
+
* accessor that throws answers with the redacted `invalid-type` row F92 fixed.
|
|
2493
|
+
*/
|
|
2494
|
+
function captureSubmittedVerificationInput(value, budgetBytes) {
|
|
2495
|
+
return captureVerificationInput(value, budgetBytes);
|
|
2496
|
+
}
|
|
2497
|
+
/** The single refusal row a bounded capture rejection earns (D16 shape). */
|
|
2498
|
+
function captureRejectionResult(rejected) {
|
|
2499
|
+
return {
|
|
2500
|
+
ok: false,
|
|
2501
|
+
diagnostics: [Object.freeze({ code: rejected.code, path: rejected.pointer })],
|
|
2502
|
+
truncated: false,
|
|
2503
|
+
};
|
|
2504
|
+
}
|
|
2505
|
+
/**
|
|
2506
|
+
* The sole plan-validation authority (D12).
|
|
2507
|
+
*
|
|
2508
|
+
* Every structural rule comes from the canonical verification-contract
|
|
2509
|
+
* definition: contract id, non-empty command list, unique non-empty ids,
|
|
2510
|
+
* closed vocabularies, executable/args shapes, working-directory policy
|
|
2511
|
+
* nullness and relative-path validation, positive-integer timeouts, and
|
|
2512
|
+
* undeclared or inherited fields at every level.
|
|
2513
|
+
*
|
|
2514
|
+
* The input domain is JSON documents — values `JSON.parse` produces or
|
|
2515
|
+
* equivalent literals. An input outside that domain (e.g. an object with a
|
|
2516
|
+
* throwing live getter) cannot smuggle its exception past this entry: the
|
|
2517
|
+
* walk failure is refused as a redacted `invalid-type` row, so callers
|
|
2518
|
+
* always observe the D16 diagnostic contract (F92).
|
|
2519
|
+
*
|
|
2520
|
+
* On success it returns a normalized own-property DTO — never the submitted
|
|
2521
|
+
* reference — so digests and downstream semantics see exactly the declared
|
|
2522
|
+
* contract fields. On failure it returns at most
|
|
2523
|
+
* `VERIFICATION_LIMITS.diagnostics` redacted code+path rows (D16).
|
|
2524
|
+
*/
|
|
2525
|
+
export function validateVerificationPlanV1(value) {
|
|
2526
|
+
const submitted = captureSubmittedVerificationInput(value, VERIFICATION_LIMITS.planBytes);
|
|
2527
|
+
if (!submitted.ok)
|
|
2528
|
+
return captureRejectionResult(submitted);
|
|
2529
|
+
const document = submitted.value;
|
|
2530
|
+
// Exact UTF-8 measure on the snapshot unless the capture's running size WAS the
|
|
2531
|
+
// byte size (pure ASCII, every leaf measurable): a multibyte document can cross
|
|
2532
|
+
// the budget only here (F99 keeps both paths exact).
|
|
2533
|
+
if (!submitted.measureExact) {
|
|
2534
|
+
const oversized = canonicalBudgetRefusal(document, VERIFICATION_LIMITS.planBytes);
|
|
2535
|
+
if (oversized)
|
|
2536
|
+
return { ok: false, diagnostics: oversized, truncated: false };
|
|
2537
|
+
}
|
|
2538
|
+
const sink = createVerificationDiagnosticSink();
|
|
2539
|
+
const plan = validateStructure(VERIFICATION_CONTRACT.plan, VERIFICATION_CONTRACT.plan.root, document, "", sink);
|
|
2540
|
+
if (sink.count() > 0)
|
|
2541
|
+
return { ok: false, ...sink.finish() };
|
|
2542
|
+
return { ok: true, plan: plan };
|
|
2543
|
+
}
|
|
2544
|
+
// ---------------------------------------------------------------------------
|
|
2545
|
+
// VerificationReceipt v1 — staged verification contracts
|
|
2546
|
+
// ---------------------------------------------------------------------------
|
|
2547
|
+
/** Contract identifier for VerificationReceipt v1 (re-exported from the canonical definition). */
|
|
2548
|
+
export { VERIFICATION_RECEIPT_CONTRACT_ID };
|
|
2549
|
+
/** Possible per-command result statuses (re-exported from the canonical definition). */
|
|
2550
|
+
export { VERIFICATION_COMMAND_STATUSES };
|
|
2551
|
+
/**
|
|
2552
|
+
* The non-pass family, derived once from the frozen vocabulary so the D4
|
|
2553
|
+
* fail-fast sequencing scan and the D8 verdict derivation can never drift
|
|
2554
|
+
* apart (order follows the vocabulary: failed, timed-out, infrastructure-error).
|
|
2555
|
+
*/
|
|
2556
|
+
const NON_PASSED_STATUSES = VERIFICATION_COMMAND_STATUSES.filter((s) => s !== "passed" && s !== "skipped");
|
|
2557
|
+
/** Verdict values derived from receipt content. */
|
|
2558
|
+
export { VERIFICATION_VERDICTS };
|
|
2559
|
+
/**
|
|
2560
|
+
* Package-internal structural shape check for VerificationReceipt v1, driven by
|
|
2561
|
+
* the canonical definition (`src/verification-contract.ts`).
|
|
2562
|
+
*
|
|
2563
|
+
* It is NOT a public entry point (D12): `validateVerificationReceiptAgainstPlan`
|
|
2564
|
+
* is the only receipt authority, so a structural PASS here is never an
|
|
2565
|
+
* alternate runtime validity claim.
|
|
2566
|
+
*/
|
|
2567
|
+
function validateVerificationReceiptShape(value) {
|
|
2568
|
+
const submitted = captureSubmittedVerificationInput(value, VERIFICATION_LIMITS.receiptBytes);
|
|
2569
|
+
if (!submitted.ok)
|
|
2570
|
+
return captureRejectionResult(submitted);
|
|
2571
|
+
const document = submitted.value;
|
|
2572
|
+
if (!submitted.measureExact) {
|
|
2573
|
+
const oversized = canonicalBudgetRefusal(document, VERIFICATION_LIMITS.receiptBytes);
|
|
2574
|
+
if (oversized)
|
|
2575
|
+
return { ok: false, diagnostics: oversized, truncated: false };
|
|
2576
|
+
}
|
|
2577
|
+
const sink = createVerificationDiagnosticSink();
|
|
2578
|
+
const receipt = validateStructure(VERIFICATION_CONTRACT.receipt, VERIFICATION_CONTRACT.receipt.root, document, "", sink);
|
|
2579
|
+
if (sink.count() > 0)
|
|
2580
|
+
return { ok: false, ...sink.finish() };
|
|
2581
|
+
return { ok: true, receipt: receipt };
|
|
2582
|
+
}
|
|
2583
|
+
// ---------------------------------------------------------------------------
|
|
2584
|
+
// Verification semantic core
|
|
2585
|
+
// ---------------------------------------------------------------------------
|
|
2586
|
+
/**
|
|
2587
|
+
* The sole receipt-validation authority (D12): one call performs the
|
|
2588
|
+
* VerificationReceipt v1 structural shape check, the VerificationPlan v1
|
|
2589
|
+
* structural check, and every plan-bound rule — commandId existence, declared
|
|
2590
|
+
* order, fast-stage subset, complete `stopOnFailure` sequencing and attribution
|
|
2591
|
+
* (D3/S4), planDigest match and verdict consistency (D2).
|
|
2592
|
+
*
|
|
2593
|
+
* It accepts unknown input and returns a normalized own-property receipt DTO;
|
|
2594
|
+
* no standalone structural receipt validator is exported, so a structural
|
|
2595
|
+
* match alone can never claim runtime validity (D13). Async because the
|
|
2596
|
+
* planDigest check composes the async digest. The input domain is JSON
|
|
2597
|
+
* documents — like the plan entry, an out-of-domain object (a throwing live
|
|
2598
|
+
* getter) is refused as a redacted `invalid-type` row rather than escaping an
|
|
2599
|
+
* attacker-chosen exception (F92).
|
|
2600
|
+
*/
|
|
2601
|
+
export async function validateVerificationReceiptAgainstPlan(receipt, plan) {
|
|
2602
|
+
const sink = createVerificationDiagnosticSink();
|
|
2603
|
+
// Validate the plan first: nothing about a receipt is meaningful against a
|
|
2604
|
+
// plan the authority itself rejects. Its diagnostics are already capped and
|
|
2605
|
+
// redacted, so they are propagated as-is rather than re-derived here.
|
|
2606
|
+
const pv = validateVerificationPlanV1(plan);
|
|
2607
|
+
if (!pv.ok)
|
|
2608
|
+
return pv;
|
|
2609
|
+
const rv = validateVerificationReceiptShape(receipt);
|
|
2610
|
+
if (!rv.ok)
|
|
2611
|
+
return rv;
|
|
2612
|
+
// Every semantic check below runs on the normalized DTOs, never on the
|
|
2613
|
+
// submitted references.
|
|
2614
|
+
const normalizedPlan = pv.plan;
|
|
2615
|
+
const normalizedReceipt = rv.receipt;
|
|
2616
|
+
// Build lookups
|
|
2617
|
+
const cmdIdx = new Map();
|
|
2618
|
+
const cmdMap = new Map();
|
|
2619
|
+
for (let i = 0; i < normalizedPlan.commands.length; i++) {
|
|
2620
|
+
cmdIdx.set(normalizedPlan.commands[i].id, i);
|
|
2621
|
+
cmdMap.set(normalizedPlan.commands[i].id, normalizedPlan.commands[i]);
|
|
2622
|
+
}
|
|
2623
|
+
/** `/results/<i>/<field>` — the only pointer shape the semantic block needs. */
|
|
2624
|
+
const atResult = (index, field) => `/results/${index}/${field}`;
|
|
2625
|
+
// 1. commandId existence + uniqueness
|
|
2626
|
+
const seen = new Set();
|
|
2627
|
+
for (let i = 0; i < normalizedReceipt.results.length; i++) {
|
|
2628
|
+
const r = normalizedReceipt.results[i];
|
|
2629
|
+
if (!cmdIdx.has(r.commandId)) {
|
|
2630
|
+
sink.push("unknown-command", atResult(i, "commandId"));
|
|
2631
|
+
}
|
|
2632
|
+
else if (seen.has(r.commandId)) {
|
|
2633
|
+
sink.push("duplicate-id", atResult(i, "commandId"));
|
|
2634
|
+
}
|
|
2635
|
+
else {
|
|
2636
|
+
seen.add(r.commandId);
|
|
2637
|
+
}
|
|
2638
|
+
}
|
|
2639
|
+
// 2. Declared order
|
|
2640
|
+
if (sink.count() === 0) {
|
|
2641
|
+
let prev = -1;
|
|
2642
|
+
for (let i = 0; i < normalizedReceipt.results.length; i++) {
|
|
2643
|
+
const idx = cmdIdx.get(normalizedReceipt.results[i].commandId);
|
|
2644
|
+
if (idx < prev) {
|
|
2645
|
+
sink.push("invalid-order", atResult(i, "commandId"));
|
|
2646
|
+
break;
|
|
2647
|
+
}
|
|
2648
|
+
prev = idx;
|
|
2649
|
+
}
|
|
2650
|
+
}
|
|
2651
|
+
// 3. Fast-stage subset: fast receipt only has fast results
|
|
2652
|
+
if (sink.count() === 0 && normalizedReceipt.stageRequested === "fast") {
|
|
2653
|
+
for (let i = 0; i < normalizedReceipt.results.length; i++) {
|
|
2654
|
+
const c = cmdMap.get(normalizedReceipt.results[i].commandId);
|
|
2655
|
+
if (c && c.stage === "full")
|
|
2656
|
+
sink.push("invalid-stage", atResult(i, "commandId"));
|
|
2657
|
+
}
|
|
2658
|
+
}
|
|
2659
|
+
// 4. D3/S4 — complete `stopOnFailure` SEQUENCING (F65). The trigger is the
|
|
2660
|
+
// earliest declared command whose own result is non-passed
|
|
2661
|
+
// (`failed | timed-out | infrastructure-error`) AND whose plan entry declares
|
|
2662
|
+
// `stopOnFailure: true`. Nothing runs after it, so every later row must be
|
|
2663
|
+
// `skipped`, and a skipped row that carries a reason must name THAT trigger:
|
|
2664
|
+
// an earlier command that was itself skipped by the stop never ran, so it
|
|
2665
|
+
// cannot be a reason. A `skipped` row with a null reason stays representable
|
|
2666
|
+
// (D3 -> verdict `incomplete`), and a later command with no row stays
|
|
2667
|
+
// representable (D7) — neither is a schema error.
|
|
2668
|
+
let trigger = null;
|
|
2669
|
+
if (sink.count() === 0) {
|
|
2670
|
+
for (let i = 0; i < normalizedReceipt.results.length; i++) {
|
|
2671
|
+
const r = normalizedReceipt.results[i];
|
|
2672
|
+
const c = cmdMap.get(r.commandId);
|
|
2673
|
+
if (!c)
|
|
2674
|
+
continue; // unknown ids were reported by check 1
|
|
2675
|
+
if (trigger === null) {
|
|
2676
|
+
if (NON_PASSED_STATUSES.includes(r.status) && c.stopOnFailure)
|
|
2677
|
+
trigger = r.commandId;
|
|
2678
|
+
continue;
|
|
2679
|
+
}
|
|
2680
|
+
if (r.status !== "skipped")
|
|
2681
|
+
sink.push("invalid-fail-fast", atResult(i, "status"));
|
|
2682
|
+
else if (r.skipReason !== null && r.skipReason !== trigger)
|
|
2683
|
+
sink.push("invalid-fail-fast", atResult(i, "skipReason"));
|
|
2684
|
+
}
|
|
2685
|
+
}
|
|
2686
|
+
// 5. D3 fail-fast attribution (per-row): a non-null reason must name an
|
|
2687
|
+
// earlier-declared, non-passed command that declares stopOnFailure.
|
|
2688
|
+
if (sink.count() === 0) {
|
|
2689
|
+
// F95 — the commandId → result index serves ONLY this check, so it is
|
|
2690
|
+
// built only when this check runs: an already-failing receipt never pays
|
|
2691
|
+
// for an O(n) map it cannot use (and the neighboring checks all gate the
|
|
2692
|
+
// same way).
|
|
2693
|
+
const resultByCmd = new Map(normalizedReceipt.results.map(r => [r.commandId, r]));
|
|
2694
|
+
for (let i = 0; i < normalizedReceipt.results.length; i++) {
|
|
2695
|
+
const r = normalizedReceipt.results[i];
|
|
2696
|
+
if (r.status !== "skipped" || r.skipReason === null)
|
|
2697
|
+
continue;
|
|
2698
|
+
const st = r.skipReason;
|
|
2699
|
+
if (!cmdIdx.has(st)) {
|
|
2700
|
+
sink.push("unknown-command", atResult(i, "skipReason"));
|
|
2701
|
+
continue;
|
|
2702
|
+
}
|
|
2703
|
+
const ri = cmdIdx.get(r.commandId);
|
|
2704
|
+
const ti = cmdIdx.get(st);
|
|
2705
|
+
if (ti >= ri) {
|
|
2706
|
+
sink.push("invalid-order", atResult(i, "skipReason"));
|
|
2707
|
+
continue;
|
|
2708
|
+
}
|
|
2709
|
+
const tr = resultByCmd.get(st);
|
|
2710
|
+
if (!tr || !NON_PASSED_STATUSES.includes(tr.status)) {
|
|
2711
|
+
sink.push("invalid-skip", atResult(i, "skipReason"));
|
|
2712
|
+
continue;
|
|
2713
|
+
}
|
|
2714
|
+
if (!cmdMap.get(st).stopOnFailure)
|
|
2715
|
+
sink.push("invalid-fail-fast", atResult(i, "skipReason"));
|
|
2716
|
+
}
|
|
2717
|
+
}
|
|
2718
|
+
// 6. planDigest match
|
|
2719
|
+
if (sink.count() === 0) {
|
|
2720
|
+
const d = await digestVerificationPlan(normalizedPlan);
|
|
2721
|
+
if (d !== normalizedReceipt.planDigest)
|
|
2722
|
+
sink.push("digest-mismatch", "/planDigest");
|
|
2723
|
+
}
|
|
2724
|
+
// 7. Verdict consistency
|
|
2725
|
+
if (sink.count() === 0) {
|
|
2726
|
+
// Inputs already validated above — use the unchecked derivation (no re-validation).
|
|
2727
|
+
const derived = deriveVerdictUnchecked(normalizedReceipt, normalizedPlan);
|
|
2728
|
+
if (derived !== normalizedReceipt.verdict)
|
|
2729
|
+
sink.push("verdict-mismatch", "/verdict");
|
|
2730
|
+
}
|
|
2731
|
+
return sink.count() > 0 ? { ok: false, ...sink.finish() } : { ok: true, receipt: normalizedReceipt };
|
|
2732
|
+
}
|
|
2733
|
+
/**
|
|
2734
|
+
* D2 — Verdict derivation: incomplete > fail > pass, assuming already-validated
|
|
2735
|
+
* inputs (no validation here — callers that pre-validate avoid a full re-scan).
|
|
2736
|
+
* A required row that is `skipped`-with-reason yields `fail`: D2's pass rule
|
|
2737
|
+
* requires every required result row to be `passed`, and a justified skip only
|
|
2738
|
+
* exists attributing to a failure (D3).
|
|
2739
|
+
*/
|
|
2740
|
+
function deriveVerdictUnchecked(receipt, plan) {
|
|
2741
|
+
const reqStage = receipt.stageRequested;
|
|
2742
|
+
// Stage required set: fast → fast commands; full → every declared command.
|
|
2743
|
+
// One set is built here and reused by both scans below — the membership test
|
|
2744
|
+
// is the only thing either pass needs from it.
|
|
2745
|
+
const requiredSet = new Set(reqStage === "full"
|
|
2746
|
+
? plan.commands.map((c) => c.id)
|
|
2747
|
+
: plan.commands.filter((c) => c.stage === "fast").map((c) => c.id));
|
|
2748
|
+
const received = new Set(receipt.results.map((r2) => r2.commandId));
|
|
2749
|
+
// Missing → incomplete
|
|
2750
|
+
for (const id of requiredSet) {
|
|
2751
|
+
if (!received.has(id))
|
|
2752
|
+
return "incomplete";
|
|
2753
|
+
}
|
|
2754
|
+
// Unjustified skip → incomplete
|
|
2755
|
+
for (const r2 of receipt.results) {
|
|
2756
|
+
if (r2.status === "skipped" && !r2.skipReason)
|
|
2757
|
+
return "incomplete";
|
|
2758
|
+
}
|
|
2759
|
+
// Failed/timed-out/infra, or a required row skipped-with-reason → fail
|
|
2760
|
+
for (const r2 of receipt.results) {
|
|
2761
|
+
if (NON_PASSED_STATUSES.includes(r2.status))
|
|
2762
|
+
return "fail";
|
|
2763
|
+
if (requiredSet.has(r2.commandId) && r2.status === "skipped")
|
|
2764
|
+
return "fail";
|
|
2765
|
+
}
|
|
2766
|
+
return "pass";
|
|
2767
|
+
}
|
|
2768
|
+
/**
|
|
2769
|
+
* D2 — Verdict derivation: incomplete > fail > pass. Validating wrapper around
|
|
2770
|
+
* {@link deriveVerdictUnchecked} — safe to call standalone on unvalidated inputs.
|
|
2771
|
+
*/
|
|
2772
|
+
export function deriveVerificationVerdict(receipt, plan) {
|
|
2773
|
+
const pv = validateVerificationPlanV1(plan);
|
|
2774
|
+
const rv = validateVerificationReceiptShape(receipt);
|
|
2775
|
+
if (!pv.ok || !rv.ok)
|
|
2776
|
+
return "incomplete";
|
|
2777
|
+
return deriveVerdictUnchecked(rv.receipt, pv.plan);
|
|
2778
|
+
}
|
|
2779
|
+
/**
|
|
2780
|
+
* D6 — Canonical serialization, shared by both contract sides.
|
|
2781
|
+
*
|
|
2782
|
+
* Inputs are projected through the canonical definition first, so the bytes —
|
|
2783
|
+
* and therefore every digest — describe the normalized own-property contract
|
|
2784
|
+
* fields, never an inherited prototype value or an undeclared extra.
|
|
2785
|
+
*
|
|
2786
|
+
* The SPEC precondition ("inputs must first pass their validators") is
|
|
2787
|
+
* enforced defensively here (F91): a declared-array cardinality beyond D14 is
|
|
2788
|
+
* refused BEFORE any serialization work runs, and the canonical form itself
|
|
2789
|
+
* must fit the contract's byte budget. A refusal is a named TypeError that
|
|
2790
|
+
* quotes only the violated limit — never the submitted content.
|
|
2791
|
+
*/
|
|
2792
|
+
function canonicalizeWithinContract(value, contract, collectionField, maxItems, budgetBytes, label) {
|
|
2793
|
+
// F97/F99 — one bounded observation, then every guard and the serialization itself
|
|
2794
|
+
// consume that snapshot. Without the capture the cardinality guard above and
|
|
2795
|
+
// `projectStructure` below would read the same submission twice, so a flipping
|
|
2796
|
+
// accessor could make the digest cover a document the guard never saw.
|
|
2797
|
+
const submitted = captureSubmittedVerificationInput(value, budgetBytes);
|
|
2798
|
+
if (!submitted.ok) {
|
|
2799
|
+
throw new TypeError(submitted.code === "limit-exceeded"
|
|
2800
|
+
? // The capture measured the canonical form past the budget — the same
|
|
2801
|
+
// refusal F91 names, reached before the serializer could finish it.
|
|
2802
|
+
`verification ${label} canonical form exceeds the D14 ${budgetBytes}-byte budget — validate before canonicalizing`
|
|
2803
|
+
: `verification ${label} input is not a readable JSON document — validate before canonicalizing`);
|
|
2804
|
+
}
|
|
2805
|
+
const document = submitted.value;
|
|
2806
|
+
if (document !== null && typeof document === "object") {
|
|
2807
|
+
const items = document[collectionField];
|
|
2808
|
+
if (Array.isArray(items) && items.length > maxItems) {
|
|
2809
|
+
throw new TypeError(`verification ${label} exceeds the D14 limit of at most ${maxItems} ${collectionField} — validate before canonicalizing`);
|
|
2810
|
+
}
|
|
2811
|
+
}
|
|
2812
|
+
const canonical = canonicalJSONValue(projectStructure(contract, contract.root, document));
|
|
2813
|
+
if (utf8Bytes(canonical) > budgetBytes) {
|
|
2814
|
+
throw new TypeError(`verification ${label} canonical form exceeds the D14 ${budgetBytes}-byte budget — validate before canonicalizing`);
|
|
2815
|
+
}
|
|
2816
|
+
return canonical;
|
|
2817
|
+
}
|
|
2818
|
+
/**
|
|
2819
|
+
* D6 — Canonical serialization of a validated `VerificationPlan v1`. The
|
|
2820
|
+
* input must first pass `validateVerificationPlanV1`; out-of-contract
|
|
2821
|
+
* cardinality or byte budgets throw a named TypeError (F91).
|
|
2822
|
+
*/
|
|
2823
|
+
export function canonicalizeVerificationPlan(plan) {
|
|
2824
|
+
return canonicalizeWithinContract(plan, VERIFICATION_CONTRACT.plan, "commands", VERIFICATION_LIMITS.commands, VERIFICATION_LIMITS.planBytes, "plan");
|
|
2825
|
+
}
|
|
2826
|
+
/**
|
|
2827
|
+
* D6 — Canonical serialization of a validated `VerificationReceipt v1`. The
|
|
2828
|
+
* input must first pass `validateVerificationReceiptAgainstPlan`;
|
|
2829
|
+
* out-of-contract cardinality or byte budgets throw a named TypeError (F91).
|
|
2830
|
+
*/
|
|
2831
|
+
export function canonicalizeVerificationReceipt(receipt) {
|
|
2832
|
+
return canonicalizeWithinContract(receipt, VERIFICATION_CONTRACT.receipt, "results", VERIFICATION_LIMITS.results, VERIFICATION_LIMITS.receiptBytes, "receipt");
|
|
2833
|
+
}
|
|
2834
|
+
/** D6 — Digest of a validated plan (inherits the F91 canonical-input guards). */
|
|
2835
|
+
export async function digestVerificationPlan(plan) {
|
|
2836
|
+
return sha256Hex(canonicalizeVerificationPlan(plan));
|
|
2837
|
+
}
|
|
2838
|
+
/** D6 — Digest of a validated receipt (inherits the F91 canonical-input guards). */
|
|
2839
|
+
export async function digestVerificationReceipt(receipt) {
|
|
2840
|
+
return sha256Hex(canonicalizeVerificationReceipt(receipt));
|
|
2841
|
+
}
|
|
2842
|
+
/**
|
|
2843
|
+
* D1 — Freshness predicate.
|
|
2844
|
+
*
|
|
2845
|
+
* Pure, async, deterministic and it throws nothing. Fixed check order (SPEC §
|
|
2846
|
+
* Stage, verdict, and freshness semantics): plan digest → candidate-snapshot
|
|
2847
|
+
* digest → acceptance fingerprint → a missing fast-stage result → an
|
|
2848
|
+
* unjustified skip → a missing full-stage result → `{ fresh: true }`.
|
|
2849
|
+
*
|
|
2850
|
+
* The two coverage codes are partitioned by the STAGE OF THE MISSING COMMAND,
|
|
2851
|
+
* which is what keeps them disjoint while `incomplete-missing-results` still
|
|
2852
|
+
* answers a full receipt that skipped a fast command:
|
|
2853
|
+
* `incomplete-stage-coverage` only fires on a `full` receipt whose declared
|
|
2854
|
+
* full-stage commands are not covered.
|
|
2855
|
+
*/
|
|
2856
|
+
/** Verification-specific freshness reason codes (D1). */
|
|
2857
|
+
export const VERIFICATION_FRESHNESS_CODES = Object.freeze([
|
|
2858
|
+
"stale-plan", "stale-candidate-snapshot", "stale-acceptance-fingerprint",
|
|
2859
|
+
"incomplete-missing-results", "incomplete-unjustified-skip", "incomplete-stage-coverage",
|
|
2860
|
+
]);
|
|
2861
|
+
export async function compareVerificationReceiptToCurrent(receipt, plan, candidateSnapshotDigest, acceptanceFingerprint) {
|
|
2862
|
+
// Validate plan/receipt FIRST so invalid (non-JSON-serializable) inputs return a
|
|
2863
|
+
// stable freshness result rather than throwing from canonicalJSONValue or
|
|
2864
|
+
// JSON.stringify — the SPEC promises this predicate is pure and throws nothing.
|
|
2865
|
+
// Validation rejects BigInt fields, circular references, and unknown fields
|
|
2866
|
+
// before any hashing runs. A payload that fails its own contract cannot
|
|
2867
|
+
// establish the plan binding, and the plan binding is the FIRST precedence
|
|
2868
|
+
// point, so the honest stable code is `stale-plan` — never an incomplete code,
|
|
2869
|
+
// which would claim a binding this predicate never verified (F63).
|
|
2870
|
+
const pv = validateVerificationPlanV1(plan);
|
|
2871
|
+
const rv = validateVerificationReceiptShape(receipt);
|
|
2872
|
+
if (!pv.ok || !rv.ok)
|
|
2873
|
+
return { fresh: false, reasonCode: "stale-plan" };
|
|
2874
|
+
const p = pv.plan;
|
|
2875
|
+
const r = rv.receipt;
|
|
2876
|
+
// Then check stale conditions (plain string comparisons — safe after validation).
|
|
2877
|
+
const pd = await digestVerificationPlan(p);
|
|
2878
|
+
if (pd !== r.planDigest)
|
|
2879
|
+
return { fresh: false, reasonCode: "stale-plan" };
|
|
2880
|
+
if (candidateSnapshotDigest !== r.candidateSnapshotDigest)
|
|
2881
|
+
return { fresh: false, reasonCode: "stale-candidate-snapshot" };
|
|
2882
|
+
if (acceptanceFingerprint !== r.acceptanceFingerprint)
|
|
2883
|
+
return { fresh: false, reasonCode: "stale-acceptance-fingerprint" };
|
|
2884
|
+
// All three bindings are current: from here on the predicate answers only
|
|
2885
|
+
// incompleteness, so the stale and incomplete blocks are mutually disjoint.
|
|
2886
|
+
const present = new Set(r.results.map((rr) => rr.commandId));
|
|
2887
|
+
const fastIds = [];
|
|
2888
|
+
const fullIds = [];
|
|
2889
|
+
for (const c of p.commands)
|
|
2890
|
+
(c.stage === "fast" ? fastIds : fullIds).push(c.id);
|
|
2891
|
+
// 1. a missing fast-stage result — every fast command is owed a row by a fast
|
|
2892
|
+
// AND a full receipt (D2 required set), in either case `missing-results`.
|
|
2893
|
+
for (const id of fastIds) {
|
|
2894
|
+
if (!present.has(id))
|
|
2895
|
+
return { fresh: false, reasonCode: "incomplete-missing-results" };
|
|
2896
|
+
}
|
|
2897
|
+
// 2. a skipped row without a reason.
|
|
2898
|
+
for (const rr of r.results) {
|
|
2899
|
+
if (rr.status === "skipped" && !rr.skipReason)
|
|
2900
|
+
return { fresh: false, reasonCode: "incomplete-unjustified-skip" };
|
|
2901
|
+
}
|
|
2902
|
+
// 3. a requested-full receipt that does not cover every declared full-stage
|
|
2903
|
+
// command. A fast receipt legitimately carries no full-stage rows (D7), so
|
|
2904
|
+
// the coverage gap is scoped to `stageRequested: "full"`.
|
|
2905
|
+
if (r.stageRequested === "full") {
|
|
2906
|
+
for (const id of fullIds) {
|
|
2907
|
+
if (!present.has(id))
|
|
2908
|
+
return { fresh: false, reasonCode: "incomplete-stage-coverage" };
|
|
2909
|
+
}
|
|
2910
|
+
}
|
|
2911
|
+
return { fresh: true };
|
|
2912
|
+
}
|
|
2913
|
+
// ---------------------------------------------------------------------------
|
|
2914
|
+
// Published canonical vectors (verification — D6)
|
|
2915
|
+
// ---------------------------------------------------------------------------
|
|
2916
|
+
/**
|
|
2917
|
+
* Published frozen canonical vectors for the verification contracts.
|
|
2918
|
+
*
|
|
2919
|
+
* Each vector is a minimal valid value whose canonical digest is deterministic
|
|
2920
|
+
* and reproducible. These vectors lock the canonicalization rules (D6) in place.
|
|
2921
|
+
* Changing any vector's expected digest would be a reviewed contract change.
|
|
2922
|
+
*/
|
|
2923
|
+
export const VERIFICATION_CANONICAL_VECTORS = Object.freeze([
|
|
2924
|
+
Object.freeze({
|
|
2925
|
+
contract: VERIFICATION_PLAN_CONTRACT_ID,
|
|
2926
|
+
digest: "43ba52cb34490733f0f37dd6407f7c5ab088f20d928837213a75a25b7bc3eb80",
|
|
2927
|
+
description: "minimal valid VerificationPlan v1 (single fast command)",
|
|
2928
|
+
}),
|
|
2929
|
+
Object.freeze({
|
|
2930
|
+
contract: VERIFICATION_RECEIPT_CONTRACT_ID,
|
|
2931
|
+
digest: "c3d244efadf9d6ae8aa8626f8e252246ed63205eef3f4604b7ba5be2f8bc210d",
|
|
2932
|
+
description: "minimal valid VerificationReceipt v1 (single passed result)",
|
|
2933
|
+
}),
|
|
2934
|
+
]);
|