owenloop 0.4.1 → 0.5.1

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.
Files changed (282) hide show
  1. package/CHANGELOG.md +71 -0
  2. package/README.md +182 -53
  3. package/bin/owenloop.mjs +50 -2
  4. package/dist/packages/work/src/agent/brief.d.ts +176 -0
  5. package/dist/packages/work/src/agent/brief.js +197 -0
  6. package/dist/packages/work/src/agent/loop.d.ts +141 -0
  7. package/dist/packages/work/src/agent/loop.js +669 -0
  8. package/dist/packages/work/src/agent/model-policy.d.ts +49 -0
  9. package/dist/packages/work/src/agent/model-policy.js +138 -0
  10. package/dist/packages/work/src/agent/workdir.d.ts +210 -0
  11. package/dist/packages/work/src/agent/workdir.js +319 -0
  12. package/dist/packages/work/src/bundle/cache.d.ts +92 -0
  13. package/dist/packages/work/src/bundle/cache.js +338 -0
  14. package/dist/packages/work/src/bundle/fetch.d.ts +87 -0
  15. package/dist/packages/work/src/bundle/fetch.js +345 -0
  16. package/dist/packages/work/src/bundle/types.d.ts +164 -0
  17. package/dist/packages/work/src/bundle/types.js +1 -0
  18. package/dist/packages/work/src/consumed-verifier.d.ts +45 -0
  19. package/dist/packages/work/src/consumed-verifier.js +205 -0
  20. package/dist/packages/work/src/credentials/owenloop.d.ts +11 -0
  21. package/dist/packages/work/src/credentials/owenloop.js +28 -0
  22. package/dist/packages/work/src/credentials/reader.d.ts +36 -0
  23. package/dist/packages/work/src/credentials/reader.js +32 -0
  24. package/dist/packages/work/src/credentials/resolve.d.ts +19 -0
  25. package/dist/packages/work/src/credentials/resolve.js +56 -0
  26. package/dist/packages/work/src/exec/instructions.d.ts +99 -0
  27. package/dist/packages/work/src/exec/instructions.js +323 -0
  28. package/dist/packages/work/src/exec/loop.d.ts +40 -0
  29. package/dist/packages/work/src/exec/loop.js +332 -0
  30. package/dist/packages/work/src/exec/payload.d.ts +29 -0
  31. package/dist/packages/work/src/exec/payload.js +54 -0
  32. package/dist/packages/work/src/exec/receipt.d.ts +41 -0
  33. package/dist/packages/work/src/exec/receipt.js +32 -0
  34. package/dist/packages/work/src/exec/runner.d.ts +71 -0
  35. package/dist/packages/work/src/exec/runner.js +256 -0
  36. package/dist/packages/work/src/harness/child-env.d.ts +100 -0
  37. package/dist/packages/work/src/harness/child-env.js +134 -0
  38. package/dist/packages/work/src/harness/claude.d.ts +140 -0
  39. package/dist/packages/work/src/harness/claude.js +837 -0
  40. package/dist/packages/work/src/harness/codex.d.ts +111 -0
  41. package/dist/packages/work/src/harness/codex.js +1024 -0
  42. package/dist/packages/work/src/harness/contract.d.ts +308 -0
  43. package/dist/packages/work/src/harness/contract.js +32 -0
  44. package/dist/packages/work/src/harness/fake.d.ts +59 -0
  45. package/dist/packages/work/src/harness/fake.js +91 -0
  46. package/dist/packages/work/src/harness/jsonrpc-stdio.d.ts +108 -0
  47. package/dist/packages/work/src/harness/jsonrpc-stdio.js +351 -0
  48. package/dist/packages/work/src/harness/permissions.d.ts +75 -0
  49. package/dist/packages/work/src/harness/permissions.js +182 -0
  50. package/dist/packages/work/src/harness/registry.d.ts +47 -0
  51. package/dist/packages/work/src/harness/registry.js +45 -0
  52. package/dist/packages/work/src/harness/session-store.d.ts +181 -0
  53. package/dist/packages/work/src/harness/session-store.js +523 -0
  54. package/dist/packages/work/src/harness/types.d.ts +29 -0
  55. package/dist/packages/work/src/harness/types.js +14 -0
  56. package/dist/packages/work/src/harnesses.d.ts +38 -0
  57. package/dist/packages/work/src/harnesses.js +38 -0
  58. package/dist/packages/work/src/hold/loop.d.ts +36 -0
  59. package/dist/packages/work/src/hold/loop.js +23 -0
  60. package/dist/packages/work/src/hold/mcp.d.ts +75 -0
  61. package/dist/packages/work/src/hold/mcp.js +264 -0
  62. package/dist/packages/work/src/hub/client.d.ts +23 -0
  63. package/dist/packages/work/src/hub/client.js +91 -0
  64. package/dist/packages/work/src/hub/types.d.ts +326 -0
  65. package/dist/packages/work/src/hub/types.js +26 -0
  66. package/dist/packages/work/src/lease/loop.d.ts +94 -0
  67. package/dist/packages/work/src/lease/loop.js +277 -0
  68. package/dist/packages/work/src/main.d.ts +1 -0
  69. package/dist/packages/work/src/main.js +48 -0
  70. package/dist/packages/work/src/mcp/server.d.ts +125 -0
  71. package/dist/packages/work/src/mcp/server.js +320 -0
  72. package/dist/packages/work/src/owenloop-bin.d.ts +1 -0
  73. package/dist/packages/work/src/owenloop-bin.js +18 -0
  74. package/dist/packages/work/src/roles/agent-run.d.ts +124 -0
  75. package/dist/packages/work/src/roles/agent-run.js +529 -0
  76. package/dist/packages/work/src/roles/exec.d.ts +48 -0
  77. package/dist/packages/work/src/roles/exec.js +228 -0
  78. package/dist/packages/work/src/roles/hold.d.ts +72 -0
  79. package/dist/packages/work/src/roles/hold.js +363 -0
  80. package/dist/packages/work/src/roles/join.d.ts +18 -0
  81. package/dist/packages/work/src/roles/join.js +204 -0
  82. package/dist/packages/work/src/roles/lint.d.ts +58 -0
  83. package/dist/packages/work/src/roles/lint.js +234 -0
  84. package/dist/packages/work/src/roles/prepare.d.ts +1 -0
  85. package/dist/packages/work/src/roles/prepare.js +249 -0
  86. package/dist/packages/work/src/roles/release.d.ts +48 -0
  87. package/dist/packages/work/src/roles/release.js +137 -0
  88. package/dist/packages/work/src/roles/sessions.d.ts +61 -0
  89. package/dist/packages/work/src/roles/sessions.js +180 -0
  90. package/dist/packages/work/src/roles/settings.d.ts +6 -0
  91. package/dist/packages/work/src/roles/settings.js +71 -0
  92. package/dist/packages/work/src/roles/shift.d.ts +13 -0
  93. package/dist/packages/work/src/roles/shift.js +250 -0
  94. package/dist/packages/work/src/roles/signals.d.ts +55 -0
  95. package/dist/packages/work/src/roles/signals.js +62 -0
  96. package/dist/packages/work/src/settings/provision.d.ts +21 -0
  97. package/dist/packages/work/src/settings/provision.js +47 -0
  98. package/dist/packages/work/src/settings/settings.d.ts +136 -0
  99. package/dist/packages/work/src/settings/settings.js +155 -0
  100. package/dist/packages/work/src/shift/client.d.ts +24 -0
  101. package/dist/packages/work/src/shift/client.js +124 -0
  102. package/dist/packages/work/src/shift/loop.d.ts +131 -0
  103. package/dist/packages/work/src/shift/loop.js +751 -0
  104. package/dist/packages/work/src/shift/protocol.d.ts +95 -0
  105. package/dist/packages/work/src/shift/protocol.js +24 -0
  106. package/dist/packages/work/src/shift/routing.d.ts +35 -0
  107. package/dist/packages/work/src/shift/routing.js +50 -0
  108. package/dist/packages/work/src/shift/runtime.d.ts +45 -0
  109. package/dist/packages/work/src/shift/runtime.js +337 -0
  110. package/dist/packages/work/src/shift/server.d.ts +23 -0
  111. package/dist/packages/work/src/shift/server.js +716 -0
  112. package/dist/packages/work/src/shift/spawn.d.ts +109 -0
  113. package/dist/packages/work/src/shift/spawn.js +158 -0
  114. package/dist/packages/work/src/shift/state.d.ts +79 -0
  115. package/dist/packages/work/src/shift/state.js +385 -0
  116. package/dist/packages/work/src/submit-proof.d.ts +36 -0
  117. package/dist/packages/work/src/submit-proof.js +93 -0
  118. package/dist/packages/work/src/usage.d.ts +6 -0
  119. package/dist/packages/work/src/usage.js +175 -0
  120. package/dist/src/add.d.ts +189 -0
  121. package/dist/src/add.js +300 -0
  122. package/dist/src/archive.d.ts +97 -0
  123. package/dist/src/archive.js +591 -0
  124. package/dist/src/bundle/index.d.ts +64 -0
  125. package/dist/src/bundle/index.js +508 -0
  126. package/dist/src/bundle/manifest.d.ts +50 -0
  127. package/dist/src/bundle/manifest.js +435 -0
  128. package/dist/src/bundle/runtime.d.ts +26 -0
  129. package/dist/src/bundle/runtime.js +64 -0
  130. package/dist/src/bundle/tar.d.ts +62 -0
  131. package/dist/src/bundle/tar.js +238 -0
  132. package/dist/src/bundle/types.d.ts +105 -0
  133. package/dist/src/bundle/types.js +21 -0
  134. package/dist/{cli.d.ts → src/cli.d.ts} +92 -7
  135. package/dist/src/cli.js +5968 -0
  136. package/dist/{credentials.d.ts → src/credentials.d.ts} +22 -15
  137. package/dist/{credentials.js → src/credentials.js} +35 -31
  138. package/dist/src/crypto/allowed-signers.d.ts +68 -0
  139. package/dist/src/crypto/allowed-signers.js +307 -0
  140. package/dist/src/crypto/canonical.d.ts +8 -0
  141. package/dist/src/crypto/canonical.js +92 -0
  142. package/dist/src/crypto/chain.d.ts +65 -0
  143. package/dist/src/crypto/chain.js +377 -0
  144. package/dist/src/crypto/dsse.d.ts +209 -0
  145. package/dist/src/crypto/dsse.js +282 -0
  146. package/dist/src/crypto/enrollment.d.ts +78 -0
  147. package/dist/src/crypto/enrollment.js +186 -0
  148. package/dist/src/crypto/index.d.ts +48 -0
  149. package/dist/src/crypto/index.js +44 -0
  150. package/dist/src/crypto/keys.d.ts +258 -0
  151. package/dist/src/crypto/keys.js +908 -0
  152. package/dist/src/crypto/org-root.d.ts +33 -0
  153. package/dist/src/crypto/org-root.js +78 -0
  154. package/dist/src/crypto/origin-rules.d.ts +56 -0
  155. package/dist/src/crypto/origin-rules.js +143 -0
  156. package/dist/src/crypto/policy-floor.d.ts +98 -0
  157. package/dist/src/crypto/policy-floor.js +353 -0
  158. package/dist/src/crypto/records.d.ts +316 -0
  159. package/dist/src/crypto/records.js +157 -0
  160. package/dist/src/crypto/scope.d.ts +49 -0
  161. package/dist/src/crypto/scope.js +83 -0
  162. package/dist/src/crypto/ssh.d.ts +171 -0
  163. package/dist/src/crypto/ssh.js +396 -0
  164. package/dist/src/crypto/submission.d.ts +33 -0
  165. package/dist/src/crypto/submission.js +47 -0
  166. package/dist/src/crypto/trust-roots.d.ts +29 -0
  167. package/dist/src/crypto/trust-roots.js +39 -0
  168. package/dist/src/crypto/verify-consumed.d.ts +67 -0
  169. package/dist/src/crypto/verify-consumed.js +259 -0
  170. package/dist/src/crypto/verify-origin.d.ts +50 -0
  171. package/dist/src/crypto/verify-origin.js +151 -0
  172. package/dist/src/crypto/verify-publication.d.ts +60 -0
  173. package/dist/src/crypto/verify-publication.js +150 -0
  174. package/dist/{defs.d.ts → src/defs.d.ts} +24 -1
  175. package/dist/{defs.js → src/defs.js} +181 -61
  176. package/dist/{engine.d.ts → src/engine.d.ts} +105 -9
  177. package/dist/{engine.js → src/engine.js} +251 -47
  178. package/dist/{factory.d.ts → src/factory.d.ts} +16 -0
  179. package/dist/{factory.js → src/factory.js} +16 -4
  180. package/dist/src/global-config.d.ts +59 -0
  181. package/dist/src/global-config.js +84 -0
  182. package/dist/{hub.d.ts → src/hub.d.ts} +280 -31
  183. package/dist/{hub.js → src/hub.js} +493 -52
  184. package/dist/src/index.d.ts +47 -0
  185. package/dist/src/index.js +41 -0
  186. package/dist/src/install.d.ts +538 -0
  187. package/dist/src/install.js +1981 -0
  188. package/dist/src/lock.d.ts +38 -0
  189. package/dist/src/lock.js +325 -0
  190. package/dist/src/mcp/serve.d.ts +109 -0
  191. package/dist/{mcp → src/mcp}/serve.js +335 -75
  192. package/dist/{mcp → src/mcp}/server.d.ts +6 -9
  193. package/dist/{mcp → src/mcp}/server.js +18 -10
  194. package/dist/{model.d.ts → src/model.d.ts} +15 -0
  195. package/dist/{model.js → src/model.js} +112 -2
  196. package/dist/src/order-resolver.d.ts +184 -0
  197. package/dist/src/order-resolver.js +252 -0
  198. package/dist/src/package-version.d.ts +10 -0
  199. package/dist/src/package-version.js +42 -0
  200. package/dist/{paths.d.ts → src/paths.d.ts} +14 -1
  201. package/dist/{paths.js → src/paths.js} +18 -0
  202. package/dist/src/schemas/enrollment-grant.v1.schema.json +90 -0
  203. package/dist/src/schemas/index.d.ts +1416 -0
  204. package/dist/src/schemas/index.js +31 -0
  205. package/dist/src/schemas/order.v1.schema.json +106 -0
  206. package/dist/src/schemas/origin.v1.schema.json +68 -0
  207. package/dist/src/schemas/policy-floor.v1.schema.json +29 -0
  208. package/dist/src/schemas/publication.v1.schema.json +31 -0
  209. package/dist/src/schemas/revocation.v1.schema.json +39 -0
  210. package/dist/src/schemas/submission.v1.schema.json +61 -0
  211. package/dist/src/store/def-source.d.ts +52 -0
  212. package/dist/src/store/def-source.js +335 -0
  213. package/dist/src/store/index-file.d.ts +69 -0
  214. package/dist/src/store/index-file.js +151 -0
  215. package/dist/src/store/index.d.ts +27 -0
  216. package/dist/src/store/index.js +22 -0
  217. package/dist/src/store/ingestor.d.ts +43 -0
  218. package/dist/src/store/ingestor.js +211 -0
  219. package/dist/src/store/install.d.ts +228 -0
  220. package/dist/src/store/install.js +555 -0
  221. package/dist/src/store/instruction-source.d.ts +49 -0
  222. package/dist/src/store/instruction-source.js +298 -0
  223. package/dist/src/store/origin-evidence.d.ts +21 -0
  224. package/dist/src/store/origin-evidence.js +66 -0
  225. package/dist/src/store/pre-commit-verifier.d.ts +68 -0
  226. package/dist/src/store/pre-commit-verifier.js +418 -0
  227. package/dist/src/store/resolve.d.ts +138 -0
  228. package/dist/src/store/resolve.js +363 -0
  229. package/dist/src/store/types.d.ts +288 -0
  230. package/dist/src/store/types.js +356 -0
  231. package/dist/{types.d.ts → src/types.d.ts} +58 -24
  232. package/dist/{untar.d.ts → src/untar.d.ts} +8 -23
  233. package/dist/src/untar.js +38 -0
  234. package/dist/{util.d.ts → src/util.d.ts} +3 -2
  235. package/dist/{util.js → src/util.js} +3 -2
  236. package/dist/{owenwork.d.ts → src/work-settings.d.ts} +22 -22
  237. package/dist/{owenwork.js → src/work-settings.js} +27 -27
  238. package/docs/agent-runner.md +86 -0
  239. package/docs/authoring.md +150 -59
  240. package/docs/bundles.md +250 -0
  241. package/docs/cli.md +1758 -163
  242. package/docs/crypto.md +816 -0
  243. package/docs/design.md +374 -52
  244. package/docs/embedding.md +135 -27
  245. package/docs/wire-contracts.md +380 -0
  246. package/examples/workflows/{command-worker.yaml → command-executor.yaml} +15 -15
  247. package/examples/workflows/compile-dev-playbook.yaml +338 -0
  248. package/examples/workflows/judges/gate-sharpness.md +39 -0
  249. package/examples/workflows/judges/security.md +34 -0
  250. package/package.json +22 -8
  251. package/plugins/claude-code/.claude-plugin/marketplace.json +14 -0
  252. package/plugins/claude-code/plugin/.claude-plugin/plugin.json +8 -0
  253. package/plugins/claude-code/plugin/.mcp.json +14 -0
  254. package/plugins/claude-code/plugin/hooks/hooks.json +26 -0
  255. package/plugins/claude-code/plugin/hooks/session-end.sh +40 -0
  256. package/plugins/claude-code/plugin/hooks/session-start.sh +52 -0
  257. package/plugins/claude-code/plugin/skills/author/SKILL.md +181 -0
  258. package/plugins/claude-code/plugin/skills/conduct/SKILL.md +106 -0
  259. package/plugins/claude-code/plugin/skills/shift/SKILL.md +105 -0
  260. package/plugins/codex/.agents/plugins/marketplace.json +21 -0
  261. package/plugins/codex/plugins/owenloop/.codex-plugin/plugin.json +7 -0
  262. package/plugins/codex/plugins/owenloop/.mcp.json +20 -0
  263. package/plugins/codex/plugins/owenloop/hooks/hooks.json +26 -0
  264. package/plugins/codex/plugins/owenloop/hooks/session-end.sh +40 -0
  265. package/plugins/codex/plugins/owenloop/hooks/session-start.sh +52 -0
  266. package/plugins/codex/plugins/owenloop/skills/author/SKILL.md +181 -0
  267. package/plugins/codex/plugins/owenloop/skills/conduct/SKILL.md +106 -0
  268. package/plugins/codex/plugins/owenloop/skills/shift/SKILL.md +105 -0
  269. package/dist/add.d.ts +0 -384
  270. package/dist/add.js +0 -834
  271. package/dist/cli.js +0 -3270
  272. package/dist/index.d.ts +0 -32
  273. package/dist/index.js +0 -23
  274. package/dist/lock.d.ts +0 -80
  275. package/dist/lock.js +0 -217
  276. package/dist/mcp/serve.d.ts +0 -84
  277. package/dist/untar.js +0 -164
  278. /package/dist/{schema.d.ts → src/schema.d.ts} +0 -0
  279. /package/dist/{schema.js → src/schema.js} +0 -0
  280. /package/dist/{store.d.ts → src/store.d.ts} +0 -0
  281. /package/dist/{store.js → src/store.js} +0 -0
  282. /package/dist/{types.js → src/types.js} +0 -0
