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
@@ -9,11 +9,13 @@
9
9
  * (snapshotted on the run) against current input versions; a moved input
10
10
  * born-rejects the output instead of greening it.
11
11
  */
12
- import { elementPath, parseElement, sealPath, } from "./paths.js";
13
- import { collectionStem, computeFingerprint, eligibleFirings, fingerprintMatches, groupBlockingWinner, isGreen, judgeNameOf, maintainDecisions, pendingOwed, plainConsumes, requiredInputs, workflowStatus, } from "./model.js";
12
+ import { elementPath, parseElement, parseWorkdirFrom, sealPath, } from "./paths.js";
13
+ import { collectionStem, computeFingerprint, eligibleFirings, fingerprintMatches, groupBlockingWinner, isEscalated, isGreen, judgeNameOf, maintainDecisions, pendingOwed, plainConsumes, rejectionEpisode, requiredInputs, workflowStatus, } from "./model.js";
14
14
  import { summarizeIssues, validateValue } from "./schema.js";
15
15
  import { hashDef } from "./defs.js";
16
+ import { claimMatches, composeCapabilities } from "./capabilities.js";
16
17
  import { localMidnightMs, nowMs, randId } from "./util.js";
18
+ import { createDefInstructionSource, OrderResolver } from "./order-resolver.js";
17
19
  const DEFAULT_REAP_TTL_MS = 2 * 60 * 60 * 1000; // 2h
18
20
  /**
19
21
  * REL-4: hard cap on `calls:` composition depth (root instance = depth 0), a
@@ -24,6 +26,8 @@ const DEFAULT_REAP_TTL_MS = 2 * 60 * 60 * 1000; // 2h
24
26
  * `maintainCalls` (spawn-time refusal) and `tickInternal` (descent guard).
25
27
  */
26
28
  const DEFAULT_MAX_CALL_DEPTH = 64;
