@gtrabanco/agentic-workflow-schema 3.2.0 → 3.3.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 CHANGED
@@ -28,6 +28,51 @@ de cada skill van dentro. Los esquemas se exportan en
28
28
  `./envelope.schema.json`, `./skill-outcome.schema.json` y
29
29
  `./workflow-snapshot.schema.json`.
30
30
 
31
+ ## Recibos de revisión con vínculo de contenido (v1)
32
+
33
+ Dos nuevos contratos versionados prueban exactamente qué diff evaluó una revisión:
34
+
35
+ - **CandidateSnapshot v1** — `baseCommit`, `candidateCommit`, `baseTree`,
36
+ `candidateTree`, manifiesto ordenado `changedPaths` y
37
+ `acceptanceFingerprint`. Los validadores estrictos rechazan claves no
38
+ declaradas, algoritmos de hash mezclados, inyección de rutas y estados
39
+ no soportados.
40
+ - **ReviewReceipt v1** — `id` opaco, `candidateSnapshotDigest`, vocabulario
41
+ cerrado de `kind` (10 valores), `verdict`, `findings` estructurados y
42
+ `policyVersion`.
43
+
44
+ ### Hash y fingerprint
45
+
46
+ ```ts
47
+ import {
48
+ digestCandidateSnapshot,
49
+ digestReviewReceipt,
50
+ computeAcceptanceFingerprint,
51
+ canonicalizeCandidateSnapshot,
52
+ canonicalizeReviewReceipt,
53
+ } from "@gtrabanco/agentic-workflow-schema";
54
+
55
+ const digest = await digestCandidateSnapshot(snapshot);
56
+ const fingerprint = await computeAcceptanceFingerprint([{ id: "AC-001", blobSha256: "..." }]);
57
+ ```
58
+
59
+ ### Predicado de frescura
60
+
61
+ ```ts
62
+ import { compareReceiptToCurrentSnapshot } from "@gtrabanco/agentic-workflow-schema";
63
+
64
+ const result = await compareReceiptToCurrentSnapshot(
65
+ receipt, currentSnapshot, currentAcceptanceInputs, policyVersion
66
+ );
67
+ // { fresh: true } | { fresh: false, reasonCode: "stale-base-tree" | "stale-candidate-tree" | "stale-manifest" | "stale-acceptance-fingerprint" | "stale-review-policy" }
68
+ ```
69
+
70
+ > ⚠️ **La validez del esquema ≠ corrección de la revisión.** Un esquema válido
71
+ > prueba que la estructura se preservó, no que la revisión fue precisa. El
72
+ vínculo de contenido es obligatorio: nunca confíes un recibo que no está
73
+ vinculado de contenido al snapshot candidato actual y a la frontera de
74
+ aceptación.
75
+
31
76
  ## Parsear un turno conducido
32
77
 
33
78
  Usa los perfiles para seleccionar el resultado requerido, añade la instrucción
package/README.md CHANGED
@@ -27,6 +27,49 @@ on Envelope v2 (use `null` when empty); skill-specific extensions belong inside
27
27
  it. The schemas are exported at `./envelope.schema.json`,
28
28
  `./skill-outcome.schema.json`, and `./workflow-snapshot.schema.json`.
29
29
 
30
+ ## Content-bound review receipts (v1)
31
+
32
+ Two new versioned contracts prove exactly which diff a review evaluated:
33
+
34
+ - **CandidateSnapshot v1** — `baseCommit`, `candidateCommit`, `baseTree`,
35
+ `candidateTree`, ordered `changedPaths` manifest, and `acceptanceFingerprint`.
36
+ Strict validators reject undeclared fields, mixed hash algorithms, path
37
+ injection, and unsupported statuses.
38
+ - **ReviewReceipt v1** — opaque `id`, `candidateSnapshotDigest`, closed `kind`
39
+ vocabulary (10 values), `verdict`, structured `findings`, and
40
+ `policyVersion`.
41
+
42
+ ### Hashing and fingerprinting
43
+
44
+ ```ts
45
+ import {
46
+ digestCandidateSnapshot,
47
+ digestReviewReceipt,
48
+ computeAcceptanceFingerprint,
49
+ canonicalizeCandidateSnapshot,
50
+ canonicalizeReviewReceipt,
51
+ } from "@gtrabanco/agentic-workflow-schema";
52
+
53
+ const digest = await digestCandidateSnapshot(snapshot);
54
+ const fingerprint = await computeAcceptanceFingerprint([{ id: "AC-001", blobSha256: "..." }]);
55
+ ```
56
+
57
+ ### Freshness predicate
58
+
59
+ ```ts
60
+ import { compareReceiptToCurrentSnapshot } from "@gtrabanco/agentic-workflow-schema";
61
+
62
+ const result = await compareReceiptToCurrentSnapshot(
63
+ receipt, currentSnapshot, currentAcceptanceInputs, policyVersion
64
+ );
65
+ // { fresh: true } | { fresh: false, reasonCode: "stale-base-tree" | "stale-candidate-tree" | "stale-manifest" | "stale-acceptance-fingerprint" | "stale-review-policy" }
66
+ ```
67
+
68
+ > ⚠️ **Schema validity ≠ review correctness.** A valid schema proves the
69
+ > structure was preserved, not that the review was accurate. Content binding
70
+ > is mandatory — never trust a receipt that is not content-bound to the current
71
+ > candidate snapshot and acceptance boundary.
72
+
30
73
  ## Parse a driven turn
31
74
 
32
75
  Use the profile metadata to select the required result, append the generated