@@ -2,15 +2,12 @@
2
2
  * A minimal, dependency-light MCP server core — newline-delimited JSON-RPC 2.0
3
3
  * over stdio, hand-rolled (O2 plan Decision 1).
4
4
  *
5
- * PROVENANCE: this is a near-verbatim copy of owenwork's proven
6
- * `src/mcp/server.ts` transport core (`createMcpServer` / `pumpStdin` /
7
- * `textResult` / the error-code consts / `LineStream`). Only this header was
8
- * changed. Consolidating the two copies into one shared package is DELIBERATELY
9
- * DEFERRED (per the O2 brief): owenloop and owenwork are separate packages with
10
- * no shared dependency today, and duplicating ~400 lines of a stable, test-pinned
11
- * transport is cheaper than standing up a shared module for it now. owenloop's
12
- * own `test/mcpcore.test.ts` re-proves the copied behavior against this file, so
13
- * drift is caught here rather than assumed.
5
+ * PROVENANCE: this transport core was ported from the execution subsystem's
6
+ * proven `src/mcp/server.ts` implementation (`createMcpServer` / `pumpStdin` /
7
+ * `textResult` / the error-code consts / `LineStream`). The implementation now
8
+ * lives in the root package so engine and execution commands ship together.
9
+ * `test/mcpcore.test.ts` re-proves the transport behavior against this file,
10
+ * so later changes are caught rather than assumed.
14
11
  *
