owenloop 0.5.10 → 0.5.12

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.
@@ -13,8 +13,11 @@ import { elementPath, parseElement, parseWorkdirFrom, sealPath, } from "./paths.
13
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 { checkInterfaceCompatibility } from "./implements.js";
17
+ import { isDefDigest, parseWorkflowCoordinate } from "./store/types.js";
16
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.txWithWorkflowSnapshots(def, () => 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
@@ -301,6 +565,24 @@ export class Engine {
301
565
  let seenGateFp;
302
566
  const needsSnapshot = Symbol('needs-workflow-snapshot');
303
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
+ }
304
586
  const transactionBody = () => {
305
587
  // 1. FRESH parent snapshot — re-read inside the write lock; never trust
306
588
  // the caller's STEP-1 map.
@@ -323,6 +605,36 @@ export class Engine {
323
605
  if (deepEqual(fp, parentCallsArt.fingerprint ?? {}))
324
606
  return null;
325
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
+ }
326
638
  // 4. Find-or-create the child (in-tx check-then-insert — absorbs the old
327
639
  // spawnChildIfAbsent guarantee, only its home moved).
328
640
  let child = this.store.findChildByParent(parentWf, callsStem);
@@ -342,11 +654,12 @@ export class Engine {
342
654
  // same bundle's workflow — the version the parent was pinned against —
343
655
  // and not to whatever a later install happened to name the same thing.
344
656
  childDef = snapshotDef;
345
- // WS-6: and the resolved child must still be the PINNED one. See
346
- // `callsPinViolation`.
347
- const violation = callsPinViolation(parentDef, childDef, step.calls);
348
- if (violation !== undefined)
349
- throw new CallsPinError(step.calls, violation);
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
+ }
350
663
  const seedProvide = {};
351
664
  for (const [childInputName, parentArtifactName] of Object.entries(step.callsInputs ?? {})) {
352
665
  const parentArt = parentArts.get(parentArtifactName);
@@ -356,16 +669,38 @@ export class Engine {
356
669
  }
357
670
  // createInstanceInTx validates the seed against the child input schema
358
671
  // and throws SchemaRefusalError (tx rolls back — no orphan child).
359
- this.createInstanceInTx(step.calls, childDef, childId, {
672
+ const childOpts = {
360
673
  producedBy: { parentWf, parentPath: callsStem },
361
674
  provide: seedProvide,
362
- });
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
+ }
363
692
  child = this.store.getWorkflow(childId);
364
693
  created = true;
365
694
  }
366
695
  else {
367
696
  // §28: read the existing child per its own pinned snapshot.
368
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
+ }
369
704
  }
370
705
  // 5. Synchronize EVERY mapped child input from the SAME fresh snapshot.
371
706
  // A freshly-seeded child already equals the snapshot, so its inputs
@@ -680,6 +1015,40 @@ export class Engine {
680
1015
  this.fire({ type: 'commit', workflow: parentWf, path: callsStem, action: 'reject' });
681
1016
  this.fireSettled(parentWf);
682
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
+ }
683
1052
  /**
684
1053
  * M2B: Maintain all `calls:` steps for a parent workflow.
685
1054
  * Called at the top of tick (outside any tx) and as cascade-up prompt.
@@ -694,7 +1063,7 @@ export class Engine {
694
1063
  this._inMaintainCalls.add(parentWf);
695
1064
  try {
696
1065
  for (const step of def.steps) {
697
- if (!step.calls)
1066
+ if (!isCallStep(step))
698
1067
  continue;
699
1068
  // STEP 1 — Gather gate stems and check gate readiness.
700
1069
  const callsStem = step.produces[0].stem; // single produced artifact name
@@ -729,7 +1098,7 @@ export class Engine {
729
1098
  // needs no in-tx recheck. Record a rejection on the parent calls artifact
730
1099
  // (clean stop; the STEP-2 F2 fingerprint guard then skips re-attempts).
731
1100
  if (!existingChild && this.callsAncestryDepth(parentWf) >= this.maxCallDepth) {
732
- this.recordCallsDepthReject(parentWf, def, callsStem, gateStems, step.calls, now);
1101
+ this.recordCallsDepthReject(parentWf, def, callsStem, gateStems, callTargetLabel(step), now);
733
1102
  continue;
734
1103
  }
735
1104
  // The find-or-create AND every mapped input sync happen in ONE
@@ -769,6 +1138,10 @@ export class Engine {
769
1138
  this.recordCallsDigestReject(parentWf, def, callsStem, gateStems, err, now);
770
1139
  continue;
771
1140
  }
1141
+ if (err instanceof InterfaceCallPinError) {
1142
+ this.recordInterfaceCallPinReject(parentWf, def, callsStem, gateStems, err, now);
1143
+ continue;
1144
+ }
772
1145
  throw err;
773
1146
  }
774
1147
  if (!provision)
@@ -779,7 +1152,12 @@ export class Engine {
779
1152
  // (idempotent maintenance — once per provision, not once per input) so a
780
1153
  // grandchild gets re-provided in the same pass.
781
1154
  if (provision.created) {
782
- 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
+ });
783
1161
  this.fireSettled(provision.childId);
784
1162
  }
785
1163
  for (const name of provision.provided) {
@@ -1222,7 +1600,7 @@ export class Engine {
1222
1600
  const arts = this.artMap(parentWf);
1223
1601
  const out = [];
1224
1602
  for (const step of def.steps) {
1225
- if (!step.calls)
1603
+ if (!isCallStep(step))
1226
1604
  continue;
1227
1605
  const stem = step.produces[0].stem;
1228
1606
  if (!this.callsGateReady(arts, step))
@@ -2096,7 +2474,7 @@ export class Engine {
2096
2474
  // ever spawned there is nothing to judge, so refuse (consistent with the
2097
2475
  // verb-guard rule below that a verdict needs a built version).
2098
2476
  const producingStep = def.steps.find((s) => s.produces.some((p) => p.stem === path));
2099
- if (producingStep?.calls) {
2477
+ if (producingStep !== undefined && isCallStep(producingStep)) {
2100
2478
  const bind = producingStep.produces.find((p) => p.stem === path)?.bind;
2101
2479
  if (requested !== undefined) {
2102
2480
  if (bind?.to !== 'modifier') {
@@ -2308,7 +2686,7 @@ export class Engine {
2308
2686
  // skip made on evidence from child version N survives arbitrary ticks
2309
2687
  // (order A) until the child actually rebuilds past N (order B).
2310
2688
  const producingStep = def.steps.find((s) => s.name === art.producer);
2311
- if (producingStep?.calls) {
2689
+ if (producingStep !== undefined && isCallStep(producingStep)) {
2312
2690
  const pin = this.childOutcomePin(workflow, path);
2313
2691
  if (pin !== undefined)
2314
2692
  fp[Engine.CHILD_OUTCOME_PIN_KEY] = pin;
@@ -2592,7 +2970,7 @@ export class Engine {
2592
2970
  // recursive child summary (all instance-crossing logic stays here, in the
2593
2971
  // engine — the pure workflowStatus never touches another instance).
2594
2972
  for (const d of st.debts) {
2595
- 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);
2596
2974
  if (!callsStep)
2597
2975
  continue;
2598
2976
  const child = this.store.findChildByParent(workflow, d.path);
@@ -3061,7 +3439,7 @@ export class Engine {
3061
3439
  let stalled = cs.debts.some((d) => d.stalled);
3062
3440
  if (!stalled) {
3063
3441
  for (const d of cs.debts) {
3064
- 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);
3065
3443
  if (!callsStep)
3066
3444
  continue;
3067
3445
  const grandchild = this.store.findChildByParent(childWf, d.path);
@@ -23,7 +23,7 @@ import { dirname, join } from 'node:path';
23
23
  import { Engine } from "./engine.js";
24
24
  import { openStore } from "./store.js";
25
25
  import { dbPathRefusingSymlink, mkdirRefusingSymlink } from "./util.js";
26
- import { finalizeDefs, loadDefs, resolveCallsTarget } from "./defs.js";
26
+ import { digestScopedCallsTargetKey, finalizeDefs, loadDefs, resolveCallsTarget } from "./defs.js";
27
27
  import { createDefInstructionSource, OrderResolver } from "./order-resolver.js";
28
28
  /**
29
29
  * Open a store, resolve definitions, and return a wired `Engine` ready to
@@ -80,8 +80,10 @@ export function createEngine(opts = {}) {
80
80
  // flat-map branch and behavior here is unchanged; the branch exists so an
81
81
  // embedder that DOES hand in store-loaded defs gets the same sibling-first
82
82
  // rule `finalizeDefs` already validated the set against.
83
- const resolveDef = (name, from) => {
84
- const d = from === undefined ? defs.get(name) : resolveCallsTarget(defs, name, from);
83
+ const resolveDef = (name, from, bundleDigest) => {
84
+ const d = bundleDigest !== undefined
85
+ ? defs.get(digestScopedCallsTargetKey(bundleDigest, name)) ?? defs.get(name)
86
+ : from === undefined ? defs.get(name) : resolveCallsTarget(defs, name, from);
85
87
  if (!d)
86
88
  throw new Error(`unknown workflow definition '${name}'`);
87
89
  return d;
@@ -1,24 +1,5 @@
1
- import type { JsonSchema, WorkflowDef } from './types.ts';
2
- /** A versioned external interface coordinate claimed in a workflow's x bag. */
3
- export interface WorkflowInterfaceClaim {
4
- name: string;
5
- version: string;
6
- }
7
- /** A named input or public output and the schema that defines its values. */
8
- export interface WorkflowInterfaceArtifact {
9
- name: string;
10
- schema?: JsonSchema;
11
- }
12
- /**
13
- * The typed portion of an external workflow interface. Its catalog coordinate
14
- * is deliberately separate: this checker compares a supplied signature and
15
- * does not resolve a hub catalog or decide whether the workflow authored a
16
- * matching x.implements claim.
17
- */
18
- export interface WorkflowInterfaceSignature {
19
- inputs: WorkflowInterfaceArtifact[];
20
- outputs: WorkflowInterfaceArtifact[];
21
- }
1
+ import type { WorkflowDef, WorkflowInterfaceSignature } from './types.ts';
2
+ export type { WorkflowInterfaceArtifact, WorkflowInterfaceClaim, WorkflowInterfaceSignature, } from './types.ts';
22
3
  /** One deterministic reason an implementation does not satisfy an interface. */
23
4
  export interface InterfaceCompatibilityIssue {
24
5
  path: string;
@@ -11,7 +11,7 @@
11
11
  * workflow definitions + a Step Agent that executes orders) layers a concrete
12
12
  * process — software delivery, research, triage — on top of it.
13
13
  */
14
- export { CallsPinError, Engine, ModifierRefusalError } from './engine.ts';
14
+ export { CallsPinError, Engine, InterfaceBindingRefusalError, InterfaceCallPinError, ModifierRefusalError, } from './engine.ts';
15
15
  export type { CommitResult, CreateOpts, DefResolver, DeferredFiring, DeferredReason, EmitResult, EngineEvent, EngineListener, EngineWorkflowStatus, Order, ReapDetail, ReapReason, TickResult, } from './engine.ts';
16
16
  export { applyCapabilityMappings, applyCapabilityRewrites, capabilityName, claimMatches, composeCapabilities, DEFAULT_MATCH_MODE, MODIFIER_SEPARATOR, } from './capabilities.ts';
17
17
  export type { CapabilityMappings, CapabilityRewrites, CrewStamps, MatchMode } from './capabilities.ts';
@@ -23,7 +23,7 @@ export { Store, openStore, readRuntimeSnapshotBundlePins, StoreVersionError } fr
23
23
  export type { ArtifactRow, RunRow, RuntimeSnapshotBundlePins, TaskRow, WorkflowRow } from './store.ts';
24
24
  export { defDigest, collectWorkflowStoreGarbage, emptyWorkflowStoreIndex, globalStoreRoot, hardenObjectModes, installWorkflowBundle, inspectCasDefs, isDefDigest, loadCasDefs, planWorkflowStoreGc, objectDestRelPath, objectDirForDigest, parseWorkflowCoordinate, parseWorkflowStoreIndex, projectStoreRoot, probeObjectDir, probeStoreRoot, readWorkflowStoreIndex, recoverWorkflowStore, resolveWorkflowCoordinate, resolveWorkflowDigest, serializeWorkflowStoreIndex, storeIndexPath, workflowCoordinate, workflowStoreStatePaths, WORKFLOW_STORE_INDEX_VERSION, WorkflowStoreError, StoreIndexError, StoreDigestError, StoreCoordinateError, StoreAmbiguityError, StoreNotFoundError, StoreIntegrityError, StoreConflictError, StoreDefinitionVerificationError, StoreOriginPolicyError, StorePathError, BundleIngestorUnavailableError, PreCommitVerifierUnavailableError, createExecutionOriginVerifier, originEvidencePath, persistOriginEvidence, readOriginEvidence, } from './store/index.ts';
25
25
  export type { BundleInstallResult, BundleIngestor, BundleSource, BundleVerificationEvidence, CasDefInspectionResult, CasDefRegistration, DefDigest, LoadCasDefsArgs, CollectWorkflowStoreGcArgs, InstallWorkflowBundleArgs, PreCommitVerifier, PlanWorkflowStoreGcArgs, ExecutionOriginVerifierInput, RecoverWorkflowStoreArgs, ResolvedWorkflowObject, ResolveWorkflowCoordinateArgs, ResolveWorkflowDigestArgs, ResolutionLevel, StoreLevel, WorkflowCoordinate, WorkflowStoreIndex, WorkflowStoreIndexEntry, WorkflowStoreGcObject, WorkflowStoreGcPlan, WorkflowStoreGcReport, WorkflowStoreStatePaths, } from './store/index.ts';
26
- export { buildDef, cancelCleanupSteps, DefError, expandIncludes, finalizeDefs, hashDef, lintDef, loadDefFile, loadDefs, loadDefsRaw, parseDef, resolveCallsTarget, SUPPORTED_ENGINE_VERSION, validateDef } from './defs.ts';
26
+ export { buildDef, cancelCleanupSteps, DefError, expandIncludes, finalizeDefs, hashDef, InterfaceCallDefinitionError, lintDef, loadDefFile, loadDefs, loadDefsRaw, parseDef, resolveCallsTarget, SUPPORTED_ENGINE_VERSION, validateDef } from './defs.ts';
27
27
  export { checkInterfaceCompatibility, implementsIssues } from './implements.ts';
28
28
  export type { InterfaceCompatibilityCheck, InterfaceCompatibilityIssue, WorkflowInterfaceArtifact, WorkflowInterfaceClaim, WorkflowInterfaceSignature, } from './implements.ts';
29
29
  export { credentialSlot, hashDefForHub, keychainServiceFor, normalizeOrigin, readStoredCredential } from './hub.ts';
@@ -45,7 +45,7 @@ export type { SchemaCheck, SchemaIssue } from './schema.ts';
45
45
  export { enrollmentGrantSchema, orderSchema, originSchema, policyFloorSchema, publicationSchema, RECORD_SCHEMAS, revocationSchema, SCHEMA_BY_PAYLOAD_TYPE, submissionSchema, WIRE_SCHEMAS, } from './schemas/index.ts';
46
46
  export { BundleError, DEFAULT_BUNDLE_LIMITS, digestBundle, inspectBundle, packBundle, unpackBundle } from './bundle/index.ts';
47
47
  export type { BundleEntryInfo, BundleErrorCode, BundleLimits, BundleManifest, BundleRuntimeRequirements, InspectOptions, InspectResult, PackOptions, PackResult, } from './bundle/index.ts';
48
- export { DEBT_STATES, SETTLED_STATES } from './types.ts';
49
- export type { Acceptance, ArtifactBiography, ArtifactData, Author, CheckFinding, CheckOptions, CheckReport, CheckStep, ConsumePattern, FiringTrigger, Fingerprint, GraphEdge, GraphNode, GraphNodeState, InputDef, InvariantDef, InvariantPredicate, InvariantViolation, JsonSchema, OnCancelDef, StepDef, ProducePattern, ReasonEntry, RejectKind, RunData, TaskData, TimelineEvent, WorkflowDef, WorkflowGraph, WorkflowTrace, } from './types.ts';
48
+ export { DEBT_STATES, isCallStep, SETTLED_STATES } from './types.ts';
49
+ export type { Acceptance, ArtifactBiography, ArtifactData, Author, CheckFinding, CheckOptions, CheckReport, CheckStep, ConsumePattern, FiringTrigger, Fingerprint, GraphEdge, GraphNode, GraphNodeState, InputDef, InterfaceCallBinding, InvariantDef, InvariantPredicate, InvariantViolation, JsonSchema, OnCancelDef, StepDef, ProducePattern, ReasonEntry, RejectKind, RunData, TaskData, TimelineEvent, WorkflowDef, WorkflowGraph, WorkflowTrace, } from './types.ts';
50
50
  export { canonicalValueBytes, valueDigestHex, buildSubmissionRecord, signSubmission } from './crypto/index.ts';
51
51
  export type { BuildSubmissionRecordInput, SubmissionProducedInput } from './crypto/index.ts';