@@ -0,0 +1,129 @@
1
+ {
2
+ "$schema": "http://json-schema.org/draft-07/schema#",
3
+ "$id": "https://github.com/gtrabanco/agentic-workflow/packages/agentic-workflow-schema/candidate-snapshot.schema.json",
4
+ "title": "agentic-workflow candidate snapshot v1",
5
+ "description": "A content-bound candidate snapshot proving exactly which diff a review evaluated. Source of truth: @gtrabanco/agentic-workflow-schema.",
6
+ "type": "object",
7
+ "additionalProperties": false,
8
+ "required": [
9
+ "contract",
10
+ "objectFormat",
11
+ "baseCommit",
12
+ "candidateCommit",
13
+ "baseTree",
14
+ "candidateTree",
15
+ "acceptanceFingerprint",
16
+ "changedPaths"
17
+ ],
18
+ "properties": {
19
+ "contract": {
20
+ "type": "string",
21
+ "const": "agentic-workflow/candidate-snapshot@1"
22
+ },
23
+ "objectFormat": {
24
+ "enum": ["sha1", "sha256"]
25
+ },
26
+ "baseCommit": {
27
+ "$ref": "#/$defs/gitObjectId"
28
+ },
29
+ "candidateCommit": {
30
+ "$ref": "#/$defs/gitObjectId"
31
+ },
32
+ "baseTree": {
33
+ "$ref": "#/$defs/gitObjectId"
34
+ },
35
+ "candidateTree": {
36
+ "$ref": "#/$defs/gitObjectId"
37
+ },
38
+ "acceptanceFingerprint": {
39
+ "type": "string",
40
+ "pattern": "^[a-f0-9]{64}$"
41
+ },
42
+ "changedPaths": {
43
+ "type": "array",
44
+ "items": {
45
+ "$ref": "#/$defs/manifestEntryV1"
46
+ }
47
+ }
48
+ },
49
+ "$defs": {
50
+ "gitObjectId": {
51
+ "type": "object",
52
+ "additionalProperties": false,
53
+ "required": ["algorithm", "hex"],
54
+ "properties": {
55
+ "algorithm": {
56
+ "enum": ["sha1", "sha256"]
57
+ },
58
+ "hex": {
59
+ "type": "string"
60
+ }
61
+ },
62
+ "anyOf": [
63
+ {
64
+ "if": { "properties": { "algorithm": { "const": "sha1" } }, "required": ["algorithm"] },
65
+ "then": { "properties": { "hex": { "type": "string", "pattern": "^[a-f0-9]{40}$" } } }
66
+ },
67
+ {
68
+ "if": { "properties": { "algorithm": { "const": "sha256" } }, "required": ["algorithm"] },
69
+ "then": { "properties": { "hex": { "type": "string", "pattern": "^[a-f0-9]{64}$" } } }
70
+ }
71
+ ]
72
+ },
73
+ "manifestEntryV1": {
74
+ "type": "object",
75
+ "additionalProperties": false,
76
+ "required": ["path", "status", "oldPath", "mode", "objectSha", "sizeBytes", "binary"],
77
+ "properties": {
78
+ "path": {
79
+ "type": "string",
80
+ "pattern": "^(?!\\0)(?!\\/)(?!.*(?:^|\\/)(?:\\.\\.|\\./))[^\\0]*$"
81
+ },
82
+ "status": {
83
+ "enum": ["added", "modified", "deleted", "renamed", "copied", "type-changed"]
84
+ },
85
+ "oldPath": {
86
+ "type": ["string", "null"]
87
+ },
88
+ "mode": {
89
+ "oneOf": [
90
+ { "enum": ["100644", "100755", "120000", "160000"] },
91
+ { "type": "null" }
92
+ ]
93
+ },
94
+ "objectSha": {
95
+ "oneOf": [
96
+ { "$ref": "#/$defs/gitObjectId" },
97
+ { "type": "null" }
98
+ ]
99
+ },
100
+ "sizeBytes": {
101
+ "oneOf": [
102
+ { "type": "integer", "minimum": 0 },
103
+ { "type": "null" }
104
+ ]
105
+ },
106
+ "binary": {
107
+ "oneOf": [
108
+ { "type": "boolean" },
109
+ { "type": "null" }
110
+ ]
111
+ }
112
+ },
113
+ "anyOf": [
114
+ {
115
+ "if": { "properties": { "status": { "const": "deleted" } }, "required": ["status"] },
116
+ "then": { "properties": { "oldPath": { "const": null } } }
117
+ },
118
+ {
119
+ "if": { "properties": { "status": { "enum": ["renamed", "copied"] } }, "required": ["status"] },
120
+ "then": { "properties": { "oldPath": { "not": { "const": null } } } }
121
+ },
122
+ {
123
+ "if": { "properties": { "status": { "enum": ["added", "modified", "type-changed"] } }, "required": ["status"] },
124
+ "then": { "properties": { "oldPath": { "const": null } } }
125
+ }
126
+ ]
127
+ }
128
+ }
129
+ }
package/dist/index.d.ts CHANGED
@@ -471,3 +471,160 @@ export declare function validateWorkflowSnapshotV1(value: unknown): WorkflowSnap
471
471
  * locations for every value it derives.
472
472
  */
473
473
  export declare function compileWorkflowSnapshot(input: WorkflowSnapshotInput): WorkflowSnapshotResult;