15
12
  * WHY hand-rolled, not `@modelcontextprotocol/sdk`: this repo's posture is two
16
13
  * runtime deps (`@cfworker/json-schema` + `yaml`). The SDK drags zod and a
@@ -47,7 +44,7 @@ const RECOGNIZED_PROTOCOL_VERSIONS = new Set([
47
44
  '2024-11-05',
48
45
  '2025-03-26',
49
46
  '2025-06-18',
50
- '2025-11-05',
47
+ '2025-11-25',
51
48
  ]);
52
49
  /** The version we answer with when the client's is missing or unrecognized. */
53
50
  const OUR_PROTOCOL_VERSION = '2025-06-18';
@@ -63,6 +60,12 @@ export function textResult(value, isError = false) {
63
60
  }
64
61
  export function createMcpServer(opts) {
65
62
  const err = opts.err ?? (() => { });
63
+ // A plugin supplies its manifest version through the MCP environment. An
64
+ // absent expectation leaves hand-run and headless MCP servers unchanged;
65
+ // only a supplied value can describe a plugin/CLI drift. The comparison is
66
+ // deferred to tools/call instead of rejecting startup, because startup
67
+ // rejection surfaces as the opaque "server transport closed unexpectedly".
68
+ const expectedPluginVersion = process.env['OWENLOOP_PLUGIN_VERSION'];
66
69
  const tools = new Map();
67
70
  for (const t of opts.tools)
68
71
  tools.set(t.name, t);
@@ -130,6 +133,11 @@ export function createMcpServer(opts) {
130
133
  },
131
134
  };
