@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 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
@@ -124,9 +169,13 @@ vez de sobrescribirlo.
124
169
 
125
170
  ## Validar o usar otro lenguaje
126
171
 
127
- Los validadores públicos son `validateEnvelopeV2Strict`,
128
- `validateSkillOutcomeV1` y `validateWorkflowSnapshotV1`. Importa un JSON Schema
129
- cuando un consumidor no TypeScript necesite el mismo límite:
172
+ Los validadores públicos de contratos son `validateEnvelopeV2Strict`,
173
+ `validateSkillOutcomeV1`, `validateWorkflowSnapshotV1`,
174
+ `validateCandidateSnapshotV1` y `validateReviewReceiptV1`; los contratos de
175
+ verificación por etapas añaden exactamente las dos entradas autoritativas nombradas
176
+ arriba, `validateVerificationPlanV1` y `validateVerificationReceiptAgainstPlan`.
177
+ Importa un JSON Schema cuando un consumidor no TypeScript necesite el mismo límite
178
+ estructural:
130
179
 
131
180
  ```ts
132
181
  import schema from "@gtrabanco/agentic-workflow-schema/skill-outcome.schema.json" with { type: "json" };
@@ -182,3 +231,251 @@ intento no reconocido, y cualquier transición no en la tabla cerrada.
182
231
 
183
232
  Consulta el [SPEC](../features/24-workflow-transition-decider/SPEC.md) para el
184
233
  diseño completo, tablas de transición y vocabulario de códigos de razón.
234
+
235
+ ## Contratos de Verificación por Etapas (feature 26)
236
+
237
+ Dos contratos wire versionados para verificación por etapas:
238
+
239
+ - `VerificationPlan v1` (`agentic-workflow/verification-plan@1`) — una lista
240
+ de comandos ordenada y no vacía donde cada comando lleva un `id` estable,
241
+ `stage: fast | full` (vocabulario cerrado `VERIFICATION_STAGES`), un
242
+ `executable` y `args` ordenados (nunca una cadena
243
+ de shell), una política de directorio de trabajo (`candidate-root` o
244
+ `relative-path` con ruta relativa validada), un `timeoutMs` positivo,
245
+ `stopOnFailure` y una clase de coste (`VERIFICATION_COST_CLASSES`). La ruta relativa validada es una cadena
246
+ **opaca**: resuélvela bajo la raíz candidata exactamente como se envió y nunca
247
+ la decodifique por porcentaje (percent-decode) antes de resolverla — la
248
+ decodificación puede convertir una ruta que el validador rechazó en una que
249
+ escapa de la raíz.
250
+
251
+ - `VerificationReceipt v1` (`agentic-workflow/verification-receipt@1`) — un
252
+ recibo vinculado al digest del plan, al digest del snapshot candidato y a la
253
+ huella de aceptación, con resultados por comando cuyo `status` (`passed |
254
+ failed | timed-out | skipped | infrastructure-error`), código de salida y
255
+ señal siguen la matriz D4, referencias de evidencia acotadas y un motivo de
256
+ omisión explícito. El veredicto global (`pass | fail | incomplete`) se deriva
257
+ del contenido del recibo.
258
+
259
+ **Autoridad de validación.** Sólo dos entradas públicas autoritativas deciden la
260
+ validez en tiempo de ejecución: `validateVerificationPlanV1(value)` para el plan y
261
+ `await validateVerificationReceiptAgainstPlan(receipt, plan)` para el recibo, que
262
+ aplica la comprobación estructural y todas las reglas vinculadas al plan en una
263
+ sola llamada. No se exporta ningún validador independiente de recibos: un recibo
264
+ solo tiene sentido frente al plan al que se vincula. Ambas aceptan entrada
265
+ desconocida y devuelven un DTO **normalizado** de propiedades propias, nunca el
266
+ objeto recibido; así ningún digest ni ninguna semántica posterior depende de
267
+ propiedades heredadas, duplicadas o no declaradas.
268
+
269
+ **Diagnósticos de fallo.** Un rechazo es `{ ok: false, diagnostics, truncated }`.
270
+ `diagnostics` contiene como máximo 50 filas congeladas `{ code, path }` en orden del
271
+ documento y `truncated` indica si ese tope descartó alguna. Una fila nunca es un
272
+ mensaje: no se devuelve ni prosa ni valores recibidos. `code` pertenece al vocabulario
273
+ cerrado `VERIFICATION_DIAGNOSTIC_CODES` y `path` es un puntero RFC 6901 construido
274
+ solo con nombres de propiedad declarados e índices de array — `/commands/3/id`,
275
+ `/results/1/commandId` o `""` para el documento completo. Una clave no declarada se
276
+ informa como `unknown-field` en su **contenedor**, porque el nombre de la clave es
277
+ dato enviado por el cliente. Recupérate de los diagnósticos usando solo cada `code`
278
+ y `path` estables, sin copiar los valores enviados a logs, errores ni telemetría.
279
+
280
+ | Código de diagnóstico | Qué responde | Recuperación del llamador |
281
+ | --- | --- | --- |
282
+ | `invalid-type` | un campo tiene un valor del tipo JSON equivocado | Proporciona el tipo JSON declarado en `path`. |
283
+ | `missing-field` | falta un campo declarado | Añade el campo requerido en `path`. |
284
+ | `unknown-field` | el objeto lleva una propiedad no declarada | Elimina claves no declaradas del contenedor en `path`. |
285
+ | `invalid-value` | un valor rompe su propia regla (vocabulario, patrón, NUL) | Sustitúyelo por un miembro permitido o un valor con formato válido y sin NUL. |
286
+ | `limit-exceeded` | se supera un tope de cardinalidad o de longitud | Reduce la colección o cadena indicada hasta `VERIFICATION_LIMITS`. |
287
+ | `duplicate-id` | el mismo id de comando aparece dos veces | Asigna ids de comando únicos y actualiza sus referencias de resultado. |
288
+ | `unknown-command` | un resultado o un motivo de omisión no nombra un comando declarado | Referencia un id declarado por el plan vinculado. |
289
+ | `invalid-order` | los resultados no siguen el orden declarado del plan | Reordena las filas de resultado según el orden del plan. |
290
+ | `invalid-stage` | el recibo lleva una fila fuera de la etapa solicitada | Elimina filas fuera de etapa o solicita la etapa que las incluye. |
291
+ | `invalid-exit-state` | código de salida y señal rompen la matriz D4 | Alinea `exitCode` y `signal` con la matriz del status de la fila. |
292
+ | `invalid-evidence` | una referencia de evidencia está mal formada (reglas D5) | Proporciona `ref` acotada, bytes no negativos y SHA-256 en minúsculas. |
293
+ | `invalid-skip` | el motivo de omisión no se justifica en un fallo previo | Usa `null` sin atribución o nombra un trigger non-pass anterior real. |
294
+ | `invalid-fail-fast` | la secuencia de `stopOnFailure` está rota | Marca como omitidas las filas posteriores y atribúyelas al trigger. |
295
+ | `digest-mismatch` | el `planDigest` del recibo no es el del plan vinculado | Recalcúlalo desde el plan vinculado validado y normalizado. |
296
+ | `verdict-mismatch` | el veredicto guardado difiere del derivado | Guarda el resultado de `deriveVerificationVerdict`. |
297
+ | `budget-exceeded` | los timeouts declarados de una etapa exceden su presupuesto agregado | Reduce timeouts hasta que la suma quede dentro de `VERIFICATION_LIMITS`. |
298
+
299
+ **Estado de JSON Schema.** `verification-plan.schema.json` y
300
+ `verification-receipt.schema.json` son **proyecciones estructurales generadas y no
301
+ autoritativas** de la definición canónica del paquete. Existen para editores y
302
+ comprobaciones de transporte; que coincidan con Draft-07 no es validez de contrato,
303
+ y las reglas semánticas (`unique-command-ids`, los dos presupuestos agregados de
304
+ etapa, los dos presupuestos de bytes canónicos) solo las aplican las dos entradas de
305
+ tiempo de ejecución anteriores — cada proyección las declara en su `$comment`. Las
306
+ proyecciones se generan en vez de editarse a mano. En un checkout del código fuente,
307
+ los mantenedores cambian la definición canónica; el único escritor es
308
+ `node scripts/generate-verification-schemas.mjs` y la comprobación de deriva exclusiva
309
+ del código fuente reconstruye antes de comparar bytes.
310
+
311
+ **Solo en un checkout del código fuente.** El tarball publicado omite
312
+ intencionadamente `scripts/`, `test/`, el código fuente y la configuración de
313
+ TypeScript del repositorio. Estos comandos del manifiesto son comprobaciones para
314
+ mantenedores en un checkout fuente, no comandos ejecutables por consumidores del
315
+ paquete instalado:
316
+
317
+ | Comando solo para checkout fuente | Propósito |
318
+ | --- | --- |
319
+ | `npm run check:verification-schemas` | reconstruir y comparar por bytes las proyecciones generadas |
320
+ | `npm run check:verification-package` | inspeccionar el contrato del tarball del paquete |
321
+ | `npm run bench:verification -- --commands 128` | ejecutar el benchmark AC10 en proceso caliente |
322
+ | `npm run test:verification-docs` | ejecutar la suite bilingüe de documentación |
323
+ | `npm run gate:verification` | componer todas las comprobaciones de release de verificación |
324
+
325
+ **Modelo de dos etapas:** solicitar `fast` ejecuta solo comandos fast; solicitar
326
+ `full` ejecuta todos los comandos fast y full. El predicado de frescura devuelve
327
+ uno de los códigos estables de `VERIFICATION_FRESHNESS_CODES` (`stale-plan | stale-candidate-snapshot |
328
+ stale-acceptance-fingerprint | incomplete-missing-results |
329
+ incomplete-unjustified-skip | incomplete-stage-coverage`) o `{ fresh: true }`.
330
+
331
+ **Regla del gate de entrega:** un gate de verificación de entrega se satisface SOLO
332
+ con un recibo fresco, que solicite `full` y tenga veredicto `pass`.
333
+
334
+ **Límite de no-ejecución:** el paquete valida, canonicaliza, digiere, deriva y
335
+ compara — no ejecuta comandos. La ejecución es responsabilidad del llamador.
336
+
337
+ ### Inventario de la API pública de verificación
338
+
339
+ La superficie completa en runtime de estos contratos es:
340
+
341
+ | Grupo de runtime | Exports |
342
+ | --- | --- |
343
+ | Contratos y vocabularios | `VERIFICATION_PLAN_CONTRACT_ID`, `VERIFICATION_RECEIPT_CONTRACT_ID`, `VERIFICATION_STAGES`, `VERIFICATION_COST_CLASSES`, `VERIFICATION_COMMAND_STATUSES`, `VERIFICATION_VERDICTS`, `VERIFICATION_DIAGNOSTIC_CODES`, `VERIFICATION_FRESHNESS_CODES`, `VERIFICATION_LIMITS`, `VERIFICATION_CANONICAL_VECTORS` |
344
+ | Validación y semántica | `validateVerificationPlanV1`, `validateVerificationReceiptAgainstPlan`, `deriveVerificationVerdict`, `compareVerificationReceiptToCurrent` |
345
+ | Canonicalización y digests | `canonicalizeVerificationPlan`, `canonicalizeVerificationReceipt`, `digestVerificationPlan`, `digestVerificationReceipt` |
346
+
347
+ TypeScript también publica estos nombres de solo tipo:
348
+
349
+ | Grupo de tipos | Exports |
350
+ | --- | --- |
351
+ | Plan | `VerificationStage`, `VerificationCostClass`, `WorkingDirectoryPolicy`, `VerificationCommandV1`, `VerificationPlanV1`, `VerificationPlanValidationResult` |
352
+ | Recibo | `VerificationCommandStatus`, `VerificationVerdict`, `VerificationStageRequest`, `EvidenceReferenceV1`, `VerificationResultV1`, `VerificationReceiptV1`, `VerificationReceiptValidationResult` |
353
+ | Diagnósticos y frescura | `VerificationDiagnosticCode`, `VerificationDiagnosticV1`, `VerificationFreshnessReasonCode`, `VerificationFreshnessResult` |
354
+
355
+ ### Límites de usabilidad
356
+
357
+ Todos los topes de v1 se publican una sola vez, en el objeto congelado
358
+ `VERIFICATION_LIMITS`, y los aplican las dos entradas autoritativas: un plan o un
359
+ recibo que los excede se rechaza, nunca se trunca en silencio.
360
+
361
+ | Límite | Valor | Se aplica a |
362
+ | --- | --- | --- |
363
+ | `commands` | 128 | comandos declarados en un plan |
364
+ | `results` | 128 | filas de resultado en un recibo |
365
+ | `argsPerCommand` | 64 | argumentos de un comando |
366
+ | `idChars` | 128 | un `id` de comando o `commandId` de resultado |
367
+ | `pathChars` | 1024 | `executable` y `workingDirectory` |
368
+ | `argChars` | 4096 | una cadena de argumento |
369
+ | `skipReasonChars` | 1024 | un `skipReason` |
370
+ | `evidenceRefChars` | 1024 | una `ref` de evidencia |
371
+ | `planBytes` | 262144 | tamaño canónico del plan (256 KiB) |
372
+ | `receiptBytes` | 524288 | tamaño canónico del recibo (512 KiB) |
373
+ | `fastCommandTimeoutMs` | 600000 | timeout de un comando fast (10 minutos) |
374
+ | `fastStageTimeoutMs` | 900000 | suma de los timeouts de todos los comandos fast (15 minutos) |
375
+ | `fullCommandTimeoutMs` | 3600000 | timeout de un comando full (60 minutos) |
376
+ | `fullStageTimeoutMs` | 7200000 | suma de los timeouts de todos los comandos full (2 horas, 120 min) |
377
+ | `diagnostics` | 50 | filas de un resultado de rechazo |
378
+
379
+ El presupuesto de bytes canónicos se mide antes de examinar el documento, así que un
380
+ payload desmedido se rechaza solo por el presupuesto. Los topes de tiempo son
381
+ deliberadamente asimétricos: un comando fast de duración máxima deja 5 minutos para
382
+ el resto de la etapa fast. `npm run bench:verification -- --commands 128` es un
383
+ comando de mantenedor solo para checkout fuente: ejecútalo desde un checkout del
384
+ código fuente, nunca desde el tarball instalado, y prueba el límite de rendimiento
385
+ declarado — un ciclo en caliente de validar → canonicalizar → digerir plan+recibo
386
+ de 128 comandos con p95 ≤ 100 ms — y sale con código distinto de cero cuando no se
387
+ cumple. La interoperabilidad entre implementaciones la fija
388
+ `VERIFICATION_CANONICAL_VECTORS`: los fixtures congelados
389
+ `{ contract, digest, description }` cuyos digests debe reproducir cualquier
390
+ canonicalizador correcto — los tests de digests del propio paquete consumen
391
+ exactamente estos payloads.
392
+
393
+ ### Ejemplo de consumo
394
+
395
+ ```ts
396
+ import {
397
+ compareVerificationReceiptToCurrent,
398
+ deriveVerificationVerdict,
399
+ digestVerificationPlan,
400
+ validateVerificationPlanV1,
401
+ validateVerificationReceiptAgainstPlan,
402
+ VERIFICATION_PLAN_CONTRACT_ID,
403
+ VERIFICATION_RECEIPT_CONTRACT_ID,
404
+ } from "@gtrabanco/agentic-workflow-schema";
405
+
406
+ const candidateDigest = "3f2a9c1e5b7d4f8a0c2e5b7d9f1a3c5e7b9d1f3a5c7e9b1d3f5a7c9e1b3d5f7a";
407
+ const acceptanceDigest = "9c4e7b1d3f5a8c2e4b6d0f2a4c6e8b0d2f4a6c8e0b2d4f6a8c0e2b4d6f8a0c24";
408
+
409
+ // 1. Declare the plan: a fast lint that stops the stage, then a full test run.
410
+ const plan = {
411
+ contract: VERIFICATION_PLAN_CONTRACT_ID,
412
+ commands: [
413
+ { id: "lint", stage: "fast" as const, executable: "npm", args: ["run", "lint"],
414
+ workingDirectoryPolicy: "candidate-root" as const, workingDirectory: null,
415
+ timeoutMs: 30_000, stopOnFailure: true, costClass: "cheap" as const },
416
+ { id: "test", stage: "full" as const, executable: "npm", args: ["test"],
417
+ workingDirectoryPolicy: "candidate-root" as const, workingDirectory: null,
418
+ timeoutMs: 120_000, stopOnFailure: false, costClass: "moderate" as const },
419
+ ],
420
+ } as const;
421
+
422
+ const pv = validateVerificationPlanV1(plan);
423
+ if (!pv.ok) throw new Error(`plan rejected: ${JSON.stringify(pv.diagnostics)}`);
424
+
425
+ // 2. Bind the receipt to one candidate and one acceptance manifest. In a real
426
+ // gate `candidateDigest` comes from `digestCandidateSnapshot(snapshot)` and
427
+ // `acceptanceDigest` comes from `computeAcceptanceFingerprint(rows)`, which
428
+ // hashes the ordered `{ id, blobSha256 }` acceptance rows — not the raw
429
+ // `ACCEPTANCE.md` blob itself.
430
+ const planDigest = await digestVerificationPlan(pv.plan);
431
+ const receipt = {
432
+ contract: VERIFICATION_RECEIPT_CONTRACT_ID,
433
+ planDigest,
434
+ candidateSnapshotDigest: candidateDigest,
435
+ acceptanceFingerprint: acceptanceDigest,
436
+ stageRequested: "full" as const,
437
+ results: [
438
+ { commandId: "lint", status: "passed" as const, exitCode: 0, signal: null,
439
+ startedAt: "2026-08-27T09:00:00Z", endedAt: "2026-08-27T09:00:12Z",
440
+ stdout: null, stderr: null, skipReason: null },
441
+ { commandId: "test", status: "passed" as const, exitCode: 0, signal: null,
442
+ startedAt: "2026-08-27T09:00:12Z", endedAt: "2026-08-27T09:02:00Z",
443
+ stdout: { ref: "evidence/test/stdout.log", bytes: 18213,
444
+ sha256: "6b1f4d8a2c5e7b0d3f6a9c2e5b8d1f4a7c0e3b6d9f2a5c8e1b4d7f0a3c6e9b2d" },
445
+ stderr: null, skipReason: null },
446
+ ],
447
+ verdict: "pass" as const,
448
+ } as const;
449
+
450
+ // 3. One call proves receipt structure and plan binding.
451
+ const rv = await validateVerificationReceiptAgainstPlan(receipt, plan);
452
+ if (!rv.ok) throw new Error(`receipt rejected: ${JSON.stringify(rv.diagnostics)}`);
453
+
454
+ // 4. A row that ran longer than its command's declared timeout is incoherent.
455
+ for (const result of rv.receipt.results) {
456
+ const declared = pv.plan.commands.find((command) => command.id === result.commandId);
457
+ if (declared === undefined || Date.parse(result.endedAt) - Date.parse(result.startedAt) > declared.timeoutMs) {
458
+ throw new Error(`${result.commandId} outran the timeout its command declared`);
459
+ }
460
+ }
461
+
462
+ // 5. The verdict is derived from content; the payload's copy is never trusted.
463
+ const derived = deriveVerificationVerdict(rv.receipt, pv.plan); // => "pass"
464
+
465
+ // 6. Freshness compares the digests the receipt was bound to with the current ones.
466
+ const freshness = await compareVerificationReceiptToCurrent(
467
+ rv.receipt, pv.plan, candidateDigest, acceptanceDigest,
468
+ );
469
+
470
+ // 7. The delivery gate needs all three conditions at once.
471
+ if (freshness.fresh === true && rv.receipt.stageRequested === "full" && derived === "pass") {
472
+ console.log("Delivery verified");
473
+ }
474
+ ```
475
+
476
+ ### Límite del consumidor
477
+
478
+ Un dialecto, runner o adaptador de AWL que emita planes y los ejecute **no forma
479
+ parte de este paquete**, y ningún issue lo sigue: este schema posee solo los
480
+ contratos, las formas canónicas y los digests. Pasa a ser trabajo futuro
481
+ independiente cuando AWL consuma el paquete publicado.
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
@@ -120,9 +163,12 @@ overwriting it.
120
163
 
121
164
  ## Validate or use another language
122
165
 
123
- The public validators are `validateEnvelopeV2Strict`, `validateSkillOutcomeV1`,
124
- and `validateWorkflowSnapshotV1`. Import a JSON Schema when a non-TypeScript
125
- consumer needs the same boundary:
166
+ The public contract validators are `validateEnvelopeV2Strict`,
167
+ `validateSkillOutcomeV1`, `validateWorkflowSnapshotV1`,
168
+ `validateCandidateSnapshotV1`, and `validateReviewReceiptV1`; the staged
169
+ verification contracts add exactly the two authoritative entries named above,
170
+ `validateVerificationPlanV1` and `validateVerificationReceiptAgainstPlan`. Import a
171
+ JSON Schema when a non-TypeScript consumer needs the same structural boundary:
126
172
 
127
173
  ```ts