474
+ /** Contract identifier for CandidateSnapshot v1. */
475
+ export declare const CANDIDATE_SNAPSHOT_CONTRACT_ID = "agentic-workflow/candidate-snapshot@1";
476
+ /** Git object hash algorithm. */
477
+ export type GitObjectFormat = "sha1" | "sha256";
478
+ /** A fully-qualified Git object identifier — algorithm + hex digest. */
479
+ export interface GitObjectId {
480
+ readonly algorithm: GitObjectFormat;
481
+ readonly hex: string;
482
+ }
483
+ /** Allowed change statuses in a manifest entry. */
484
+ export type ChangeStatus = "added" | "modified" | "deleted" | "renamed" | "copied" | "type-changed";
485
+ /** Git file mode — serialized as string; null when not applicable. */
486
+ export type GitMode = "100644" | "100755" | "120000" | "160000";
487
+ /** A single entry in the changed-paths manifest. */
488
+ export interface ManifestEntryV1 {
489
+ readonly path: string;
490
+ readonly status: ChangeStatus;
491
+ readonly oldPath: string | null;
492
+ readonly mode: GitMode | null;
493
+ readonly objectSha: GitObjectId | null;
494
+ readonly sizeBytes: number | null;
495
+ readonly binary: boolean | null;
496
+ }
497
+ /** A content-bound candidate snapshot — proves exactly what a review evaluated. */
498
+ export interface CandidateSnapshotV1 {
499
+ readonly contract: typeof CANDIDATE_SNAPSHOT_CONTRACT_ID;
500
+ readonly objectFormat: GitObjectFormat;
501
+ readonly baseCommit: GitObjectId;
502
+ readonly candidateCommit: GitObjectId;
503
+ readonly baseTree: GitObjectId;
504
+ readonly candidateTree: GitObjectId;
505
+ readonly acceptanceFingerprint: string;
506
+ readonly changedPaths: readonly ManifestEntryV1[];
507
+ }
508
+ export type CandidateSnapshotValidationResult = {
509
+ ok: true;
510
+ snapshot: CandidateSnapshotV1;
511
+ } | {
512
+ ok: false;
513
+ errors: string[];
514
+ };
515
+ /**
516
+ * Structural validation of a CandidateSnapshot v1.
517
+ * Rejects undeclared fields, enforces GitObjectId format, path-byte ordering,
518
+ * null-applicability matrix, and the empty-diff rule.
519
+ */
520
+ export declare function validateCandidateSnapshotV1(value: unknown): CandidateSnapshotValidationResult;
521
+ /** Contract identifier for ReviewReceipt v1. */
522
+ export declare const REVIEW_RECEIPT_CONTRACT_ID = "agentic-workflow/review-receipt@1";
523
+ /** All review kinds supported by the workflow. */
524
+ export declare const REVIEW_KINDS: readonly ["implementation", "security", "verification", "debt", "design", "accessibility", "brand", "performance", "seo", "audit"];
525
+ /** Finding severity levels. */
526
+ export declare const FINDING_SEVERITIES: readonly ["info", "low", "medium", "high", "critical"];
527
+ /** A line-level piece of evidence attached to a finding. */
528
+ export interface FindingEvidenceV1 {
529
+ readonly path: string;
530
+ readonly line?: number;
531
+ }
532
+ /** A single finding within a review receipt. */
533
+ export interface FindingV1 {
534
+ readonly id: string;
535
+ readonly severity: (typeof FINDING_SEVERITIES)[number];
536
+ readonly summary: string;
537
+ readonly evidence?: FindingEvidenceV1;
538
+ readonly refs: readonly string[];
539
+ }
540
+ /** A content-bound review receipt — proves exactly what was reviewed. */
541
+ export interface ReviewReceiptV1 {
542
+ readonly contract: typeof REVIEW_RECEIPT_CONTRACT_ID;
543
+ readonly id: string;
544
+ readonly candidateSnapshotDigest: string;
545
+ readonly kind: (typeof REVIEW_KINDS)[number];
546
+ readonly verdict: "pass" | "fail";
547
+ readonly findings: readonly FindingV1[];
548
+ readonly reviewer: string;
549
+ readonly sessionId: string;
550
+ readonly startedAt: string;
551
+ readonly finishedAt: string;
552
+ readonly diagnostics: readonly string[];
553
+ readonly policyVersion: string;
554
+ }
555
+ export type ReviewReceiptValidationResult = {
556
+ ok: true;
557
+ receipt: ReviewReceiptV1;
558
+ } | {
559
+ ok: false;
560
+ errors: string[];
561
+ };
562
+ /**
563
+ * Structural validation of a ReviewReceipt v1.
564
+ * Rejects undeclared fields, enforces closed vocabularies, format rules,
565
+ * and constraints on timestamps and finding structure.
566
+ */
567
+ export declare function validateReviewReceiptV1(value: unknown): ReviewReceiptValidationResult;
568
+ /** Staleness reason codes — one per detectable dimension. */
569
+ export declare const STALE_REASON_CODES: readonly ["stale-base-tree", "stale-candidate-tree", "stale-manifest", "stale-acceptance-fingerprint", "stale-review-policy"];
570
+ export type StaleReasonCode = (typeof STALE_REASON_CODES)[number];
571
+ export type FreshResult = {
572
+ fresh: true;
573
+ };
574
+ export type StaleResult = {
575
+ fresh: false;
576
+ reasonCode: StaleReasonCode;
577
+ };
578
+ export type FreshnessResult = FreshResult | StaleResult;
579
+ /**
580
+ * D4 — Canonicalize a CandidateSnapshotV1.
581
+ * Produces deterministic JSON with declaration-order keys and sorted changedPaths.
582
+ */
583
+ export declare function canonicalizeCandidateSnapshot(snapshot: CandidateSnapshotV1): string;
584
+ /**
585
+ * D4 — Canonicalize a ReviewReceiptV1.
586
+ * Findings are sorted by ascending byte order of their stable ids.
587
+ */
588
+ export declare function canonicalizeReviewReceipt(receipt: ReviewReceiptV1): string;
589
+ /** D4 — Digest a CandidateSnapshotV1 via canonical serialization. */
590
+ export declare function digestCandidateSnapshot(snapshot: CandidateSnapshotV1): Promise<string>;
591
+ /** D4 — Digest a ReviewReceiptV1 via canonical serialization. */
592
+ export declare function digestReviewReceipt(receipt: ReviewReceiptV1): Promise<string>;
593
+ /**
594
+ * D2 — Compute the acceptance fingerprint from an ordered array of
595
+ * {id, blobSha256} entries. Returns lowercase hex SHA-256 over their
596
+ * canonical serialization (sorted by byte-order of id).
597
+ */
598
+ export declare function computeAcceptanceFingerprint(inputs: ReadonlyArray<{
599
+ id: string;
600
+ blobSha256: string;
601
+ }>): Promise<string>;
602
+ /**
603
+ * D1 — Compare a receipt against the current candidate snapshot and
604
+ * acceptance fingerprint. Returns exactly one stable reason code per stale
605
+ * dimension, or `{fresh: true}` when everything matches.
606
+ *
607
+ * Comparison order (per spec): baseCommit → candidateCommit → changedPaths
608
+ * (canonical equality) → acceptanceFingerprint → policyVersion.
609
+ * Everything equal AND snapshot digest === receipt.candidateSnapshotDigest → fresh.
610
+ */
611
+ export declare function compareReceiptToCurrentSnapshot(receipt: ReviewReceiptV1, snapshot: CandidateSnapshotV1, acceptanceInputs: ReadonlyArray<{
612
+ id: string;
613
+ blobSha256: string;
614
+ }>, policyVersion: string): Promise<FreshnessResult>;
615
+ export interface CanonicalVectorV1 {
616
+ /** Contract name. */
617
+ contract: string;
618
+ /** Expected SHA-256 hex digest. */
619
+ digest: string;
620
+ /** Description of what this vector tests. */
621
+ description: string;
622
+ }
623
+ /**
624
+ * Published frozen canonical vectors. Each vector is a minimal valid value
625
+ * whose canonical digest is deterministic and reproducible.
626
+ *
627
+ * These vectors lock the canonicalization rules (D4) in place.
628
+ * Changing any vector's expected digest would be a reviewed contract change.
629
+ */
630
+ export declare const CANONICAL_VECTORS: ReadonlyArray<CanonicalVectorV1>;
package/dist/index.js CHANGED
@@ -1817,3 +1817,577 @@ export function compileWorkflowSnapshot(input) {
1817
1817
  ? { ok: true, snapshot: validation.snapshot }
1818
1818
  : { ok: false, errors: validation.errors };
1819
1819
  }
