@gtrabanco/agentic-workflow-schema 2.0.0 → 3.0.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
@@ -2,18 +2,11 @@
2
2
 
3
3
  > 🇬🇧 [English version](README.md)
4
4
 
5
- Tipos, JSON Schema, y parser/validador para el **sobre-máquina** de
6
- [agentic-workflow](https://github.com/gtrabanco/agentic-workflow) — el
7
- bloque JSON fijo con el que termina un turno de agente conducido (emitido
8
- siempre por `workflow-status`, y por cualquier otra skill cuando el driver
9
- inyecta el fragmento canónico de system-prompt — ver el protocolo de driver
10
- abajo), para que orquestadores externos puedan enrutar el flujo de trabajo
11
- programáticamente (qué comando sigue, en qué nivel de modelo).
12
-
13
- Cero dependencias en tiempo de ejecución. Fuente de verdad del contrato:
14
- [`skills/orchestration-envelope/SKILL.md`](https://github.com/gtrabanco/agentic-workflow/blob/main/skills/orchestration-envelope/SKILL.md);
15
- protocolo de driver:
16
- [`docs/workflow/ORCHESTRATION.md`](https://github.com/gtrabanco/agentic-workflow/blob/main/docs/workflow/ORCHESTRATION.md).
5
+ Contratos máquina sin dependencias de ejecución para
6
+ [agentic-workflow](https://github.com/gtrabanco/agentic-workflow). La versión 3
7
+ mantiene el envelope establecido de `workflow-status`, pero ofrece a los
8
+ drivers headless un resultado menor para las skills de trabajo y estado
9
+ determinista compilado desde documentos.
17
10
 
18
11
  ## Instalación
19
12
 
@@ -21,180 +14,118 @@ protocolo de driver:
21
14
  npm install @gtrabanco/agentic-workflow-schema
22
15
  ```
23
16
 
24
- ## Uso
17
+ ## Tres contratos, propietarios distintos
18
+
19
+ | Contrato | Propietario | Uso |
20
+ | --- | --- | --- |
21
+ | Envelope v2 | `workflow-status` | Resultado completo del sensor de solo lectura y consumidores existentes. |
22
+ | SkillOutcome v1 | Un turno de skill conducido | Resultado pequeño controlado por el modelo: ruta, bloqueantes, preguntas, descubrimientos y referencias de evidencia. |
23
+ | WorkflowSnapshot v1 | El driver | Hechos deterministas de repositorio y documentos, con procedencia, desconocidos y contradicciones. |
24
+
25
+ Todos los JSON Schema son estrictos: se rechazan claves no declaradas. `detail`
26
+ es obligatorio en Envelope v2 (usa `null` cuando está vacío); las extensiones
27
+ de cada skill van dentro. Los esquemas se exportan en
28
+ `./envelope.schema.json`, `./skill-outcome.schema.json` y
29
+ `./workflow-snapshot.schema.json`.
30
+
31
+ ## Parsear un turno conducido
32
+
33
+ Usa los perfiles para seleccionar el resultado requerido, añade la instrucción
34
+ generada sólo a una invocación headless y parsea la respuesta final.
25
35
 
26
36
  ```ts
27
37
  import {
28
- parseEnvelope,
29
- isTerminal,
30
- isRunHalt,
38
+ parseTurn,
39
+ renderOutputInstruction,
40
+ WORKFLOW_SKILL_PROFILES,
31
41
  } from "@gtrabanco/agentic-workflow-schema";
32
42
 
33
- const output = await runAgentHeadless("Follow the installed SKILL.md for: /workflow-status --json-only");
43
+ const skill = "audit-pr";
44
+ const profile = WORKFLOW_SKILL_PROFILES.find((entry) => entry.skill === skill);
45
+ if (profile === undefined) throw new Error(`Unknown workflow skill: ${skill}`);
34
46
 
35
- const result = parseEnvelope(output); // extracts the LAST fenced ```json block
47
+ const output = await invokeAgent({
48
+ prompt: "Follow the installed skill for /audit-pr.",
49
+ systemAppend: renderOutputInstruction(skill),
50
+ });
51
+
52
+ const result = parseTurn({ skill, text: output, context: { unitId: "12-machine-contract" } });
36
53
  if (!result.ok) throw new Error(result.errors.join("; "));
37
54
 
38
- const env = result.envelope; // fully typed
39
- if (isRunHalt(env)) stopEverythingAndPage(env.blockers);
40
- else if (isTerminal(env.state)) askHuman(env);
41
- else invokeNext(env.next.recommended, env.next.tier); // "strong" | "cheap"
55
+ // result.outcome es SkillOutcome v1; result.envelope solo existe para v2.
56
+ route(result.outcome.next.intent, result.outcome.next.targets);
42
57
  ```
43
58
 
44
- El contrato de parseo es exactamente lo que prometen las skills: **el
45
- último bloque
46
- ```` ```json ````…```` ``` ```` entre comillas del mensaje final es el
47
- sobre**, uno por turno, todas las claves de nivel superior siempre
48
- presentes.
59
+ Ante un resultado ausente o inválido, reinvoca la *misma sesión una vez* con
60
+ `Emit only the machine result for the turn above.` y vuelve a parsear. El
61
+ segundo fallo es un fallo del driver. No conviertas prosa arbitraria en hechos
62
+ estructurados.
49
63
 
50
- También exportados: `extractLastJsonBlock(text)`, `validateEnvelope(value)`,
51
- `ENVELOPE_STATES` (el enum de 11 estados), `TERMINAL_STATES`, y cada tipo
52
- de campo. También se distribuye un **JSON Schema** agnóstico de lenguaje —
53
- funciona con el mínimo de `engines.node` (>=18):
64
+ `workflow-status` conserva su Envelope v2 nativo. Los consumidores existentes
65
+ pueden continuar con `parseEnvelope(text)`; los nuevos usan
66
+ `parseEnvelopeV2Strict(text)` o el uniforme `parseTurn({skill, text})`.
54
67
 
55
- ```ts
56
- import { createRequire } from "node:module";
57
- const schema = createRequire(import.meta.url)("@gtrabanco/agentic-workflow-schema/envelope.schema.json");
58
- ```
68
+ ## Compilar estado determinista
59
69
 
60
- En Node 20.10+/22, la forma más nueva de import-attributes también
61
- funciona:
70
+ El paquete nunca lee el sistema de archivos, Git ni una forja. El llamador
71
+ aporta los documentos exactos y los hechos del repositorio que ya leyó, por lo
72
+ que los snapshots son reproducibles y se pueden cachear por `sourceRevision`.
62
73
 
63
74
  ```ts
64
- import schema from "@gtrabanco/agentic-workflow-schema/envelope.schema.json" with { type: "json" };
65
- ```
75
+ import { compileWorkflowSnapshot } from "@gtrabanco/agentic-workflow-schema";
76
+
77
+ const result = compileWorkflowSnapshot({
78
+ sourceRevision: headSha,
79
+ repository: { branch, headSha, dirty },
80
+ documents: [
81
+ { path: "docs/workflow/REPOSITORY_STATE.md", content: repositoryState },
82
+ { path: "docs/features/ROADMAP.md", content: roadmap },
83
+ { path: "docs/features/12-machine-contract/SPEC.md", content: spec },
84
+ { path: "docs/features/12-machine-contract/progress.md", content: progress },
85
+ ],
86
+ });
87
+ if (!result.ok) throw new Error(result.errors.join("; "));
66
88
 
67
- ## El sobre, campo por campo
68
-
69
- Cada clave de nivel superior está **siempre presente** (`required` en el
70
- JSON Schema) — una skill que no tiene nada que reportar para una clave usa
71
- `null` / `[]` / `0`, nunca la omite. **Cerrado** = el enum exacto de abajo
72
- es exhaustivo (el validador rechaza cualquier otra cosa); **abierto** =
73
- forma libre, cualquier valor del tipo indicado.
74
-
75
- | Campo | Tipo | Valores | Significado |
76
- |---|---|---|---|
77
- | `skill` | string | abierto (no vacío) | Qué skill produjo este sobre. |
78
- | `state` | enum | **cerrado** — los 11 estados de abajo | La clave de enrutamiento. Todo lo que decide un orquestador empieza aquí. |
79
- | `summary` | string | abierto | Una frase en texto plano: qué pasó este turno. |
80
- | `unit.type` | enum | **cerrado** — `feature` · `fix` · `docs` · `none` | Qué tipo de unidad trabajó el turno. |
81
- | `unit.id` | string\|null | abierto | El identificador de la unidad (`NN-slug` para features, `n-topic` para fixes). |
82
- | `unit.issue` | integer\|null | abierto | El número del issue de rastreo, cuando la unidad nace de un issue. |
83
- | `unit.branch` | string\|null | abierto | La rama de trabajo. |
84
- | `phase.current` | string\|null | abierto (por convención `P1`, `P2`, …) | Fase recién trabajada, para features en fases (M/L). |
85
- | `phase.total` / `phase.completed` | integer\|null | abierto | Recuentos de fase; `null` para unidades de pase único. |
86
- | `pr.number` / `pr.url` / `pr.head_sha` | int/str\|null | abierto | El PR de la unidad, una vez que existe. |
87
- | `pr.state` | enum | **cerrado** — `open` · `merged` · `none` | El estado de merge vive en la forja, no en el roadmap. |
88
- | `pr.merge_ready` | boolean\|null | abierto | `true` solo después de un veredicto MERGE-READY de `audit-pr` sobre la cabeza actual. |
89
- | `pr.ci` | enum | **cerrado** — `green` · `red` · `pending` · `none` · `null` | `none` = el proyecto no tiene CI; `null` = no comprobado este turno. |
90
- | `gates.verification` | enum | **cerrado** — `green` · `red` · `not-run` · `null` | La propia puerta del proyecto (chequeo de tipos + tests + build) tal como se ejecutó por última vez. |
91
- | `gates.review_pending` / `gates.audit_pending` | boolean\|null | abierto | Si la revisión obligatoria / auditoría de merge todavía tiene que suceder. |
92
- | `findings.fix_now[]` | array de objetos | items: `id`/`file`/`axis`/`class`/`route` (abierto), `severity` (**cerrado** — `high`·`med`·`low`), `suggested_tier` (**cerrado** — `strong`·`cheap`) | Hallazgos que deben incorporarse a la rama ACTUAL antes de que avance — un item por cada fila sin foldear del ledger de fold fix-now (`review-findings.md`) de la unidad. |
93
- | `findings.issues_filed[]` | array de enteros | abierto | Números de issue creados/actualizados este turno. |
94
- | `findings.untriaged` | integer ≥ 0 | abierto | Hallazgos todavía sin destino — las skills cuyo contrato enruta todo deben reportar `0`. |
95
- | `findings.decisions_recorded` | integer ≥ 0 | abierto | Decisiones escritas en registros clase `decisions.md` este turno. |
96
- | `blockers[].kind` | enum | **cerrado** — `dependency` · `issue` · `gate` · `merge-conflict` · `substrate` · `input` | Por qué la unidad (o la ejecución) no puede avanzar. |
97
- | `blockers[].scope` | enum | **cerrado** — `unit` · `run` | `run` significa parar-el-mundo: nada más avanza tampoco. |
98
- | `blockers[].id` / `blockers[].detail` | string | abierto | Qué exactamente (un slug, `#N`, un nombre de check) + una línea de contexto. |
99
- | `dependencies.unmet[]` / `dependencies.build_order[]` | arrays de string | abierto | Referencias de roadmap/issue no cumplidas, y el orden más-profundo-primero para construirlas. |
100
- | `recommendations.product_audit` | boolean | abierto | `true` cuando una desviación recurrente sugiere que las suposiciones fundacionales están obsoletas. |
101
- | `recommendations.reason` | string\|null | abierto | Por qué (requerido en la práctica cuando el flag es `true`). |
102
- | `needs_input` | object\|null | `question` (abierto) + `options[]` (abierto) | No-nulo solo en `state: NEEDS_INPUT` — la decisión humana a mostrar, con opciones concretas. Nada se adivinó. |
103
- | `next.recommended` | string | abierto (una invocación de skill) | El único mejor comando siguiente. |
104
- | `next.alternatives[]` | array de string | abierto | Las otras elecciones defendibles. |
105
- | `next.tier` | enum | **cerrado** — `strong` · `cheap` | Qué clase de modelo merece el siguiente paso — juicio vs. mecánico. |
106
- | `detail` | any | abierto (específico de la skill) | Carga útil por skill — p. ej. `workflow-status` lleva aquí el árbol completo del proyecto (`features`, `fixes`, `startable_now`, `blocked_units`, `crash_recovery`, …). |
107
-
108
- ### La tabla de enrutamiento de `state` (cerrada — exactamente estos 11)
109
-
110
- | `state` | Significado | Acción del orquestador |
111
- |---|---|---|
112
- | `OK` | La skill terminó su trabajo | Invocar `next.recommended` en `next.tier` |
113
- | `CONTINUE` | Misma unidad, más del mismo trabajo | Reinvocar `next.recommended` (los checkpoints consultivos también aterrizan aquí — la alternativa está listada) |
114
- | `READY_FOR_REVIEW` | Unidad terminada; revisión obligatoria a continuación | `/review-change` en un modelo fuerte, contexto nuevo |
115
- | `READY_FOR_AUDIT` | Revisión limpia | `/audit-pr` (fuerte) |
116
- | `MERGE_READY` | Auditoría aprobada sobre el SHA de cabeza actual | El humano fusiona — o lo hace tu política de auto-merge escrita |
117
- | `MERGED` | Un auto-merge autorizado se ejecutó este turno | Siguiente unidad: consultar `workflow-status` |
118
- | `NEEDS_FIXES` | `findings.fix_now` no está vacío | Incorporar en la rama (commit Y push), luego reejecutar la puerta que los emitió |
119
- | `BLOCKED` | Dependencia no cumplida / causa externa | Seguir `dependencies.build_order`, o resolver `blockers[]` |
120
- | `NEEDS_INPUT` | Un humano debe decidir | Mostrar `needs_input.question` + `options`; reanudar con la respuesta |
121
- | `FAILED` | Reintentos agotados | Detener esta unidad; un humano la revisa |
122
- | `HALT` | Descubrimiento de parar-el-mundo (`blockers[].scope: "run"`) | Detener toda la ejecución; nada avanza hasta que un humano lo despeje |
123
-
124
- `isTerminal(state)` cubre `NEEDS_INPUT` / `FAILED` / `HALT` (+
125
- `MERGE_READY` con puerta humana); `isRunHalt(envelope)` es la comprobación
126
- de `HALT` / bloqueador con alcance de ejecución.
127
-
128
- ## Orquestar con este esquema
129
-
130
- Dos patrones, ambos consumiendo el mismo sobre. En ambos, **inyecta el
131
- fragmento canónico de system-prompt** en cada invocación headless (las
132
- skills no emiten el sobre por sí solas — `workflow-status` es la única
133
- excepción):
134
-
135
- ```text
136
- Every turn you produce MUST end with exactly one fenced ```json block matching
137
- the orchestration envelope schema (all top-level keys present; values only
138
- from verified command output). Emit nothing after it.
89
+ const { snapshot } = result;
90
+ // snapshot.unit, snapshot.phase, snapshot.provenance,
91
+ // snapshot.unknowns y snapshot.contradictions son deterministas.
139
92
  ```
140
93
 
141
- …y ejecuta el **bucle de reparación** ante un fallo de parseo — un
142
- reintento, luego falla el paso:
94
+ El compilador informa de fase actual desconocida en vez de adivinar a partir de
95
+ prosa ambigua de progreso. Un `Status: contradicted` declarado se conserva en
96
+ `snapshot.contradictions`: enrútalo a resolución del estado del repositorio en
97
+ vez de sobrescribirlo.
98
+
99
+ ## Validar o usar otro lenguaje
100
+
101
+ Los validadores públicos son `validateEnvelopeV2Strict`,
102
+ `validateSkillOutcomeV1` y `validateWorkflowSnapshotV1`. Importa un JSON Schema
103
+ cuando un consumidor no TypeScript necesite el mismo límite:
143
104
 
144
105
  ```ts
145
- async function turn(prompt: string) {
146
- let out = await invokeAgent(prompt, { system: SNIPPET });
147
- let r = parseEnvelope(out);
148
- if (!r.ok) {
149
- out = await invokeAgent("Emit only the machine envelope for the turn above.", { resume: true });
150
- r = parseEnvelope(out);
151
- if (!r.ok) throw new Error(`step failed: no valid envelope (${r.errors.join("; ")})`);
152
- }
153
- return r.envelope;
154
- }
106
+ import schema from "@gtrabanco/agentic-workflow-schema/skill-outcome.schema.json" with { type: "json" };
155
107
  ```
156
108
 
157
- **Patrón 1 — bucle de driver fijo** (empieza aquí): consulta el sensor,
158
- enruta por `state`, repite. Esqueleto completo en
159
- [`docs/workflow/ORCHESTRATION.md`](https://github.com/gtrabanco/agentic-workflow/blob/main/docs/workflow/ORCHESTRATION.md),
160
- incluido el protocolo de reinicio de recuperación ante caídas (pista
161
- `--last-envelope` + diario de sobres solo-anexar).
109
+ En versiones de Node sin atributos de importación JSON, carga el esquema con
110
+ `createRequire`. El paquete soporta Node 18 y posteriores.
162
111
 
163
- **Patrón 2 — flujos de trabajo dinámicos** (el patrón conductor): un
164
- contexto conductor de larga duración *escribe y monitoriza* el plan de
165
- trabajo; cada trabajador se ejecuta en un **contexto limpio** y solo su
166
- sobre fluye de vuelta hacia arriba — el conductor nunca ingiere
167
- transcripciones en bruto, que es lo que le permite mantenerse de larga
168
- duración sin degradarse. El sobre es precisamente el "resultado
169
- estructurado" que necesita este patrón:
112
+ ## Compatibilidad y versionado
170
113
 
171
- ```ts
172
- // Conductor: fan out independent units (workflow-status said they're startable
173
- // in parallel and the project declares `worktrees`), read back only envelopes.
174
- const status = await turn("Follow the installed SKILL.md for: /workflow-status --json-only");
175
- const units = status.detail.startable_now as string[];
176
-
177
- const results = await Promise.all(
178
- units.map((u) => turn(`Follow the installed SKILL.md for: /execute-phase ${u}`))
179
- );
180
-
181
- for (const env of results) {
182
- if (isRunHalt(env)) throw new Error(`HALT: ${JSON.stringify(env.blockers)}`);
183
- if (env.state === "NEEDS_FIXES")
184
- await turn(`Fold the fix-now findings on ${env.unit.branch}: ${JSON.stringify(env.findings.fix_now)}`);
185
- }
186
- // The conductor's own context grew by a few KB of envelopes — not by N transcripts.
187
- ```
114
+ `parseTurn` acepta primero v2 estricto y después sólo estas reparaciones legacy
115
+ nombradas:
188
116
 
189
- Piso de seguridad para cualquier driver, bucle fijo o dinámico: nunca
190
- saltarse una puerta `review_pending`/`audit_pending`, nunca fusionar salvo
191
- con un `MERGE_READY` fresco ligado al SHA de cabeza actual, y tratar
192
- `HALT` como terminal hasta que un humano lo despeje.
117
+ - un `detail` ausente pasa a `null`;
118
+ - el `design_candidates` raíz legacy se mueve a `detail.design_candidates`;
119
+ - la forma conocida de `audit-pr` puede tomar un id numérico de unidad de un
120
+ contexto fiable coincidente, un recuento de cero issues como `[]` y una fila
121
+ de gate nativa como bloqueante canónico.
193
122
 
194
- ## Versionado
123
+ Rechaza un recuento de issues no cero sin identidades, un id de unidad no
124
+ coincidente y prosa sin estructura. Los diagnósticos de compatibilidad hacen
125
+ visible cada reparación al driver.
195
126
 
196
- El semver de este paquete sigue al **contrato del sobre**, no al
197
- repositorio: cambio disruptivo del esquema (clave eliminada/renombrada,
198
- estado eliminado) → major; aditivo (clave opcional nueva, estado nuevo) →
199
- minor; arreglos/docs → patch. Cuando cambia la skill
200
- `orchestration-envelope`, este paquete cambia en el mismo PR.
127
+ Los majors del paquete señalan un cambio incompatible en cualquier contrato
128
+ publicado. Los campos aditivos son minor; arreglos de parser, documentación o
129
+ implementación son patch. Consulta la
130
+ [orquestación programática](../../docs/workflow/ORCHESTRATION.es.md) para el
131
+ protocolo de driver.
package/README.md CHANGED
@@ -2,18 +2,11 @@
2
2
 
3
3
  > 🇪🇸 [Versión en español](README.es.md)
4
4
 
5
- Types, JSON Schema, and parser/validator for the
6
- [agentic-workflow](https://github.com/gtrabanco/agentic-workflow) **machine
7
- envelope** — the fixed JSON block a driven agent turn ends with (emitted by
8
- `workflow-status` always, and by any other skill when the driver injects the
9
- canonical system-prompt snippet — see the driver protocol below), so external
10
- orchestrators can route the workflow programmatically (which command next, on
11
- which model tier).
12
-
13
- Zero runtime dependencies. Source of truth for the contract:
14
- [`skills/orchestration-envelope/SKILL.md`](https://github.com/gtrabanco/agentic-workflow/blob/main/skills/orchestration-envelope/SKILL.md);
15
- driver protocol:
16
- [`docs/workflow/ORCHESTRATION.md`](https://github.com/gtrabanco/agentic-workflow/blob/main/docs/workflow/ORCHESTRATION.md).
5
+ Zero-runtime-dependency machine contracts for
6
+ [agentic-workflow](https://github.com/gtrabanco/agentic-workflow). Version 3
7
+ keeps the established `workflow-status` envelope while giving headless drivers
8
+ a smaller result for working skills and deterministic state compiled from
9
+ documents.
17
10
 
18
11
  ## Install
19
12
 
@@ -21,171 +14,115 @@ driver protocol:
21
14
  npm install @gtrabanco/agentic-workflow-schema
22
15
  ```
23
16
 
24
- ## Use
17
+ ## Three contracts, distinct owners
18
+
19
+ | Contract | Owner | Use |
20
+ | --- | --- | --- |
21
+ | Envelope v2 | `workflow-status` | Full read-only sensor result and existing consumers. |
22
+ | SkillOutcome v1 | A driven skill turn | Small model-owned outcome, route, blockers, questions, discoveries, and evidence references. |
23
+ | WorkflowSnapshot v1 | The driver | Deterministic repository and document facts, with provenance, unknowns, and contradictions. |
24
+
25
+ All JSON Schemas are strict: undeclared keys are rejected. `detail` is required
26
+ on Envelope v2 (use `null` when empty); skill-specific extensions belong inside
27
+ it. The schemas are exported at `./envelope.schema.json`,
28
+ `./skill-outcome.schema.json`, and `./workflow-snapshot.schema.json`.
29
+
30
+ ## Parse a driven turn
31
+
32
+ Use the profile metadata to select the required result, append the generated
33
+ instruction only to a headless invocation, then parse the final reply.
25
34
 
26
35
  ```ts
27
36
  import {
28
- parseEnvelope,
29
- isTerminal,
30
- isRunHalt,
37
+ parseTurn,
38
+ renderOutputInstruction,
39
+ WORKFLOW_SKILL_PROFILES,
31
40
  } from "@gtrabanco/agentic-workflow-schema";
32
41
 
33
- const output = await runAgentHeadless("Follow the installed SKILL.md for: /workflow-status --json-only");
42
+ const skill = "audit-pr";
43
+ const profile = WORKFLOW_SKILL_PROFILES.find((entry) => entry.skill === skill);
44
+ if (profile === undefined) throw new Error(`Unknown workflow skill: ${skill}`);
34
45
 
35
- const result = parseEnvelope(output); // extracts the LAST fenced ```json block
46
+ const output = await invokeAgent({
47
+ prompt: "Follow the installed skill for /audit-pr.",
48
+ systemAppend: renderOutputInstruction(skill),
49
+ });
50
+
51
+ const result = parseTurn({ skill, text: output, context: { unitId: "12-machine-contract" } });
36
52
  if (!result.ok) throw new Error(result.errors.join("; "));
37
53
 
38
- const env = result.envelope; // fully typed
39
- if (isRunHalt(env)) stopEverythingAndPage(env.blockers);
40
- else if (isTerminal(env.state)) askHuman(env);
41
- else invokeNext(env.next.recommended, env.next.tier); // "strong" | "cheap"
54
+ // result.outcome is SkillOutcome v1; result.envelope is non-null only for v2.
55
+ route(result.outcome.next.intent, result.outcome.next.targets);
42
56
  ```
43
57
 
44
- The parse contract is exactly what the skills promise: **the last fenced
45
- ```` ```json ````…```` ``` ```` block of the final message is the envelope**,
46
- one per turn, all top-level keys always present.
58
+ On a malformed result, re-invoke the *same session once* with `Emit only the
59
+ machine result for the turn above.` and parse again. A second failure is a
60
+ driver-level failure. Do not promote arbitrary prose to structured facts.
47
61
 
48
- Also exported: `extractLastJsonBlock(text)`, `validateEnvelope(value)`,
49
- `ENVELOPE_STATES` (the 11-state enum), `TERMINAL_STATES`, and every field
50
- type. A language-agnostic **JSON Schema** ships too — works on the
51
- `engines.node` minimum (>=18):
62
+ `workflow-status` keeps its native Envelope v2 result. Existing consumers may
63
+ continue to use `parseEnvelope(text)`; new consumers use
64
+ `parseEnvelopeV2Strict(text)` or the uniform `parseTurn({skill, text})`.
52
65
 
53
- ```ts
54
- import { createRequire } from "node:module";
55
- const schema = createRequire(import.meta.url)("@gtrabanco/agentic-workflow-schema/envelope.schema.json");
56
- ```
66
+ ## Compile deterministic state
57
67
 
58
- On Node 20.10+/22, the newer import-attributes form also works:
68
+ The package never reads the filesystem, Git, or a forge. The caller supplies
69
+ the exact documents and repository facts it has already read, so snapshots are
70
+ reproducible and safe to cache by `sourceRevision`.
59
71
 
60
72
  ```ts
61
- import schema from "@gtrabanco/agentic-workflow-schema/envelope.schema.json" with { type: "json" };
62
- ```
73
+ import { compileWorkflowSnapshot } from "@gtrabanco/agentic-workflow-schema";
74
+
75
+ const result = compileWorkflowSnapshot({
76
+ sourceRevision: headSha,
77
+ repository: { branch, headSha, dirty },
78
+ documents: [
79
+ { path: "docs/workflow/REPOSITORY_STATE.md", content: repositoryState },
80
+ { path: "docs/features/ROADMAP.md", content: roadmap },
81
+ { path: "docs/features/12-machine-contract/SPEC.md", content: spec },
82
+ { path: "docs/features/12-machine-contract/progress.md", content: progress },
83
+ ],
84
+ });
85
+ if (!result.ok) throw new Error(result.errors.join("; "));
63
86
 
64
- ## The envelope, field by field
65
-
66
- Every top-level key is **always present** (`required` in the JSON Schema) —
67
- a skill that has nothing to report for a key uses `null` / `[]` / `0`, never
68
- omits it. **Closed** = the exact enum below is exhaustive (the validator
69
- rejects anything else); **open** = free-form, any value of the stated type.
70
-
71
- | Field | Type | Values | Meaning |
72
- |---|---|---|---|
73
- | `skill` | string | open (non-empty) | Which skill produced this envelope. |
74
- | `state` | enum | **closed** — the 11 states below | The routing key. Everything an orchestrator decides starts here. |
75
- | `summary` | string | open | One plain-text sentence: what happened this turn. |
76
- | `unit.type` | enum | **closed** — `feature` · `fix` · `docs` · `none` | What kind of unit the turn worked on. |
77
- | `unit.id` | string\|null | open | The unit's identifier (`NN-slug` for features, `n-topic` for fixes). |
78
- | `unit.issue` | integer\|null | open | The tracking issue number, when the unit is issue-born. |
79
- | `unit.branch` | string\|null | open | The working branch. |
80
- | `phase.current` | string\|null | open (by convention `P1`, `P2`, …) | Phase just worked, for phased (M/L) features. |
81
- | `phase.total` / `phase.completed` | integer\|null | open | Phase counts; `null` for single-pass units. |
82
- | `pr.number` / `pr.url` / `pr.head_sha` | int/str\|null | open | The unit's PR, once it exists. |
83
- | `pr.state` | enum | **closed** — `open` · `merged` · `none` | Merge state lives in the forge, not the roadmap. |
84
- | `pr.merge_ready` | boolean\|null | open | `true` only after an `audit-pr` MERGE-READY verdict on the current head. |
85
- | `pr.ci` | enum | **closed** — `green` · `red` · `pending` · `none` · `null` | `none` = the project has no CI; `null` = not checked this turn. |
86
- | `gates.verification` | enum | **closed** — `green` · `red` · `not-run` · `null` | The project's own gate (type-check + tests + build) as last RUN. |
87
- | `gates.review_pending` / `gates.audit_pending` | boolean\|null | open | Whether the mandatory review / merge audit still has to happen. |
88
- | `findings.fix_now[]` | object array | items: `id`/`file`/`axis`/`class`/`route` (open), `severity` (**closed** — `high`·`med`·`low`), `suggested_tier` (**closed** — `strong`·`cheap`) | Findings that must fold into the CURRENT branch before it advances — one item per unfolded row of the unit's `review-findings.md` fold ledger. |
89
- | `findings.issues_filed[]` | integer array | open | Issue numbers created/updated this turn. |
90
- | `findings.untriaged` | integer ≥ 0 | open | Findings still without a destination — skills whose contract routes everything must report `0`. |
91
- | `findings.decisions_recorded` | integer ≥ 0 | open | Decisions written to `decisions.md`-class records this turn. |
92
- | `blockers[].kind` | enum | **closed** — `dependency` · `issue` · `gate` · `merge-conflict` · `substrate` · `input` | Why the unit (or run) cannot proceed. |
93
- | `blockers[].scope` | enum | **closed** — `unit` · `run` | `run` means stop-the-world: nothing else proceeds either. |
94
- | `blockers[].id` / `blockers[].detail` | string | open | What exactly (a slug, `#N`, a check name) + one line of context. |
95
- | `dependencies.unmet[]` / `dependencies.build_order[]` | string arrays | open | Unmet roadmap/issue refs, and the deepest-first order to build them. |
96
- | `recommendations.product_audit` | boolean | open | `true` when recurring drift suggests the founding assumptions are stale. |
97
- | `recommendations.reason` | string\|null | open | Why (required in practice when the flag is `true`). |
98
- | `needs_input` | object\|null | `question` (open) + `options[]` (open) | Non-null only on `state: NEEDS_INPUT` — the human decision to surface, with concrete options. Nothing was guessed. |
99
- | `next.recommended` | string | open (a skill invocation) | The single best next command. |
100
- | `next.alternatives[]` | string array | open | The other defensible choices. |
101
- | `next.tier` | enum | **closed** — `strong` · `cheap` | Which model class the next step deserves — judgment vs mechanical. |
102
- | `detail` | any | open (skill-specific) | Per-skill payload — e.g. `workflow-status` carries the full project tree (`features`, `fixes`, `startable_now`, `blocked_units`, `crash_recovery`, …) here. |
103
-
104
- ### The `state` routing table (closed — exactly these 11)
105
-
106
- | `state` | Meaning | Orchestrator action |
107
- |---|---|---|
108
- | `OK` | Skill finished its job | Invoke `next.recommended` on `next.tier` |
109
- | `CONTINUE` | Same unit, more of the same work | Re-invoke `next.recommended` (advisory checkpoints also land here — the alternative is listed) |
110
- | `READY_FOR_REVIEW` | Unit finished; mandatory review next | `/review-change` on a strong model, fresh context |
111
- | `READY_FOR_AUDIT` | Review clean | `/audit-pr` (strong) |
112
- | `MERGE_READY` | Audit passed on the current head SHA | Human merges — or your written auto-merge policy does |
113
- | `MERGED` | An authorized auto-merge ran this turn | Next unit: poll `workflow-status` |
114
- | `NEEDS_FIXES` | `findings.fix_now` is non-empty | Fold on-branch (commit AND push), then re-run the gate that emitted them |
115
- | `BLOCKED` | Unmet dependency / external cause | Follow `dependencies.build_order`, or resolve `blockers[]` |
116
- | `NEEDS_INPUT` | A human must decide | Surface `needs_input.question` + `options`; resume with the answer |
117
- | `FAILED` | Retries exhausted | Stop this unit; a human looks |
118
- | `HALT` | Stop-the-world discovery (`blockers[].scope: "run"`) | Stop the whole run; nothing proceeds until a human clears it |
119
-
120
- `isTerminal(state)` covers `NEEDS_INPUT` / `FAILED` / `HALT` (+ human-gated
121
- `MERGE_READY`); `isRunHalt(envelope)` is the `HALT` / run-scoped-blocker check.
122
-
123
- ## Orchestrating with this schema
124
-
125
- Two patterns, both consuming the same envelope. In both, **inject the
126
- canonical system-prompt snippet** into every headless invocation (skills do
127
- not emit the envelope on their own — `workflow-status` is the one exception):
128
-
129
- ```text
130
- Every turn you produce MUST end with exactly one fenced ```json block matching
131
- the orchestration envelope schema (all top-level keys present; values only
132
- from verified command output). Emit nothing after it.
87
+ const { snapshot } = result;
88
+ // snapshot.unit, snapshot.phase, snapshot.provenance,
89
+ // snapshot.unknowns, and snapshot.contradictions are deterministic.
133
90
  ```
134
91
 
135
- …and run the **repair loop** on parse failure — one retry, then fail the step:
92
+ The compiler deliberately reports an unknown current phase instead of guessing
93
+ from ambiguous progress prose. A declared `Status: contradicted` is retained in
94
+ `snapshot.contradictions`; route it to repository-state resolution rather than
95
+ overwriting it.
96
+
97
+ ## Validate or use another language
98
+
99
+ The public validators are `validateEnvelopeV2Strict`, `validateSkillOutcomeV1`,
100
+ and `validateWorkflowSnapshotV1`. Import a JSON Schema when a non-TypeScript
101
+ consumer needs the same boundary:
136
102
 
137
103
  ```ts
138
- async function turn(prompt: string) {
139
- let out = await invokeAgent(prompt, { system: SNIPPET });
140
- let r = parseEnvelope(out);
141
- if (!r.ok) {
142
- out = await invokeAgent("Emit only the machine envelope for the turn above.", { resume: true });
143
- r = parseEnvelope(out);
144
- if (!r.ok) throw new Error(`step failed: no valid envelope (${r.errors.join("; ")})`);
145
- }
146
- return r.envelope;
147
- }
104
+ import schema from "@gtrabanco/agentic-workflow-schema/skill-outcome.schema.json" with { type: "json" };
148
105
  ```
149
106
 
150
- **Pattern 1 — fixed driver loop** (start here): poll the sensor, route on
151
- `state`, repeat. Full skeleton in
152
- [`docs/workflow/ORCHESTRATION.md`](https://github.com/gtrabanco/agentic-workflow/blob/main/docs/workflow/ORCHESTRATION.md),
153
- including the crash-recovery restart protocol (`--last-envelope` hint +
154
- append-only envelope journal).
107
+ For Node versions without JSON import attributes, load the schema with
108
+ `createRequire`. The package supports Node 18 and later.
155
109
 
156
- **Pattern 2 — dynamic workflows** (the conductor pattern): one long-running
157
- conductor context *writes and monitors* the work plan; every worker runs in a
158
- **clean context** and only its envelope flows back up — the conductor never
159
- ingests raw transcripts, which is what lets it stay long-running without
160
- degrading. The envelope is precisely the "structured result" this pattern
161
- needs:
110
+ ## Compatibility and versioning
162
111
 
163
- ```ts
164
- // Conductor: fan out independent units (workflow-status said they're startable
165
- // in parallel and the project declares `worktrees`), read back only envelopes.
166
- const status = await turn("Follow the installed SKILL.md for: /workflow-status --json-only");
167
- const units = status.detail.startable_now as string[];
168
-
169
- const results = await Promise.all(
170
- units.map((u) => turn(`Follow the installed SKILL.md for: /execute-phase ${u}`))
171
- );
172
-
173
- for (const env of results) {
174
- if (isRunHalt(env)) throw new Error(`HALT: ${JSON.stringify(env.blockers)}`);
175
- if (env.state === "NEEDS_FIXES")
176
- await turn(`Fold the fix-now findings on ${env.unit.branch}: ${JSON.stringify(env.findings.fix_now)}`);
177
- }
178
- // The conductor's own context grew by a few KB of envelopes — not by N transcripts.
179
- ```
112
+ `parseTurn` accepts strict v2 first, then only these named legacy repairs:
180
113
 
181
- Safety floor for any driver, fixed loop or dynamic: never skip a
182
- `review_pending`/`audit_pending` gate, never merge on anything but a fresh
183
- `MERGE_READY` bound to the current head SHA, and treat `HALT` as terminal
184
- until a human clears it.
114
+ - a missing `detail` becomes `null`;
115
+ - legacy root `design_candidates` moves to `detail.design_candidates`;
116
+ - the known `audit-pr` form may map a numeric unit id from matching trusted
117
+ driver context, zero issue count to `[]`, and a native gate row to a canonical
118
+ blocker.
185
119
 
186
- ## Versioning
120
+ It refuses a nonzero issue count without identities, an unmatched unit id, and
121
+ unstructured prose. The compatibility diagnostics make every repair visible to
122
+ the driver.
187
123
 
188
- This package's semver tracks the **envelope contract**, not the repo:
189
- breaking schema change (key removed/renamed, state removed) → major;
190
- additive (new optional key, new state) → minor; fixes/docs → patch. When the
191
- `orchestration-envelope` skill changes, this package changes in the same PR.
124
+ Package major versions signal a breaking change to any published contract.
125
+ Additive contract fields are minor; parser, documentation, or implementation
126
+ fixes are patch releases. See
127
+ [programmatic orchestration](../../docs/workflow/ORCHESTRATION.md) for the
128
+ driver protocol.