owenloop 0.5.0 → 0.5.2

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 (229) hide show
  1. package/CHANGELOG.md +67 -0
  2. package/README.md +144 -35
  3. package/bin/owenloop.mjs +49 -1
  4. package/dist/packages/work/src/agent/brief.d.ts +29 -4
  5. package/dist/packages/work/src/agent/brief.js +49 -4
  6. package/dist/packages/work/src/agent/capability-model.d.ts +123 -0
  7. package/dist/packages/work/src/agent/capability-model.js +148 -0
  8. package/dist/packages/work/src/agent/loop.d.ts +56 -7
  9. package/dist/packages/work/src/agent/loop.js +166 -9
  10. package/dist/packages/work/src/bundle/cache.d.ts +7 -5
  11. package/dist/packages/work/src/bundle/cache.js +20 -6
  12. package/dist/packages/work/src/bundle/fetch.d.ts +7 -5
  13. package/dist/packages/work/src/bundle/fetch.js +27 -7
  14. package/dist/packages/work/src/bundle/types.d.ts +8 -4
  15. package/dist/packages/work/src/consumed-verifier.d.ts +45 -0
  16. package/dist/packages/work/src/consumed-verifier.js +205 -0
  17. package/dist/packages/work/src/exec/instructions.d.ts +99 -0
  18. package/dist/packages/work/src/exec/instructions.js +323 -0
  19. package/dist/packages/work/src/exec/loop.d.ts +29 -1
  20. package/dist/packages/work/src/exec/loop.js +313 -35
  21. package/dist/packages/work/src/exec/payload.d.ts +29 -0
  22. package/dist/packages/work/src/exec/payload.js +54 -0
  23. package/dist/packages/work/src/exec/receipt.d.ts +9 -6
  24. package/dist/packages/work/src/exec/receipt.js +12 -1
  25. package/dist/packages/work/src/exec/runner.d.ts +7 -1
  26. package/dist/packages/work/src/exec/runner.js +84 -3
  27. package/dist/packages/work/src/harness/child-env.js +7 -0
  28. package/dist/packages/work/src/harness/claude.d.ts +20 -8
  29. package/dist/packages/work/src/harness/claude.js +260 -58
  30. package/dist/packages/work/src/harness/codex.d.ts +5 -4
  31. package/dist/packages/work/src/harness/codex.js +169 -41
  32. package/dist/packages/work/src/harness/contract.d.ts +36 -11
  33. package/dist/packages/work/src/harness/fake.js +1 -0
  34. package/dist/packages/work/src/harness/jsonrpc-stdio.js +7 -0
  35. package/dist/packages/work/src/harness/permissions.d.ts +16 -3
  36. package/dist/packages/work/src/harness/permissions.js +102 -13
  37. package/dist/packages/work/src/harness/session-store.d.ts +30 -10
  38. package/dist/packages/work/src/harness/session-store.js +317 -89
  39. package/dist/packages/work/src/hold/mcp.d.ts +25 -5
  40. package/dist/packages/work/src/hold/mcp.js +134 -12
  41. package/dist/packages/work/src/hub/client.d.ts +8 -1
  42. package/dist/packages/work/src/hub/client.js +15 -1
  43. package/dist/packages/work/src/hub/types.d.ts +137 -33
  44. package/dist/packages/work/src/hub/types.js +8 -10
  45. package/dist/packages/work/src/mcp/server.js +1 -1
  46. package/dist/packages/work/src/owenloop-bin.d.ts +1 -0
  47. package/dist/packages/work/src/owenloop-bin.js +18 -0
  48. package/dist/packages/work/src/roles/agent-run.d.ts +12 -6
  49. package/dist/packages/work/src/roles/agent-run.js +115 -34
  50. package/dist/packages/work/src/roles/exec.d.ts +8 -0
  51. package/dist/packages/work/src/roles/exec.js +27 -2
  52. package/dist/packages/work/src/roles/hold.d.ts +6 -0
  53. package/dist/packages/work/src/roles/hold.js +83 -13
  54. package/dist/packages/work/src/roles/lint.d.ts +3 -4
  55. package/dist/packages/work/src/roles/lint.js +41 -7
  56. package/dist/packages/work/src/roles/settings.js +19 -2
  57. package/dist/packages/work/src/roles/shift.d.ts +1 -0
  58. package/dist/packages/work/src/roles/shift.js +36 -2
  59. package/dist/packages/work/src/settings/settings.d.ts +70 -1
  60. package/dist/packages/work/src/settings/settings.js +90 -4
  61. package/dist/packages/work/src/shift/logretention.d.ts +253 -0
  62. package/dist/packages/work/src/shift/logretention.js +407 -0
  63. package/dist/packages/work/src/shift/logsink.d.ts +14 -0
  64. package/dist/packages/work/src/shift/logsink.js +98 -0
  65. package/dist/packages/work/src/shift/loop.d.ts +32 -4
  66. package/dist/packages/work/src/shift/loop.js +687 -166
  67. package/dist/packages/work/src/shift/protocol.d.ts +128 -1
  68. package/dist/packages/work/src/shift/protocol.js +14 -0
  69. package/dist/packages/work/src/shift/runtime.d.ts +16 -0
  70. package/dist/packages/work/src/shift/runtime.js +291 -5
  71. package/dist/packages/work/src/shift/server.d.ts +13 -0
  72. package/dist/packages/work/src/shift/server.js +61 -36
  73. package/dist/packages/work/src/shift/spawn.d.ts +115 -19
  74. package/dist/packages/work/src/shift/spawn.js +234 -30
  75. package/dist/packages/work/src/shift/state.d.ts +76 -49
  76. package/dist/packages/work/src/shift/state.js +350 -103
  77. package/dist/packages/work/src/shift/truncate.d.ts +35 -0
  78. package/dist/packages/work/src/shift/truncate.js +73 -0
  79. package/dist/packages/work/src/submit-proof.d.ts +61 -0
  80. package/dist/packages/work/src/submit-proof.js +119 -0
  81. package/dist/packages/work/src/submit-value.d.ts +48 -0
  82. package/dist/packages/work/src/submit-value.js +118 -0
  83. package/dist/packages/work/src/usage.d.ts +1 -1
  84. package/dist/packages/work/src/usage.js +11 -0
  85. package/dist/src/add.d.ts +64 -259
  86. package/dist/src/add.js +81 -615
  87. package/dist/src/archive.d.ts +97 -0
  88. package/dist/src/archive.js +591 -0
  89. package/dist/src/bundle/index.d.ts +64 -0
  90. package/dist/src/bundle/index.js +508 -0
  91. package/dist/src/bundle/manifest.d.ts +50 -0
  92. package/dist/src/bundle/manifest.js +435 -0
  93. package/dist/src/bundle/runtime.d.ts +26 -0
  94. package/dist/src/bundle/runtime.js +64 -0
  95. package/dist/src/bundle/tar.d.ts +62 -0
  96. package/dist/src/bundle/tar.js +238 -0
  97. package/dist/src/bundle/types.d.ts +105 -0
  98. package/dist/src/bundle/types.js +21 -0
  99. package/dist/src/capabilities.d.ts +93 -0
  100. package/dist/src/capabilities.js +101 -0
  101. package/dist/src/cli.d.ts +90 -20
  102. package/dist/src/cli.js +2421 -374
  103. package/dist/src/credentials.d.ts +4 -3
  104. package/dist/src/credentials.js +21 -19
  105. package/dist/src/crypto/allowed-signers.d.ts +68 -0
  106. package/dist/src/crypto/allowed-signers.js +307 -0
  107. package/dist/src/crypto/canonical.d.ts +8 -0
  108. package/dist/src/crypto/canonical.js +92 -0
  109. package/dist/src/crypto/chain.d.ts +65 -0
  110. package/dist/src/crypto/chain.js +377 -0
  111. package/dist/src/crypto/dsse.d.ts +209 -0
  112. package/dist/src/crypto/dsse.js +282 -0
  113. package/dist/src/crypto/enrollment.d.ts +78 -0
  114. package/dist/src/crypto/enrollment.js +186 -0
  115. package/dist/src/crypto/index.d.ts +48 -0
  116. package/dist/src/crypto/index.js +44 -0
  117. package/dist/src/crypto/keys.d.ts +258 -0
  118. package/dist/src/crypto/keys.js +908 -0
  119. package/dist/src/crypto/org-root.d.ts +33 -0
  120. package/dist/src/crypto/org-root.js +78 -0
  121. package/dist/src/crypto/origin-rules.d.ts +56 -0
  122. package/dist/src/crypto/origin-rules.js +143 -0
  123. package/dist/src/crypto/policy-floor.d.ts +98 -0
  124. package/dist/src/crypto/policy-floor.js +353 -0
  125. package/dist/src/crypto/records.d.ts +319 -0
  126. package/dist/src/crypto/records.js +168 -0
  127. package/dist/src/crypto/scope.d.ts +49 -0
  128. package/dist/src/crypto/scope.js +83 -0
  129. package/dist/src/crypto/ssh.d.ts +171 -0
  130. package/dist/src/crypto/ssh.js +396 -0
  131. package/dist/src/crypto/submission.d.ts +33 -0
  132. package/dist/src/crypto/submission.js +47 -0
  133. package/dist/src/crypto/trust-roots.d.ts +29 -0
  134. package/dist/src/crypto/trust-roots.js +39 -0
  135. package/dist/src/crypto/verify-consumed.d.ts +67 -0
  136. package/dist/src/crypto/verify-consumed.js +259 -0
  137. package/dist/src/crypto/verify-origin.d.ts +50 -0
  138. package/dist/src/crypto/verify-origin.js +151 -0
  139. package/dist/src/crypto/verify-publication.d.ts +60 -0
  140. package/dist/src/crypto/verify-publication.js +150 -0
  141. package/dist/src/defs.d.ts +24 -1
  142. package/dist/src/defs.js +335 -27
  143. package/dist/src/engine.d.ts +211 -6
  144. package/dist/src/engine.js +459 -59
  145. package/dist/src/factory.d.ts +16 -0
  146. package/dist/src/factory.js +16 -4
  147. package/dist/src/global-config.d.ts +59 -0
  148. package/dist/src/global-config.js +84 -0
  149. package/dist/src/hub.d.ts +102 -32
  150. package/dist/src/hub.js +147 -58
  151. package/dist/src/index.d.ts +19 -2
  152. package/dist/src/index.js +23 -2
  153. package/dist/src/install.d.ts +538 -0
  154. package/dist/src/install.js +1981 -0
  155. package/dist/src/lock.d.ts +15 -57
  156. package/dist/src/lock.js +251 -143
  157. package/dist/src/mcp/serve.d.ts +46 -22
  158. package/dist/src/mcp/serve.js +174 -44
  159. package/dist/src/mcp/server.js +12 -1
  160. package/dist/src/model.d.ts +51 -0
  161. package/dist/src/model.js +157 -1
  162. package/dist/src/order-resolver.d.ts +184 -0
  163. package/dist/src/order-resolver.js +252 -0
  164. package/dist/src/package-version.d.ts +10 -0
  165. package/dist/src/package-version.js +42 -0
  166. package/dist/src/paths.d.ts +14 -1
  167. package/dist/src/paths.js +18 -0
  168. package/dist/src/schemas/enrollment-grant.v1.schema.json +90 -0
  169. package/dist/src/schemas/index.d.ts +1433 -0
  170. package/dist/src/schemas/index.js +31 -0
  171. package/dist/src/schemas/order.v1.schema.json +120 -0
  172. package/dist/src/schemas/origin.v1.schema.json +68 -0
  173. package/dist/src/schemas/policy-floor.v1.schema.json +29 -0
  174. package/dist/src/schemas/publication.v1.schema.json +31 -0
  175. package/dist/src/schemas/revocation.v1.schema.json +39 -0
  176. package/dist/src/schemas/submission.v1.schema.json +61 -0
  177. package/dist/src/store/def-source.d.ts +52 -0
  178. package/dist/src/store/def-source.js +335 -0
  179. package/dist/src/store/index-file.d.ts +69 -0
  180. package/dist/src/store/index-file.js +151 -0
  181. package/dist/src/store/index.d.ts +27 -0
  182. package/dist/src/store/index.js +22 -0
  183. package/dist/src/store/ingestor.d.ts +43 -0
  184. package/dist/src/store/ingestor.js +211 -0
  185. package/dist/src/store/install.d.ts +228 -0
  186. package/dist/src/store/install.js +555 -0
  187. package/dist/src/store/instruction-source.d.ts +49 -0
  188. package/dist/src/store/instruction-source.js +298 -0
  189. package/dist/src/store/origin-evidence.d.ts +21 -0
  190. package/dist/src/store/origin-evidence.js +66 -0
  191. package/dist/src/store/pre-commit-verifier.d.ts +68 -0
  192. package/dist/src/store/pre-commit-verifier.js +418 -0
  193. package/dist/src/store/resolve.d.ts +138 -0
  194. package/dist/src/store/resolve.js +363 -0
  195. package/dist/src/store/types.d.ts +288 -0
  196. package/dist/src/store/types.js +356 -0
  197. package/dist/src/store.d.ts +33 -1
  198. package/dist/src/store.js +57 -4
  199. package/dist/src/types.d.ts +146 -12
  200. package/dist/src/untar.d.ts +8 -23
  201. package/dist/src/untar.js +10 -136
  202. package/docs/agent-runner.md +86 -0
  203. package/docs/authoring.md +64 -6
  204. package/docs/bundles.md +350 -0
  205. package/docs/cli.md +1298 -106
  206. package/docs/crypto.md +832 -0
  207. package/docs/design.md +342 -20
  208. package/docs/embedding.md +132 -25
  209. package/docs/shift-logs.md +642 -0
  210. package/docs/wire-contracts.md +395 -0
  211. package/package.json +6 -1
  212. package/plugins/claude-code/.claude-plugin/marketplace.json +14 -0
  213. package/plugins/claude-code/plugin/.claude-plugin/plugin.json +8 -0
  214. package/plugins/claude-code/plugin/.mcp.json +14 -0
  215. package/plugins/claude-code/plugin/hooks/hooks.json +26 -0
  216. package/plugins/claude-code/plugin/hooks/session-end.sh +40 -0
  217. package/plugins/claude-code/plugin/hooks/session-start.sh +52 -0
  218. package/plugins/claude-code/plugin/skills/author/SKILL.md +181 -0
  219. package/plugins/claude-code/plugin/skills/conduct/SKILL.md +106 -0
  220. package/plugins/claude-code/plugin/skills/shift/SKILL.md +105 -0
  221. package/plugins/codex/.agents/plugins/marketplace.json +21 -0
  222. package/plugins/codex/plugins/owenloop/.codex-plugin/plugin.json +7 -0
  223. package/plugins/codex/plugins/owenloop/.mcp.json +20 -0
  224. package/plugins/codex/plugins/owenloop/hooks/hooks.json +26 -0
  225. package/plugins/codex/plugins/owenloop/hooks/session-end.sh +40 -0
  226. package/plugins/codex/plugins/owenloop/hooks/session-start.sh +52 -0
  227. package/plugins/codex/plugins/owenloop/skills/author/SKILL.md +181 -0
  228. package/plugins/codex/plugins/owenloop/skills/conduct/SKILL.md +106 -0
  229. package/plugins/codex/plugins/owenloop/skills/shift/SKILL.md +105 -0
