owenloop 0.5.9 → 0.5.11

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 (86) hide show
  1. package/CHANGELOG.md +51 -0
  2. package/README.md +77 -37
  3. package/bin/owenloop.mjs +16 -1
  4. package/dist/packages/work/src/agent/loop.js +7 -0
  5. package/dist/packages/work/src/bundle/pull.d.ts +21 -0
  6. package/dist/packages/work/src/bundle/pull.js +118 -0
  7. package/dist/packages/work/src/exec/instructions.d.ts +4 -1
  8. package/dist/packages/work/src/exec/instructions.js +3 -0
  9. package/dist/packages/work/src/exec/loop.d.ts +1 -1
  10. package/dist/packages/work/src/exec/loop.js +92 -14
  11. package/dist/packages/work/src/harness/claude.js +16 -0
  12. package/dist/packages/work/src/harness/codex.d.ts +8 -0
  13. package/dist/packages/work/src/harness/codex.js +27 -1
  14. package/dist/packages/work/src/harness/contract.d.ts +9 -0
  15. package/dist/packages/work/src/roles/agent-run.js +38 -10
  16. package/dist/packages/work/src/roles/exec.js +25 -8
  17. package/dist/packages/work/src/shift/loop.js +118 -4
  18. package/dist/packages/work/src/shift/runtime.d.ts +3 -0
  19. package/dist/packages/work/src/shift/runtime.js +10 -1
  20. package/dist/packages/work/src/submit-proof.d.ts +11 -8
  21. package/dist/packages/work/src/submit-proof.js +11 -8
  22. package/dist/src/capabilities.d.ts +70 -6
  23. package/dist/src/capabilities.js +49 -6
  24. package/dist/src/capability-mapping-client.d.ts +29 -0
  25. package/dist/src/capability-mapping-client.js +160 -0
  26. package/dist/src/cli.d.ts +2 -2
  27. package/dist/src/cli.js +1200 -166
  28. package/dist/src/defs.d.ts +41 -1
  29. package/dist/src/defs.js +461 -92
  30. package/dist/src/engine.d.ts +108 -22
  31. package/dist/src/engine.js +573 -85
  32. package/dist/src/factory.js +5 -3
  33. package/dist/src/hub.d.ts +77 -0
  34. package/dist/src/hub.js +162 -0
  35. package/dist/src/implements.d.ts +37 -0
  36. package/dist/src/implements.js +790 -0
  37. package/dist/src/index.d.ts +12 -10
  38. package/dist/src/index.js +7 -6
  39. package/dist/src/mcp/serve.js +254 -45
  40. package/dist/src/mcp/server.d.ts +10 -7
  41. package/dist/src/mcp/server.js +53 -8
  42. package/dist/src/model.d.ts +46 -10
  43. package/dist/src/model.js +224 -78
  44. package/dist/src/order-resolver.js +1 -0
  45. package/dist/src/store/def-source.d.ts +19 -0
  46. package/dist/src/store/def-source.js +87 -17
  47. package/dist/src/store/gc-recovery.d.ts +46 -0
  48. package/dist/src/store/gc-recovery.js +258 -0
  49. package/dist/src/store/gc.d.ts +94 -0
  50. package/dist/src/store/gc.js +563 -0
  51. package/dist/src/store/index.d.ts +3 -1
  52. package/dist/src/store/index.js +2 -0
  53. package/dist/src/store/install.d.ts +34 -5
  54. package/dist/src/store/install.js +73 -11
  55. package/dist/src/store/pre-commit-verifier.js +42 -2
  56. package/dist/src/store/snapshot-guard.d.ts +18 -0
  57. package/dist/src/store/snapshot-guard.js +94 -0
  58. package/dist/src/store.d.ts +66 -4
  59. package/dist/src/store.js +333 -12
  60. package/dist/src/types.d.ts +97 -17
  61. package/dist/src/types.js +4 -0
  62. package/dist/src/util.js +4 -1
  63. package/docs/authoring.md +214 -9
  64. package/docs/bundles.md +19 -0
  65. package/docs/cli.md +270 -30
  66. package/docs/crypto.md +13 -7
  67. package/docs/design.md +107 -46
  68. package/docs/evals/mcp-charter-baseline.json +428 -0
  69. package/docs/mcp-charter-eval.md +124 -0
  70. package/docs/shift-logs.md +18 -0
  71. package/docs/wire-contracts.md +28 -7
  72. package/examples/workflows/compile-dev-playbook.yaml +1 -1
  73. package/examples/workflows/ship.yaml +28 -2
  74. package/package.json +2 -1
  75. package/plugins/claude-code/plugin/.claude-plugin/plugin.json +1 -1
  76. package/plugins/claude-code/plugin/.mcp.json +1 -1
  77. package/plugins/claude-code/plugin/skills/author/SKILL.md +22 -0
  78. package/plugins/claude-code/plugin/skills/ephemeral/SKILL.md +95 -0
  79. package/plugins/claude-code/plugin/skills/graduate/SKILL.md +156 -0
  80. package/plugins/claude-code/plugin/skills/plan/SKILL.md +236 -0
  81. package/plugins/codex/plugins/owenloop/.codex-plugin/plugin.json +1 -1
  82. package/plugins/codex/plugins/owenloop/.mcp.json +1 -1
  83. package/plugins/codex/plugins/owenloop/skills/author/SKILL.md +22 -0
  84. package/plugins/codex/plugins/owenloop/skills/ephemeral/SKILL.md +95 -0
  85. package/plugins/codex/plugins/owenloop/skills/graduate/SKILL.md +156 -0
  86. package/plugins/codex/plugins/owenloop/skills/plan/SKILL.md +236 -0
@@ -10,11 +10,14 @@
10
10
  * born-rejects the output instead of greening it.
11
11
  */
12
12
  import { elementPath, parseElement, parseWorkdirFrom, sealPath, } from "./paths.js";
13
- import { collectionStem, computeFingerprint, eligibleFirings, fingerprintMatches, groupBlockingWinner, isEscalated, isGreen, judgeNameOf, maintainDecisions, owedSchema, pendingOwed, plainConsumes, rejectionEpisode, requiredInputs, workflowStatus, } from "./model.js";
13
+ import { collectionStem, computeFingerprint, eligibleFirings, fingerprintMatches, groupBlockingWinner, isEscalated, isGreen, judgeNameOf, maintainDecisions, owedSchema, pendingOwed, plainConsumes, rejectionEpisode, requiredInputs, workflowDone, workflowStatus, } from "./model.js";
14
14
  import { summarizeIssues, validateValue } from "./schema.js";
15
15
  import { hashDef } from "./defs.js";
16
- import { applyCapabilityRewrites, claimMatches, composeCapabilities } from "./capabilities.js";
16
+ import { checkInterfaceCompatibility } from "./implements.js";
17
+ import { isDefDigest, parseWorkflowCoordinate } from "./store/types.js";
18
+ import { applyCapabilityMappings, applyCapabilityRewrites, claimMatches, composeCapabilities } from "./capabilities.js";
17
19
  import { localMidnightMs, nowMs, randId } from "./util.js";
20
+ import { isCallStep } from "./types.js";
18
21
  import { createDefInstructionSource, OrderResolver } from "./order-resolver.js";
19
22
  const DEFAULT_REAP_TTL_MS = 2 * 60 * 60 * 1000; // 2h