132
135
  try {
136
+ // Keep the check at the transport choke point so every registered tool is
137
+ // covered, but leave unknown tools on the normal -32601 path above.
138
+ if (expectedPluginVersion !== undefined && expectedPluginVersion !== opts.version) {
139
+ throw new Error(`owenloop plugin ${expectedPluginVersion} does not match owenloop CLI ${opts.version}. Run: owenloop setup`);
140
+ }
133
141
  const result = await reg.handler(args, ctx);
134
142
  // A CLIENT-cancelled call sends NO response frame (the JSON-RPC/MCP
135
143
  // cancel contract). A close-cancelled call still replies — see InFlight.
@@ -431,3 +431,18 @@ export declare function applyOutcome(def: WorkflowDef, arts: Map<string, Artifac
431
431
  * Pure — no store, no engine, no IO.
432
432
  */
433
433
  export declare function modelCheck(def: WorkflowDef, opts?: CheckOptions): CheckReport;
434
+ /**
435
+ * The single "definite defect" predicate over a modelCheck `report`, shared by
436
+ * every acceptance gate that accepts or rejects a def (`check`, `add`'s GitHub
437
+ * route, `add`'s workflow-bundle route, `push`). A pure function of the report
438
+ * object — it does NOT read or change how any caller seeded its modelCheck
439
+ * (install/push seed `assumeProvided: true`; check seeds
440
+ * `assumeProvided: !strictInputs`).
441
+ *
442
+ * invariant violations and structurally-dead steps are ALWAYS definite (sound
443
+ * regardless of bounds); a true deadlock counts ONLY when the search was
444
+ * exhaustive (`!bounded`) because a tight maxCollectionSize cap can manufacture
445
+ * a spurious one. `unreachedSteps` is deliberately EXCLUDED — it is a bounds
446
+ * artifact ("raise --max-states/--max-depth"), never a definite defect.
447
+ */
448
+ export declare function hasDefiniteCheckDefect(report: CheckReport): boolean;
@@ -386,6 +386,66 @@ function idleEligible(step, arts, time) {
386
386
  return false; // allGreen owns this condition
387
387
  return true;
388
388
  }
389
+ /**
390
+ * Is a `calls:` step's gate ready in this state — i.e. is every parent artifact
391
+ * wired into `callsInputs` green?
392
+ *
393
+ * This is the model-side mirror of `Engine.callsGateReady` (engine.ts) and MUST
394
+ * read the same field it does: `callsInputs`, the mapping {child input name →
395
+ * parent artifact name}. A `calls:` step's `StepDef.consumes` is ALWAYS `[]`
396
+ * (`buildStep` hardcodes it — "eligibility is engine-managed", defs.ts), so
397
+ * gating on `plainConsumes(step)` is vacuously true for every `calls:` step and
398
+ * is NOT a gate at all. An empty `callsInputs` gate is genuinely always ready —
399
+ * same rule the engine applies.
400
+ */
401
+ function callsGateReady(step, arts) {
402
+ const gateStems = Object.values(step.callsInputs ?? {});
403
+ return gateStems.every((s) => isGreen(arts.get(s)));
404
+ }
405
+ /**
406
+ * The `calls:` discharges available in THIS state — one firing per `calls:` step
407
+ * whose gate is ready (the engine would provision/re-provide the child now) and
408
+ * whose produced artifact is still a debt (the child has not yet discharged it).
409
+ *
410
+ * Why this exists: `eligibleFirings` skips every `calls:` step (M2 — the engine
411
+ * spawns a child rather than issuing a worker order), and `modelCheck` explores
412
+ * ONE def with no child engine attached. Without modeling the handoff, the
413
+ * exploration mistakes "waiting on a child I can't see" for "structurally dead",
414
+ * which made `hasDefiniteCheckDefect` reject EVERY `calls:`-using def at install
415
+ * time — including the repo's own `examples/workflows/provisioned-delivery.yaml`.
416
+ *
417
+ * This is a TRANSITION, not a reclassification. That distinction is the whole
418
+ * point: an earlier version of this fix was a def-wide boolean OR'd into the
419
+ * deadlock/stall branch, which relabelled EVERY zero-firing state in the def —
420
+ * so one unrelated `calls:` step anywhere in a def suppressed every genuine
421
+ * deadlock in it. Modeling the discharge as a successor state instead keeps the
422
+ * classification strictly per-state: the child greens ITS OWN artifact and
423
+ * nothing else, so a deadlock elsewhere in the same def is still reached and
424
+ * still reported.
425
+ *
426
+ * Kept separate from `eligibleFirings` deliberately: that function is the LIVE
427
+ * engine scheduler and a `calls:` step must never become a worker order. These
428
+ * firings are consumed only by `modelCheck`'s successor expansion.
429
+ */
430
+ function callsDischargeFirings(def, arts) {
431
+ const firings = [];
432
+ for (const step of def.steps) {
433
+ if (!step.calls)
434
+ continue;
435
+ if (!callsGateReady(step, arts))
436
+ continue;
437
+ const outs = plainOutputs(step).filter((p) => isDebt(arts.get(p)));
438
+ if (outs.length === 0)
439
+ continue;
440
+ firings.push({
441
+ step: step.name,
442
+ key: '',
443
+ inputs: Object.values(step.callsInputs ?? {}),
444
+ outputs: outs,
445
+ });
446
+ }
447
+ return firings;
448
+ }
389
449
  /**
390
450
  * Every firing eligible *right now* — inputs satisfied AND an owed/rejected
391
451
  * output to discharge. This is the scheduling gate (§11.4): necessary, not
@@ -1628,7 +1688,7 @@ function eligibleOutcomes(def, arts, firing) {
1628
1688
  return ['green'];
1629
1689
  // §24: a judge firing's own verdict is against the judged stem, not against a
1630
1690
  // produce of its own (judge steps declare `produces: []`). Model the two verbs
1631
- // the judge agent can issue (green/reject, Q2) as their own outcomes, entirely
1691
+ // the judge Step Agent can issue (green/reject, Q2) as their own outcomes, entirely
1632
1692
  // separate from the producer-outcome branches below.
1633
1693
  if (step.judges) {
1634
1694
  // §26: if this is the last pending judge and approving would flip the
@@ -1648,6 +1708,16 @@ function eligibleOutcomes(def, arts, firing) {
1648
1708
  }
1649
1709
  return ['judge-approve', 'judge-reject'];
1650
1710
  }
1711
+ // M2: a `calls:` firing is the machine handing off to a child instance, not a
1712
+ // worker order. The only outcome the PARENT def can observe is the child's
1713
+ // terminal outcome cascading up as a green on the calls artifact. None of the
1714
+ // worker-verb outcomes apply: there is no worker to schema-reject a value, no
1715
+ // consumer to judgment-reject (a calls: step declares `consumes: []`), and a
1716
+ // calls: produce may carry neither `judges:` nor `group:` (rejected by
1717
+ // `buildStep`). Modeling only the green keeps the successor set faithful to
1718
+ // what the engine can actually do here.
1719
+ if (step.calls)
1720
+ return ['green'];
1651
1721
  const stem = collectionStem(step);
1652
1722
  const outPath = firing.outputs[0] ?? '';
1653
1723
  const el = parseElement(outPath);
@@ -2029,7 +2099,28 @@ export function modelCheck(def, opts = {}) {
2029
2099
  }
2030
2100
  continue; // done states have no successors
2031
2101
  }
2032
- const firings = status.eligible;
2102
+ // WS-6 — model the `calls:` handoff as a real TRANSITION, not a
2103
+ // reclassification. M2 makes `eligibleFirings` skip every `calls:` step (the
2104
+ // engine spawns a child to discharge it, so it must never become a worker
2105
+ // firing), and the model has no child engine attached. Left unmodeled, a
2106
+ // state waiting on a child reaches the classification branch below with zero
2107
+ // firings and gets called a TRUE deadlock — asserting this report's own
2108
+ // documented claim ("no path to completion even at unlimited attempts"),
2109
+ // which is false: the engine does spawn the child and the debt is
2110
+ // discharged.
2111
+ //
2112
+ // The child is modeled as a single opaque green of the calls artifact — the
2113
+ // only thing the parent def can observe about it. `callsDischargeFirings`
2114
+ // gates per-step on `callsInputs` (the same field `Engine.callsGateReady`
2115
+ // reads), so a `calls:` step whose gate is NOT green yields no firing and
2116
+ // the state is classified on its own merits. Because the discharge greens
2117
+ // only that step's own artifact, an unrelated deadlock elsewhere in the same
2118
+ // def is still reached and still reported.
2119
+ //
2120
+ // `eligibleFirings` (the LIVE engine scheduler) and `hasDefiniteCheckDefect`
2121
+ // (shared by check / add / push / install) are deliberately untouched.
2122
+ const callsFirings = callsDischargeFirings(def, node.arts);
2123
+ const firings = [...status.eligible, ...callsFirings];
2033
2124
  // Non-done state with no eligible firings: classify by recomputing eligibility
2034
2125
  // as if every freeze/stall were lifted (unlimited attempts). If a producer
2035
2126
  // would re-arm → an EXPECTED stall state (a by-design brake). If not → a
@@ -2103,3 +2194,22 @@ export function modelCheck(def, opts = {}) {
2103
2194
  }
2104
2195
  return report;
2105
2196
  }
2197
+ /**
2198
+ * The single "definite defect" predicate over a modelCheck `report`, shared by
2199
+ * every acceptance gate that accepts or rejects a def (`check`, `add`'s GitHub
2200
+ * route, `add`'s workflow-bundle route, `push`). A pure function of the report
2201
+ * object — it does NOT read or change how any caller seeded its modelCheck
2202
+ * (install/push seed `assumeProvided: true`; check seeds
2203
+ * `assumeProvided: !strictInputs`).
2204
+ *
2205
+ * invariant violations and structurally-dead steps are ALWAYS definite (sound
2206
+ * regardless of bounds); a true deadlock counts ONLY when the search was
2207
+ * exhaustive (`!bounded`) because a tight maxCollectionSize cap can manufacture
2208
+ * a spurious one. `unreachedSteps` is deliberately EXCLUDED — it is a bounds
2209
+ * artifact ("raise --max-states/--max-depth"), never a definite defect.
2210
+ */
2211
+ export function hasDefiniteCheckDefect(report) {
2212
+ return (report.invariantViolations.length > 0 ||
2213
+ report.structurallyDeadSteps.length > 0 ||
2214
+ (!report.bounded && report.deadlocks.length > 0));
2215
+ }
@@ -0,0 +1,184 @@
1
+ /**
2
+ * Reference-mode order resolution (WP-B1).
3
+ *
4
+ * Orders are REFERENCE packets: they carry a `defDigest` identifying the
5
+ * pinned definition snapshot that emitted them, plus routing fields
6
+ * (`workflow`/`step`/`key`/...), the dynamic `consumes` values, and the
7
+ * dynamic `owes` feedback — but NEVER the authored static instruction bytes
8
+ * (the prompt body, the command string, or static acceptance text).
9
+ *
10
+ * This module is the one boundary that turns a reference back into static
11
+ * instructions: `(defDigest, step, key)` → the exact authored bytes
12
+ * `{ prompt?, command?, acceptance? }`. The CLI and the embedded/library path
13
+ * use the SAME resolver implementation — there is no second, local-only
14
+ * resolution path and no verify-mode branch. An unknown digest is a named
15
+ * refusal ({@link UnknownDefDigestError}) thrown before any caller can
16
+ * execute a prompt or command; there is no fallback to definition-name
17
+ * lookup and no empty-instructions return for an unknown digest.
18
+ *
19
+ * Scope: {@link createDefInstructionSource} resolves over loaded, validated
20
+ * `WorkflowDef` objects. The content-addressed store adapter lives in
21
+ * `src/store/instruction-source.ts`; it primes asynchronously, verifies local
22
+ * bundle objects, and then serves the same synchronous lookup seam. Neither
23
+ * source changes the `Order` shape or the resolver's callers.
24
+ */
25
+ import type { Order, WorkflowDef } from './types.ts';
26
+ /** A reference to a step's static instructions inside a pinned definition. */
27
+ export interface OrderInstructionRef {
28
+ /** Identity of the definition snapshot that emitted the order. */
29
+ defDigest: string;
30
+ /** The step name (synthesized judge step names resolve too — they are ordinary StepDefs in the compiled snapshot). */
31
+ step: string;
32
+ /** The binding key: '' for plain/reduce/collection steps, the element path for map elements. */
33
+ key: string;
34
+ }
35
+ /**
36
+ * The exact authored instruction bytes for one `(defDigest, step, key)`
37
+ * reference. Every field is optional because the source may not carry each:
38
+ * a command step has no agent prompt body semantics the other way around,
39
+ * and the current engine grammar has no standalone authored acceptance —
40
+ * only an injected WP-A3-compatible source or a verified fixture supplies
41
+ * `acceptance`. The resolver returns the authored bytes UNTRANSFORMED: no
42
+ * trimming, no newline normalization, no YAML re-serialization. It never
43
+ * fabricates a value that is absent.
44
+ */
45
+ export interface ResolvedInstructions {
46
+ /** The authored prompt body bytes, exactly as authored. */
47
+ prompt?: string;
48
+ /** The authored command string bytes, exactly as authored. */
49
+ command?: string;
50
+ /** Optional static, source-owned acceptance instruction bytes. Never derived from the artifact lifecycle state. */
51
+ acceptance?: string;
52
+ }
53
+ /**
54
+ * A resolved instruction record also carries the authored step metadata needed
55
+ * to materialize runtime placeholders. `maxAttempts` is required even when a
56
+ * prompt is absent so every source has one explicit, deterministic contract for
57
+ * `${MAX_ATTEMPTS}` rather than silently falling back to an empty string.
58
+ */
59
+ export interface ResolvedInstructionRecord extends ResolvedInstructions {
60
+ maxAttempts: number;
61
+ }
62
+ /** The typed result of a source lookup. Missing and ambiguous references are distinct. */
63
+ export type OrderInstructionLookup = {
64
+ status: 'resolved';
65
+ instructions: ResolvedInstructionRecord;
66
+ } | {
67
+ status: 'unknown-digest';
68
+ } | {
69
+ status: 'unknown-step';
70
+ } | {
71
+ status: 'ambiguous-step';
72
+ };
73
+ /**
74
+ * The narrow digest/instruction source seam. WP-B1 ships the loaded-definition
75
+ * adapter ({@link createDefInstructionSource}); WP-A3 can later inject an
76
+ * implementation backed by its content-addressed store (canonical bundle
77
+ * digests and verified instructions) without touching the engine's order
78
+ * shape or callers.
79
+ */
80
+ export interface OrderInstructionSource {
81
+ /**
82
+ * The identity digest for a loaded definition. Called by `buildOrder` for
83
+ * the exact pinned snapshot it emits against; the adapter registers that
84
+ * snapshot under the returned digest as a side effect, so the order stays
85
+ * resolvable after the live definition map changes.
86
+ */
87
+ digestOf(def: WorkflowDef): string;
88
+ /**
89
+ * Resolve one reference to its exact instruction bytes and materialization
90
+ * metadata. The result must distinguish an unknown digest from a known
91
+ * digest with a missing step; the resolver reserves UnknownDefDigestError
92
+ * for the former.
93
+ */
94
+ lookup(ref: OrderInstructionRef): OrderInstructionLookup;
95
+ }
96
+ /**
97
+ * The named refusal for an unresolvable digest: thrown at the resolver
98
+ * boundary when no verified definition/instruction record exists for the
99
+ * digest, before any caller can execute an agent prompt or command. Carries
100
+ * the rejected digest on the instance and names it in the message. Never
101
+ * falls back to name lookup and never returns empty instructions instead.
102
+ */
103
+ export declare class UnknownDefDigestError extends Error {
104
+ readonly name = "UnknownDefDigestError";
105
+ readonly defDigest: string;
106
+ constructor(defDigest: string);
107
+ }
108
+ /**
109
+ * The digest is known, but the referenced step is not present in that
110
+ * definition snapshot. This is deliberately distinct from
111
+ * {@link UnknownDefDigestError}: a malformed reference must not claim that a
112
+ * verified definition digest is unknown.
113
+ */
114
+ export declare class UnknownInstructionError extends Error {
115
+ readonly name = "UnknownInstructionError";
116
+ readonly defDigest: string;
117
+ readonly step: string;
118
+ readonly key: string;
119
+ constructor(ref: OrderInstructionRef);
120
+ }
121
+ /** A bundle digest contains the referenced step name in more than one workflow. */
122
+ export declare class AmbiguousInstructionError extends Error {
123
+ readonly name = "AmbiguousInstructionError";
124
+ readonly defDigest: string;
125
+ readonly step: string;
126
+ readonly key: string;
127
+ constructor(ref: OrderInstructionRef);
128
+ }
129
+ /**
130
+ * Create the WP-B1 loaded-definition adapter: an in-memory
131
+ * {@link OrderInstructionSource} over validated `WorkflowDef` objects. Not a
132
+ * content-addressed store — a temporary implementation of the seam that a
133
+ * WP-A3 source replaces by injection. Definitions are indexed by digest on
134
+ * demand: {@link OrderInstructionSource.digestOf} registers the exact
135
+ * snapshot it digested, and `add` registers every seed def up front, so a
136
+ * seeded source can resolve orders without `buildOrder` ever touching it
137
+ * (e.g. injected-source tests).
138
+ */
139
+ export declare function createDefInstructionSource(seeds?: Iterable<WorkflowDef>): OrderInstructionSource;
140
+ /** The runtime fields an order contributes to placeholder materialization. */
141
+ export interface OrderRuntimeVars {
142
+ workflow: string;
143
+ run: string;
144
+ key: string;
145
+ index?: number;
146
+ }
147
+ /**
148
+ * The runtime placeholder substitution for an order's authored prompt body.
149
+ * Same semantics as the engine's pre-reference-mode rendering: every
150
+ * `${WORKFLOW}`/`${RUN}`/`${STEP}`/`${KEY}`/`${INDEX}`/`${MAX_ATTEMPTS}`
151
+ * occurrence is replaced; an unknown placeholder name is left unchanged,
152
+ * byte for byte. Lives here (not on the low-level source) because the
153
+ * values are runtime fields of the reference order, not authored bytes —
154
+ * the source returns the body as authored, and materialization happens at
155
+ * resolution time, never back onto the order. `maxAttempts` is the AUTHORED
156
+ * step default (from the resolved step, not the order) — matching the old
157
+ * `buildOrder` semantics exactly, including the step-generic note below.
158
+ */
159
+ export declare function substituteOrderVars(body: string, runtime: OrderRuntimeVars, opts?: {
160
+ step?: string;
161
+ maxAttempts?: number;
162
+ }): string;
163
+ /**
164
+ * An order-facing resolver over an {@link OrderInstructionSource} — the one
165
+ * resolution path both the CLI and embedded callers use. The low-level
166
+ * boundary (`resolve`) calls the source's three-key lookup and raises the
167
+ * named refusal; the convenience layer (`resolveOrder`) materializes the
168
+ * runtime placeholders on top of the exact authored bytes. Neither method
169
+ * ever mutates the stored/emitted order.
170
+ */
171
+ export declare class OrderResolver {
172
+ private readonly source;
173
+ constructor(source: OrderInstructionSource);
174
+ /** The low-level `(defDigest, step, key)` boundary: exact authored bytes or a typed refusal. */
175
+ resolve(ref: OrderInstructionRef): ResolvedInstructionRecord;
176
+ /**
177
+ * Resolve a reference-mode order's static instructions and materialize the
178
+ * runtime placeholders (`${WORKFLOW}`/`${RUN}`/`${STEP}`/`${KEY}`/
179
+ * `${INDEX}`/`${MAX_ATTEMPTS}`) in the prompt using the order's own
180
+ * runtime fields. Returns a fresh object — the order itself is never
181
+ * modified, and the materialized prompt is never written back onto it.
182
+ */
183
+ resolveOrder(order: Order): ResolvedInstructions;
184
+ }
@@ -0,0 +1,252 @@
1
+ /**
2
+ * Reference-mode order resolution (WP-B1).
3
+ *
4
+ * Orders are REFERENCE packets: they carry a `defDigest` identifying the
5
+ * pinned definition snapshot that emitted them, plus routing fields
6
+ * (`workflow`/`step`/`key`/...), the dynamic `consumes` values, and the
7
+ * dynamic `owes` feedback — but NEVER the authored static instruction bytes
8
+ * (the prompt body, the command string, or static acceptance text).
9
+ *
10
+ * This module is the one boundary that turns a reference back into static
11
+ * instructions: `(defDigest, step, key)` → the exact authored bytes
12
+ * `{ prompt?, command?, acceptance? }`. The CLI and the embedded/library path
13
+ * use the SAME resolver implementation — there is no second, local-only
14
+ * resolution path and no verify-mode branch. An unknown digest is a named
15
+ * refusal ({@link UnknownDefDigestError}) thrown before any caller can
16
+ * execute a prompt or command; there is no fallback to definition-name
17
+ * lookup and no empty-instructions return for an unknown digest.
18
+ *
19
+ * Scope: {@link createDefInstructionSource} resolves over loaded, validated
20
+ * `WorkflowDef` objects. The content-addressed store adapter lives in
21
+ * `src/store/instruction-source.ts`; it primes asynchronously, verifies local
22
+ * bundle objects, and then serves the same synchronous lookup seam. Neither
23
+ * source changes the `Order` shape or the resolver's callers.
24
+ */
25
+ import { createHash } from 'node:crypto';
26
+ /**
27
+ * The named refusal for an unresolvable digest: thrown at the resolver
28
+ * boundary when no verified definition/instruction record exists for the
29
+ * digest, before any caller can execute an agent prompt or command. Carries
30
+ * the rejected digest on the instance and names it in the message. Never
31
+ * falls back to name lookup and never returns empty instructions instead.
32
+ */
33
+ export class UnknownDefDigestError extends Error {
34
+ name = 'UnknownDefDigestError';
35
+ defDigest;
36
+ constructor(defDigest) {
37
+ super(`unknown defDigest '${defDigest}' — no verified definition/instruction record exists for this digest; refusing to resolve instructions`);
38
+ this.defDigest = defDigest;
39
+ }
40
+ }
41
+ /**
42
+ * The digest is known, but the referenced step is not present in that
43
+ * definition snapshot. This is deliberately distinct from
44
+ * {@link UnknownDefDigestError}: a malformed reference must not claim that a
45
+ * verified definition digest is unknown.
46
+ */
47
+ export class UnknownInstructionError extends Error {
48
+ name = 'UnknownInstructionError';
49
+ defDigest;
50
+ step;
51
+ key;
52
+ constructor(ref) {
53
+ super(`unknown instruction step '${ref.step}' for defDigest '${ref.defDigest}' and key '${ref.key}'`);
54
+ this.defDigest = ref.defDigest;
55
+ this.step = ref.step;
56
+ this.key = ref.key;
57
+ }
58
+ }
59
+ /** A bundle digest contains the referenced step name in more than one workflow. */
60
+ export class AmbiguousInstructionError extends Error {
61
+ name = 'AmbiguousInstructionError';
62
+ defDigest;
63
+ step;
64
+ key;
65
+ constructor(ref) {
66
+ super(`ambiguous instruction step '${ref.step}' for defDigest '${ref.defDigest}' and key '${ref.key}' — multiple workflows in the verified bundle define that step`);
67
+ this.defDigest = ref.defDigest;
68
+ this.step = ref.step;
69
+ this.key = ref.key;
70
+ }
71
+ }
72
+ /**
73
+ * Digest a compiled definition's instruction-bearing content. This is the
74
+ * WP-B1 FALLBACK identity: a full (untruncated) sha256 over a canonical JSON
75
+ * projection of exactly the fields an order's resolution depends on —
76
+ * `name`, `engine`, `inputs`, `outputs`, `invariants`, `x`, `executors`,
77
+ * and every step's authored instruction/routing fields. Deliberately
78
+ * EXCLUDED: the source-location-only metadata `WorkflowDef.dir` (identical
79
+ * content loaded from a different directory keeps the same identity) and the
80
+ * `@internal` `_includes` (always absent on a fully-expanded def anyway).
81
+ *
82
+ * This is NOT hashDef's 16-hex accidental-drift hash, and it is not an
83
+ * adversarial trust claim — WP-A3's content-addressed store replaces it with
84
+ * canonical bundle digests through the same {@link OrderInstructionSource}
85
+ * seam. The projection is stable: JSON.stringify preserves insertion order,
86
+ * and buildDef/loadDefFile build fields in one deterministic order.
87
+ */
88
+ export function defInstructionDigest(def) {
89
+ const stepProjection = (s) => ({
90
+ name: s.name,
91
+ consumes: s.consumes.map((c) => c.raw),
92
+ produces: s.produces.map((p) => p.raw),
93
+ ...(s.generates !== undefined ? { generates: s.generates.map((g) => g.raw) } : {}),
94
+ invalidates: s.invalidates,
95
+ cadence: s.cadence,
96
+ maxRunsPerDay: s.maxRunsPerDay,
97
+ parallel: s.parallel,
98
+ maxAttempts: s.maxAttempts,
99
+ maxSchemaFailures: s.maxSchemaFailures,
100
+ ...(s.model !== undefined ? { model: s.model } : {}),
101
+ ...(s.executor !== undefined ? { executor: s.executor } : {}),
102
+ ...(s.command !== undefined ? { command: s.command } : {}),
103
+ ...(s.spec !== undefined ? { spec: s.spec } : {}),
104
+ ...(s.workdir !== undefined ? { workdir: s.workdir } : {}),
105
+ ...(s.workdirFrom !== undefined ? { workdirFrom: s.workdirFrom } : {}),
106
+ ...(s.terminal !== undefined ? { terminal: s.terminal } : {}),
107
+ ...(s.effect !== undefined ? { effect: s.effect } : {}),
108
+ ...(s.on !== undefined ? { on: s.on } : {}),
109
+ ...(s.idleAfterMs !== undefined ? { idleAfterMs: s.idleAfterMs } : {}),
110
+ ...(s.reapTtlMs !== undefined ? { reapTtlMs: s.reapTtlMs } : {}),
111
+ ...(s.capabilities !== undefined ? { capabilities: s.capabilities } : {}),
112
+ ...(s.maxLeaseMs !== undefined ? { maxLeaseMs: s.maxLeaseMs } : {}),
113
+ ...(s.calls !== undefined ? { calls: s.calls } : {}),
114
+ ...(s.callsInputs !== undefined ? { callsInputs: s.callsInputs } : {}),
115
+ ...(s.judges !== undefined ? { judges: s.judges } : {}),
116
+ ...(s.groups !== undefined ? { groups: s.groups } : {}),
117
+ ...(s.x !== undefined ? { x: s.x } : {}),
118
+ body: s.body,
119
+ });
120
+ const projection = {
121
+ name: def.name,
122
+ engine: def.engine,
123
+ inputs: def.inputs,
124
+ ...(def.outputs !== undefined ? { outputs: def.outputs } : {}),
125
+ ...(def.invariants !== undefined ? { invariants: def.invariants } : {}),
126
+ ...(def.x !== undefined ? { x: def.x } : {}),
127
+ ...(def.executors !== undefined ? { executors: def.executors } : {}),
128
+ steps: def.steps.map(stepProjection),
129
+ };
130
+ return createHash('sha256').update(JSON.stringify(projection)).digest('hex');
131
+ }
132
+ /**
133
+ * Create the WP-B1 loaded-definition adapter: an in-memory
134
+ * {@link OrderInstructionSource} over validated `WorkflowDef` objects. Not a
135
+ * content-addressed store — a temporary implementation of the seam that a
136
+ * WP-A3 source replaces by injection. Definitions are indexed by digest on
137
+ * demand: {@link OrderInstructionSource.digestOf} registers the exact
138
+ * snapshot it digested, and `add` registers every seed def up front, so a
139
+ * seeded source can resolve orders without `buildOrder` ever touching it
140
+ * (e.g. injected-source tests).
141
+ */
142
+ export function createDefInstructionSource(seeds) {
143
+ const byDigest = new Map();
144
+ const register = (def) => {
145
+ const digest = defInstructionDigest(def);
146
+ // Keep a private deep snapshot. The caller may mutate the definition or a
147
+ // public defs map after an order is emitted; the digest must continue to
148
+ // address the exact instruction bytes that were hashed.
149
+ byDigest.set(digest, structuredClone(def));
150
+ return digest;
151
+ };
152
+ if (seeds !== undefined)
153
+ for (const def of seeds)
154
+ register(def);
155
+ return {
156
+ digestOf: (def) => register(def),
157
+ lookup: (ref) => {
158
+ const def = byDigest.get(ref.defDigest);
159
+ if (def === undefined)
160
+ return { status: 'unknown-digest' };
161
+ const step = def.steps.find((s) => s.name === ref.step);
162
+ if (step === undefined)
163
+ return { status: 'unknown-step' };
164
+ return {
165
+ status: 'resolved',
166
+ instructions: {
167
+ // StepDef.body is always a string. Preserve an authored empty body as
168
+ // prompt: '' rather than converting an exact value into absence.
169
+ prompt: step.body,
170
+ ...(step.command !== undefined ? { command: step.command } : {}),
171
+ maxAttempts: step.maxAttempts,
172
+ },
173
+ };
174
+ },
175
+ };
176
+ }
177
+ /**
178
+ * The runtime placeholder substitution for an order's authored prompt body.
179
+ * Same semantics as the engine's pre-reference-mode rendering: every
180
+ * `${WORKFLOW}`/`${RUN}`/`${STEP}`/`${KEY}`/`${INDEX}`/`${MAX_ATTEMPTS}`
181
+ * occurrence is replaced; an unknown placeholder name is left unchanged,
182
+ * byte for byte. Lives here (not on the low-level source) because the
183
+ * values are runtime fields of the reference order, not authored bytes —
184
+ * the source returns the body as authored, and materialization happens at
185
+ * resolution time, never back onto the order. `maxAttempts` is the AUTHORED
186
+ * step default (from the resolved step, not the order) — matching the old
187
+ * `buildOrder` semantics exactly, including the step-generic note below.
188
+ */
189
+ export function substituteOrderVars(body, runtime, opts = {}) {
190
+ return body.replace(/\$\{(\w+)\}/g, (m, k) => {
191
+ switch (k) {
192
+ case 'WORKFLOW': return runtime.workflow;
193
+ case 'RUN': return runtime.run;
194
+ case 'STEP': return opts.step ?? m;
195
+ case 'KEY': return runtime.key;
196
+ case 'INDEX': return runtime.index === undefined ? '' : String(runtime.index);
197
+ // Intentionally step-generic: a single firing can discharge multiple
198
+ // outputs (order.outputs) at once, so there is no single produce to
199
+ // resolve a per-produce maxAttempts override against here. This
200
+ // always reflects the step default even when individual produces
201
+ // override it (see model.ts effectiveMaxAttempts()).
202
+ case 'MAX_ATTEMPTS': return String(opts.maxAttempts ?? '');
203
+ default: return m;
204
+ }
205
+ });
206
+ }
207
+ /**
208
+ * An order-facing resolver over an {@link OrderInstructionSource} — the one
209
+ * resolution path both the CLI and embedded callers use. The low-level
210
+ * boundary (`resolve`) calls the source's three-key lookup and raises the
211
+ * named refusal; the convenience layer (`resolveOrder`) materializes the
212
+ * runtime placeholders on top of the exact authored bytes. Neither method
213
+ * ever mutates the stored/emitted order.
214
+ */
215
+ export class OrderResolver {
216
+ source;
217
+ constructor(source) {
218
+ this.source = source;
219
+ }
220
+ /** The low-level `(defDigest, step, key)` boundary: exact authored bytes or a typed refusal. */
221
+ resolve(ref) {
222
+ const result = this.source.lookup(ref);
223
+ if (result.status === 'unknown-digest')
224
+ throw new UnknownDefDigestError(ref.defDigest);
225
+ if (result.status === 'unknown-step')
226
+ throw new UnknownInstructionError(ref);
227
+ if (result.status === 'ambiguous-step')
228
+ throw new AmbiguousInstructionError(ref);
229
+ return result.instructions;
230
+ }
231
+ /**
232
+ * Resolve a reference-mode order's static instructions and materialize the
233
+ * runtime placeholders (`${WORKFLOW}`/`${RUN}`/`${STEP}`/`${KEY}`/
234
+ * `${INDEX}`/`${MAX_ATTEMPTS}`) in the prompt using the order's own
235
+ * runtime fields. Returns a fresh object — the order itself is never
236
+ * modified, and the materialized prompt is never written back onto it.
237
+ */
238
+ resolveOrder(order) {
239
+ const ref = { defDigest: order.defDigest, step: order.step, key: order.key };
240
+ // Keep this helper on the public low-level boundary. This is the same
241
+ // typed lookup/refusal path used by bare references; no caller can bypass
242
+ // digest verification or step-reference errors through resolveOrder.
243
+ const resolved = this.resolve(ref);
244
+ const { maxAttempts, ...instructions } = resolved;
245
+ if (resolved.prompt === undefined)
246
+ return instructions;
247
+ return {
248
+ ...instructions,
249
+ prompt: substituteOrderVars(resolved.prompt, { workflow: order.workflow, run: order.run, key: order.key, ...(order.index !== undefined ? { index: order.index } : {}) }, { step: order.step, maxAttempts }),
250
+ };
251
+ }
252
+ }
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Read the package version from either the source or built package layout.
3
+ *
4
+ * The source file lives under `src/`, while the emitted file lives under
5
+ * `dist/src/`. Keep the read runtime-based rather than importing JSON so the
6
+ * build's `rootDir: "."` output layout stays unchanged. A missing or malformed
7
+ * package manifest must not take down the stdio MCP server, so the helper
8
+ * memoizes and returns the existing unknown-version sentinel instead.
9
+ */
10
+ export declare function packageVersion(): string;