29
+ /** The artifact-history `action` written when an escalation promotes an offer. */
30
+ const ESCALATION_ACTION = 'escalated';
27
31
  /**
28
32
  * F2: a typed refusal for a produced-value/input-value schema mismatch, thrown
29
33
  * by `createInstance` (seed provide) and `provideInput`. Distinct from a bare
@@ -53,9 +57,108 @@ export class SchemaRefusalError extends Error {
53
57
  this.issues = issues;
54
58
  }
55
59
  }
60
+ /**
61
+ * WS-6: a `calls:` step resolved to a child definition that is NOT the one the
62
+ * parent's own bundle pinned. Thrown from inside `provisionCallsChild`'s
63
+ * transaction, so the whole provisioning tx rolls back — no child row, no
64
+ * partial input sync — and `maintainCalls` converts it into a visible debt on
65
+ * the parent's `calls:` artifact (see `recordCallsDigestReject`). The failure
66
+ * mode this prevents is silent: without it, a newer install of the same package
67
+ * would let a running parent spawn a DIFFERENT workflow body than the one it was
68
+ * pinned against, and nothing would say so.
69
+ */
70
+ export class CallsPinError extends Error {
71
+ name = 'CallsPinError';
72
+ /** The `calls:` target text exactly as the parent def wrote it. */
73
+ target;
74
+ /** Human-readable statement of which pin was violated and how. */
75
+ detail;
76
+ constructor(target, detail) {
77
+ super(`calls target '${target}' failed its pin check: ${detail}`);
78
+ this.target = target;
79
+ this.detail = detail;
80
+ }
81
+ }
82
+ /**
83
+ * WS-6: check that `childDef` is the definition the parent's own bundle pinned
84
+ * for the `calls:` target `target`. Returns `undefined` when the edge is fine,
85
+ * or a human-readable violation string.
86
+ *
87
+ * THREE CASES, and the FIRST two are the whole point of the check:
88
+ *
89
+ * 1. `target` is BARE and `parentDef` came from a CAS bundle
90
+ * (`parentDef.bundleDigest` is set). The pin is BUNDLE-digest equality: the
91
+ * v2 bundle format carries no per-workflow digest, and `assertLockCoverage`
92
+ * deliberately skips non-versioned refs, so a sibling's pin IS its
93
+ * containing bundle's own digest. `childDef.bundleDigest` must equal
94
+ * `parentDef.bundleDigest`.
95
+ *
96
+ * 2. `target` is an explicit `namespace/name@version` reference AND the parent
97
+ * bundle's manifest `lock` names it. The lock value is a canonical BUNDLE
98
+ * digest (`bundle.yaml.lock` validates lowercase 64-hex; `assertLockCoverage`
99
+ * requires an entry for every versioned target), so it is compared against
100
+ * `childDef.bundleDigest` — NOT against `defInstructionDigest`, which
101
+ * projects one definition and is a different digest kind entirely.
102
+ *
103
+ * 3. Everything else — a parent with no CAS provenance, or a versioned target
104
+ * with no lock entry reachable — is UNPINNED and passes. This is what keeps
105
+ * every filesystem def, every `owenloop add` def, and every legacy unpinned
106
+ * instance behaving exactly as before: no provenance, no check.
107
+ */
108
+ function callsPinViolation(parentDef, childDef, target) {
109
+ if (target.includes('/')) {
110
+ const pinned = parentDef.bundleLock?.[target];
111
+ if (pinned === undefined)
112
+ return undefined; // no lock entry reachable — unpinned
113
+ if (childDef.bundleDigest === undefined) {
114
+ return `parent bundle pins it to ${pinned} but the resolved definition carries no bundle provenance`;
115
+ }
116
+ if (childDef.bundleDigest !== pinned) {
117
+ return `parent bundle pins it to ${pinned} but the resolved definition comes from ${childDef.bundleDigest}`;
118
+ }
119
+ return undefined;
120
+ }
121
+ if (parentDef.bundleDigest === undefined)
122
+ return undefined; // parent not CAS-installed — unpinned
123
+ if (childDef.bundleDigest !== parentDef.bundleDigest) {
124
+ const found = childDef.bundleDigest ?? 'no bundle (a project-local or add-installed definition)';
125
+ return `a bare calls: target must be a sibling in the parent's own bundle ${parentDef.bundleDigest}, but it resolved to ${found}`;
126
+ }
127
+ return undefined;
128
+ }
129
+ /**
130
+ * Thrown by `createInstance` when the requested modifier is not in the def's
131
+ * declared `modifiers` set (including the case of a def that declares none).
132
+ * Its own class so the hub can map it to a 400 instead of an opaque 500 —
133
+ * this is a caller mistake, not an engine fault.
134
+ */
135
+ export class ModifierRefusalError extends Error {
136
+ defName;
137
+ modifier;
138
+ /** The def's declared modifier set — empty when the def declares none. */
139
+ declared;
140
+ constructor(defName, modifier, declared) {
141
+ super(declared.length === 0
142
+ ? `workflow '${defName}' declares no modifiers:, so it cannot be started with modifier '${modifier}'`
143
+ : `modifier '${modifier}' is not declared by workflow '${defName}' (declared: ${declared.join(', ')})`);
144
+ this.name = 'ModifierRefusalError';
145
+ this.defName = defName;
146
+ this.modifier = modifier;
147
+ this.declared = declared;
148
+ }
149
+ }
56
150
  export class Engine {
57
151
  store;
58
152
  resolveDef;
153
+ /**
154
+ * The reference-mode instruction boundary (WP-B1): where an order's
155
+ * `defDigest` turns back into exact authored instructions. Injected when a
156
+ * host supplies a WP-A3-compatible source; otherwise a loaded-definition
157
+ * adapter that still emits and resolves reference orders (not a
158
+ * compatibility mode). Public read-only facade: {@link Engine.resolver}.
159
+ */
160
+ instructionSource;
161
+ resolver;
59
162
  reapTtlMs;
60
163
  maxLeaseMs;
61
164
  maxCallDepth;
@@ -66,6 +169,8 @@ export class Engine {
66
169
  constructor(store, resolveDef, opts = {}) {
67
170
  this.store = store;
68
171
  this.resolveDef = resolveDef;
172
+ this.instructionSource = opts.instructionSource ?? createDefInstructionSource();
173
+ this.resolver = new OrderResolver(this.instructionSource);
69
174
  this.reapTtlMs = opts.reapTtlMs ?? DEFAULT_REAP_TTL_MS;
70
175
  this.maxLeaseMs = opts.maxLeaseMs;
71
176
  this.maxCallDepth = opts.maxCallDepth ?? DEFAULT_MAX_CALL_DEPTH;
@@ -114,6 +219,17 @@ export class Engine {
114
219
  wfData.title = opts.title;
115
220
  if (opts.params !== undefined)
116
221
  wfData.params = opts.params;
222
+ // Validated against the SNAPSHOT being pinned on this same row, not
223
+ // against a live re-resolution — the modifier and the vocabulary that
224
+ // legitimizes it are stamped together and stay consistent for the life of
225
+ // the instance, even if the def is republished with a different set.
226
+ if (opts.modifier !== undefined) {
227
+ const declared = def.modifiers ?? [];
228
+ if (!declared.includes(opts.modifier)) {
229
+ throw new ModifierRefusalError(defName, opts.modifier, declared);
230
+ }
231
+ wfData.modifier = opts.modifier;
232
+ }
117
233
  this.store.insertWorkflow(id, wfData, opts.producedBy);
118
234
  for (const input of def.inputs) {
119
235
  const provided = opts.provide?.[input.name];
@@ -173,7 +289,7 @@ export class Engine {
173
289
  * orphan child row, no partial input sync — preserving the F2 contract; the
174
290
  * caller records it as a debt on the parent calls artifact.
175
291
  */
176
- provisionCallsChild(parentWf, step, callsStem, gateStems, now) {
292
+ provisionCallsChild(parentWf, parentDef, step, callsStem, gateStems, now) {
177
293
  // B2: the gate fingerprint of the exact in-tx snapshot the seed/re-provide
178
294
  // validation ran against. Captured fresh inside `run()` so a retry re-reads
179
295
  // it; carried out on a `SchemaRefusalError` so `recordCallsSchemaReject` can
@@ -210,7 +326,17 @@ export class Engine {
210
326
  let childDef;
211
327
  if (!child) {
212
328
  const childId = randId('wf');
213
- childDef = this.resolveDef(step.calls);
329
+ // WS-6: resolve IN THE PARENT'S SCOPE. `parentDef` is the parent's own
330
+ // §28 pin (defFor prefers `defSnapshot` over the live resolver), so a
331
+ // bare `calls:` from a def installed out of a CAS bundle binds to that
332
+ // same bundle's workflow — the version the parent was pinned against —
333
+ // and not to whatever a later install happened to name the same thing.
334
+ childDef = this.resolveDef(step.calls, parentDef);
335
+ // WS-6: and the resolved child must still be the PINNED one. See
336
+ // `callsPinViolation`.
337
+ const violation = callsPinViolation(parentDef, childDef, step.calls);
338
+ if (violation !== undefined)
339
+ throw new CallsPinError(step.calls, violation);
214
340
  const seedProvide = {};
215
341
  for (const [childInputName, parentArtifactName] of Object.entries(step.callsInputs ?? {})) {
216
342
  const parentArt = parentArts.get(parentArtifactName);
@@ -486,6 +612,49 @@ export class Engine {
486
612
  this.fire({ type: 'commit', workflow: parentWf, path: callsStem, action: 'reject' });
487
613
  this.fireSettled(parentWf);
488
614
  }
615
+ /**
616
+ * WS-6: record a `calls:` PIN violation as a debt on the PARENT calls
617
+ * artifact. Same clean-stop mechanism as `recordCallsDepthReject` — mark the
618
+ * artifact `rejected` and stamp the current gate fingerprint so the STEP-2 F2
619
+ * guard skips re-attempts instead of crash-looping the same refusal every
620
+ * tick — with a different, actionable message.
621
+ *
622
+ * Kept as its OWN recorder rather than folded into `recordCallsDepthReject`:
623
+ * the two refusals differ in what they mean (a depth trip says the definition
624
+ * set has a cycle that bypassed load-time validation; a pin violation says the
625
+ * installed store no longer holds the version this parent was pinned against)
626
+ * and therefore in what an operator should do next. Merging them into one
627
+ * parameterized recorder would blur exactly the distinction the message exists
628
+ * to carry.
629
+ *
630
+ * Like the depth recorder, this one needs NO carry-and-compare gate guard: a
631
+ * pin violation is decided from immutable provenance (the parent's §28 pinned
632
+ * snapshot and the resolved child's bundle digest), not from the gate
633
+ * snapshot, so a refusal decided at time T stays valid at recording time no
634
+ * matter what moved concurrently.
635
+ */
636
+ recordCallsDigestReject(parentWf, def, callsStem, gateStems, err, now) {
637
+ const text = `calls target '${err.target}' failed its pin check: ${err.detail}; `
638
+ + `the parent is pinned to the definition it was created against (§28), so this spawn was refused rather than `
639
+ + `run a different workflow body than the one that was pinned — reinstall the pinned bundle, or start a new `
640
+ + `parent instance against the current one`;
641
+ this.store.tx(() => {
642
+ const art = this.store.getArtifact(parentWf, callsStem);
643
+ if (!art)
644
+ return; // not yet materialized by pendingOwed — nothing to stamp
645
+ const gateArts = this.artMap(parentWf);
646
+ const fp = computeFingerprint(gateArts, gateStems);
647
+ this.store.putArtifact({
648
+ ...art,
649
+ acceptance: 'rejected',
650
+ fingerprint: fp,
651
+ reasons: [...art.reasons, reason('reject', 'structural', 'engine', text, art.version)],
652
+ });
653
+ this.settle(parentWf, def, now);
654
+ });
655
+ this.fire({ type: 'commit', workflow: parentWf, path: callsStem, action: 'reject' });
656
+ this.fireSettled(parentWf);
657
+ }
489
658
  /**
490
659
  * M2B: Maintain all `calls:` steps for a parent workflow.
491
660
  * Called at the top of tick (outside any tx) and as cascade-up prompt.
@@ -551,7 +720,7 @@ export class Engine {
551
720
  // schema-reject branch) instead of crash-looping every subsequent tick.
552
721
  let provision;
553
722
  try {
554
- provision = this.provisionCallsChild(parentWf, step, callsStem, gateStems, now);
723
+ provision = this.provisionCallsChild(parentWf, def, step, callsStem, gateStems, now);
555
724
  }
556
725
  catch (err) {
557
726
  if (err instanceof SchemaRefusalError) {
@@ -565,6 +734,15 @@ export class Engine {
565
734
  }
566
735
  continue;
567
736
  }
737
+ // WS-6: a pin violation is not a bug either — it means the installed
738
+ // store no longer holds the bundle this parent was pinned against. It
739
+ // becomes a visible debt on the PARENT calls artifact (never a silent
740
+ // divergent run, and never an uncaught throw that would take the whole
741
+ // tick down), and the STEP-2 F2 guard then stops the re-attempt loop.
742
+ if (err instanceof CallsPinError) {
743
+ this.recordCallsDigestReject(parentWf, def, callsStem, gateStems, err, now);
744
+ continue;
745
+ }
568
746
  throw err;
569
747
  }
570
748
  if (!provision)
@@ -806,7 +984,9 @@ export class Engine {
806
984
  * only this instance's own orders. See `TickResult` for the fold semantics.
807
985
  */
808
986
  tick(workflow, opts = {}) {
809
- return this.tickInternal(workflow, opts.now ?? nowMs(), opts.deep ?? true, opts.capabilities ?? [], new Set(), 0);
987
+ // `capabilities` is passed through AS GIVEN — an omitted filter (undefined)
988
+ // and an empty list are different claims. See `claimMatches`.
989
+ return this.tickInternal(workflow, opts.now ?? nowMs(), opts.deep ?? true, opts.capabilities, new Set(), 0, undefined, opts.matchModes ?? {});
810
990
  }
811
991
  /**
812
992
  * The recursive tick worker. Runs this instance's own maintain → reap →
@@ -847,7 +1027,7 @@ export class Engine {
847
1027
  * edge it hangs from. The guard is silent (no debt/reasons/events), mirroring
848
1028
  * the abort discipline of `publishCallsGreen`/`provisionCallsChild`.
849
1029
  */
850
- tickInternal(workflow, now, deep, capabilities, visited, depth, parentEdge) {
1030
+ tickInternal(workflow, now, deep, capabilities, visited, depth, parentEdge, matchModes = {}) {
851
1031
  if (depth > this.maxCallDepth) {
852
1032
  throw new Error(`calls depth limit exceeded (maxCallDepth=${this.maxCallDepth}) ticking '${workflow}': `
853
1033
  + `a calls: composition is deeper than the bound, which usually means a calls: cycle `
@@ -856,7 +1036,10 @@ export class Engine {
856
1036
  if (visited.has(workflow))
857
1037
  return { workflow, orders: [], reaped: 0, deferred: [] };
858
1038
  visited.add(workflow);
859
- const def = this.defFor(workflow);
1039
+ // ONE run-record read per frame yields both the pinned def and the run's
1040
+ // routing modifier. Each frame reads its OWN instance, so a calls: child is
1041
+ // composed against the child's modifier, never the parent's.
1042
+ const { def, modifier } = this.instanceFor(workflow);
860
1043
  // M2B: maintain calls: child instances before the normal tick/reap/claim cycle.
861
1044
  this.maintainCalls(workflow, def, now);
862
1045
  // B1: set inside the frame tx when the parent↔child consistency guard fires;
@@ -893,24 +1076,25 @@ export class Engine {
893
1076
  // Compute time facts for idle eligibility (clock-read boundary).
894
1077
  const timeFacts = this.computeTimeFacts(def, workflow, arts, now);
895
1078
  const firings = eligibleFirings(def, arts, timeFacts);
896
- const { selected, deferred } = this.applySchedule(workflow, def, firings, now, capabilities);
897
- // Clear alarm_at for any idle firing that was selected (consume the alarm).
898
- for (const f of selected) {
899
- if (f.cause === 'idle') {
900
- this.store.clearAlarm(workflow, f.step);
901
- }
902
- }
1079
+ const { selected, deferred } = this.applySchedule(workflow, def, firings, now, arts, capabilities, modifier, matchModes);
903
1080
  const orders = [];
904
1081
  const allDeferred = [...deferred];
905
1082
  for (const f of selected) {
906
- const claimed = this.claim(workflow, def, f, arts, now);
1083
+ const claimed = this.claim(workflow, def, f, arts, now, modifier);
907
1084
  if (claimed === 'in-flight') {
908
1085
  const d = { step: f.step, key: f.key, inputs: f.inputs, outputs: f.outputs, reason: 'in-flight' };
909
1086
  if (f.index !== undefined)
910
1087
  d.index = f.index;
911
1088
  allDeferred.push(d);
912
1089
  }
1090
+ else if (claimed && typeof claimed === 'object' && 'deferred' in claimed) {
1091
+ allDeferred.push(claimed.deferred);
1092
+ }
913
1093
  else if (claimed) {
1094
+ // Consume an idle alarm only after the order and run are claimed. A
1095
+ // workdir-unresolved firing must retain its alarm so the next tick can retry.
1096
+ if (f.cause === 'idle')
1097
+ this.store.clearAlarm(workflow, f.step);
914
1098
  orders.push(claimed);
915
1099
  }
916
1100
  }
@@ -931,7 +1115,7 @@ export class Engine {
931
1115
  parentWf: workflow,
932
1116
  step,
933
1117
  callsStem: step.produces[0].stem,
934
- });
1118
+ }, matchModes);
935
1119
  // orders: flatten; each Order already carries its own `workflow`.
936
1120
  result.orders.push(...cr.orders);
937
1121
  // deferred: stamp child-originated entries with the child id, preserving
@@ -1001,13 +1185,25 @@ export class Engine {
1001
1185
  }
1002
1186
  /**
1003
1187
  * Per-step cadence + daily budget + parallel cap over the eligible firings.
1004
- * A2: `capabilities` is the tick caller's optional claim filter — when non-empty, a
1005
- * step whose own `capabilities` are also non-empty is only schedulable when the two
1006
- * intersect; a disjoint step's firings are deferred as `'capability-mismatch'`.
1188
+ *
1189
+ * A2: `capabilities` is the tick caller's claim filter, matched against the
1190
+ * step's OFFERED capabilities — the authored list composed with the modifier
1191
+ * this firing will actually be offered under (`wise` + `deep` → `wise:deep`),
1192
+ * which is the same list the order will carry. `claimMatches` owns the rule;
1193
+ * see it for the four cases (no filter presented, capability-silent step,
1194
+ * empty caller list, both non-empty) and for what `matchModes` changes.
1195
+ * A firing this caller may not claim is deferred as `'capability-mismatch'`.
1007
1196
  * Filtering here (before cadence/budget) means a mismatched firing never
1008
1197
  * consumes the caller's slots and never perturbs cadence math.
1198
+ *
1199
+ * The filter is per FIRING, not per step, because §7 escalation is per firing:
1200
+ * on a map step one element may have escalated to `build:deep` while its
1201
+ * siblings are still offered at `build:standard`, and a crew bound to only one
1202
+ * of those must be judged against the compound its own firing carries. With no
1203
+ * escalation authored every firing of a step composes identically, so this
1204
+ * behaves exactly as a per-step filter would.
1009
1205
  */
1010
- applySchedule(workflow, def, firings, now, capabilities) {
1206
+ applySchedule(workflow, def, firings, now, arts, capabilities, modifier, matchModes) {
1011
1207
  const midnight = localMidnightMs(now);
1012
1208
  const selected = [];
1013
1209
  const deferred = [];
@@ -1018,18 +1214,23 @@ export class Engine {
1018
1214
  deferred.push(d);
1019
1215
  };
1020
1216
  for (const step of def.steps) {
1021
- const stepFirings = firings.filter((f) => f.step === step.name);
1022
- if (stepFirings.length === 0)
1217
+ const all = firings.filter((f) => f.step === step.name);
1218
+ if (all.length === 0)
1023
1219
  continue;
1024
- // A2: caller capability filter vs. step capabilities. Both non-empty and disjoint →
1025
- // this caller must not claim the step; defer every firing and skip it
1026
- // before it touches cadence/budget/slot math.
1027
- if (capabilities.length > 0 && step.capabilities && step.capabilities.length > 0 &&
1028
- !step.capabilities.some((l) => capabilities.includes(l))) {
1029
- for (const f of stepFirings)
1220
+ // A2: caller capability filter vs. this firing's COMPOSED offer. Composed
1221
+ // here, not authored, so a caller bound to `wise:deep` is judged against
1222
+ // what the order will actually carry — including when `deep` came from the
1223
+ // escalation rule rather than the run.
1224
+ const stepFirings = [];
1225
+ for (const f of all) {
1226
+ const offered = composeCapabilities(step.capabilities, this.routingFor(step, f, arts, modifier).modifier);
1227
+ if (claimMatches(offered, capabilities, matchModes))
1228
+ stepFirings.push(f);
1229
+ else
1030
1230
  defer(f, 'capability-mismatch');
1031
- continue;
1032
1231
  }
1232
+ if (stepFirings.length === 0)
1233
+ continue;
1033
1234
  const latest = this.store.latestRun(workflow, step.name);
1034
1235
  if (latest && now - latest.createdAt < step.cadenceSecs * 1000) {
1035
1236
  for (const f of stepFirings)
@@ -1103,7 +1304,7 @@ export class Engine {
1103
1304
  return this.staleness(task, now, ttl, maxLease) === 'fresh';
1104
1305
  }
1105
1306
  /** Claim a firing's lease via CAS, snapshot the fingerprint, open a run. */
1106
- claim(workflow, def, f, arts, now) {
1307
+ claim(workflow, def, f, arts, now, modifier) {
1107
1308
  const existing = this.store.getTask(workflow, f.step, f.key);
1108
1309
  if (existing && existing.status === 'claimed') {
1109
1310
  const run = existing.run ? this.store.getRun(existing.run) : undefined;
@@ -1126,7 +1327,21 @@ export class Engine {
1126
1327
  // CONFLICT DO UPDATE, no history table), so the issued order is unrecoverable
1127
1328
  // later unless captured here; this persisted packet is the replay/eval/paper
1128
1329
  // trail record (buildOrder is deterministic modulo run id).
1129
- const order = this.buildOrder(def, workflow, runId, f, arts);
1330
+ // §7: the modifier THIS offer composes with — the run's, or the step's
1331
+ // escalation target. Recomputed here rather than passed down from
1332
+ // `applySchedule` so the offer and the filter read the same function on the
1333
+ // same in-tx `arts` snapshot; nothing between them can move.
1334
+ const routing = this.routingFor(this.step(def, f.step), f, arts, modifier);
1335
+ const order = this.buildOrder(def, workflow, runId, f, arts, fp, routing);
1336
+ if (typeof order === 'object' && 'deferred' in order)
1337
+ return order;
1338
+ // One history record per rejection episode. Written HERE, not in
1339
+ // `buildOrder` (which is store-pure) and not on the deferred path (an offer
1340
+ // that never became an order promoted nothing). Idempotence is the store's:
1341
+ // the row id is derived from the episode, so the recomputation this rule
1342
+ // performs on every subsequent offer of the same episode inserts nothing.
1343
+ if (routing.escalation)
1344
+ this.recordEscalation(workflow, f, routing.escalation, now);
1130
1345
  // Stamp the run with the tick's clock so cadence/budget compare on one clock.
1131
1346
  this.store.insertRun(runId, { workflow, step: f.step, key: f.key, fingerprint: fp, order, ...(f.cause ? { cause: f.cause } : {}) }, now);
1132
1347
  this.store.putTask({
@@ -1140,7 +1355,18 @@ export class Engine {
1140
1355
  });
1141
1356
  return order;
1142
1357
  }
1143
- buildOrder(def, workflow, runId, f, arts) {
1358
+ /**
1359
+ * Build the reference-mode order for a firing (WP-B1). Carries the pinned
1360
+ * snapshot's `defDigest` plus routing/reference fields, dynamic `consumes`
1361
+ * values, and dynamic `owes` feedback — but NEVER authored prompt or
1362
+ * command text, and no `owes[].acceptance` (the lifecycle state is dynamic
1363
+ * engine state, not instructions). The digest comes from the instruction
1364
+ * source's identity for the exact `def` passed in — the pinned snapshot
1365
+ * from `defFor(workflow)`, never a fresh name lookup — and that same
1366
+ * snapshot is registered under the digest (a side effect of `digestOf`),
1367
+ * so the order stays resolvable after the live definition map changes.
1368
+ */
1369
+ buildOrder(def, workflow, runId, f, arts, consumedFingerprint, routing = {}) {
1144
1370
  const step = this.step(def, f.step);
1145
1371
  const consumes = {};
1146
1372
  for (const p of f.inputs) {
@@ -1148,11 +1374,71 @@ export class Engine {
1148
1374
  if (a?.value !== undefined)
1149
1375
  consumes[p] = a.value;
1150
1376
  }
1377
+ const unresolved = (detail) => {
1378
+ const deferred = {
1379
+ step: f.step,
1380
+ key: f.key,
1381
+ inputs: f.inputs,
1382
+ outputs: f.outputs,
1383
+ reason: 'workdir-unresolved',
1384
+ detail,
1385
+ };
1386
+ if (f.index !== undefined)
1387
+ deferred.index = f.index;
1388
+ return { deferred };
1389
+ };
1390
+ let resolvedWorkdir;
1391
+ if (step.workdirFrom !== undefined) {
1392
+ const parsed = parseWorkdirFrom(step.workdirFrom, step.consumes);
1393
+ if (!parsed) {
1394
+ return unresolved(`workdirFrom '${step.workdirFrom}': expected a consumed stem followed by a non-empty dotted value path`);
1395
+ }
1396
+ if (parsed.mode !== 'plain') {
1397
+ return unresolved(`workdirFrom '${step.workdirFrom}': source stem '${parsed.stem}' is not a plain consume`);
1398
+ }
1399
+ let value = consumes[parsed.stem];
1400
+ const segments = parsed.path.split('.');
1401
+ for (let i = 0; i < segments.length; i++) {
1402
+ const segment = segments[i];
1403
+ const pathAt = segments.slice(0, i + 1).join('.');
1404
+ if (value === undefined) {
1405
+ return unresolved(`workdirFrom '${step.workdirFrom}': value at '${pathAt}' is undefined`);
1406
+ }
1407
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) {
1408
+ return unresolved(`workdirFrom '${step.workdirFrom}': value at '${pathAt}' is not an object`);
1409
+ }
1410
+ if (!Object.prototype.hasOwnProperty.call(value, segment)) {
1411
+ return unresolved(`workdirFrom '${step.workdirFrom}': value at '${pathAt}' is undefined`);
1412
+ }
1413
+ value = value[segment];
1414
+ }
1415
+ if (typeof value !== 'string' || value.trim().length === 0) {
1416
+ return unresolved(`workdirFrom '${step.workdirFrom}': value at '${parsed.path}' must be a non-empty string`);
1417
+ }
1418
+ resolvedWorkdir = value;
1419
+ }
1420
+ else if (step.workdir !== undefined) {
1421
+ resolvedWorkdir = step.workdir;
1422
+ }
1423
+ // Digest registration is part of emitting an order. Keep it after dynamic
1424
+ // workdir resolution so an unresolved firing does not register an order
1425
+ // identity or reach the run insert below.
1426
+ const defDigest = this.instructionSource.digestOf(def);
1151
1427
  const owes = f.outputs.map((p) => {
1152
1428
  const a = arts.get(p);
1153
1429
  return {
1154
1430
  path: p,
1155
- acceptance: a?.acceptance ?? 'owed',
1431
+ // The TARGET version this claim's next successful producer commit will
1432
+ // land, not the currently-committed one: `green()` writes
1433
+ // `art.version + 1`, so that is the version a consumer will later see
1434
+ // and check a submission proof against. Issued by the engine inside the
1435
+ // claim transaction and persisted with the immutable order, so every
1436
+ // retry of the same claim reads the same target. Refusal paths that
1437
+ // leave the run open (schema-reject) do NOT bump the artifact, so the
1438
+ // target stays correct across in-claim retries; a path that does commit
1439
+ // closes the run, and a stale target then fails the consumer's version
1440
+ // check — a refusal, never an admitted unverified value.
1441
+ version: (a?.version ?? 0) + 1,
1156
1442
  judgmentRejects: a?.judgmentRejects ?? 0,
1157
1443
  schemaRejects: a?.schemaRejects ?? 0,
1158
1444
  reasons: a?.reasons ?? [],
@@ -1163,34 +1449,38 @@ export class Engine {
1163
1449
  workflow,
1164
1450
  step: f.step,
1165
1451
  key: f.key,
1452
+ defDigest,
1166
1453
  inputs: f.inputs,
1167
1454
  outputs: f.outputs,
1168
- prompt: substitute(step.body, {
1169
- WORKFLOW: workflow,
1170
- RUN: runId,
1171
- STEP: f.step,
1172
- KEY: f.key,
1173
- INDEX: f.index === undefined ? '' : String(f.index),
1174
- // Intentionally step-generic: a single firing can discharge multiple
1175
- // outputs (f.outputs) at once, so there is no single produce to
1176
- // resolve a per-produce maxAttempts override against here. This
1177
- // always reflects the step default even when individual produces
1178
- // override it (see model.ts effectiveMaxAttempts()).
1179
- MAX_ATTEMPTS: String(step.maxAttempts),
1180
- }),
1455
+ ...(resolvedWorkdir !== undefined ? { workdir: resolvedWorkdir } : {}),
1181
1456
  consumes,
1457
+ consumedFingerprint: { ...consumedFingerprint },
1182
1458
  owes,
1183
1459
  };
1184
1460
  if (f.index !== undefined)
1185
1461
  order.index = f.index;
1186
- if (step.workdir !== undefined)
1187
- order.workdir = step.workdir;
1462
+ // The routing snapshot of THIS offer. `capabilities` is the composed list —
1463
+ // absent on a capability-silent step, since there is nothing to compose
1464
+ // onto. `modifier` is stamped whenever the offer carries one, even for a
1465
+ // capability-silent step, so the brief can surface the grade of service
1466
+ // regardless of how the step routes; on an escalated offer it is the
1467
+ // escalation target, and `escalated` marks it as such so the hub does not
1468
+ // have to diff it against the run record. A claimed order is never
1469
+ // recomposed: composition happens per offer, and this record is what the
1470
+ // shift resolved against.
1471
+ const offered = composeCapabilities(step.capabilities, routing.modifier);
1472
+ if (offered.length > 0)
1473
+ order.capabilities = offered;
1474
+ if (routing.modifier !== undefined)
1475
+ order.modifier = routing.modifier;
1476
+ if (routing.escalation !== undefined)
1477
+ order.escalated = true;
1188
1478
  if (step.model !== undefined)
1189
1479
  order.model = step.model;
1190
1480
  if (step.executor !== undefined)
1191
- order.executor = step.executor;
1192
- if (step.command !== undefined)
1193
- order.command = step.command;
1481
+ order.worker = step.executor;
1482
+ if (step.judges !== undefined)
1483
+ order.judge = step.judges;
1194
1484
  if (step.spec !== undefined)
1195
1485
  order.spec = step.spec;
1196
1486
  if (step.x !== undefined)
@@ -1199,6 +1489,18 @@ export class Engine {
1199
1489
  order.cause = f.cause;
1200
1490
  return order;
1201
1491
  }
1492
+ /**
1493
+ * Resolve an order's static instructions through the SAME `(defDigest,
1494
+ * step, key)` boundary {@link Engine.resolver} uses: exact authored prompt
1495
+ * and command bytes (plus source-owned acceptance when the source carries
1496
+ * it), with the runtime placeholders materialized in the prompt. Purely a
1497
+ * read — never mutates the stored/emitted order, and never re-embeds text
1498
+ * on it. Throws `UnknownDefDigestError` when no verified record exists for
1499
+ * the order's digest — before any caller can execute a prompt or command.
1500
+ */
1501
+ resolveOrder(order) {
1502
+ return this.resolver.resolveOrder(order);
1503
+ }
1202
1504
  // ---- producer commits ------------------------------------------------------
1203
1505
  /**
1204
1506
  * Commit a singleton/map output green — or born-reject it if an input moved.
@@ -2415,7 +2717,16 @@ export class Engine {
2415
2717
  }
2416
2718
  return { workflow: childWf, def: childDef.name, done: cs.done, stalled, debts: cs.debts.length };
2417
2719
  }
2418
- defFor(workflow) {
2720
+ /**
2721
+ * The two per-instance facts a tick needs, from ONE run-record read: the def
2722
+ * this instance is pinned to, and the routing modifier it carries.
2723
+ *
2724
+ * Offer-time composition needs the modifier inside the claim path, where the
2725
+ * run record was not previously in scope. Reading it here — in the same
2726
+ * `getWorkflow` the def resolution already performs, once per tick frame —
2727
+ * keeps that cost at zero extra reads rather than one per claim.
2728
+ */
2729
+ instanceFor(workflow) {
2419
2730
  const wf = this.store.getWorkflow(workflow);
2420
2731
  if (!wf)
2421
2732
  throw new Error(`no such workflow instance: ${workflow}`);
@@ -2423,9 +2734,101 @@ export class Engine {
2423
2734
  // Rows created before this feature shipped have no snapshot — fall back
2424
2735
  // to today's name-resolution, unchanged. This is the compatibility path,
2425
2736
  // not an error: an un-pinned instance behaves exactly as it always has.
2426
- if (wf.defSnapshot !== undefined)
2427
- return wf.defSnapshot;
2428
- return this.resolveDef(wf.def);
2737
+ const def = wf.defSnapshot !== undefined ? wf.defSnapshot : this.resolveDef(wf.def);
2738
+ return wf.modifier !== undefined ? { def, modifier: wf.modifier } : { def };
2739
+ }
2740
+ defFor(workflow) {
2741
+ return this.instanceFor(workflow).def;
2742
+ }
2743
+ /**
2744
+ * §7: the modifier ONE offer of ONE firing composes with — the run's, or the
2745
+ * step's escalation target when the escalation rule has tripped.
2746
+ *
2747
+ * Derived, never stored. Every offer re-evaluates it from the artifact
2748
+ * counters, which is what makes the transition atomic (there is no separate
2749
+ * write that could half-apply), idempotent (recomputing it changes nothing),
2750
+ * and self-reversing (a human `retry` zeroes `judgmentRejects`, and the very
2751
+ * next offer composes with the run's modifier again).
2752
+ *
2753
+ * The trigger is per OUTPUT PATH: the firing escalates when any path it owes
2754
+ * has taken `escalation.after` judgment rejections. For a plain step that is
2755
+ * its single produce; for a map step each element firing escalates on its own
2756
+ * element's count, so one bad element does not promote the whole step.
2757
+ *
2758
+ * Three cases return the run's modifier untouched:
2759
+ * - the step authors no `escalation:` block — rejections run the normal
2760
+ * retry path at the same compound until the stall brake;
2761
+ * - no owed path has reached the threshold yet;
2762
+ * - the run's modifier ALREADY equals the escalation target — there is
2763
+ * nothing to promote, so no `escalated` flag and no history record. A
2764
+ * `deep` run whose builder escalates to `deep` is a no-op, not an event.
2765
+ *
2766
+ * `escalation` on the result is set ONLY in the case that actually changed
2767
+ * the routing; `claim` writes the history record from it.
2768
+ */
2769
+ routingFor(step, f, arts, runModifier) {
2770
+ const rule = step.escalation;
2771
+ if (rule === undefined || rule.modifier === runModifier) {
2772
+ return runModifier !== undefined ? { modifier: runModifier } : {};
2773
+ }
2774
+ // `f.outputs` order is the def's produce order, so the reported path is
2775
+ // deterministic when more than one output has crossed the threshold.
2776
+ const path = f.outputs.find((p) => isEscalated(arts.get(p), rule.after));
2777
+ if (path === undefined)
2778
+ return runModifier !== undefined ? { modifier: runModifier } : {};
2779
+ const art = arts.get(path);
2780
+ const escalation = {
2781
+ path,
2782
+ to: rule.modifier,
2783
+ after: rule.after,
2784
+ judgmentRejects: art?.judgmentRejects ?? 0,
2785
+ episode: rejectionEpisode(art),
2786
+ atVersion: art?.version ?? 0,
2787
+ };
2788
+ if (runModifier !== undefined)
2789
+ escalation.from = runModifier;
2790
+ return { modifier: rule.modifier, escalation };
2791
+ }
2792
+ /**
2793
+ * Write the ONE artifact-history record for an escalation promotion.
2794
+ *
2795
+ * `version: 0` on purpose. The promotion belongs to the artifact across a
2796
+ * whole rejection episode, not to any single produced version — the episode
2797
+ * spans every attempt from the crossing rejection to the human `retry` that
2798
+ * ends it, and those attempts each produce their own version. Anchoring the
2799
+ * record to a version would either mislabel it or (since the row id mixes in
2800
+ * the version) write one row per version, breaking the once-per-episode
2801
+ * guarantee. `getArtifactHistory` collects version-0 events in its
2802
+ * artifact-level `events` bucket, which is exactly where this belongs; the
2803
+ * version the promotion took effect at is in `metadata.atVersion`.
2804
+ *
2805
+ * The dedupe key is `(step, firing key, episode)`. Step and key are in it
2806
+ * because two different steps can owe the same path in different firings; the
2807
+ * episode ordinal is what makes a SECOND promotion, after a human `retry` and
2808
+ * three fresh rejections, a distinct row rather than a swallowed duplicate.
2809
+ */
2810
+ recordEscalation(workflow, f, e, now) {
2811
+ this.store.recordArtifactEvent({
2812
+ workflow,
2813
+ path: e.path,
2814
+ version: 0,
2815
+ action: ESCALATION_ACTION,
2816
+ actor: 'engine',
2817
+ dedupe: `${ESCALATION_ACTION}:${f.step}:${f.key}:${e.episode}`,
2818
+ timestamp: now,
2819
+ reason: `step '${f.step}' escalated to modifier '${e.to}' after ${e.judgmentRejects} judgment rejection(s)`
2820
+ + ` (threshold ${e.after})`,
2821
+ metadata: {
2822
+ step: f.step,
2823
+ key: f.key,
2824
+ to: e.to,
2825
+ after: e.after,
2826
+ judgmentRejects: e.judgmentRejects,
2827
+ episode: e.episode,
2828
+ atVersion: e.atVersion,
2829
+ ...(e.from !== undefined ? { from: e.from } : {}),
2830
+ },
2831
+ });
2429
2832
  }
2430
2833
  step(def, name) {
2431
2834
  const l = def.steps.find((x) => x.name === name);
@@ -2526,9 +2929,6 @@ function nextIndex(arts, stem) {
2526
2929
  }
2527
2930
  return max + 1;
2528
2931
  }
2529
- function substitute(body, vars) {
2530
- return body.replace(/\$\{(\w+)\}/g, (m, k) => (k in vars ? vars[k] ?? '' : m));
2531
- }
2532
2932
  /** M2B: structural deep-equal, order-insensitive on object keys (artifact values are always JSON-shaped). */
2533
2933
  function deepEqual(a, b) {
2534
2934
  if (a === b)