20
23
  /**
@@ -80,6 +83,74 @@ export class CallsPinError extends Error {
80
83
  this.detail = detail;
81
84
  }
82
85
  }
86
+ /**
87
+ * A caller-supplied start binding is missing, malformed, unresolved, or
88
+ * incompatible. This is a named 400-class refusal: no workflow row exists when
89
+ * it is thrown from the public start path.
90
+ */
91
+ export class InterfaceBindingRefusalError extends Error {
92
+ name = 'InterfaceBindingRefusalError';
93
+ workflow;
94
+ step;
95
+ interfaceName;
96
+ interfaceVersion;
97
+ detail;
98
+ constructor(workflow, step, claim, detail) {
99
+ const interfaceName = typeof claim?.name === 'string' && claim.name.trim() !== '' ? claim.name : undefined;
100
+ const interfaceVersion = typeof claim?.version === 'string' && claim.version.trim() !== '' ? claim.version : undefined;
101
+ const coordinate = interfaceName === undefined
102
+ ? 'an unknown interface coordinate'
103
+ : `'${interfaceName}${interfaceVersion === undefined ? '' : `@${interfaceVersion}`}'`;
104
+ super(`refusing to start workflow '${workflow}': interface binding for ${coordinate} `
105
+ + `(step '${step}') ${detail}`);
106
+ this.workflow = workflow;
107
+ this.step = step;
108
+ this.interfaceName = interfaceName;
109
+ this.interfaceVersion = interfaceVersion;
110
+ this.detail = detail;
111
+ }
112
+ }
113
+ /**
114
+ * A persisted interface binding no longer agrees with the optimistically
115
+ * resolved child at spawn time. The provision transaction rolls back and the
116
+ * parent call artifact receives one visible structural refusal.
117
+ */
118
+ export class InterfaceCallPinError extends Error {
119
+ name = 'InterfaceCallPinError';
120
+ interface;
121
+ target;
122
+ detail;
123
+ constructor(claim, target, detail) {
124
+ super(`interface call '${claim.name}@${claim.version}' bound to '${target}' failed its pin check: ${detail}`);
125
+ this.interface = { ...claim };
126
+ this.target = target;
127
+ this.detail = detail;
128
+ }
129
+ }
130
+ function sameInterfaceClaim(a, b) {
131
+ return a.name === b.name && a.version === b.version;
132
+ }
133
+ function callTargetLabel(step) {
134
+ if (step.calls !== undefined)
135
+ return step.calls;
136
+ const claim = step.callsInterface;
137
+ return claim === undefined ? '<invalid call step>' : `${claim.name}@${claim.version}`;
138
+ }
139
+ function hasExactImplementationClaim(def, expected) {
140
+ const claims = def.x?.implements;
141
+ if (!Array.isArray(claims))
142
+ return false;
143
+ return claims.some((claim) => {
144
+ if (typeof claim !== 'object' || claim === null || Array.isArray(claim))
145
+ return false;
146
+ const record = claim;
147
+ const keys = Object.keys(record);
148
+ return keys.length === 2
149
+ && keys.every((key) => key === 'name' || key === 'version')
150
+ && record.name === expected.name
151
+ && record.version === expected.version;
152
+ });
153
+ }
83
154
  /**
84
155
  * WS-6: check that `childDef` is the definition the parent's own bundle pinned
85
156
  * for the `calls:` target `target`. Returns `undefined` when the edge is fine,
@@ -193,11 +264,198 @@ export class Engine {
193
264
  };
194
265
  }
195
266
  // ---- instance lifecycle ----------------------------------------------------
267
+ /** Validate, resolve, and JSON-normalize every supplied start binding. */
268
+ normalizeInterfaceBindings(defName, def, supplied) {
269
+ const raw = supplied ?? [];
270
+ const refuse = (step, claim, detail) => {
271
+ throw new InterfaceBindingRefusalError(defName, step, claim, detail);
272
+ };
273
+ const rawBindings = Array.isArray(raw)
274
+ ? raw
275
+ : refuse('interfaceBindings', undefined, 'must be supplied as an array');
276
+ const bindings = [];
277
+ const targets = [];
278
+ for (const [index, candidate] of rawBindings.entries()) {
279
+ const stepLabel = `interfaceBindings[${index}]`;
280
+ if (typeof candidate !== 'object' || candidate === null || Array.isArray(candidate)) {
281
+ refuse(stepLabel, undefined, 'must be an object');
282
+ }
283
+ const candidateRecord = candidate;
284
+ const extraBindingKeys = Object.keys(candidateRecord)
285
+ .filter((key) => key !== 'interface' && key !== 'target' && key !== 'digest' && key !== 'signature');
286
+ if (extraBindingKeys.length > 0) {
287
+ refuse(stepLabel, undefined, `has unknown field${extraBindingKeys.length === 1 ? '' : 's'} ${extraBindingKeys.join(', ')}`);
288
+ }
289
+ const cloned = (() => {
290
+ try {
291
+ const json = JSON.stringify(candidateRecord);
292
+ if (json === undefined)
293
+ return refuse(stepLabel, undefined, 'is not JSON-serializable');
294
+ return JSON.parse(json);
295
+ }
296
+ catch (error) {
297
+ if (error instanceof InterfaceBindingRefusalError)
298
+ throw error;
299
+ return refuse(stepLabel, undefined, `is not JSON-serializable: ${error.message}`);
300
+ }
301
+ })();
302
+ const interfaceValue = cloned.interface;
303
+ if (typeof interfaceValue !== 'object' || interfaceValue === null || Array.isArray(interfaceValue)) {
304
+ refuse(stepLabel, undefined, ".interface must be a map with exactly 'name' and 'version'");
305
+ }
306
+ const interfaceRecord = interfaceValue;
307
+ const claim = {
308
+ ...(typeof interfaceRecord.name === 'string' ? { name: interfaceRecord.name } : {}),
309
+ ...(typeof interfaceRecord.version === 'string' ? { version: interfaceRecord.version } : {}),
310
+ };
311
+ const extraInterfaceKeys = Object.keys(interfaceRecord).filter((key) => key !== 'name' && key !== 'version');
312
+ if (extraInterfaceKeys.length > 0) {
313
+ refuse(stepLabel, claim, `.interface has unknown field${extraInterfaceKeys.length === 1 ? '' : 's'} ${extraInterfaceKeys.join(', ')}`);
314
+ }
315
+ const interfaceName = typeof interfaceRecord.name === 'string' && interfaceRecord.name.trim() !== ''
316
+ ? interfaceRecord.name
317
+ : refuse(stepLabel, claim, '.interface.name must be a non-empty string');
318
+ const interfaceVersion = typeof interfaceRecord.version === 'string' && interfaceRecord.version.trim() !== ''
319
+ ? interfaceRecord.version
320
+ : refuse(stepLabel, claim, '.interface.version must be a non-empty string');
321
+ const normalizedClaim = {
322
+ name: interfaceName,
323
+ version: interfaceVersion,
324
+ };
325
+ if (bindings.some((binding) => sameInterfaceClaim(binding.interface, normalizedClaim))) {
326
+ refuse(stepLabel, normalizedClaim, 'is duplicated; each exact name/version pair must have one unambiguous binding');
327
+ }
328
+ const target = typeof cloned.target === 'string'
329
+ ? cloned.target
330
+ : refuse(stepLabel, normalizedClaim, '.target must be an exact installed workflow coordinate');
331
+ try {
332
+ parseWorkflowCoordinate(target);
333
+ }
334
+ catch (error) {
335
+ refuse(stepLabel, normalizedClaim, `.target is not an exact installed workflow coordinate: ${error.message}`);
336
+ }
337
+ const digest = typeof cloned.digest === 'string' && isDefDigest(cloned.digest)
338
+ ? cloned.digest
339
+ : refuse(stepLabel, normalizedClaim, '.digest must be a canonical lowercase 64-hex bundle digest');
340
+ const signatureRecord = typeof cloned.signature === 'object'
341
+ && cloned.signature !== null
342
+ && !Array.isArray(cloned.signature)
343
+ ? cloned.signature
344
+ : refuse(stepLabel, normalizedClaim, '.signature must be a map with inputs and outputs arrays');
345
+ const extraSignatureKeys = Object.keys(signatureRecord).filter((key) => key !== 'inputs' && key !== 'outputs');
346
+ if (extraSignatureKeys.length > 0) {
347
+ refuse(stepLabel, normalizedClaim, `.signature has unknown field${extraSignatureKeys.length === 1 ? '' : 's'} ${extraSignatureKeys.join(', ')}`);
348
+ }
349
+ const normalizeArtifacts = (value, path) => {
350
+ const artifacts = Array.isArray(value)
351
+ ? value
352
+ : refuse(stepLabel, normalizedClaim, `.signature.${path} must be an array`);
353
+ return artifacts.map((artifact, artifactIndex) => {
354
+ if (typeof artifact !== 'object' || artifact === null || Array.isArray(artifact)) {
355
+ refuse(stepLabel, normalizedClaim, `.signature.${path}[${artifactIndex}] must be an object`);
356
+ }
357
+ const artifactRecord = artifact;
358
+ const extraArtifactKeys = Object.keys(artifactRecord).filter((key) => key !== 'name' && key !== 'schema');
359
+ if (extraArtifactKeys.length > 0) {
360
+ refuse(stepLabel, normalizedClaim, `.signature.${path}[${artifactIndex}] has unknown field${extraArtifactKeys.length === 1 ? '' : 's'} ${extraArtifactKeys.join(', ')}`);
361
+ }
362
+ const artifactName = typeof artifactRecord.name === 'string' && artifactRecord.name.trim() !== ''
363
+ ? artifactRecord.name
364
+ : refuse(stepLabel, normalizedClaim, `.signature.${path}[${artifactIndex}].name must be a non-empty string`);
365
+ if (artifactRecord.schema !== undefined
366
+ && typeof artifactRecord.schema !== 'boolean'
367
+ && (typeof artifactRecord.schema !== 'object' || artifactRecord.schema === null || Array.isArray(artifactRecord.schema))) {
368
+ refuse(stepLabel, normalizedClaim, `.signature.${path}[${artifactIndex}].schema must be a JSON Schema object or boolean`);
369
+ }
370
+ return artifactRecord.schema === undefined
371
+ ? { name: artifactName }
372
+ : { name: artifactName, schema: artifactRecord.schema };
373
+ });
374
+ };
375
+ const signature = {
376
+ inputs: normalizeArtifacts(signatureRecord.inputs, 'inputs'),
377
+ outputs: normalizeArtifacts(signatureRecord.outputs, 'outputs'),
378
+ };
379
+ const targetDef = (() => {
380
+ try {
381
+ return this.resolveDef(target, def, digest);
382
+ }
383
+ catch (error) {
384
+ return refuse(stepLabel, normalizedClaim, `cannot resolve target '${target}' at digest ${digest}: ${error.message}`);
385
+ }
386
+ })();
387
+ if (targetDef.bundleDigest !== digest) {
388
+ refuse(stepLabel, normalizedClaim, `resolved target '${target}' carries bundle digest ${targetDef.bundleDigest ?? '<none>'}, expected ${digest}`);
389
+ }
390
+ if (!hasExactImplementationClaim(targetDef, normalizedClaim)) {
391
+ refuse(stepLabel, normalizedClaim, `target '${target}' does not carry an exact valid x.implements claim for ${normalizedClaim.name}@${normalizedClaim.version}`);
392
+ }
393
+ const targetOutputs = targetDef.outputs ?? [];
394
+ if (targetOutputs.length !== 1) {
395
+ refuse(stepLabel, normalizedClaim, `target '${target}' declares ${targetOutputs.length} public outputs; interface calls v1 requires exactly one`);
396
+ }
397
+ const signatureInputNames = new Set(signature.inputs.map((input) => input.name));
398
+ const targetInputNames = new Set(targetDef.inputs.map((input) => input.name));
399
+ for (const interfaceStep of def.steps) {
400
+ if (interfaceStep.callsInterface === undefined || !sameInterfaceClaim(interfaceStep.callsInterface, normalizedClaim))
401
+ continue;
402
+ for (const childInput of Object.keys(interfaceStep.callsInputs ?? {})) {
403
+ if (!signatureInputNames.has(childInput)) {
404
+ refuse(interfaceStep.name, normalizedClaim, `maps input '${childInput}', which the supplied interface signature does not declare`);
405
+ }
406
+ if (!targetInputNames.has(childInput)) {
407
+ refuse(interfaceStep.name, normalizedClaim, `maps input '${childInput}', which target '${target}' does not declare`);
408
+ }
409
+ }
410
+ }
411
+ const compatibility = checkInterfaceCompatibility(signature, targetDef);
412
+ if (!compatibility.compatible) {
413
+ refuse(stepLabel, normalizedClaim, `target '${target}' is incompatible: ${compatibility.issues.map((issue) => issue.message).join('; ')}`);
414
+ }
415
+ bindings.push({
416
+ interface: normalizedClaim,
417
+ target,
418
+ digest,
419
+ signature,
420
+ });
421
+ targets.push(targetDef);
422
+ }
423
+ for (const step of def.steps) {
424
+ if (step.callsInterface === undefined)
425
+ continue;
426
+ if (!bindings.some((binding) => sameInterfaceClaim(binding.interface, step.callsInterface))) {
427
+ refuse(step.name, step.callsInterface, 'is missing; every directly called interface must be bound at instance start');
428
+ }
429
+ }
430
+ return { bindings, targets };
431
+ }
432
+ /** Pure child-insert guard over an already-normalized inherited binding set. */
433
+ assertDirectInterfaceBindings(defName, def, bindings) {
434
+ for (const step of def.steps) {
435
+ if (step.callsInterface === undefined)
436
+ continue;
437
+ const binding = (bindings ?? []).find((candidate) => sameInterfaceClaim(candidate.interface, step.callsInterface));
438
+ if (binding === undefined) {
439
+ throw new InterfaceBindingRefusalError(defName, step.name, step.callsInterface, 'is missing from the inherited immutable binding set');
440
+ }
441
+ const interfaceInputs = new Set(binding.signature.inputs.map((input) => input.name));
442
+ for (const childInput of Object.keys(step.callsInputs ?? {})) {
443
+ if (!interfaceInputs.has(childInput)) {
444
+ throw new InterfaceBindingRefusalError(defName, step.name, step.callsInterface, `maps input '${childInput}', which the inherited interface signature does not declare`);
445
+ }
446
+ }
447
+ }
448
+ }
196
449
  /** Start a workflow instance: persist it, seed its declared inputs, settle. */