package/dist/src/model.js CHANGED
@@ -121,6 +121,52 @@ export function isHeld(a) {
121
121
  return false;
122
122
  return a.reasons.length > 0 && a.reasons[a.reasons.length - 1].kind === 'invalidated-irreversible';
123
123
  }
124
+ /**
125
+ * §7 escalation trigger: has this artifact been judgment-rejected at least
126
+ * `after` times in the CURRENT rejection episode?
127
+ *
128
+ * Reads `judgmentRejects`, the same counter `isStalled` reads and the same one
129
+ * `retry` zeroes — so "current episode" needs no separate bookkeeping: a human
130
+ * `retry` resets the counter and the trigger goes false again by itself.
131
+ *
132
+ * The state this tests is derived, never stored. Every offer of the step
133
+ * re-evaluates it, so the transition cannot half-apply, cannot be lost, and
134
+ * cannot be applied twice to one offer. It is deliberately independent of
135
+ * `acceptance`: unlike `isStalled` (which describes a FROZEN artifact and must
136
+ * only be true while it is sitting rejected), this describes the routing of the
137
+ * NEXT offer, and by the time that offer is built the artifact has been re-armed
138
+ * to `owed`.
139
+ *
140
+ * `after` comes from the step's authored `escalation.after`. Install validation
141
+ * (`defs.ts` R2) guarantees `after < effectiveMaxAttempts`, so there is always a
142
+ * window between "escalate" and "freeze" in which the escalated attempt runs.
143
+ */
144
+ export function isEscalated(a, after) {
145
+ return !!a && a.judgmentRejects >= after;
146
+ }
147
+ /**
148
+ * Which rejection episode this artifact is in: 0 before any human `retry`, 1
149
+ * after the first, and so on.
150
+ *
151
+ * `retry` is the only lever that ends an episode (it zeroes `judgmentRejects`),
152
+ * and it appends a `'retry'` entry to the append-only reason thread — so
153
+ * counting those entries yields a monotonic episode ordinal with no new column
154
+ * and no new state to keep consistent.
155
+ *
156
+ * Used to key an escalation's ONE history record per episode. It is not used to
157
+ * decide anything: the trigger above reads the counter, which is authoritative.
158
+ * If the thread and the counter ever disagreed, the ordinal would only mislabel
159
+ * a history row, never change routing.
160
+ */
161
+ export function rejectionEpisode(a) {
162
+ if (!a)
163
+ return 0;
164
+ let n = 0;
165
+ for (const r of a.reasons)
166
+ if (r.action === 'retry')
167
+ n++;
168
+ return n;
169
+ }
124
170
  /** Resolve the effective maxAttempts for a specific produce, falling back to
125
171
  * the owning step's default (§6). `produce` may be undefined if the artifact
126
172
  * couldn't be matched to a produce pattern (defensive; should not happen for
@@ -386,6 +432,66 @@ function idleEligible(step, arts, time) {
386
432
  return false; // allGreen owns this condition
387
433
  return true;
388
434
  }
435
+ /**
436
+ * Is a `calls:` step's gate ready in this state — i.e. is every parent artifact
437
+ * wired into `callsInputs` green?
438
+ *
439
+ * This is the model-side mirror of `Engine.callsGateReady` (engine.ts) and MUST
440
+ * read the same field it does: `callsInputs`, the mapping {child input name →
441
+ * parent artifact name}. A `calls:` step's `StepDef.consumes` is ALWAYS `[]`
442
+ * (`buildStep` hardcodes it — "eligibility is engine-managed", defs.ts), so
443
+ * gating on `plainConsumes(step)` is vacuously true for every `calls:` step and
444
+ * is NOT a gate at all. An empty `callsInputs` gate is genuinely always ready —
445
+ * same rule the engine applies.
446
+ */
447
+ function callsGateReady(step, arts) {
448
+ const gateStems = Object.values(step.callsInputs ?? {});
449
+ return gateStems.every((s) => isGreen(arts.get(s)));
450
+ }
451
+ /**
452
+ * The `calls:` discharges available in THIS state — one firing per `calls:` step
453
+ * whose gate is ready (the engine would provision/re-provide the child now) and
454
+ * whose produced artifact is still a debt (the child has not yet discharged it).
455
+ *
456
+ * Why this exists: `eligibleFirings` skips every `calls:` step (M2 — the engine
457
+ * spawns a child rather than issuing a worker order), and `modelCheck` explores
458
+ * ONE def with no child engine attached. Without modeling the handoff, the
459
+ * exploration mistakes "waiting on a child I can't see" for "structurally dead",
460
+ * which made `hasDefiniteCheckDefect` reject EVERY `calls:`-using def at install
461
+ * time — including the repo's own `examples/workflows/provisioned-delivery.yaml`.
462
+ *
463
+ * This is a TRANSITION, not a reclassification. That distinction is the whole
464
+ * point: an earlier version of this fix was a def-wide boolean OR'd into the
465
+ * deadlock/stall branch, which relabelled EVERY zero-firing state in the def —
466
+ * so one unrelated `calls:` step anywhere in a def suppressed every genuine
467
+ * deadlock in it. Modeling the discharge as a successor state instead keeps the
468
+ * classification strictly per-state: the child greens ITS OWN artifact and
469
+ * nothing else, so a deadlock elsewhere in the same def is still reached and
470
+ * still reported.
471
+ *
472
+ * Kept separate from `eligibleFirings` deliberately: that function is the LIVE
473
+ * engine scheduler and a `calls:` step must never become a worker order. These
474
+ * firings are consumed only by `modelCheck`'s successor expansion.
475
+ */
476
+ function callsDischargeFirings(def, arts) {
477
+ const firings = [];
478
+ for (const step of def.steps) {
479
+ if (!step.calls)
480
+ continue;
481
+ if (!callsGateReady(step, arts))
482
+ continue;
483
+ const outs = plainOutputs(step).filter((p) => isDebt(arts.get(p)));
484
+ if (outs.length === 0)
485
+ continue;
486
+ firings.push({
487
+ step: step.name,
488
+ key: '',
489
+ inputs: Object.values(step.callsInputs ?? {}),
490
+ outputs: outs,
491
+ });
492
+ }
493
+ return firings;
494
+ }
389
495
  /**
390
496
  * Every firing eligible *right now* — inputs satisfied AND an owed/rejected
391
497
  * output to discharge. This is the scheduling gate (§11.4): necessary, not
@@ -1648,6 +1754,16 @@ function eligibleOutcomes(def, arts, firing) {
1648
1754
  }
1649
1755
  return ['judge-approve', 'judge-reject'];
1650
1756
  }
1757
+ // M2: a `calls:` firing is the machine handing off to a child instance, not a
1758
+ // worker order. The only outcome the PARENT def can observe is the child's
1759
+ // terminal outcome cascading up as a green on the calls artifact. None of the
1760
+ // worker-verb outcomes apply: there is no worker to schema-reject a value, no
1761
+ // consumer to judgment-reject (a calls: step declares `consumes: []`), and a
1762
+ // calls: produce may carry neither `judges:` nor `group:` (rejected by
1763
+ // `buildStep`). Modeling only the green keeps the successor set faithful to
1764
+ // what the engine can actually do here.
1765
+ if (step.calls)
1766
+ return ['green'];
1651
1767
  const stem = collectionStem(step);
1652
1768
  const outPath = firing.outputs[0] ?? '';
1653
1769
  const el = parseElement(outPath);
@@ -2029,7 +2145,28 @@ export function modelCheck(def, opts = {}) {
2029
2145
  }
2030
2146
  continue; // done states have no successors
2031
2147
  }
2032
- const firings = status.eligible;
2148
+ // WS-6 — model the `calls:` handoff as a real TRANSITION, not a
2149
+ // reclassification. M2 makes `eligibleFirings` skip every `calls:` step (the
2150
+ // engine spawns a child to discharge it, so it must never become a worker
2151
+ // firing), and the model has no child engine attached. Left unmodeled, a
2152
+ // state waiting on a child reaches the classification branch below with zero
2153
+ // firings and gets called a TRUE deadlock — asserting this report's own
2154
+ // documented claim ("no path to completion even at unlimited attempts"),
2155
+ // which is false: the engine does spawn the child and the debt is
2156
+ // discharged.
2157
+ //
2158
+ // The child is modeled as a single opaque green of the calls artifact — the
2159
+ // only thing the parent def can observe about it. `callsDischargeFirings`
2160
+ // gates per-step on `callsInputs` (the same field `Engine.callsGateReady`
2161
+ // reads), so a `calls:` step whose gate is NOT green yields no firing and
2162
+ // the state is classified on its own merits. Because the discharge greens
2163
+ // only that step's own artifact, an unrelated deadlock elsewhere in the same
2164
+ // def is still reached and still reported.
2165
+ //
2166
+ // `eligibleFirings` (the LIVE engine scheduler) and `hasDefiniteCheckDefect`
2167
+ // (shared by check / add / push / install) are deliberately untouched.
2168
+ const callsFirings = callsDischargeFirings(def, node.arts);
2169
+ const firings = [...status.eligible, ...callsFirings];
2033
2170
  // Non-done state with no eligible firings: classify by recomputing eligibility
2034
2171
  // as if every freeze/stall were lifted (unlimited attempts). If a producer
2035
2172
  // would re-arm → an EXPECTED stall state (a by-design brake). If not → a
@@ -2103,3 +2240,22 @@ export function modelCheck(def, opts = {}) {
2103
2240
  }
2104
2241
  return report;
2105
2242
  }
2243
+ /**
2244
+ * The single "definite defect" predicate over a modelCheck `report`, shared by
2245
+ * every acceptance gate that accepts or rejects a def (`check`, `add`'s GitHub
2246
+ * route, `add`'s workflow-bundle route, `push`). A pure function of the report
2247
+ * object — it does NOT read or change how any caller seeded its modelCheck
2248
+ * (install/push seed `assumeProvided: true`; check seeds
2249
+ * `assumeProvided: !strictInputs`).
2250
+ *
2251
+ * invariant violations and structurally-dead steps are ALWAYS definite (sound
2252
+ * regardless of bounds); a true deadlock counts ONLY when the search was
2253
+ * exhaustive (`!bounded`) because a tight maxCollectionSize cap can manufacture
2254
+ * a spurious one. `unreachedSteps` is deliberately EXCLUDED — it is a bounds
2255
+ * artifact ("raise --max-states/--max-depth"), never a definite defect.
2256
+ */
2257
+ export function hasDefiniteCheckDefect(report) {
2258
+ return (report.invariantViolations.length > 0 ||
2259
+ report.structurallyDeadSteps.length > 0 ||
2260
+ (!report.bounded && report.deadlocks.length > 0));
2261
+ }
@@ -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;
@@ -0,0 +1,42 @@
1
+ import { existsSync, readFileSync } from 'node:fs';
2
+ import { fileURLToPath } from 'node:url';
3
+ let cachedPackageVersion;
4
+ /**
5
+ * Read the package version from either the source or built package layout.
6
+ *
7
+ * The source file lives under `src/`, while the emitted file lives under
8
+ * `dist/src/`. Keep the read runtime-based rather than importing JSON so the
9
+ * build's `rootDir: "."` output layout stays unchanged. A missing or malformed
10
+ * package manifest must not take down the stdio MCP server, so the helper
11
+ * memoizes and returns the existing unknown-version sentinel instead.
12
+ */
13
+ export function packageVersion() {
14
+ if (cachedPackageVersion !== undefined)
15
+ return cachedPackageVersion;
16
+ try {
17
+ const candidates = [
18
+ new URL('../package.json', import.meta.url),
19
+ new URL('../../package.json', import.meta.url),
20
+ ];
21
+ for (const candidate of candidates) {
22
+ try {
23
+ const path = fileURLToPath(candidate);
24
+ if (!existsSync(path))
25
+ continue;
26
+ const parsed = JSON.parse(readFileSync(path, 'utf8'));
27
+ if (typeof parsed.version === 'string' && parsed.version.length > 0) {
28
+ cachedPackageVersion = parsed.version;
29
+ return cachedPackageVersion;
30
+ }
31
+ }
32
+ catch {
33
+ // Try the other layout, then fall back without throwing.
34
+ }
35
+ }
36
+ }
37
+ catch {
38
+ // Keep the stdio server alive if URL/path resolution itself fails.
39
+ }
40
+ cachedPackageVersion = '0.0.0';
41
+ return cachedPackageVersion;
42
+ }