1820
+ // ===========================================================================
1821
+ // Content-bound review receipts — CandidateSnapshot v1
1822
+ // ===========================================================================
1823
+ /** Contract identifier for CandidateSnapshot v1. */
1824
+ export const CANDIDATE_SNAPSHOT_CONTRACT_ID = "agentic-workflow/candidate-snapshot@1";
1825
+ // ---------------------------------------------------------------------------
1826
+ // Internal helpers
1827
+ // ---------------------------------------------------------------------------
1828
+ const SHA1_RE = /^[a-f0-9]{40}$/;
1829
+ const SHA256_RE = /^[a-f0-9]{64}$/;
1830
+ const FP_RE = /^[a-f0-9]{64}$/;
1831
+ const VALID_MODES = new Set(["100644", "100755", "120000", "160000"]);
1832
+ const VALID_STATUSES = new Set(["added", "modified", "deleted", "renamed", "copied", "type-changed"]);
1833
+ function isGitObjectId(v) {
1834
+ if (!isObj(v))
1835
+ return false;
1836
+ const keys = Object.keys(v);
1837
+ if (keys.length !== 2)
1838
+ return false;
1839
+ if (v.algorithm !== "sha1" && v.algorithm !== "sha256")
1840
+ return false;
1841
+ if (v.hex === undefined || typeof v.hex !== "string")
1842
+ return false;
1843
+ if (v.algorithm === "sha1" && !SHA1_RE.test(v.hex))
1844
+ return false;
1845
+ if (v.algorithm === "sha256" && !SHA256_RE.test(v.hex))
1846
+ return false;
1847
+ return true;
1848
+ }
1849
+ function hasUndeclaredKeys(actual, known) {
1850
+ return Object.keys(actual).filter((k) => !known.includes(k));
1851
+ }
1852
+ /**
1853
+ * Compare two UTF-8 strings in ascending unsigned-byte order.
1854
+ * Returns < 0 if a < b, > 0 if a > b, 0 if equal.
1855
+ */
1856
+ const _utf8Encoder = new TextEncoder();
1857
+ function utf8ByteCompare(a, b) {
1858
+ const ba = _utf8Encoder.encode(a);
1859
+ const bb = _utf8Encoder.encode(b);
1860
+ const len = Math.min(ba.length, bb.length);
1861
+ for (let i = 0; i < len; i++) {
1862
+ const diff = ba[i] - bb[i];
1863
+ if (diff !== 0)
1864
+ return diff;
1865
+ }
1866
+ return ba.length - bb.length;
1867
+ }
1868
+ /**
1869
+ * Structural validation of a CandidateSnapshot v1.
1870
+ * Rejects undeclared fields, enforces GitObjectId format, path-byte ordering,
1871
+ * null-applicability matrix, and the empty-diff rule.
1872
+ */
1873
+ export function validateCandidateSnapshotV1(value) {
1874
+ const errors = [];
1875
+ if (!isObj(value)) {
1876
+ return { ok: false, errors: ["candidate snapshot is not a JSON object"] };
1877
+ }
1878
+ // --- contract id ---
1879
+ if (value.contract !== CANDIDATE_SNAPSHOT_CONTRACT_ID) {
1880
+ errors.push(`contract must be "${CANDIDATE_SNAPSHOT_CONTRACT_ID}" (got: ${String(value.contract)})`);
1881
+ }
1882
+ // --- top-level undeclared keys ---
1883
+ const knownTopKeys = [
1884
+ "contract", "objectFormat", "baseCommit", "candidateCommit",
1885
+ "baseTree", "candidateTree", "acceptanceFingerprint", "changedPaths",
1886
+ ];
1887
+ const topExtra = hasUndeclaredKeys(value, knownTopKeys);
1888
+ for (const k of topExtra) {
1889
+ errors.push(`${k} is not a valid candidate-snapshot field`);
1890
+ }
1891
+ // --- objectFormat ---
1892
+ const objectFormat = value.objectFormat;
1893
+ if (objectFormat !== "sha1" && objectFormat !== "sha256") {
1894
+ errors.push(`objectFormat must be "sha1" | "sha256" (got: ${String(objectFormat)})`);
1895
+ }
1896
+ // --- GitObjectId fields (baseCommit, candidateCommit, baseTree, candidateTree) ---
1897
+ for (const key of ["baseCommit", "candidateCommit", "baseTree", "candidateTree"]) {
1898
+ if (!isGitObjectId(value[key])) {
1899
+ errors.push(`${key} must be a GitObjectId {algorithm:"${objectFormat}", hex:/^[a-f0-9]{${objectFormat === "sha1" ? 40 : 64}}$/}`);
1900
+ }
1901
+ else if (value[key].algorithm !== objectFormat) {
1902
+ errors.push(`${key}.algorithm must match objectFormat "${objectFormat}" (got: ${value[key].algorithm})`);
1903
+ }
1904
+ }
1905
+ // --- acceptanceFingerprint ---
1906
+ if (typeof value.acceptanceFingerprint !== "string" || !FP_RE.test(value.acceptanceFingerprint)) {
1907
+ errors.push("acceptanceFingerprint must be a lowercase SHA-256 hex string (64 chars)");
1908
+ }
1909
+ // --- changedPaths ---
1910
+ if (!Array.isArray(value.changedPaths)) {
1911
+ errors.push("changedPaths must be an array");
1912
+ }
1913
+ else {
1914
+ const entries = value.changedPaths;
1915
+ let seenPaths = new Set();
1916
+ let prevPath = "";
1917
+ for (let i = 0; i < entries.length; i++) {
1918
+ const entry = entries[i];
1919
+ const prefix = `changedPaths[${i}]`;
1920
+ if (!isObj(entry)) {
1921
+ errors.push(`${prefix} must be an object`);
1922
+ continue;
1923
+ }
1924
+ // Unknown keys
1925
+ const knownEntryKeys = ["path", "status", "oldPath", "mode", "objectSha", "sizeBytes", "binary"];
1926
+ const extra = hasUndeclaredKeys(entry, knownEntryKeys);
1927
+ for (const k of extra) {
1928
+ errors.push(`${prefix}.${k} is not a valid field`);
1929
+ }
1930
+ // path
1931
+ if (typeof entry.path !== "string") {
1932
+ errors.push(`${prefix}.path must be a string`);
1933
+ }
1934
+ else {
1935
+ if (entry.path.includes("\0")) {
1936
+ errors.push(`${prefix}.path must not contain NUL`);
1937
+ }
1938
+ if (entry.path.startsWith("/")) {
1939
+ errors.push(`${prefix}.path must not be absolute`);
1940
+ }
1941
+ const segments = entry.path.split("/");
1942
+ if (segments.some((s) => s === ".." || s.startsWith(".."))) {
1943
+ errors.push(`${prefix}.path must not contain a ".." segment`);
1944
+ }
1945
+ // Byte-order check
1946
+ if (utf8ByteCompare(entry.path, prevPath) < 0) {
1947
+ errors.push(`${prefix}.path is not in ascending byte order`);
1948
+ }
1949
+ prevPath = entry.path;
1950
+ // Duplicate check
1951
+ if (seenPaths.has(entry.path)) {
1952
+ errors.push(`${prefix}.path is a duplicate`);
1953
+ }
1954
+ seenPaths.add(entry.path);
1955
+ }
1956
+ // status
1957
+ if (typeof entry.status !== "string" || !VALID_STATUSES.has(entry.status)) {
1958
+ errors.push(`${prefix}.status must be one of added|modified|deleted|renamed|copied|type-changed (got: ${String(entry.status)})`);
1959
+ }
1960
+ // oldPath
1961
+ const status = entry.status;
1962
+ if ((status === "renamed" || status === "copied") && entry.oldPath === null) {
1963
+ errors.push(`${prefix}.renamed/copied entries require a non-null oldPath`);
1964
+ }
1965
+ else if ((status !== "renamed" && status !== "copied") && entry.oldPath !== null) {
1966
+ errors.push(`${prefix}.oldPath must be null when status is ${status}`);
1967
+ }
1968
+ // objectSha
1969
+ if (status === "deleted" && entry.objectSha !== null) {
1970
+ errors.push(`${prefix}.objectSha must be null for deleted entries`);
1971
+ }
1972
+ else if (status !== "deleted" && !isGitObjectId(entry.objectSha)) {
1973
+ // For non-deleted, objectSha should be a GitObjectId
1974
+ if (entry.objectSha !== null && !isGitObjectId(entry.objectSha)) {
1975
+ errors.push(`${prefix}.objectSha must be a GitObjectId or null`);
1976
+ }
1977
+ }
1978
+ // mode
1979
+ if (entry.mode !== null && !VALID_MODES.has(entry.mode)) {
1980
+ errors.push(`${prefix}.mode must be one of 100644|100755|120000|160000 or null (got: ${String(entry.mode)})`);
1981
+ }
1982
+ // sizeBytes
1983
+ if (entry.sizeBytes !== null) {
1984
+ if (typeof entry.sizeBytes !== "number" || entry.sizeBytes < 0 || !Number.isInteger(entry.sizeBytes)) {
1985
+ errors.push(`${prefix}.sizeBytes must be a non-negative integer or null`);
1986
+ }
1987
+ else if (entry.mode === "160000") {
1988
+ errors.push(`${prefix}.sizeBytes must be null for gitlinks (mode 160000)`);
1989
+ }
1990
+ }
1991
+ // binary
1992
+ if (entry.binary !== null && typeof entry.binary !== "boolean") {
1993
+ errors.push(`${prefix}.binary must be a boolean or null`);
1994
+ }
1995
+ else if (entry.mode === "160000" && entry.binary !== null) {
1996
+ errors.push(`${prefix}.binary must be null for gitlinks (mode 160000)`);
1997
+ }
1998
+ }
1999
+ }
2000
+ // --- Empty-diff rule ---
2001
+ if (Array.isArray(value.changedPaths) && value.changedPaths.length === 0) {
2002
+ // Check if baseTree equals candidateTree
2003
+ if (isGitObjectId(value.baseTree) && isGitObjectId(value.candidateTree)) {
2004
+ if (value.baseTree.hex !== value.candidateTree.hex) {
2005
+ errors.push("empty changedPaths requires baseTree and candidateTree to be identical (empty diff rule)");
2006
+ }
2007
+ }
2008
+ }
2009
+ if (errors.length > 0) {
2010
+ return { ok: false, errors };
2011
+ }
2012
+ return { ok: true, snapshot: value };
2013
+ }
2014
+ // ===========================================================================
2015
+ // Content-bound review receipts — ReviewReceipt v1
2016
+ // ===========================================================================
2017
+ /** Contract identifier for ReviewReceipt v1. */
2018
+ export const REVIEW_RECEIPT_CONTRACT_ID = "agentic-workflow/review-receipt@1";
2019
+ /** All review kinds supported by the workflow. */
2020
+ export const REVIEW_KINDS = [
2021
+ "implementation", "security", "verification", "debt",
2022
+ "design", "accessibility", "brand", "performance", "seo", "audit",
2023
+ ];
2024
+ /** Finding severity levels. */
2025
+ export const FINDING_SEVERITIES = [
2026
+ "info", "low", "medium", "high", "critical",
2027
+ ];
2028
+ const REVIEW_KINDS_SET = new Set(REVIEW_KINDS);
2029
+ const FINDING_SEVERITIES_SET = new Set(FINDING_SEVERITIES);
2030
+ // ---------------------------------------------------------------------------
2031
+ // Validator: validateReviewReceiptV1
2032
+ // ---------------------------------------------------------------------------
2033
+ const DIGEST_RE = /^[a-f0-9]{64}$/;
2034
+ const ISO_8601_RE = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?Z$/;
2035
+ /**
2036
+ * Structural validation of a ReviewReceipt v1.
2037
+ * Rejects undeclared fields, enforces closed vocabularies, format rules,
2038
+ * and constraints on timestamps and finding structure.
2039
+ */
2040
+ export function validateReviewReceiptV1(value) {
2041
+ const errors = [];
2042
+ if (!isObj(value)) {
2043
+ return { ok: false, errors: ["review receipt is not a JSON object"] };
2044
+ }
2045
+ // --- contract id ---
2046
+ if (value.contract !== REVIEW_RECEIPT_CONTRACT_ID) {
2047
+ errors.push(`contract must be "${REVIEW_RECEIPT_CONTRACT_ID}" (got: ${String(value.contract)})`);
2048
+ }
2049
+ // --- top-level undeclared keys ---
2050
+ const knownReceiptKeys = [
2051
+ "contract", "id", "candidateSnapshotDigest", "kind", "verdict",
2052
+ "findings", "reviewer", "sessionId", "startedAt", "finishedAt",
2053
+ "diagnostics", "policyVersion",
2054
+ ];
2055
+ const topExtra = hasUndeclaredKeys(value, knownReceiptKeys);
2056
+ for (const k of topExtra) {
2057
+ errors.push(`${k} is not a valid review-receipt field`);
2058
+ }
2059
+ // --- id ---
2060
+ if (typeof value.id !== "string" || value.id.length === 0) {
2061
+ errors.push("id must be a non-empty string");
2062
+ }
2063
+ // --- candidateSnapshotDigest ---
2064
+ if (typeof value.candidateSnapshotDigest !== "string" || !DIGEST_RE.test(value.candidateSnapshotDigest)) {
2065
+ errors.push("candidateSnapshotDigest must be a lowercase SHA-256 hex string (64 chars)");
2066
+ }
2067
+ // --- kind ---
2068
+ if (typeof value.kind !== "string" || !REVIEW_KINDS_SET.has(value.kind)) {
2069
+ errors.push(`kind must be one of ${REVIEW_KINDS.join("|")} (got: ${String(value.kind)})`);
2070
+ }
2071
+ // --- verdict ---
2072
+ if (value.verdict !== "pass" && value.verdict !== "fail") {
2073
+ errors.push(`verdict must be "pass" | "fail" (got: ${String(value.verdict)})`);
2074
+ }
2075
+ // --- findings ---
2076
+ if (!Array.isArray(value.findings)) {
2077
+ errors.push("findings must be an array");
2078
+ }
2079
+ else {
2080
+ const findings = value.findings;
2081
+ let seenFindingIds = new Set();
2082
+ for (let i = 0; i < findings.length; i++) {
2083
+ const f = findings[i];
2084
+ const prefix = `findings[${i}]`;
2085
+ if (!isObj(f)) {
2086
+ errors.push(`${prefix} must be an object`);
2087
+ continue;
2088
+ }
2089
+ // Unknown keys on finding
2090
+ const knownFindingKeys = ["id", "severity", "summary", "evidence", "refs"];
2091
+ const findingExtra = hasUndeclaredKeys(f, knownFindingKeys);
2092
+ for (const k of findingExtra) {
2093
+ errors.push(`${prefix}.${k} is not a valid field`);
2094
+ }
2095
+ // id
2096
+ if (typeof f.id !== "string" || f.id.length === 0) {
2097
+ errors.push(`${prefix}.id must be a non-empty string`);
2098
+ }
2099
+ else {
2100
+ if (seenFindingIds.has(f.id)) {
2101
+ errors.push(`${prefix}.id is a duplicate`);
2102
+ }
2103
+ seenFindingIds.add(f.id);
2104
+ }
2105
+ // severity
2106
+ if (typeof f.severity !== "string" || !FINDING_SEVERITIES_SET.has(f.severity)) {
2107
+ errors.push(`${prefix}.severity must be one of ${FINDING_SEVERITIES.join("|")} (got: ${String(f.severity)})`);
2108
+ }
2109
+ // summary
2110
+ if (typeof f.summary !== "string" || f.summary.length === 0) {
2111
+ errors.push(`${prefix}.summary must be a non-empty string`);
2112
+ }
2113
+ // evidence
2114
+ if (f.evidence !== undefined && f.evidence !== null) {
2115
+ if (isObj(f.evidence)) {
2116
+ const evidenceKeys = Object.keys(f.evidence);
2117
+ const knownEvidenceKeys = ["path", "line"];
2118
+ const evidenceExtra = hasUndeclaredKeys(f.evidence, knownEvidenceKeys);
2119
+ for (const k of evidenceExtra) {
2120
+ errors.push(`${prefix}.evidence.${k} is not a valid field`);
2121
+ }
2122
+ if (typeof f.evidence.path !== "string") {
2123
+ errors.push(`${prefix}.evidence.path must be a string`);
2124
+ }
2125
+ if (f.evidence.line !== undefined && f.evidence.line !== null) {
2126
+ if (typeof f.evidence.line !== "number" || !Number.isInteger(f.evidence.line) || f.evidence.line < 1) {
2127
+ errors.push(`${prefix}.evidence.line must be an integer >= 1`);
2128
+ }
2129
+ }
2130
+ }
2131
+ else {
2132
+ errors.push(`${prefix}.evidence must be an object or null`);
2133
+ }
2134
+ }
2135
+ // refs
2136
+ if (!Array.isArray(f.refs)) {
2137
+ errors.push(`${prefix}.refs must be an array`);
2138
+ }
2139
+ else {
2140
+ for (let j = 0; j < f.refs.length; j++) {
2141
+ if (typeof f.refs[j] !== "string") {
2142
+ errors.push(`${prefix}.refs[${j}] must be a string`);
2143
+ break;
2144
+ }
2145
+ }
2146
+ }
2147
+ }
2148
+ }
2149
+ // --- reviewer ---
2150
+ if (typeof value.reviewer !== "string" || value.reviewer.length === 0) {
2151
+ errors.push("reviewer must be a non-empty string");
2152
+ }
2153
+ // --- sessionId ---
2154
+ if (typeof value.sessionId !== "string" || value.sessionId.length === 0) {
2155
+ errors.push("sessionId must be a non-empty string");
2156
+ }
2157
+ // --- startedAt / finishedAt (ISO-8601 UTC) ---
2158
+ if (typeof value.startedAt !== "string" || !ISO_8601_RE.test(value.startedAt)) {
2159
+ errors.push("startedAt must be an ISO-8601 UTC timestamp");
2160
+ }
2161
+ if (typeof value.finishedAt !== "string" || !ISO_8601_RE.test(value.finishedAt)) {
2162
+ errors.push("finishedAt must be an ISO-8601 UTC timestamp");
2163
+ }
2164
+ // finishedAt >= startedAt — Date.parse is safe because the regex only
2165
+ // accepts Z-suffix (UTC) so no mixed-offset ambiguity remains.
2166
+ if (typeof value.startedAt === "string" && typeof value.finishedAt === "string" &&
2167
+ ISO_8601_RE.test(value.startedAt) && ISO_8601_RE.test(value.finishedAt)) {
2168
+ if (Date.parse(value.finishedAt) < Date.parse(value.startedAt)) {
2169
+ errors.push("finishedAt must be >= startedAt");
2170
+ }
2171
+ }
2172
+ // --- diagnostics ---
2173
+ if (!Array.isArray(value.diagnostics)) {
2174
+ errors.push("diagnostics must be an array");
2175
+ }
2176
+ else {
2177
+ for (let i = 0; i < value.diagnostics.length; i++) {
2178
+ if (typeof value.diagnostics[i] !== "string") {
2179
+ errors.push(`diagnostics[${i}] must be a string`);
2180
+ break;
2181
+ }
2182
+ }
2183
+ }
2184
+ // --- policyVersion ---
2185
+ if (typeof value.policyVersion !== "string" || value.policyVersion.length === 0) {
2186
+ errors.push("policyVersion must be a non-empty string");
2187
+ }
2188
+ if (errors.length > 0) {
2189
+ return { ok: false, errors };
2190
+ }
2191
+ return { ok: true, receipt: value };
2192
+ }
2193
+ // ===========================================================================
2194
+ // Canonical content-binding core (D2, D4, D1)
2195
+ // ===========================================================================
2196
+ /** Staleness reason codes — one per detectable dimension. */
2197
+ export const STALE_REASON_CODES = [
2198
+ "stale-base-tree",
2199
+ "stale-candidate-tree",
2200
+ "stale-manifest",
2201
+ "stale-acceptance-fingerprint",
2202
+ "stale-review-policy",
2203
+ ];
2204
+ // ---------------------------------------------------------------------------
2205
+ // D4 — Canonical serialization helpers
2206
+ // ---------------------------------------------------------------------------
2207
+ function canonicalJSONValue(v) {
2208
+ if (v === null)
2209
+ return "null";
2210
+ if (typeof v === "string")
2211
+ return JSON.stringify(v);
2212
+ if (typeof v === "number")
2213
+ return JSON.stringify(v);
2214
+ if (typeof v === "boolean")
2215
+ return JSON.stringify(v);
2216
+ if (Array.isArray(v)) {
2217
+ return "[" + v.map(canonicalJSONValue).join(",") + "]";
2218
+ }
2219
+ if (typeof v === "object") {
2220
+ const keys = Object.keys(v).sort();
2221
+ return "{" + keys.map(k => JSON.stringify(k) + ":" + canonicalJSONValue(v[k])).join(",") + "}";
2222
+ }
2223
+ return JSON.stringify(v);
2224
+ }
2225
+ /**
2226
+ * D4 — Canonicalize a CandidateSnapshotV1.
2227
+ * Produces deterministic JSON with declaration-order keys and sorted changedPaths.
2228
+ */
2229
+ export function canonicalizeCandidateSnapshot(snapshot) {
2230
+ const sortedPaths = [...snapshot.changedPaths].sort((a, b) => utf8ByteCompare(a.path, b.path));
2231
+ const obj = {
2232
+ contract: snapshot.contract,
2233
+ objectFormat: snapshot.objectFormat,
2234
+ baseCommit: snapshot.baseCommit,
2235
+ candidateCommit: snapshot.candidateCommit,
2236
+ baseTree: snapshot.baseTree,
2237
+ candidateTree: snapshot.candidateTree,
2238
+ acceptanceFingerprint: snapshot.acceptanceFingerprint,
2239
+ changedPaths: sortedPaths,
2240
+ };
2241
+ return canonicalJSONValue(obj);
2242
+ }
2243
+ /**
2244
+ * D4 — Canonicalize a ReviewReceiptV1.
2245
+ * Findings are sorted by ascending byte order of their stable ids.
2246
+ */
2247
+ export function canonicalizeReviewReceipt(receipt) {
2248
+ const sortedFindings = [...receipt.findings].sort((a, b) => utf8ByteCompare(a.id, b.id));
2249
+ const obj = {
2250
+ contract: receipt.contract,
2251
+ id: receipt.id,
2252
+ candidateSnapshotDigest: receipt.candidateSnapshotDigest,
2253
+ kind: receipt.kind,
2254
+ verdict: receipt.verdict,
2255
+ findings: sortedFindings,
2256
+ reviewer: receipt.reviewer,
2257
+ sessionId: receipt.sessionId,
2258
+ startedAt: receipt.startedAt,
2259
+ finishedAt: receipt.finishedAt,
2260
+ diagnostics: receipt.diagnostics,
2261
+ policyVersion: receipt.policyVersion,
2262
+ };
2263
+ return canonicalJSONValue(obj);
2264
+ }
2265
+ // ---------------------------------------------------------------------------
2266
+ // SHA-256 hashing
2267
+ // ---------------------------------------------------------------------------
2268
+ /** D4 — SHA-256 hex digest (async via Web Crypto). */
2269
+ async function sha256Hex(data) {
2270
+ const encoder = new TextEncoder();
2271
+ const buf = encoder.encode(data);
2272
+ const hashBuffer = await crypto.subtle.digest("SHA-256", buf);
2273
+ const hashArray = new Uint8Array(hashBuffer);
2274
+ return Array.from(hashArray).map(b => b.toString(16).padStart(2, "0")).join("");
2275
+ }
2276
+ /** D4 — Digest a CandidateSnapshotV1 via canonical serialization. */
2277
+ export async function digestCandidateSnapshot(snapshot) {
2278
+ return sha256Hex(canonicalizeCandidateSnapshot(snapshot));
2279
+ }
2280
+ /** D4 — Digest a ReviewReceiptV1 via canonical serialization. */
2281
+ export async function digestReviewReceipt(receipt) {
2282
+ return sha256Hex(canonicalizeReviewReceipt(receipt));
2283
+ }
2284
+ // ---------------------------------------------------------------------------
2285
+ // D2 — Acceptance fingerprint
2286
+ // ---------------------------------------------------------------------------
2287
+ /**
2288
+ * D2 — Compute the acceptance fingerprint from an ordered array of
2289
+ * {id, blobSha256} entries. Returns lowercase hex SHA-256 over their
2290
+ * canonical serialization (sorted by byte-order of id).
2291
+ */
2292
+ export async function computeAcceptanceFingerprint(inputs) {
2293
+ const sorted = [...inputs].sort((a, b) => utf8ByteCompare(a.id, b.id));
2294
+ const obj = {
2295
+ inputs: sorted,
2296
+ };
2297
+ return sha256Hex(canonicalJSONValue(obj));
2298
+ }
2299
+ // ---------------------------------------------------------------------------
2300
+ // D1 — Freshness predicate
2301
+ // ---------------------------------------------------------------------------
2302
+ /** Deep- equality for two JSON values. */
2303
+ function deepEqual(a, b) {
2304
+ if (a === b)
2305
+ return true;
2306
+ if (typeof a !== typeof b)
2307
+ return false;
2308
+ if (a === null || b === null)
2309
+ return a === b;
2310
+ if (typeof a !== "object")
2311
+ return false;
2312
+ if (Array.isArray(a) !== Array.isArray(b))
2313
+ return false;
2314
+ if (Array.isArray(a)) {
2315
+ const bArr = b;
2316
+ if (a.length !== bArr.length)
2317
+ return false;
2318
+ for (let i = 0; i < a.length; i++) {
2319
+ if (!deepEqual(a[i], bArr[i]))
2320
+ return false;
2321
+ }
2322
+ return true;
2323
+ }
2324
+ const aObj = a;
2325
+ const bObj = b;
2326
+ const ka = Object.keys(aObj);
2327
+ const kb = Object.keys(bObj);
2328
+ if (ka.length !== kb.length)
2329
+ return false;
2330
+ ka.sort();
2331
+ kb.sort();
2332
+ for (let i = 0; i < ka.length; i++) {
2333
+ if (ka[i] !== kb[i])
2334
+ return false;
2335
+ if (!deepEqual(aObj[ka[i]], bObj[kb[i]]))
2336
+ return false;
2337
+ }
2338
+ return true;
2339
+ }
2340
+ /**
2341
+ * D1 — Compare a receipt against the current candidate snapshot and
2342
+ * acceptance fingerprint. Returns exactly one stable reason code per stale
2343
+ * dimension, or `{fresh: true}` when everything matches.
2344
+ *
2345
+ * Comparison order (per spec): baseCommit → candidateCommit → changedPaths
2346
+ * (canonical equality) → acceptanceFingerprint → policyVersion.
2347
+ * Everything equal AND snapshot digest === receipt.candidateSnapshotDigest → fresh.
2348
+ */
2349
+ export async function compareReceiptToCurrentSnapshot(receipt, snapshot, acceptanceInputs, policyVersion) {
2350
+ // 1. policyVersion — O(1) short-circuit (per comparison order: baseCommit →
2351
+ // candidateCommit → changedPaths → acceptanceFingerprint → policyVersion;
2352
+ // policyVersion is checked last in order but is the cheapest so we
2353
+ // short-circuit first; the remaining base/candidate/manifest dimensions
2354
+ // are conflated into stale-base-tree because the receipt only stores the
2355
+ // single candidateSnapshotDigest and cannot carry individual field values).
2356
+ if (policyVersion !== receipt.policyVersion) {
2357
+ return { fresh: false, reasonCode: "stale-review-policy" };
2358
+ }
2359
+ // 2. acceptance fingerprint — compare computed from current inputs against
2360
+ // the snapshot's stored fingerprint.
2361
+ const currentFP = await computeAcceptanceFingerprint(acceptanceInputs);
2362
+ if (currentFP !== snapshot.acceptanceFingerprint) {
2363
+ return { fresh: false, reasonCode: "stale-acceptance-fingerprint" };
2364
+ }
2365
+ // 3. digest — baseCommit / candidateCommit / changedPaths dimension.
2366
+ // The receipt carries only the single candidateSnapshotDigest so we
2367
+ // cannot distinguish which sub-field changed; return the first dimension
2368
+ // in the canonical comparison order.
2369
+ const currentDigest = await digestCandidateSnapshot(snapshot);
2370
+ if (currentDigest !== receipt.candidateSnapshotDigest) {
2371
+ return { fresh: false, reasonCode: "stale-base-tree" };
2372
+ }
2373
+ return { fresh: true };
2374
+ }
2375
+ /**
2376
+ * Published frozen canonical vectors. Each vector is a minimal valid value
2377
+ * whose canonical digest is deterministic and reproducible.
2378
+ *
2379
+ * These vectors lock the canonicalization rules (D4) in place.
2380
+ * Changing any vector's expected digest would be a reviewed contract change.
2381
+ */
2382
+ export const CANONICAL_VECTORS = Object.freeze([
2383
+ {
2384
+ contract: "agentic-workflow/candidate-snapshot@1",
2385
+ digest: "d85671a09c73836fea421013c0d2537dfc233988083d981f7daca869af55ec7a",
2386
+ description: "minimal valid snapshot (empty diff, sha1)",
2387
+ },
2388
+ {
2389
+ contract: "agentic-workflow/review-receipt@1",
2390
+ digest: "8ae86246d83da2611380098910920b8850779a77613897e5d8efa4dd197d16e6",
2391
+ description: "minimal valid receipt (single finding)",
2392
+ },
2393
+ ]);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gtrabanco/agentic-workflow-schema",
3
- "version": "3.2.0",
3
+ "version": "3.3.0",
4
4
  "description": "Versioned machine contracts, JSON Schemas, parsers, and deterministic document snapshots for agentic-workflow orchestration.",