197
450
  createInstance(defName, opts = {}) {
198
451
  const def = this.resolveDef(defName);
452
+ const normalized = this.normalizeInterfaceBindings(defName, def, opts.interfaceBindings);
199
453
  const id = randId('wf');
200
- this.store.tx(() => this.createInstanceInTx(defName, def, id, opts));
454
+ const createOpts = {
455
+ ...opts,
456
+ ...(normalized.bindings.length === 0 ? { interfaceBindings: undefined } : { interfaceBindings: normalized.bindings }),
457
+ };
458
+ this.store.txWithWorkflowSnapshots([def, ...normalized.targets], () => this.createInstanceInTx(defName, def, id, createOpts));
201
459
  this.fire({ type: 'instance', workflow: id, def: defName });
202
460
  this.fireSettled(id);
203
461
  return id;
@@ -211,6 +469,10 @@ export class Engine {
211
469
  * under a single `BEGIN IMMEDIATE` without nesting transactions.
212
470
  */
213
471
  createInstanceInTx(defName, def, id, opts) {
472
+ // Root starts were fully resolved before SQLite; children inherit that
473
+ // normalized set. Re-check only direct presence here so a statically-called
474
+ // descendant can never be inserted without the interface it will need.
475
+ this.assertDirectInterfaceBindings(defName, def, opts.interfaceBindings);
214
476
  // §28: pin this instance to the def it was created against — a snapshot
215
477
  // of the fully-expanded compiled def plus its content hash. Every new
216
478
  // instance is stamped; "no snapshot" is strictly a legacy-row
@@ -220,6 +482,8 @@ export class Engine {
220
482
  wfData.title = opts.title;
221
483
  if (opts.params !== undefined)
222
484
  wfData.params = opts.params;
485
+ if (opts.interfaceBindings !== undefined)
486
+ wfData.interfaceBindings = opts.interfaceBindings;
223
487
  // Validated against the SNAPSHOT being pinned on this same row, not
224
488
  // against a live re-resolution — the modifier and the vocabulary that
225
489
  // legitimizes it are stamped together. Later bound-artifact writes still
@@ -299,7 +563,27 @@ export class Engine {
299
563
  // gate advance landed" (discard). Pure computation over the already-fetched
300
564
  // `parentArts` — no extra in-tx store read (E2 busy_timeout GOTCHA-safe).
301
565
  let seenGateFp;
302
- const run = () => this.store.tx(() => {
566
+ const needsSnapshot = Symbol('needs-workflow-snapshot');
567
+ let snapshotDef;
568
+ let optimisticInterfaceBinding;
569
+ // Interface targets are selected once, stored on the parent, and resolved by
570
+ // exact digest BEFORE either the workflow-store guard or SQLite write lock.
571
+ // The transaction below re-reads and compares the persisted selection.
572
+ if (step.callsInterface !== undefined) {
573
+ const parent = this.store.getWorkflow(parentWf);
574
+ const binding = parent?.interfaceBindings?.find((candidate) => sameInterfaceClaim(candidate.interface, step.callsInterface));
575
+ if (binding === undefined) {
576
+ throw new InterfaceCallPinError(step.callsInterface, '<missing>', 'the parent workflow row has no matching immutable start-time binding');
577
+ }
578
+ optimisticInterfaceBinding = binding;
579
+ try {
580
+ snapshotDef = this.resolveDef(binding.target, parentDef, binding.digest);
581
+ }
582
+ catch (error) {
583
+ throw new InterfaceCallPinError(step.callsInterface, binding.target, `the exact digest-scoped target could not be resolved: ${error.message}`);
584
+ }
585
+ }
586
+ const transactionBody = () => {
303
587
  // 1. FRESH parent snapshot — re-read inside the write lock; never trust
304
588
  // the caller's STEP-1 map.
305
589
  const parentArts = this.artMap(parentWf);
@@ -321,24 +605,61 @@ export class Engine {
321
605
  if (deepEqual(fp, parentCallsArt.fingerprint ?? {}))
322
606
  return null;
323
607
  }
608
+ // Re-read immutable instance state under the SAME BEGIN IMMEDIATE as the
609
+ // gate, find-or-create, and input sync. Interface calls compare both the
610
+ // stored selection and the already-loaded child's bundle digest here;
611
+ // there is no resolver/catalog/filesystem access inside this boundary.
612
+ const parentRow = this.store.getWorkflow(parentWf);
613
+ if (parentRow === undefined)
614
+ throw new Error(`no such workflow instance: ${parentWf}`);
615
+ let target;
616
+ if (step.callsInterface !== undefined) {
617
+ const freshBinding = parentRow.interfaceBindings?.find((candidate) => sameInterfaceClaim(candidate.interface, step.callsInterface));
618
+ if (freshBinding === undefined) {
619
+ throw new InterfaceCallPinError(step.callsInterface, optimisticInterfaceBinding?.target ?? '<missing>', 'the matching persisted binding disappeared before child provisioning');
620
+ }
621
+ if (optimisticInterfaceBinding === undefined
622
+ || freshBinding.target !== optimisticInterfaceBinding.target
623
+ || freshBinding.digest !== optimisticInterfaceBinding.digest) {
624
+ throw new InterfaceCallPinError(step.callsInterface, freshBinding.target, `the persisted binding changed from ${optimisticInterfaceBinding?.target ?? '<missing>'}`
625
+ + `@${optimisticInterfaceBinding?.digest ?? '<missing>'} to ${freshBinding.target}@${freshBinding.digest}`);
626
+ }
627
+ if (snapshotDef === undefined) {
628
+ throw new InterfaceCallPinError(step.callsInterface, freshBinding.target, 'no exact target was resolved before the write transaction');
629
+ }
630
+ if (snapshotDef.bundleDigest !== freshBinding.digest) {
631
+ throw new InterfaceCallPinError(step.callsInterface, freshBinding.target, `the resolved definition carries bundle digest ${snapshotDef.bundleDigest ?? '<none>'}, expected ${freshBinding.digest}`);
632
+ }
633
+ target = freshBinding.target;
634
+ }
635
+ else {
636
+ target = step.calls;
637
+ }
324
638
  // 4. Find-or-create the child (in-tx check-then-insert — absorbs the old
325
639
  // spawnChildIfAbsent guarantee, only its home moved).
326
640
  let child = this.store.findChildByParent(parentWf, callsStem);
327
641
  let created = false;
328
642
  let childDef;
329
643
  if (!child) {
644
+ // Resolving a new child's CAS def must happen before its coordinated
645
+ // transaction acquires SQLite. Return a read-only sentinel on the
646
+ // first pass; `run` resolves, locks/revalidates the bundle store, and
647
+ // then repeats every gate/child read under the guarded write tx.
648
+ if (snapshotDef === undefined)
649
+ return needsSnapshot;
330
650
  const childId = randId('wf');
331
651
  // WS-6: resolve IN THE PARENT'S SCOPE. `parentDef` is the parent's own
332
652
  // §28 pin (defFor prefers `defSnapshot` over the live resolver), so a
333
653
  // bare `calls:` from a def installed out of a CAS bundle binds to that
334
654
  // same bundle's workflow — the version the parent was pinned against —
335
655
  // and not to whatever a later install happened to name the same thing.
336
- childDef = this.resolveDef(step.calls, parentDef);
337
- // WS-6: and the resolved child must still be the PINNED one. See
338
- // `callsPinViolation`.
339
- const violation = callsPinViolation(parentDef, childDef, step.calls);
340
- if (violation !== undefined)
341
- throw new CallsPinError(step.calls, violation);
656
+ childDef = snapshotDef;
657
+ // WS-6: concrete calls retain their existing authoring-time pin path.
658
+ if (step.calls !== undefined) {
659
+ const violation = callsPinViolation(parentDef, childDef, step.calls);
660
+ if (violation !== undefined)
661
+ throw new CallsPinError(step.calls, violation);
662
+ }
342
663
  const seedProvide = {};
343
664
  for (const [childInputName, parentArtifactName] of Object.entries(step.callsInputs ?? {})) {
344
665
  const parentArt = parentArts.get(parentArtifactName);
@@ -348,16 +669,38 @@ export class Engine {
348
669
  }
349
670
  // createInstanceInTx validates the seed against the child input schema
350
671
  // and throws SchemaRefusalError (tx rolls back — no orphan child).
351
- this.createInstanceInTx(step.calls, childDef, childId, {
672
+ const childOpts = {
352
673
  producedBy: { parentWf, parentPath: callsStem },
353
674
  provide: seedProvide,
354
- });
675
+ };
676
+ if (parentRow.interfaceBindings !== undefined) {
677
+ childOpts.interfaceBindings = parentRow.interfaceBindings;
678
+ }
679
+ try {
680
+ this.createInstanceInTx(target, childDef, childId, childOpts);
681
+ }
682
+ catch (error) {
683
+ if (error instanceof InterfaceBindingRefusalError) {
684
+ const missingClaim = {
685
+ name: error.interfaceName ?? '<unknown>',
686
+ version: error.interfaceVersion ?? '<unknown>',
687
+ };
688
+ throw new InterfaceCallPinError(missingClaim, target, error.detail);
689
+ }
690
+ throw error;
691
+ }
355
692
  child = this.store.getWorkflow(childId);
356
693
  created = true;
357
694
  }
358
695
  else {
359
696
  // §28: read the existing child per its own pinned snapshot.
360
697
  childDef = this.defFor(child.id);
698
+ if (step.callsInterface !== undefined) {
699
+ const expectedDigest = optimisticInterfaceBinding.digest;
700
+ if (child.def !== target || childDef.bundleDigest !== expectedDigest) {
701
+ throw new InterfaceCallPinError(step.callsInterface, target, `existing child is '${child.def}' at digest ${childDef.bundleDigest ?? '<none>'}, expected '${target}' at ${expectedDigest}`);
702
+ }
703
+ }
361
704
  }
362
705
  // 5. Synchronize EVERY mapped child input from the SAME fresh snapshot.
363
706
  // A freshly-seeded child already equals the snapshot, so its inputs
@@ -395,7 +738,22 @@ export class Engine {
395
738
  if (created || provided.length > 0)
396
739
  this.settle(child.id, childDef, now);
397
740
  return { childId: child.id, created, provided };
398
- });
741
+ };
742
+ const transact = () => snapshotDef === undefined
743
+ ? this.store.tx(transactionBody)
744
+ : this.store.txWithWorkflowSnapshots(snapshotDef, transactionBody);
745
+ const run = () => {
746
+ let result = transact();
747
+ if (result !== needsSnapshot)
748
+ return result;
749
+ // Resolve optimistically outside both locks. The snapshot guard then
750
+ // revalidates this CAS provenance under add.lock before SQLite begins.
751
+ snapshotDef = this.resolveDef(step.calls, parentDef);
752
+ result = transact();
753
+ if (result === needsSnapshot)
754
+ throw new Error('internal error: guarded child provision requested no snapshot');
755
+ return result;
756
+ };
399
757
  try {
400
758
  return run();
401
759
  }
@@ -469,7 +827,7 @@ export class Engine {
469
827
  const freshDef = this.resolveDef(wf.def);
470
828
  const newHash = hashDef(freshDef);
471
829
  const previousHash = wf.defHash;
472
- this.store.tx(() => {
830
+ this.store.txWithWorkflowSnapshots(freshDef, () => {
473
831
  this.store.repinWorkflowDef(workflow, freshDef, newHash);
474
832
  this.settle(workflow, freshDef);
475
833
  });
@@ -490,11 +848,11 @@ export class Engine {
490
848
  */
491
849
  static CHILD_OUTCOME_PIN_KEY = '__child_outcome_version__';
492
850
  /**
493
- * F4: the single place that computes "what child-outcome version is this
494
- * calls: artifact currently resting on" — used both when machine-greening
495
- * (STEP 6) and when stamping the pin at verdict time (reject propagation,
496
- * human skip). Returns undefined if no child has ever been spawned (nothing
497
- * to pin to).
851
+ * F4: the single verdict-time helper that computes "what child-outcome
852
+ * version is this calls: artifact currently resting on" for reject
853
+ * propagation and human skip. STEP 6 publication reads and stamps the version
854
+ * from its authoritative in-transaction snapshot instead. Returns undefined
855
+ * if no child has ever been spawned (nothing to pin to).
498
856
  */
499
857
  childOutcomePin(parentWf, callsPath) {
500
858
  const child = this.store.findChildByParent(parentWf, callsPath);
@@ -657,12 +1015,47 @@ export class Engine {
657
1015
  this.fire({ type: 'commit', workflow: parentWf, path: callsStem, action: 'reject' });
658
1016
  this.fireSettled(parentWf);
659
1017
  }
1018
+ /** Persist one interface-binding/pin refusal with the unchanged-gate guard. */
1019
+ recordInterfaceCallPinReject(parentWf, def, callsStem, gateStems, err, now) {
1020
+ const text = `interface call '${err.interface.name}@${err.interface.version}' bound to '${err.target}' `
1021
+ + `failed its immutable start-time pin check: ${err.detail}; this provision was refused without creating or replacing a child row — `
1022
+ + `restore the pinned bundle or start a new parent with a valid binding`;
1023
+ let recorded = false;
1024
+ this.store.tx(() => {
1025
+ const art = this.store.getArtifact(parentWf, callsStem);
1026
+ if (!art)
1027
+ return;
1028
+ const gateArts = this.artMap(parentWf);
1029
+ const fp = computeFingerprint(gateArts, gateStems);
1030
+ const alreadyRecorded = art.acceptance === 'rejected'
1031
+ && deepEqual(fp, art.fingerprint ?? {})
1032
+ && art.reasons.some((entry) => entry.action === 'reject'
1033
+ && entry.kind === 'structural'
1034
+ && entry.by === 'engine'
1035
+ && entry.text === text);
1036
+ if (alreadyRecorded)
1037
+ return;
1038
+ this.store.putArtifact({
1039
+ ...art,
1040
+ acceptance: 'rejected',
1041
+ fingerprint: fp,
1042
+ reasons: [...art.reasons, reason('reject', 'structural', 'engine', text, art.version)],
1043
+ });
1044
+ this.settle(parentWf, def, now);
1045
+ recorded = true;
1046
+ });
1047
+ if (!recorded)
1048
+ return;
1049
+ this.fire({ type: 'commit', workflow: parentWf, path: callsStem, action: 'reject' });
1050
+ this.fireSettled(parentWf);
1051
+ }
660
1052
  /**
661
1053
  * M2B: Maintain all `calls:` steps for a parent workflow.
662
1054
  * Called at the top of tick (outside any tx) and as cascade-up prompt.
663
1055
  * For each calls: step: spawn the child if gate is ready and no child exists;
664
1056
  * re-attach if it exists; re-provide if parent inputs moved; machine-green
665
- * the parent artifact when the child's declared output is green.
1057
+ * the parent artifact when the child's declared output is green and the
1058
+ * whole child workflow is done.
666
1059
  */
667
1060
  maintainCalls(parentWf, def, now) {
668
1061
  if (this._inMaintainCalls.has(parentWf))
@@ -670,7 +1063,7 @@ export class Engine {
670
1063
  this._inMaintainCalls.add(parentWf);
671
1064
  try {
672
1065
  for (const step of def.steps) {
673
- if (!step.calls)
1066
+ if (!isCallStep(step))
674
1067
  continue;
675
1068
  // STEP 1 — Gather gate stems and check gate readiness.
676
1069
  const callsStem = step.produces[0].stem; // single produced artifact name
@@ -705,7 +1098,7 @@ export class Engine {
705
1098
  // needs no in-tx recheck. Record a rejection on the parent calls artifact
706
1099
  // (clean stop; the STEP-2 F2 fingerprint guard then skips re-attempts).
707
1100
  if (!existingChild && this.callsAncestryDepth(parentWf) >= this.maxCallDepth) {
708
- this.recordCallsDepthReject(parentWf, def, callsStem, gateStems, step.calls, now);
1101
+ this.recordCallsDepthReject(parentWf, def, callsStem, gateStems, callTargetLabel(step), now);
709
1102
  continue;
710
1103
  }
711
1104
  // The find-or-create AND every mapped input sync happen in ONE
@@ -745,6 +1138,10 @@ export class Engine {
745
1138
  this.recordCallsDigestReject(parentWf, def, callsStem, gateStems, err, now);
746
1139
  continue;
747
1140
  }
1141
+ if (err instanceof InterfaceCallPinError) {
1142
+ this.recordInterfaceCallPinReject(parentWf, def, callsStem, gateStems, err, now);
1143
+ continue;
1144
+ }
748
1145
  throw err;
749
1146
  }
750
1147
  if (!provision)
@@ -755,7 +1152,12 @@ export class Engine {
755
1152
  // (idempotent maintenance — once per provision, not once per input) so a
756
1153
  // grandchild gets re-provided in the same pass.
757
1154
  if (provision.created) {
758
- this.fire({ type: 'instance', workflow: provision.childId, def: step.calls });
1155
+ const createdChild = this.store.getWorkflow(provision.childId);
1156
+ this.fire({
1157
+ type: 'instance',
1158
+ workflow: provision.childId,
1159
+ def: createdChild?.def ?? callTargetLabel(step),
1160
+ });
759
1161
  this.fireSettled(provision.childId);
760
1162
  }
761
1163
  for (const name of provision.provided) {
@@ -786,23 +1188,25 @@ export class Engine {
786
1188
  // rearmCallsGreen). Under WAL + BEGIN IMMEDIATE no other connection can
787
1189
  // commit between that in-tx re-read and the write, so a cross-connection
788
1190
  // interleave — the parent gate advanced to a newer version, or the child
789
- // outcome re-armed, between this stale pre-read and the write — is caught
790
- // in-tx and the pass aborts (helper returns false, nothing written),
791
- // deferring to the next tick. The published value, the gate fingerprint
792
- // it claims, and the child-outcome pin therefore always come from ONE
793
- // atomic snapshot. commit/settled events fire only when the helper wrote,
794
- // so an aborted pass is silent to listeners.
1191
+ // outcome re-armed, or the child's completion state changed, between
1192
+ // this stale pre-read and the write — is caught in-tx and the pass aborts
1193
+ // (helper returns false, nothing written), deferring to the next tick.
1194
+ // The published value, whole-child done result, gate fingerprint, and
1195
+ // child-outcome pin therefore always come from ONE atomic snapshot.
1196
+ // commit/settled events fire only when the helper wrote, so an aborted
1197
+ // pass is silent to listeners.
795
1198
  //
796
1199
  // Re-read after potential re-provide.
797
1200
  childArts = this.artMap(existingChild.id);
798
1201
  childOutcomeArt = childArts.get(childOutcomeStem);
1202
+ const childIsDone = workflowDone(childDef, childArts);
799
1203
  const parentCallsArt = this.store.getArtifact(parentWf, callsStem);
800
1204
  // F2: don't machine-green over a schema-rejected debt — it needs a
801
1205
  // human `retry` (or a moved gate, handled by the guard above) before
802
1206
  // this step revisits it.
803
1207
  if (parentCallsArt?.acceptance === 'rejected')
804
1208
  continue;
805
- if (isGreen(childOutcomeArt) && childOutcomeArt?.value !== undefined) {
1209
+ if (isGreen(childOutcomeArt) && childOutcomeArt?.value !== undefined && childIsDone) {
806
1210
  const alreadyGreen = isGreen(parentCallsArt);
807
1211
  const sameValue = alreadyGreen && deepEqual(childOutcomeArt.value, parentCallsArt?.value);
808
1212
  // F4: version-pinning. Only machine-green when the child outcome's
@@ -823,11 +1227,13 @@ export class Engine {
823
1227
  }
824
1228
  }
825
1229
  }
826
- else if (!isGreen(childOutcomeArt) && isGreen(parentCallsArt) && parentCallsArt) {
827
- // M2B-REARM: child's outcome is no longer green (e.g. re-provide re-armed it)
828
- // but the parent calls: artifact is still green. Re-arm it to owed so downstream
829
- // re-runs when the child completes again. This handles gate re-arm (test f):
830
- // the cascade can't detect this because deliver step has consumes: [].
1230
+ else if ((!isGreen(childOutcomeArt) || !childIsDone) && isGreen(parentCallsArt) && parentCallsArt) {
1231
+ // M2B-REARM: the child outcome is no longer green (e.g. re-provide
1232
+ // re-armed it), OR the outcome is green while the child still has
1233
+ // outstanding work. Re-arm the parent mirror to owed so deep descent
1234
+ // can keep driving the child and downstream re-runs only after the
1235
+ // whole child completes. The cascade cannot detect either condition
1236
+ // because a calls: step declares consumes: [].
831
1237
  if (this.rearmCallsGreen(parentWf, def, callsStem, existingChild.id, childOutcomeStem, now)) {
832
1238
  this.fire({ type: 'commit', workflow: parentWf, path: callsStem, action: 'retry' });
833
1239
  this.fireSettled(parentWf);
@@ -883,11 +1289,18 @@ export class Engine {
883
1289
  const child = this.store.findChildByParent(parentWf, callsStem);
884
1290
  if (!child || child.id !== expectedChildId)
885
1291
  return false;
1292
+ const childDef = this.defFor(child.id);
1293
+ const currentChildOutcomeStem = childDef.outputs?.[0];
1294
+ if (currentChildOutcomeStem !== childOutcomeStem)
1295
+ return false;
886
1296
  const childArts = this.artMap(child.id);
887
- const childOutcomeArt = childArts.get(childOutcomeStem);
888
- // Child re-armed between the pre-read and here → defer.
1297
+ const childOutcomeArt = childArts.get(currentChildOutcomeStem);
1298
+ // Child re-armed, or still has outstanding work, between the pre-read and
1299
+ // here → defer. Only this in-tx snapshot authorizes publication.
889
1300
  if (!childOutcomeArt || !isGreen(childOutcomeArt) || childOutcomeArt.value === undefined)
890
1301
  return false;
1302
+ if (!workflowDone(childDef, childArts))
1303
+ return false;
891
1304
  // Gate still ready, and the child still consistent with the gate values
892
1305
  // the fingerprint is about to claim (the heart of the fix).
893
1306
  if (!this.callsGateReady(parentArts, step))
@@ -919,11 +1332,12 @@ export class Engine {
919
1332
  /**
920
1333
  * STEP 6 re-arm as the mirror-image atomic guard. maintainCalls' optimistic
921
1334
  * pre-read decides only WHETHER to call this; the parent artifact AND the
922
- * child outcome are re-read inside the write lock, and the re-arm happens only
923
- * if the parent is still green AND the child outcome is still NOT green in-tx.
924
- * If the child went green between the optimistic read and the tx, this does
925
- * nothing (returns false) and the next maintainCalls pass publishes normally.
926
- * Returns true only when it wrote.
1335
+ * child definition/artifacts are re-read inside the write lock, and the
1336
+ * re-arm happens only if the parent is still green AND either the child
1337
+ * outcome is non-green or the whole child is unfinished in-tx. If the outcome
1338
+ * is green and the child is done by then, this does nothing (returns false)
1339
+ * and the next maintainCalls pass publishes normally. Returns true only when
1340
+ * it wrote.
927
1341
  */
928
1342
  rearmCallsGreen(parentWf, def, callsStem, expectedChildId, childOutcomeStem, now) {
929
1343
  return this.store.tx(() => {
@@ -933,19 +1347,34 @@ export class Engine {
933
1347
  const child = this.store.findChildByParent(parentWf, callsStem);
934
1348
  if (!child || child.id !== expectedChildId)
935
1349
  return false;
936
- const childOutcomeArt = this.artMap(child.id).get(childOutcomeStem);
937
- // Child went green in-tx → don't re-arm; let the green branch publish next pass.
938
- if (isGreen(childOutcomeArt))
1350
+ const childDef = this.defFor(child.id);
1351
+ const currentChildOutcomeStem = childDef.outputs?.[0];
1352
+ if (currentChildOutcomeStem !== childOutcomeStem)
1353
+ return false;
1354
+ const childArts = this.artMap(child.id);
1355
+ const childOutcomeArt = childArts.get(currentChildOutcomeStem);
1356
+ const childIsDone = workflowDone(childDef, childArts);
1357
+ // Green outcome plus whole-child completion means the mirror is valid.
1358
+ if (isGreen(childOutcomeArt) && childIsDone)
939
1359
  return false;
1360
+ const childOutcomeGreenButUnfinished = isGreen(childOutcomeArt) && !childIsDone;
1361
+ let fingerprint = artNow.fingerprint;
1362
+ let reasonText = 'gate input moved: child re-running';
1363
+ if (childOutcomeGreenButUnfinished) {
1364
+ fingerprint = { ...(artNow.fingerprint ?? {}) };
1365
+ delete fingerprint[Engine.CHILD_OUTCOME_PIN_KEY];
1366
+ reasonText = 'called workflow is not done';
1367
+ }
940
1368
  this.store.putArtifact({
941
1369
  ...artNow,
942
1370
  acceptance: 'owed',
1371
+ fingerprint,
943
1372
  reasons: [...artNow.reasons, {
944
1373
  at: nowMs(),
945
1374
  action: 'reopen',
946
1375
  kind: 'structural',
947
1376
  by: 'engine',
948
- text: 'gate input moved: child re-running',
1377
+ text: reasonText,
949
1378
  fromVersion: artNow.version,
950
1379
  }],
951
1380
  });
@@ -988,7 +1417,7 @@ export class Engine {
988
1417
  tick(workflow, opts = {}) {
989
1418
  // `capabilities` is passed through AS GIVEN — an omitted filter (undefined)
990
1419
  // and an empty list are different claims. See `claimMatches`.
991
- return this.tickInternal(workflow, opts.now ?? nowMs(), opts.deep ?? true, opts.capabilities, new Set(), 0, undefined, opts.matchModes ?? {}, opts.capabilityRewrites ?? {}, opts.crewStamps ?? {});
1420
+ return this.tickInternal(workflow, opts.now ?? nowMs(), opts.deep ?? true, opts.capabilities, new Set(), 0, undefined, opts.matchModes ?? {}, opts.capabilityMappings ?? {}, opts.capabilityRewrites ?? {}, opts.crewStamps ?? {});
992
1421
  }
993
1422
  /**
994
1423
  * The recursive tick worker. Runs this instance's own maintain → reap →
@@ -1029,7 +1458,7 @@ export class Engine {
1029
1458
  * edge it hangs from. The guard is silent (no debt/reasons/events), mirroring
1030
1459
  * the abort discipline of `publishCallsGreen`/`provisionCallsChild`.
1031
1460
  */
1032
- tickInternal(workflow, now, deep, capabilities, visited, depth, parentEdge, matchModes = {}, capabilityRewrites = {}, crewStamps = {}) {
1461
+ tickInternal(workflow, now, deep, capabilities, visited, depth, parentEdge, matchModes = {}, capabilityMappings = {}, capabilityRewrites = {}, crewStamps = {}) {
1033
1462
  if (depth > this.maxCallDepth) {
1034
1463
  throw new Error(`calls depth limit exceeded (maxCallDepth=${this.maxCallDepth}) ticking '${workflow}': `
1035
1464
  + `a calls: composition is deeper than the bound, which usually means a calls: cycle `
@@ -1078,11 +1507,11 @@ export class Engine {
1078
1507
  // Compute time facts for idle eligibility (clock-read boundary).
1079
1508
  const timeFacts = this.computeTimeFacts(def, workflow, arts, now);
1080
1509
  const firings = eligibleFirings(def, arts, timeFacts);
1081
- const { selected, deferred } = this.applySchedule(workflow, def, firings, now, arts, capabilities, modifier, matchModes, capabilityRewrites);
1510
+ const { selected, deferred } = this.applySchedule(workflow, def, firings, now, arts, capabilities, modifier, matchModes, capabilityMappings, capabilityRewrites);
1082
1511
  const orders = [];
1083
1512
  const allDeferred = [...deferred];
1084
1513
  for (const f of selected) {
1085
- const claimed = this.claim(workflow, def, f, arts, now, modifier, capabilityRewrites, crewStamps);
1514
+ const claimed = this.claim(workflow, def, f, arts, now, modifier, capabilityMappings, capabilityRewrites, crewStamps);
1086
1515
  if (claimed === 'in-flight') {
1087
1516
  const d = { step: f.step, key: f.key, inputs: f.inputs, outputs: f.outputs, reason: 'in-flight' };
1088
1517
  if (f.index !== undefined)
@@ -1117,7 +1546,7 @@ export class Engine {
1117
1546
  parentWf: workflow,
1118
1547
  step,
1119
1548
  callsStem: step.produces[0].stem,
1120
- }, matchModes, capabilityRewrites, crewStamps);
1549
+ }, matchModes, capabilityMappings, capabilityRewrites, crewStamps);
1121
1550
  // orders: flatten; each Order already carries its own `workflow`.
1122
1551
  result.orders.push(...cr.orders);
1123
1552
  // deferred: stamp child-originated entries with the child id, preserving
@@ -1171,7 +1600,7 @@ export class Engine {
1171
1600
  const arts = this.artMap(parentWf);
1172
1601
  const out = [];
1173
1602
  for (const step of def.steps) {
1174
- if (!step.calls)
1603
+ if (!isCallStep(step))
1175
1604
  continue;
1176
1605
  const stem = step.produces[0].stem;
1177
1606
  if (!this.callsGateReady(arts, step))
@@ -1189,9 +1618,11 @@ export class Engine {
1189
1618
  * Per-step cadence + daily budget + parallel cap over the eligible firings.
1190
1619
  *
1191
1620
  * A2: `capabilities` is the tick caller's claim filter, matched against the
1192
- * step's OFFERED capabilities — the authored list composed with the modifier
1193
- * this firing will actually be offered under (`wise` + `deep` → `wise:deep`),
1194
- * which is the same list the order will carry. `claimMatches` owns the rule;
1621
+ * step's OFFERED capabilities — the authored list mapped onto the caller's
1622
+ * own capability names, composed with the modifier this firing will actually
1623
+ * be offered under (`wise` + `deep` → `wise:deep`), then rewritten by any
1624
+ * reroute the caller decided on, which is the same list the order will carry.
1625
+ * `claimMatches` owns the rule;
1195
1626
  * see it for the four cases (no filter presented, capability-silent step,
1196
1627
  * empty caller list, both non-empty) and for what `matchModes` changes.
1197
1628
  * A firing this caller may not claim is deferred as `'capability-mismatch'`.
@@ -1205,7 +1636,7 @@ export class Engine {
1205
1636
  * escalation authored every firing of a step composes identically, so this
1206
1637
  * behaves exactly as a per-step filter would.
1207
1638
  */
1208
- applySchedule(workflow, def, firings, now, arts, capabilities, modifier, matchModes, capabilityRewrites) {
1639
+ applySchedule(workflow, def, firings, now, arts, capabilities, modifier, matchModes, capabilityMappings, capabilityRewrites) {
1209
1640
  const midnight = localMidnightMs(now);
1210
1641
  const selected = [];
1211
1642
  const deferred = [];
@@ -1221,13 +1652,14 @@ export class Engine {
1221
1652
  continue;
1222
1653
  // A2: caller capability filter vs. this firing's COMPOSED offer. Composed
1223
1654
  // here, not authored, so a caller bound to `wise:deep` is judged against
1224
- // what the order will actually carry — including when `deep` came from the
1655
+ // what the order will actually carry — including a mapping onto the org's
1656
+ // own capability vocabulary, including when `deep` came from the
1225
1657
  // escalation rule rather than the run, and including a reroute the caller
1226
- // decided on. The filter and `buildOrder` apply the same two functions in
1227
- // the same order, so what is matched is always what gets stamped.
1658
+ // decided on. The filter and `buildOrder` apply the same three functions
1659
+ // in the same order, so what is matched is always what gets stamped.
1228
1660
  const stepFirings = [];
1229
1661
  for (const f of all) {
1230
- const composed = composeCapabilities(step.capabilities, this.routingFor(step, f, arts, modifier).modifier);
1662
+ const composed = composeCapabilities(applyCapabilityMappings(step.capabilities, capabilityMappings), this.routingFor(step, f, arts, modifier).modifier);
1231
1663
  const { offered } = applyCapabilityRewrites(composed, capabilityRewrites);
1232
1664
  if (claimMatches(offered, capabilities, matchModes))
1233
1665
  stepFirings.push(f);
@@ -1309,7 +1741,7 @@ export class Engine {
1309
1741
  return this.staleness(task, now, ttl, maxLease) === 'fresh';
1310
1742
  }
1311
1743
  /** Claim a firing's lease via CAS, snapshot the fingerprint, open a run. */
1312
- claim(workflow, def, f, arts, now, modifier, capabilityRewrites = {}, crewStamps = {}) {
1744
+ claim(workflow, def, f, arts, now, modifier, capabilityMappings = {}, capabilityRewrites = {}, crewStamps = {}) {
1313
1745
  const existing = this.store.getTask(workflow, f.step, f.key);
1314
1746
  if (existing && existing.status === 'claimed') {
1315
1747
  const run = existing.run ? this.store.getRun(existing.run) : undefined;
@@ -1337,7 +1769,7 @@ export class Engine {
1337
1769
  // `applySchedule` so the offer and the filter read the same function on the
1338
1770
  // same in-tx `arts` snapshot; nothing between them can move.
1339
1771
  const routing = this.routingFor(this.step(def, f.step), f, arts, modifier);
1340
- const order = this.buildOrder(def, workflow, runId, f, arts, fp, routing, capabilityRewrites, crewStamps);
1772
+ const order = this.buildOrder(def, workflow, runId, f, arts, fp, routing, capabilityMappings, capabilityRewrites, crewStamps);
1341
1773
  if (typeof order === 'object' && 'deferred' in order)
1342
1774
  return order;
1343
1775
  // One history record per rejection episode. Written HERE, not in
@@ -1371,7 +1803,7 @@ export class Engine {
1371
1803
  * snapshot is registered under the digest (a side effect of `digestOf`),
1372
1804
  * so the order stays resolvable after the live definition map changes.
1373
1805
  */
1374
- buildOrder(def, workflow, runId, f, arts, consumedFingerprint, routing = {}, capabilityRewrites = {}, crewStamps = {}) {
1806
+ buildOrder(def, workflow, runId, f, arts, consumedFingerprint, routing = {}, capabilityMappings = {}, capabilityRewrites = {}, crewStamps = {}) {
1375
1807
  const step = this.step(def, f.step);
1376
1808
  const consumes = {};
1377
1809
  for (const p of f.inputs) {
@@ -1463,12 +1895,17 @@ export class Engine {
1463
1895
  // land, not the currently-committed one: `green()` writes
1464
1896
  // `art.version + 1`, so that is the version a consumer will later see
1465
1897
  // and check a submission proof against. Issued by the engine inside the
1466
- // claim transaction and persisted with the immutable order, so every
1467
- // retry of the same claim reads the same target. Refusal paths that
1468
- // leave the run open (schema-reject) do NOT bump the artifact, so the
1469
- // target stays correct across in-claim retries; a path that does commit
1470
- // closes the run, and a stale target then fails the consumer's version
1471
- // check — a refusal, never an admitted unverified value.
1898
+ // claim transaction and persisted with the order.
1899
+ //
1900
+ // The target stays correct across every in-claim retry that does NOT
1901
+ // move the artifact — the schema reject and the artifact-bind reject in
1902
+ // `green()` leave the run open without bumping `version`. A judgment or
1903
+ // human reject also leaves the claim open, but it FOLLOWS a commit that
1904
+ // already bumped the artifact, so the frozen target is one behind from
1905
+ // that point on. `restampOwedTarget` re-stamps it at the reject site
1906
+ // for exactly that case; see its doc comment. A stale target that
1907
+ // escaped anyway fails the consumer's version check — a refusal, never
1908
+ // an admitted unverified value.
1472
1909
  version: (a?.version ?? 0) + 1,
1473
1910
  judgmentRejects: a?.judgmentRejects ?? 0,
1474
1911
  schemaRejects: a?.schemaRejects ?? 0,
@@ -1490,16 +1927,20 @@ export class Engine {
1490
1927
  };
1491
1928
  if (f.index !== undefined)
1492
1929
  order.index = f.index;
1493
- // The routing snapshot of THIS offer. `capabilities` is the composed list —
1494
- // absent on a capability-silent step, since there is nothing to compose
1495
- // onto. `modifier` is stamped whenever the offer carries one, even for a
1930
+ // The routing snapshot of THIS offer. `capabilities` is the mapped-then-
1931
+ // composed list — absent on a capability-silent step, since there is
1932
+ // nothing to map or compose onto. A mapping substitutes the org's own
1933
+ // capability name for the authored one before the modifier is attached, so
1934
+ // one entry covers every grade the step can be offered at; the authored
1935
+ // name stays recoverable through `defDigest`, which pins the def that wrote
1936
+ // it. `modifier` is stamped whenever the offer carries one, even for a
1496
1937
  // capability-silent step, so the brief can surface the grade of service
1497
1938
  // regardless of how the step routes; on an escalated offer it is the
1498
1939
  // escalation target, and `escalated` marks it as such so the hub does not
1499
1940
  // have to diff it against the run record. A claimed order is never
1500
1941
  // recomposed: composition happens per offer, and this record is what the
1501
1942
  // shift resolved against.
1502
- const { offered, reroutedFrom } = applyCapabilityRewrites(composeCapabilities(step.capabilities, routing.modifier), capabilityRewrites);
1943
+ const { offered, reroutedFrom } = applyCapabilityRewrites(composeCapabilities(applyCapabilityMappings(step.capabilities, capabilityMappings), routing.modifier), capabilityRewrites);
1503
1944
  if (offered.length > 0)
1504
1945
  order.capabilities = offered;
1505
1946
  const crews = [];
@@ -1855,7 +2296,7 @@ export class Engine {
1855
2296
  });
1856
2297
  this.fire({ type: 'commit', workflow, run, path: result.path, action: 'green', outcome: result.outcome });
1857
2298
  if (result.outcome === 'born-rejected') {
1858
- this.fire({ type: 'closed', workflow, run, outcome: 'no_work' });
2299
+ this.fire({ type: 'closed', workflow, run, outcome: 'released' });
1859
2300
  }
1860
2301
  this.fireSettled(workflow);
1861
2302
  // M2B cascade-up prompt: if this workflow has a producedBy link, trigger parent maintainCalls.
@@ -1954,7 +2395,7 @@ export class Engine {
1954
2395
  });
1955
2396
  this.fire({ type: 'commit', workflow, run, path: stem, action: 'emit', outcome: result.outcome });
1956
2397
  if (result.outcome === 'born-rejected') {
1957
- this.fire({ type: 'closed', workflow, run, outcome: 'no_work' });
2398
+ this.fire({ type: 'closed', workflow, run, outcome: 'released' });
1958
2399
  }
1959
2400
  this.fireSettled(workflow);
1960
2401
  return result;
@@ -1993,7 +2434,7 @@ export class Engine {
1993
2434
  });
1994
2435
  this.fire({ type: 'commit', workflow, run, path: result.path, action: 'seal', outcome: result.outcome });
1995
2436
  if (result.outcome === 'born-rejected') {
1996
- this.fire({ type: 'closed', workflow, run, outcome: 'no_work' });
2437
+ this.fire({ type: 'closed', workflow, run, outcome: 'released' });
1997
2438
  }
1998
2439
  this.fireSettled(workflow);
1999
2440
  return result;
@@ -2033,7 +2474,7 @@ export class Engine {
2033
2474
  // ever spawned there is nothing to judge, so refuse (consistent with the
2034
2475
  // verb-guard rule below that a verdict needs a built version).
2035
2476
  const producingStep = def.steps.find((s) => s.produces.some((p) => p.stem === path));
2036
- if (producingStep?.calls) {
2477
+ if (producingStep !== undefined && isCallStep(producingStep)) {
2037
2478
  const bind = producingStep.produces.find((p) => p.stem === path)?.bind;
2038
2479
  if (requested !== undefined) {
2039
2480
  if (bind?.to !== 'modifier') {
@@ -2102,6 +2543,12 @@ export class Engine {
2102
2543
  approvals: undefined,
2103
2544
  reasons: [...art.reasons, reason('reject', 'judgment', by, text, art.version, requested)],
2104
2545
  });
2546
+ // The producer's claim survives this reject (settle() writes artifact rows
2547
+ // only), so its frozen target is now one behind the version the next
2548
+ // commit will land. `art` is the pre-write snapshot and a reject does not
2549
+ // bump `version`, so `art.version + 1` is the same expression buildOrder
2550
+ // stamps at issue.
2551
+ this.restampOwedTarget(workflow, art.producer, path, art.version + 1);
2105
2552
  this.settle(workflow, def);
2106
2553
  return { outcome: 'rejected' };
2107
2554
  });
@@ -2113,7 +2560,7 @@ export class Engine {
2113
2560
  ...(result.outcome === 'born-rejected' ? { outcome: 'born-rejected' } : {}),
2114
2561
  });
2115
2562
  if (result.outcome === 'born-rejected' && releasedRun !== undefined) {
2116
- this.fire({ type: 'closed', workflow, run: releasedRun, outcome: 'no_work' });
2563
+ this.fire({ type: 'closed', workflow, run: releasedRun, outcome: 'released' });
2117
2564
  }
2118
2565
  this.fireSettled(workflow);
2119
2566
  return result;
@@ -2156,6 +2603,11 @@ export class Engine {
2156
2603
  approvals: undefined,
2157
2604
  reasons: [...childArt.reasons, reason('reject', 'judgment', `parent:${by}`, text, childArt.version, requested)],
2158
2605
  });
2606
+ // Same stranding as the plain reject above, one instance down: the child's
2607
+ // producing step can hold an open claim in the CHILD workflow. The parent
2608
+ // `calls` artifact reopened below needs no re-stamp — a `calls:` step never
2609
+ // becomes a worker order (src/model.ts), so no claim owes it.
2610
+ this.restampOwedTarget(child.id, childArt.producer, childOutcomeStem, childArt.version + 1);
2159
2611
  this.settle(child.id, childDef);
2160
2612
  // Parent calls artifact → reopened to owed (not left rejected), pinned
2161
2613
  // to the just-rejected child outcome version.
@@ -2234,7 +2686,7 @@ export class Engine {
2234
2686
  // skip made on evidence from child version N survives arbitrary ticks
2235
2687
  // (order A) until the child actually rebuilds past N (order B).
2236
2688
  const producingStep = def.steps.find((s) => s.name === art.producer);
2237
- if (producingStep?.calls) {
2689
+ if (producingStep !== undefined && isCallStep(producingStep)) {
2238
2690
  const pin = this.childOutcomePin(workflow, path);
2239
2691
  if (pin !== undefined)
2240
2692
  fp[Engine.CHILD_OUTCOME_PIN_KEY] = pin;
@@ -2380,7 +2832,10 @@ export class Engine {
2380
2832
  step: r.step,
2381
2833
  key: r.key ?? '',
2382
2834
  status: 'idle',
2383
- attempts: task.attempts,
2835
+ // A public close hands back a real claimed lease. Count the churn so
2836
+ // pickup-window lapses and explicit holder releases are visible in
2837
+ // instance status; released runs still remain outside run budgets.
2838
+ attempts: outcome === 'released' ? task.attempts + 1 : task.attempts,
2384
2839
  ...(task.alarmAt !== undefined ? { alarmAt: task.alarmAt } : {}),
2385
2840
  });
2386
2841
  }
@@ -2515,7 +2970,7 @@ export class Engine {
2515
2970
  // recursive child summary (all instance-crossing logic stays here, in the
2516
2971
  // engine — the pure workflowStatus never touches another instance).
2517
2972
  for (const d of st.debts) {
2518
- const callsStep = def.steps.find((s) => s.calls && s.produces[0].stem === d.path);
2973
+ const callsStep = def.steps.find((s) => isCallStep(s) && s.produces[0].stem === d.path);
2519
2974
  if (!callsStep)
2520
2975
  continue;
2521
2976
  const child = this.store.findChildByParent(workflow, d.path);
@@ -2823,15 +3278,48 @@ export class Engine {
2823
3278
  });
2824
3279
  }
2825
3280
  /**
2826
- * §12.2 born-reject lease release: close the run (`no_work`) and re-arm its
3281
+ * Re-stamp the owed version target for `path` on any OPEN claim that owes it.
3282
+ *
3283
+ * The target frozen at claim issue is `committed + 1`. That stays correct for
3284
+ * every refusal that leaves the run open WITHOUT bumping the artifact (the
3285
+ * schema reject and the artifact-bind reject in `green()`). It goes stale for
3286
+ * a judgment/human reject, which is preceded by a commit that already bumped
3287
+ * the artifact and which leaves the SAME claim live to retry: the next commit
3288
+ * lands `committed + 1` from the new committed version, while the producer is
3289
+ * still signing the old number into its proof's `produced[].version`. The
3290
+ * proof row is then stored under a key the envelope does not name, and the
3291
+ * consumer's version check refuses the artifact.
3292
+ *
3293
+ * Matching is by owed path, not by task key, so it is correct for map
3294
+ * elements without re-deriving the binding key. Runs inside the caller's open
3295
+ * tx (plain store writes, no nested tx).
3296
+ */
3297
+ restampOwedTarget(workflow, producer, path, target) {
3298
+ for (const task of this.store.listTasks(workflow)) {
3299
+ if (task.step !== producer || task.status !== 'claimed' || task.run === undefined)
3300
+ continue;
3301
+ // A closed run's next claim rebuilds the order from scratch and already
3302
+ // gets a fresh target, so only an open one can strand.
3303
+ const run = this.store.getRun(task.run);
3304
+ if (!run || run.outcome !== undefined)
3305
+ continue;
3306
+ this.store.restampOrderTarget(task.run, path, target);
3307
+ }
3308
+ }
3309
+ /**
3310
+ * §12.2 born-reject lease release: close the run (`released`) and re-arm its
2827
3311
  * task to `idle` so the firing is immediately re-claimable next tick. Runs
2828
3312
  * inside the caller's open tx (plain store write, no nested tx). Unlike reap()
2829
- * it does NOT bump attempts — a CAS-stale born-reject is not lease churn. The
3313
+ * it does NOT bump attempts — a CAS-stale born-reject is not lease churn. For
3314
+ * the same reason the outcome is `released` and not `no_work`: the step never
3315
+ * ran, so the run must not spend the daily budget or restart the cadence
3316
+ * clock either. `no_work` is reserved for a step that DID run and had nothing
3317
+ * to produce, which is a firing and does spend both. The
2830
3318
  * `closed` event is fired by the caller AFTER the tx commits (post-commit
2831
3319
  * ordering), matching public close().
2832
3320
  */
2833
3321
  releaseLeaseOnBornReject(workflow, run) {
2834
- this.store.updateRun(run, { outcome: 'no_work' });
3322
+ this.store.updateRun(run, { outcome: 'released' });
2835
3323
  const r = this.store.getRun(run);
2836
3324
  if (!r)
2837
3325
  return;
@@ -2951,7 +3439,7 @@ export class Engine {
2951
3439
  let stalled = cs.debts.some((d) => d.stalled);
2952
3440
  if (!stalled) {
2953
3441
  for (const d of cs.debts) {
2954
- const callsStep = childDef.steps.find((s) => s.calls && s.produces[0].stem === d.path);
3442
+ const callsStep = childDef.steps.find((s) => isCallStep(s) && s.produces[0].stem === d.path);
2955
3443
  if (!callsStep)
2956
3444
  continue;
2957
3445
  const grandchild = this.store.findChildByParent(childWf, d.path);