128
174
  import schema from "@gtrabanco/agentic-workflow-schema/skill-outcome.schema.json" with { type: "json" };
@@ -175,3 +221,246 @@ Additive contract fields are minor; parser, documentation, or implementation
175
221
  fixes are patch releases. See
176
222
  [programmatic orchestration](../../docs/workflow/ORCHESTRATION.md) for the
177
223
  driver protocol.
224
+
225
+ ## Staged Verification Contracts (feature 26)
226
+
227
+ Two versioned wire contracts for staged verification:
228
+
229
+ - `VerificationPlan v1` (`agentic-workflow/verification-plan@1`) — an ordered,
230
+ non-empty command list where each command carries a stable `id`,
231
+ `stage: fast | full` (the closed `VERIFICATION_STAGES` vocabulary), an
232
+ `executable` and ordered `args` (never a shell
233
+ string), a working-directory policy (`candidate-root` or `relative-path` with
234
+ validated relative path), a positive `timeoutMs`, `stopOnFailure`, and a
235
+ cost class (`VERIFICATION_COST_CLASSES`). The validated relative path is an **opaque** string: resolve it
236
+ under the candidate root exactly as submitted, and never percent-decode it
237
+ before resolution — decoding can turn a path the validator rejected into one
238
+ that escapes the root.
239
+
240
+ - `VerificationReceipt v1` (`agentic-workflow/verification-receipt@1`) — a receipt that
241
+ binds to the plan digest, candidate-snapshot digest, and acceptance
242
+ fingerprint, carrying per-command results with status (`passed | failed |
243
+ timed-out | skipped | infrastructure-error`), exit-code/signal per the D4
244
+ matrix, bounded evidence references, and an explicit skip reason. The
245
+ overall verdict (`pass | fail | incomplete`) is derived from the receipt
246
+ content.
247
+
248
+ **Validation authority.** Exactly two public authoritative entries decide runtime
249
+ validity: `validateVerificationPlanV1(value)` for a plan, and
250
+ `await validateVerificationReceiptAgainstPlan(receipt, plan)` for a receipt, which
251
+ performs the structural check and every plan-bound rule in one call. No standalone
252
+ receipt validator is exported — a receipt is only meaningful against the plan it
253
+ binds to. Both accept unknown input and both return a **normalized** own-property
254
+ DTO on success rather than the object you handed them, so digests and downstream
255
+ semantics never depend on inherited, duplicated or undeclared properties.
256
+
257
+ **Failure diagnostics.** A rejection is `{ ok: false, diagnostics, truncated }`.
258
+ `diagnostics` holds at most 50 frozen `{ code, path }` rows in document order and
259
+ `truncated` says whether that ceiling dropped any. A row is never a message: no
260
+ prose and no submitted value is ever returned. `code` comes from the closed
261
+ `VERIFICATION_DIAGNOSTIC_CODES` vocabulary and `path` is an RFC 6901 JSON Pointer
262
+ built only from declared property names and array indices — `/commands/3/id`,
263
+ `/results/1/commandId`, or `""` for the payload as a whole. An undeclared key is
264
+ reported as `unknown-field` on its **container**, because the key name is itself
265
+ submitted data. Recover from diagnostics using only each stable `code` and `path`,
266
+ without copying submitted values into logs, errors, or telemetry.
267
+
268
+ | Diagnostic code | What it answers for | Caller recovery |
269
+ | --- | --- | --- |
270
+ | `invalid-type` | a field holds a value of the wrong JSON type | Supply the declared JSON type at `path`. |
271
+ | `missing-field` | a declared field is absent | Add the required field at `path`. |
272
+ | `unknown-field` | the object carries an undeclared property | Remove undeclared keys from the container at `path`. |
273
+ | `invalid-value` | a value breaks its own rule (vocabulary, pattern, NUL) | Replace it with an allowed vocabulary member or format-valid, NUL-free value. |
274
+ | `limit-exceeded` | a cardinality or length ceiling is crossed | Reduce the indicated collection or string to `VERIFICATION_LIMITS`. |
275
+ | `duplicate-id` | the same command id appears twice | Assign unique command ids, then update their result references. |
276
+ | `unknown-command` | a result or skip reason names no declared command | Reference an id declared by the bound plan. |
277
+ | `invalid-order` | results do not follow the plan's declared order | Reorder result rows to match plan order. |
278
+ | `invalid-stage` | a receipt carries a row outside its requested stage | Remove out-of-stage rows or request the stage that includes them. |
279
+ | `invalid-exit-state` | exit code and signal break the D4 matrix | Align `exitCode` and `signal` with the row's status matrix. |
280
+ | `invalid-evidence` | an evidence reference is malformed (D5 content rules) | Provide a bounded `ref`, non-negative byte count, and lowercase SHA-256. |
281
+ | `invalid-skip` | a skip reason is not justified by a failed predecessor | Use `null` when unattributed, or name an earlier actual non-pass trigger. |
282
+ | `invalid-fail-fast` | `stopOnFailure` sequencing is broken | Mark rows after the trigger skipped and attribute them to that trigger. |
283
+ | `digest-mismatch` | the receipt's `planDigest` is not the bound plan's | Recompute it from the validated, normalized bound plan. |
284
+ | `verdict-mismatch` | the stored verdict differs from the derived one | Store the result of `deriveVerificationVerdict`. |
285
+ | `budget-exceeded` | a stage's declared timeouts exceed its aggregate budget | Reduce command timeouts until the stage sum is within `VERIFICATION_LIMITS`. |
286
+
287
+ **JSON Schema status.** `verification-plan.schema.json` and
288
+ `verification-receipt.schema.json` are generated, **non-authoritative structural
289
+ projections** of the package's canonical contract definition. They exist for editors
290
+ and transport checks; a Draft-07 match is not contract validity, and semantic rules
291
+ (`unique-command-ids`, both aggregate stage budgets, both canonical byte budgets) are
292
+ enforced only by the two runtime entries above — each projection discloses them in
293
+ its `$comment`. The projections are generated rather than hand-edited. In a source
294
+ checkout, maintainers change the canonical definition; the only writer is
295
+ `node scripts/generate-verification-schemas.mjs`, and the source-only drift check
296
+ rebuilds before comparing bytes.
297
+
298
+ **Source-checkout-only commands.** The published tarball intentionally omits the
299
+ repository's `scripts/`, `test/`, source, and TypeScript configuration. These
300
+ manifest commands are maintainer checks for a source checkout, not commands an
301
+ installed-package consumer can run:
302
+
303
+ | Source-checkout-only command | Purpose |
304
+ | --- | --- |
305
+ | `npm run check:verification-schemas` | rebuild and byte-check generated projections |
306
+ | `npm run check:verification-package` | inspect the package tarball contract |
307
+ | `npm run bench:verification -- --commands 128` | run the AC10 warm-process benchmark |
308
+ | `npm run test:verification-docs` | run the executable bilingual documentation suite |
309
+ | `npm run gate:verification` | compose all verification release checks |
310
+
311
+ **Two-stage model:** requesting `fast` executes only fast commands; requesting
312
+ `full` executes every fast and full command. The freshness predicate returns
313
+ one of the stable `VERIFICATION_FRESHNESS_CODES` reason codes (`stale-plan | stale-candidate-snapshot |
314
+ stale-acceptance-fingerprint | incomplete-missing-results |
315
+ incomplete-unjustified-skip | incomplete-stage-coverage`) or `{ fresh: true }`.
316
+
317
+ **Delivery-gate rule:** a delivery verification gate is satisfied ONLY by a
318
+ receipt that is fresh, requests `full`, and has verdict `pass`.
319
+
320
+ **No-execution boundary:** the package validates, canonicalizes, digests,
321
+ derives, and compares — it does not execute commands. The caller owns execution.
322
+
323
+ ### Public verification API inventory
324
+
325
+ The complete runtime surface for these contracts is:
326
+
327
+ | Runtime group | Exports |
328
+ | --- | --- |
329
+ | Contract and vocabulary values | `VERIFICATION_PLAN_CONTRACT_ID`, `VERIFICATION_RECEIPT_CONTRACT_ID`, `VERIFICATION_STAGES`, `VERIFICATION_COST_CLASSES`, `VERIFICATION_COMMAND_STATUSES`, `VERIFICATION_VERDICTS`, `VERIFICATION_DIAGNOSTIC_CODES`, `VERIFICATION_FRESHNESS_CODES`, `VERIFICATION_LIMITS`, `VERIFICATION_CANONICAL_VECTORS` |
330
+ | Validation and semantics | `validateVerificationPlanV1`, `validateVerificationReceiptAgainstPlan`, `deriveVerificationVerdict`, `compareVerificationReceiptToCurrent` |
331
+ | Canonicalization and digests | `canonicalizeVerificationPlan`, `canonicalizeVerificationReceipt`, `digestVerificationPlan`, `digestVerificationReceipt` |
332
+
333
+ TypeScript also publishes these type-only names:
334
+
335
+ | Type group | Exports |
336
+ | --- | --- |
337
+ | Plan | `VerificationStage`, `VerificationCostClass`, `WorkingDirectoryPolicy`, `VerificationCommandV1`, `VerificationPlanV1`, `VerificationPlanValidationResult` |
338
+ | Receipt | `VerificationCommandStatus`, `VerificationVerdict`, `VerificationStageRequest`, `EvidenceReferenceV1`, `VerificationResultV1`, `VerificationReceiptV1`, `VerificationReceiptValidationResult` |
339
+ | Diagnostics and freshness | `VerificationDiagnosticCode`, `VerificationDiagnosticV1`, `VerificationFreshnessReasonCode`, `VerificationFreshnessResult` |
340
+
341
+ ### Usability limits
342
+
343
+ Every v1 ceiling is published once, as the frozen `VERIFICATION_LIMITS` object, and
344
+ is enforced by the two authoritative entries: an over-limit plan or receipt is
345
+ rejected, never silently truncated.
346
+
347
+ | Limit | Value | Applies to |
348
+ | --- | --- | --- |
349
+ | `commands` | 128 | commands declared in one plan |
350
+ | `results` | 128 | result rows in one receipt |
351
+ | `argsPerCommand` | 64 | arguments in one command |
352
+ | `idChars` | 128 | a command `id` or result `commandId` |
353
+ | `pathChars` | 1024 | `executable` and `workingDirectory` |
354
+ | `argChars` | 4096 | a single argument string |
355
+ | `skipReasonChars` | 1024 | a `skipReason` |
356
+ | `evidenceRefChars` | 1024 | an evidence `ref` |
357
+ | `planBytes` | 262144 | canonical plan size (256 KiB) |
358
+ | `receiptBytes` | 524288 | canonical receipt size (512 KiB) |
359
+ | `fastCommandTimeoutMs` | 600000 | one fast command's timeout (10 min) |
360
+ | `fastStageTimeoutMs` | 900000 | every fast command's timeouts summed (15 min) |
361
+ | `fullCommandTimeoutMs` | 3600000 | one full command's timeout (60 min) |
362
+ | `fullStageTimeoutMs` | 7200000 | every full command's timeouts summed (2 h, i.e. 120 min) |
363
+ | `diagnostics` | 50 | rows in one failure result |
364
+
365
+ The canonical byte budget is measured before a payload is examined, so an oversized
366
+ document is refused by the budget alone. The time ceilings are deliberately
367
+ asymmetric: one maximum-length fast command leaves 5 minutes for the rest of the
368
+ fast stage. `npm run bench:verification -- --commands 128` is a
369
+ source-checkout-only maintainer command: run it from a source checkout, never
370
+ from the installed tarball, and it proves the declared performance bound — a warm
371
+ 128-command plan+receipt validate → canonicalize → digest cycle at p95 ≤ 100 ms —
372
+ and exits non-zero when it is not met. Cross-implementation
373
+ interoperability is pinned by `VERIFICATION_CANONICAL_VECTORS`, the frozen
374
+ `{ contract, digest, description }` fixtures whose digests any correct
375
+ canonicalizer must reproduce — the package's own digest tests consume exactly
376
+ these payloads.
377
+
378
+ ### Consumer example
379
+
380
+ ```ts
381
+ import {
382
+ compareVerificationReceiptToCurrent,
383
+ deriveVerificationVerdict,
384
+ digestVerificationPlan,
385
+ validateVerificationPlanV1,
386
+ validateVerificationReceiptAgainstPlan,
387
+ VERIFICATION_PLAN_CONTRACT_ID,
388
+ VERIFICATION_RECEIPT_CONTRACT_ID,
389
+ } from "@gtrabanco/agentic-workflow-schema";
390
+
391
+ const candidateDigest = "3f2a9c1e5b7d4f8a0c2e5b7d9f1a3c5e7b9d1f3a5c7e9b1d3f5a7c9e1b3d5f7a";
392
+ const acceptanceDigest = "9c4e7b1d3f5a8c2e4b6d0f2a4c6e8b0d2f4a6c8e0b2d4f6a8c0e2b4d6f8a0c24";
393
+
394
+ // 1. Declare the plan: a fast lint that stops the stage, then a full test run.
395
+ const plan = {
396
+ contract: VERIFICATION_PLAN_CONTRACT_ID,
397
+ commands: [
398
+ { id: "lint", stage: "fast" as const, executable: "npm", args: ["run", "lint"],
399
+ workingDirectoryPolicy: "candidate-root" as const, workingDirectory: null,
400
+ timeoutMs: 30_000, stopOnFailure: true, costClass: "cheap" as const },
401
+ { id: "test", stage: "full" as const, executable: "npm", args: ["test"],
402
+ workingDirectoryPolicy: "candidate-root" as const, workingDirectory: null,
403
+ timeoutMs: 120_000, stopOnFailure: false, costClass: "moderate" as const },
404
+ ],
405
+ } as const;
406
+
407
+ const pv = validateVerificationPlanV1(plan);
408
+ if (!pv.ok) throw new Error(`plan rejected: ${JSON.stringify(pv.diagnostics)}`);
409
+
410
+ // 2. Bind the receipt to one candidate and one acceptance manifest. In a real
411
+ // gate `candidateDigest` comes from `digestCandidateSnapshot(snapshot)` and
412
+ // `acceptanceDigest` comes from `computeAcceptanceFingerprint(rows)`, which
413
+ // hashes the ordered `{ id, blobSha256 }` acceptance rows — not the raw
414
+ // `ACCEPTANCE.md` blob itself.
415
+ const planDigest = await digestVerificationPlan(pv.plan);
416
+ const receipt = {
417
+ contract: VERIFICATION_RECEIPT_CONTRACT_ID,
418
+ planDigest,
419
+ candidateSnapshotDigest: candidateDigest,
420
+ acceptanceFingerprint: acceptanceDigest,
421
+ stageRequested: "full" as const,
422
+ results: [
423
+ { commandId: "lint", status: "passed" as const, exitCode: 0, signal: null,
424
+ startedAt: "2026-08-27T09:00:00Z", endedAt: "2026-08-27T09:00:12Z",
425
+ stdout: null, stderr: null, skipReason: null },
426
+ { commandId: "test", status: "passed" as const, exitCode: 0, signal: null,
427
+ startedAt: "2026-08-27T09:00:12Z", endedAt: "2026-08-27T09:02:00Z",
428
+ stdout: { ref: "evidence/test/stdout.log", bytes: 18213,
429
+ sha256: "6b1f4d8a2c5e7b0d3f6a9c2e5b8d1f4a7c0e3b6d9f2a5c8e1b4d7f0a3c6e9b2d" },
430
+ stderr: null, skipReason: null },
431
+ ],
432
+ verdict: "pass" as const,
433
+ } as const;
434
+
435
+ // 3. One call proves receipt structure and plan binding.
436
+ const rv = await validateVerificationReceiptAgainstPlan(receipt, plan);
437
+ if (!rv.ok) throw new Error(`receipt rejected: ${JSON.stringify(rv.diagnostics)}`);
438
+
439
+ // 4. A row that ran longer than its command's declared timeout is incoherent.
440
+ for (const result of rv.receipt.results) {
441
+ const declared = pv.plan.commands.find((command) => command.id === result.commandId);
442
+ if (declared === undefined || Date.parse(result.endedAt) - Date.parse(result.startedAt) > declared.timeoutMs) {
443
+ throw new Error(`${result.commandId} outran the timeout its command declared`);
444
+ }
445
+ }
446
+
447
+ // 5. The verdict is derived from content; the payload's copy is never trusted.
448
+ const derived = deriveVerificationVerdict(rv.receipt, pv.plan); // => "pass"
449
+
450
+ // 6. Freshness compares the digests the receipt was bound to with the current ones.
451
+ const freshness = await compareVerificationReceiptToCurrent(
452
+ rv.receipt, pv.plan, candidateDigest, acceptanceDigest,
453
+ );
454
+
455
+ // 7. The delivery gate needs all three conditions at once.
456
+ if (freshness.fresh === true && rv.receipt.stageRequested === "full" && derived === "pass") {
457
+ console.log("Delivery verified");
458
+ }
459
+ ```
460
+
461
+ ### Consumer boundary
462
+
463
+ An AWL dialect, runner or adapter that emits plans and executes them is **not part
464
+ of this package**, and no issue tracks it: this schema owns the contracts, the
465
+ canonical forms and the digests only. It becomes independent future work once AWL
466
+ consumes the released package.