5
5
  "keywords": [
6
6
  "agentic-workflow",
@@ -28,13 +28,17 @@
28
28
  },
29
29
  "./envelope.schema.json": "./envelope.schema.json",
30
30
  "./skill-outcome.schema.json": "./skill-outcome.schema.json",
31
- "./workflow-snapshot.schema.json": "./workflow-snapshot.schema.json"
31
+ "./workflow-snapshot.schema.json": "./workflow-snapshot.schema.json",
32
+ "./candidate-snapshot.schema.json": "./candidate-snapshot.schema.json",
33
+ "./review-receipt.schema.json": "./review-receipt.schema.json"
32
34
  },
33
35
  "files": [
34
36
  "dist",
35
37
  "envelope.schema.json",
36
38
  "skill-outcome.schema.json",
37
39
  "workflow-snapshot.schema.json",
40
+ "candidate-snapshot.schema.json",
41
+ "review-receipt.schema.json",
38
42
  "README.md",
39
43
  "README.es.md",
40
44
  "LICENSE"
@@ -51,6 +55,7 @@
51
55
  "prepublishOnly": "npm test"
52
56
  },
53
57
  "devDependencies": {
58
+ "ajv": "^8.20.0",
54
59
  "typescript": "6"
55
60
  }
56
61
  }
@@ -0,0 +1,130 @@
1
+ {
2
+ "$schema": "http://json-schema.org/draft-07/schema#",
3
+ "$id": "https://github.com/gtrabanco/agentic-workflow/packages/agentic-workflow-schema/review-receipt.schema.json",
4
+ "title": "agentic-workflow review receipt v1",
5
+ "description": "A content-bound review receipt proving exactly which diff and acceptance boundary a review evaluated. Source of truth: @gtrabanco/agentic-workflow-schema.",
6
+ "type": "object",
7
+ "additionalProperties": false,
8
+ "required": [
9
+ "contract",
10
+ "id",
11
+ "candidateSnapshotDigest",
12
+ "kind",
13
+ "verdict",
14
+ "findings",
15
+ "reviewer",
16
+ "sessionId",
17
+ "startedAt",
18
+ "finishedAt",
19
+ "diagnostics",
20
+ "policyVersion"
21
+ ],
22
+ "properties": {
23
+ "contract": {
24
+ "type": "string",
25
+ "const": "agentic-workflow/review-receipt@1"
26
+ },
27
+ "id": {
28
+ "type": "string",
29
+ "minLength": 1,
30
+ "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$"
31
+ },
32
+ "candidateSnapshotDigest": {
33
+ "type": "string",
34
+ "pattern": "^[a-f0-9]{64}$"
35
+ },
36
+ "kind": {
37
+ "enum": [
38
+ "implementation",
39
+ "security",
40
+ "verification",
41
+ "debt",
42
+ "design",
43
+ "accessibility",
44
+ "brand",
45
+ "performance",
46
+ "seo",
47
+ "audit"
48
+ ]
49
+ },
50
+ "verdict": {
51
+ "enum": ["pass", "fail"]
52
+ },
53
+ "findings": {
54
+ "type": "array",
55
+ "items": {
56
+ "$ref": "#/$defs/findingV1"
57
+ }
58
+ },
59
+ "reviewer": {
60
+ "type": "string",
61
+ "minLength": 1
62
+ },
63
+ "sessionId": {
64
+ "type": "string",
65
+ "minLength": 1
66
+ },
67
+ "startedAt": {
68
+ "type": "string",
69
+ "pattern": "^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(?:\\.\\d+)?(?:Z|[+-]\\d{2}:\\d{2})$"
70
+ },
71
+ "finishedAt": {
72
+ "type": "string",
73
+ "pattern": "^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(?:\\.\\d+)?(?:Z|[+-]\\d{2}:\\d{2})$"
74
+ },
75
+ "diagnostics": {
76
+ "type": "array",
77
+ "items": {
78
+ "type": "string"
79
+ }
80
+ },
81
+ "policyVersion": {
82
+ "type": "string",
83
+ "minLength": 1
84
+ }
85
+ },
86
+ "$defs": {
87
+ "findingV1": {
88
+ "type": "object",
89
+ "additionalProperties": false,
90
+ "required": ["id", "severity", "summary", "refs"],
91
+ "properties": {
92
+ "id": {
93
+ "type": "string",
94
+ "minLength": 1,
95
+ "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$"
96
+ },
97
+ "severity": {
98
+ "enum": ["info", "low", "medium", "high", "critical"]
99
+ },
100
+ "summary": {
101
+ "type": "string",
102
+ "minLength": 1
103
+ },
104
+ "evidence": {
105
+ "$ref": "#/$defs/findingEvidenceV1"
106
+ },
107
+ "refs": {
108
+ "type": "array",
109
+ "items": {
110
+ "type": "string"
111
+ }
112
+ }
113
+ }
114
+ },
115
+ "findingEvidenceV1": {
116
+ "type": "object",
117
+ "additionalProperties": false,
118
+ "required": ["path"],
119
+ "properties": {
120
+ "path": {
121
+ "type": "string"
122
+ },
123
+ "line": {
124
+ "type": "integer",
125
+ "minimum": 1
126
+ }
127
+ }
128
+ }
129
+ }
130
+ }