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
package/dist/src/store.js CHANGED
@@ -13,7 +13,141 @@
13
13
  * and (de)serialized at the boundary so callers always see real objects.
14
14
  */
15
15
  import { DatabaseSync } from 'node:sqlite';
16
+ import { lstatSync } from 'node:fs';
16
17
  import { detId, nowMs } from "./util.js";
18
+ import { compareStoreText, defDigest, isDefDigest, parseWorkflowCoordinate } from "./store/types.js";
19
+ import { withWorkflowSnapshotStoreGuard } from "./store/snapshot-guard.js";
20
+ function exactCallsFromSnapshot(record, workflow) {
21
+ const rawSteps = record.steps;
22
+ if (rawSteps === undefined)
23
+ return [];
24
+ if (!Array.isArray(rawSteps)) {
25
+ throw new Error(`workflow '${workflow}' has malformed def_snapshot.steps: expected an array`);
26
+ }
27
+ const exactCalls = new Set();
28
+ for (const [index, rawStep] of rawSteps.entries()) {
29
+ if (typeof rawStep !== 'object' || rawStep === null || Array.isArray(rawStep)) {
30
+ throw new Error(`workflow '${workflow}' has malformed def_snapshot.steps[${index}]: expected an object`);
31
+ }
32
+ const calls = rawStep.calls;
33
+ if (calls === undefined)
34
+ continue;
35
+ if (typeof calls !== 'string') {
36
+ throw new Error(`workflow '${workflow}' has malformed def_snapshot.steps[${index}].calls: expected a string`);
37
+ }
38
+ if (!calls.includes('@'))
39
+ continue;
40
+ try {
41
+ parseWorkflowCoordinate(calls);
42
+ }
43
+ catch (error) {
44
+ throw new Error(`workflow '${workflow}' has malformed exact def_snapshot calls target ${JSON.stringify(calls)}: ` +
45
+ error.message);
46
+ }
47
+ const rawLock = record.bundleLock;
48
+ if (typeof rawLock === 'object'
49
+ && rawLock !== null
50
+ && !Array.isArray(rawLock)
51
+ && Object.prototype.hasOwnProperty.call(rawLock, calls))
52
+ continue;
53
+ exactCalls.add(calls);
54
+ }
55
+ return [...exactCalls].sort(compareStoreText);
56
+ }
57
+ /**
58
+ * Read bundle pins from an EXISTING runtime database without migrating or
59
+ * otherwise writing it. GC deliberately cannot use {@link openStore}: opening
60
+ * the normal store enables write-oriented pragmas and schema migration, while
61
+ * a dry run must remain observational. Legacy databases without the workflow
62
+ * table or def_snapshot column simply predate snapshot pinning and contribute
63
+ * no pins.
64
+ */
65
+ export function readRuntimeSnapshotBundlePins(path) {
66
+ if (lstatSync(path, { throwIfNoEntry: false }) === undefined)
67
+ return [];
68
+ const db = new DatabaseSync(path, { readOnly: true });
69
+ try {
70
+ const hasMeta = db
71
+ .prepare(`SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'meta'`)
72
+ .get() !== undefined;
73
+ if (hasMeta) {
74
+ const row = db.prepare(`SELECT v FROM meta WHERE k = 'schema_version'`).get();
75
+ const current = row?.v;
76
+ if (current !== undefined && parseInt(current, 10) > parseInt(SCHEMA_VERSION, 10)) {
77
+ throw new StoreVersionError(`database schema_version ${current} is newer than this owenloop's schema_version ${SCHEMA_VERSION}; ` +
78
+ 'upgrade your owenloop install to open this database');
79
+ }
80
+ }
81
+ const hasWorkflow = db
82
+ .prepare(`SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'workflow'`)
83
+ .get() !== undefined;
84
+ if (!hasWorkflow)
85
+ return [];
86
+ const columns = db.prepare('PRAGMA table_info(workflow)').all();
87
+ const hasSnapshotColumn = columns.some((column) => column.name === 'def_snapshot');
88
+ const hasBindingsColumn = columns.some((column) => column.name === 'interface_bindings');
89
+ if (!hasSnapshotColumn && !hasBindingsColumn)
90
+ return [];
91
+ const snapshotProjection = hasSnapshotColumn ? 'def_snapshot' : 'NULL AS def_snapshot';
92
+ const bindingProjection = hasBindingsColumn ? 'interface_bindings' : 'NULL AS interface_bindings';
93
+ const predicates = [
94
+ ...(hasSnapshotColumn ? ['def_snapshot IS NOT NULL'] : []),
95
+ ...(hasBindingsColumn ? ['interface_bindings IS NOT NULL'] : []),
96
+ ];
97
+ const rows = db
98
+ .prepare(`SELECT id, ${snapshotProjection}, ${bindingProjection} FROM workflow `
99
+ + `WHERE ${predicates.join(' OR ')} ORDER BY created_at, id`)
100
+ .all();
101
+ return rows.map((row) => {
102
+ let record = {};
103
+ if (row.def_snapshot !== null) {
104
+ let snapshot;
105
+ try {
106
+ snapshot = JSON.parse(row.def_snapshot);
107
+ }
108
+ catch (error) {
109
+ throw new Error(`workflow '${row.id}' has malformed def_snapshot JSON: ${error.message}`);
110
+ }
111
+ if (typeof snapshot !== 'object' || snapshot === null || Array.isArray(snapshot)) {
112
+ throw new Error(`workflow '${row.id}' has malformed def_snapshot: expected an object`);
113
+ }
114
+ record = snapshot;
115
+ }
116
+ const rawDigest = record.bundleDigest;
117
+ let bundleDigest;
118
+ if (rawDigest !== undefined && rawDigest !== '') {
119
+ if (typeof rawDigest !== 'string' || !isDefDigest(rawDigest)) {
120
+ throw new Error(`workflow '${row.id}' has noncanonical def_snapshot.bundleDigest ${JSON.stringify(rawDigest)}`);
121
+ }
122
+ bundleDigest = rawDigest;
123
+ }
124
+ const rawLock = record.bundleLock;
125
+ if (rawLock !== undefined && (typeof rawLock !== 'object' || rawLock === null || Array.isArray(rawLock))) {
126
+ throw new Error(`workflow '${row.id}' has malformed def_snapshot.bundleLock: expected an object`);
127
+ }
128
+ const bundleLock = Object.entries((rawLock ?? {})).map(([target, digest]) => {
129
+ if (typeof digest !== 'string' || !isDefDigest(digest)) {
130
+ throw new Error(`workflow '${row.id}' has noncanonical def_snapshot.bundleLock[${JSON.stringify(target)}] ` +
131
+ `${JSON.stringify(digest)}`);
132
+ }
133
+ return digest;
134
+ });
135
+ const exactCalls = row.def_snapshot === null ? [] : exactCallsFromSnapshot(record, row.id);
136
+ const interfaceBindingDigests = [
137
+ ...new Set((parseStoredInterfaceBindings(row.interface_bindings, row.id) ?? []).map((binding) => binding.digest)),
138
+ ].sort(compareStoreText);
139
+ return {
140
+ ...(bundleDigest === undefined ? {} : { bundleDigest }),
141
+ bundleLock: [...new Set(bundleLock)].sort(compareStoreText),
142
+ ...(exactCalls.length === 0 ? {} : { exactCalls }),
143
+ ...(interfaceBindingDigests.length === 0 ? {} : { interfaceBindingDigests }),
144
+ };
145
+ });
146
+ }
147
+ finally {
148
+ db.close();
149
+ }
150
+ }
17
151
  // ---- deterministic ids -------------------------------------------------------
18
152
  export function artifactId(workflow, path) {
19
153
  return detId('art', workflow, path);
@@ -30,6 +164,7 @@ CREATE TABLE IF NOT EXISTS workflow (
30
164
  params TEXT NOT NULL DEFAULT '{}',
31
165
  modifier TEXT,
32
166
  meta TEXT,
167
+ interface_bindings TEXT,
33
168
  created_at INTEGER NOT NULL
34
169
  );
35
170
 
@@ -154,8 +289,11 @@ CREATE TABLE IF NOT EXISTS meta (
154
289
  *
155
290
  * Bumped to '11' for bound artifacts: the `workflow` table gains nullable
156
291
  * JSON `meta` for non-routing `meta.<key>` artifact binds.
292
+ *
293
+ * Bumped to '12' for immutable start-time interface-call bindings: the
294
+ * `workflow` table gains nullable JSON `interface_bindings`.
157
295
  */
158
- const SCHEMA_VERSION = '11';
296
+ const SCHEMA_VERSION = '12';
159
297
  /** Thrown by the `Store` constructor when the on-disk `schema_version` is
160
298
  * newer than this binary's `SCHEMA_VERSION` — the operator needs to
161
299
  * upgrade their owenloop install to open this database. */
@@ -228,6 +366,98 @@ function fromJson(s, fallback, ctx) {
228
366
  throw new Error(`Corrupt JSON in ${ctx.table}.${ctx.column} for row ${ctx.id}: ${msg}`);
229
367
  }
230
368
  }
369
+ function parseStoredInterfaceBindings(s, workflow) {
370
+ const value = fromJson(s, undefined, {
371
+ table: 'workflow',
372
+ id: workflow,
373
+ column: 'interface_bindings',
374
+ });
375
+ if (value === undefined)
376
+ return undefined;
377
+ if (!Array.isArray(value)) {
378
+ throw new Error(`workflow '${workflow}' has malformed interface_bindings: expected an array`);
379
+ }
380
+ const seenClaims = new Set();
381
+ for (const [index, binding] of value.entries()) {
382
+ const path = `workflow '${workflow}' interface_bindings[${index}]`;
383
+ if (typeof binding !== 'object' || binding === null || Array.isArray(binding)) {
384
+ throw new Error(`${path} is malformed: expected an object`);
385
+ }
386
+ const record = binding;
387
+ const bindingKeys = Object.keys(record).filter((key) => key !== 'interface' && key !== 'target' && key !== 'digest' && key !== 'signature');
388
+ if (bindingKeys.length > 0) {
389
+ throw new Error(`${path} is malformed: unknown field${bindingKeys.length === 1 ? '' : 's'} ${bindingKeys.join(', ')}`);
390
+ }
391
+ const claim = record.interface;
392
+ if (typeof claim !== 'object' || claim === null || Array.isArray(claim)) {
393
+ throw new Error(`${path}.interface is malformed: expected an object`);
394
+ }
395
+ const claimRecord = claim;
396
+ const claimKeys = Object.keys(claimRecord).filter((key) => key !== 'name' && key !== 'version');
397
+ if (claimKeys.length > 0) {
398
+ throw new Error(`${path}.interface is malformed: unknown field${claimKeys.length === 1 ? '' : 's'} ${claimKeys.join(', ')}`);
399
+ }
400
+ if (typeof claimRecord.name !== 'string' || claimRecord.name.trim() === ''
401
+ || typeof claimRecord.version !== 'string' || claimRecord.version.trim() === '') {
402
+ throw new Error(`${path}.interface is malformed: name and version must be non-empty strings`);
403
+ }
404
+ const claimKey = JSON.stringify([claimRecord.name, claimRecord.version]);
405
+ if (seenClaims.has(claimKey)) {
406
+ throw new Error(`${path}.interface is malformed: duplicate interface claim ${claimRecord.name}@${claimRecord.version}`);
407
+ }
408
+ seenClaims.add(claimKey);
409
+ if (typeof record.target !== 'string') {
410
+ throw new Error(`${path}.target is malformed: expected an exact workflow coordinate`);
411
+ }
412
+ try {
413
+ parseWorkflowCoordinate(record.target);
414
+ }
415
+ catch (error) {
416
+ throw new Error(`${path}.target is malformed: ${error.message}`);
417
+ }
418
+ if (typeof record.digest !== 'string' || !isDefDigest(record.digest)) {
419
+ throw new Error(`${path}.digest is noncanonical: ${JSON.stringify(record.digest)}`);
420
+ }
421
+ const signature = record.signature;
422
+ if (typeof signature !== 'object' || signature === null || Array.isArray(signature)) {
423
+ throw new Error(`${path}.signature is malformed: expected an object`);
424
+ }
425
+ const signatureRecord = signature;
426
+ const signatureKeys = Object.keys(signatureRecord).filter((key) => key !== 'inputs' && key !== 'outputs');
427
+ if (signatureKeys.length > 0) {
428
+ throw new Error(`${path}.signature is malformed: unknown field${signatureKeys.length === 1 ? '' : 's'} ${signatureKeys.join(', ')}`);
429
+ }
430
+ if (!Array.isArray(signatureRecord.inputs) || !Array.isArray(signatureRecord.outputs)) {
431
+ throw new Error(`${path}.signature is malformed: inputs and outputs must be arrays`);
432
+ }
433
+ const signatureArtifacts = {
434
+ inputs: signatureRecord.inputs,
435
+ outputs: signatureRecord.outputs,
436
+ };
437
+ for (const direction of ['inputs', 'outputs']) {
438
+ for (const [artifactIndex, artifact] of signatureArtifacts[direction].entries()) {
439
+ const artifactPath = `${path}.signature.${direction}[${artifactIndex}]`;
440
+ if (typeof artifact !== 'object' || artifact === null || Array.isArray(artifact)) {
441
+ throw new Error(`${artifactPath} is malformed: expected an object`);
442
+ }
443
+ const artifactRecord = artifact;
444
+ const artifactKeys = Object.keys(artifactRecord).filter((key) => key !== 'name' && key !== 'schema');
445
+ if (artifactKeys.length > 0) {
446
+ throw new Error(`${artifactPath} is malformed: unknown field${artifactKeys.length === 1 ? '' : 's'} ${artifactKeys.join(', ')}`);
447
+ }
448
+ if (typeof artifactRecord.name !== 'string' || artifactRecord.name.trim() === '') {
449
+ throw new Error(`${artifactPath}.name is malformed: expected a non-empty string`);
450
+ }
451
+ if (artifactRecord.schema !== undefined
452
+ && typeof artifactRecord.schema !== 'boolean'
453
+ && (typeof artifactRecord.schema !== 'object' || artifactRecord.schema === null || Array.isArray(artifactRecord.schema))) {
454
+ throw new Error(`${artifactPath}.schema is malformed: expected a JSON Schema object or boolean`);
455
+ }
456
+ }
457
+ }
458
+ }
459
+ return value;
460
+ }
231
461
  function mapArtifact(r) {
232
462
  const out = {
233
463
  id: r.id,
@@ -380,11 +610,15 @@ function mapWorkflow(r) {
380
610
  });
381
611
  if (meta !== undefined)
382
612
  out.meta = meta;
613
+ const interfaceBindings = parseStoredInterfaceBindings(r.interface_bindings, r.id);
614
+ if (interfaceBindings !== undefined)
615
+ out.interfaceBindings = interfaceBindings;
383
616
  return out;
384
617
  }
385
618
  // ---- the store ---------------------------------------------------------------
386
619
  export class Store {
387
620
  db;
621
+ activeSnapshotDigests = new Set();
388
622
  constructor(path) {
389
623
  this.db = new DatabaseSync(path);
390
624
  // Connection-scoped only — no file mutation, safe before the version check.
@@ -540,6 +774,9 @@ export class Store {
540
774
  if (!wfCols.some((c) => c.name === 'meta')) {
541
775
  this.db.exec(`ALTER TABLE workflow ADD COLUMN meta TEXT`);
542
776
  }
777
+ if (!wfCols.some((c) => c.name === 'interface_bindings')) {
778
+ this.db.exec(`ALTER TABLE workflow ADD COLUMN interface_bindings TEXT`);
779
+ }
543
780
  // Only a genuine pre-v8 -> v8 upgrade may backfill the current projection's
544
781
  // reason thread. Re-opening an already-v8 database must not manufacture a
545
782
  // second copy of its lifecycle events (even though the legacy keys differ
@@ -581,6 +818,35 @@ export class Store {
581
818
  throw err;
582
819
  }
583
820
  }
821
+ /**
822
+ * Persist one or more CAS-backed definition snapshots under the same
823
+ * workflow-store lock used by install and GC. Reachability is revalidated
824
+ * before `BEGIN IMMEDIATE`; the guarded digest set then authorizes only the
825
+ * low-level snapshot writes performed by this transaction.
826
+ */
827
+ txWithWorkflowSnapshots(snapshots, fn) {
828
+ const defs = Array.isArray(snapshots) ? snapshots : [snapshots];
829
+ return withWorkflowSnapshotStoreGuard(defs, (guardedDigests) => {
830
+ for (const digest of guardedDigests)
831
+ this.activeSnapshotDigests.add(digest);
832
+ try {
833
+ return this.tx(fn);
834
+ }
835
+ finally {
836
+ for (const digest of guardedDigests)
837
+ this.activeSnapshotDigests.delete(digest);
838
+ }
839
+ });
840
+ }
841
+ assertWorkflowSnapshotGuard(snapshot) {
842
+ if (snapshot?.bundleDigest === undefined || (snapshot.bundleStoreRoots?.length ?? 0) === 0)
843
+ return;
844
+ const digest = defDigest(snapshot.bundleDigest);
845
+ if (!this.activeSnapshotDigests.has(digest)) {
846
+ throw new Error(`refusing uncoordinated workflow snapshot write for bundle ${digest}: ` +
847
+ 'use txWithWorkflowSnapshots so bundle GC cannot race the commit');
848
+ }
849
+ }
584
850
  // -- meta --------------------------------------------------------------------
585
851
  getMeta(k) {
586
852
  const row = this.db.prepare('SELECT v FROM meta WHERE k = ?').get(k);
@@ -593,12 +859,13 @@ export class Store {
593
859
  }
594
860
  // -- workflow ----------------------------------------------------------------
595
861
  insertWorkflow(id, data, producedBy) {
862
+ this.assertWorkflowSnapshotGuard(data.defSnapshot);
596
863
  const at = nowMs();
597
864
  this.db
598
865
  .prepare(`INSERT INTO workflow
599
- (id, def, title, params, produced_by_wf, produced_by_path, def_snapshot, def_hash, modifier, meta, created_at)
600
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)
601
- .run(id, data.def, data.title ?? null, JSON.stringify(data.params ?? {}), producedBy?.parentWf ?? null, producedBy?.parentPath ?? null, toJson(data.defSnapshot), data.defHash ?? null, data.modifier ?? null, toJson(data.meta), at);
866
+ (id, def, title, params, produced_by_wf, produced_by_path, def_snapshot, def_hash, modifier, meta, interface_bindings, created_at)
867
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)
868
+ .run(id, data.def, data.title ?? null, JSON.stringify(data.params ?? {}), producedBy?.parentWf ?? null, producedBy?.parentPath ?? null, toJson(data.defSnapshot), data.defHash ?? null, data.modifier ?? null, toJson(data.meta), toJson(data.interfaceBindings), at);
602
869
  return this.getWorkflow(id);
603
870
  }
604
871
  /**
@@ -607,6 +874,7 @@ export class Store {
607
874
  * decide what "drift" means, it just persists what the engine computed.
608
875
  */
609
876
  repinWorkflowDef(id, snapshot, hash) {
877
+ this.assertWorkflowSnapshotGuard(snapshot);
610
878
  this.db
611
879
  .prepare('UPDATE workflow SET def_snapshot = ?, def_hash = ? WHERE id = ?')
612
880
  .run(JSON.stringify(snapshot), hash, id);
@@ -924,8 +1192,10 @@ export class Store {
924
1192
  if (!cur)
925
1193
  throw new Error(`run not found: ${id}`);
926
1194
  // order_json is DELIBERATELY excluded from `merged` and the UPDATE below:
927
- // the order packet is immutable after claim (§8 / Gap 1). Omitting it makes
928
- // that structural — no close/outcome/summary write can ever clobber it.
1195
+ // no close/outcome/summary write can ever clobber the order packet, and
1196
+ // omitting the column makes that structural rather than a convention.
1197
+ // `restampOrderTarget` below is the ONE writer of order_json after claim,
1198
+ // and it rewrites a single `owes[].version` and nothing else.
929
1199
  const merged = {
930
1200
  workflow: cur.workflow,
931
1201
  step: cur.step,
@@ -941,28 +1211,79 @@ export class Store {
941
1211
  .run(merged.key ?? '', merged.outcome ?? null, merged.summary ?? null, merged.sessionId ?? null, toJson(merged.fingerprint), merged.cause ?? null, nowMs(), id);
942
1212
  return this.getRun(id);
943
1213
  }
1214
+ /**
1215
+ * Re-stamp ONE owed version target on a run's persisted order packet.
1216
+ *
1217
+ * The order is frozen at claim with exactly one exception, and this is it.
1218
+ * When a reject re-arms a still-open claim, the artifact has already been
1219
+ * bumped by the commit that preceded the reject, so the target the claim
1220
+ * froze at issue names a version the next commit will overshoot — and the
1221
+ * producer would sign that stale number into its submission proof while the
1222
+ * hub keys the stored proof row by the version actually committed. Everything
1223
+ * else about the packet stays frozen, and `updateRun` still cannot touch it
1224
+ * at all.
1225
+ *
1226
+ * No-ops when the run has no persisted order (pre-schema-v7 rows), when the
1227
+ * order does not owe `path`, or when the target already is `version` — so
1228
+ * callers can call it unconditionally, and re-stamping is idempotent.
1229
+ */
1230
+ restampOrderTarget(id, path, version) {
1231
+ const cur = this.getRun(id);
1232
+ if (!cur?.order)
1233
+ return;
1234
+ const owed = cur.order.owes.find((o) => o.path === path);
1235
+ if (owed === undefined || owed.version === version)
1236
+ return;
1237
+ // Rebuilt immutably (map, not in-place mutation) so no caller is left
1238
+ // holding a half-mutated Order read before this write.
1239
+ const next = {
1240
+ ...cur.order,
1241
+ owes: cur.order.owes.map((o) => (o.path === path ? { ...o, version } : o)),
1242
+ };
1243
+ this.db
1244
+ .prepare('UPDATE run SET order_json = ?, updated_at = ? WHERE id = ?')
1245
+ .run(toJson(next), nowMs(), id);
1246
+ }
944
1247
  getRun(id) {
945
1248
  const r = this.db.prepare('SELECT * FROM run WHERE id = ?').get(id);
946
1249
  return r ? mapRun(r) : undefined;
947
1250
  }
948
- /** How many runs of this step since `sinceMs` (for the daily budget window). */
1251
+ /**
1252
+ * How many runs of this step since `sinceMs` (for the daily budget window).
1253
+ *
1254
+ * `released` RUNS ARE EXCLUDED — a lease returned unused is not a firing. See
1255
+ * `RunData.outcome` for why this is not the same as `no_work`, which stays
1256
+ * counted because the step did run.
1257
+ */
949
1258
  countRuns(workflow, step, sinceMs) {
950
1259
  const row = this.db
951
- .prepare('SELECT COUNT(*) AS n FROM run WHERE workflow = ? AND step = ? AND created_at >= ?')
1260
+ .prepare('SELECT COUNT(*) AS n FROM run WHERE workflow = ? AND step = ? AND created_at >= ?'
1261
+ + " AND (outcome IS NULL OR outcome != 'released')")
952
1262
  .get(workflow, step, sinceMs);
953
1263
  return row.n;
954
1264
  }
955
- /** The most recent run of this step, if any (for cadence gating). */
1265
+ /**
1266
+ * The most recent run of this step, if any (for cadence gating).
1267
+ *
1268
+ * `released` runs are excluded for the same reason `countRuns` excludes them:
1269
+ * a lease handed straight back did not fire the step, so it must not restart
1270
+ * the cadence clock. Without this a server that claims and releases on every
1271
+ * sweep holds a throttled step off indefinitely — each handback pushes the
1272
+ * next eligible time further out than the sweep interval that produced it.
1273
+ */
956
1274
  latestRun(workflow, step) {
957
1275
  const r = this.db
958
- .prepare('SELECT * FROM run WHERE workflow = ? AND step = ? ORDER BY created_at DESC LIMIT 1')
1276
+ .prepare("SELECT * FROM run WHERE workflow = ? AND step = ? AND (outcome IS NULL OR outcome != 'released')"
1277
+ + ' ORDER BY created_at DESC LIMIT 1')
959
1278
  .get(workflow, step);
960
1279
  return r ? mapRun(r) : undefined;
961
1280
  }
962
1281
  /**
963
1282
  * Count of consecutive trailing `failed` runs for this step+key — the
964
- * crash-step signal. Any closed run that is NOT `failed` (ok/no_work/skipped)
965
- * breaks the streak; still-open runs (outcome NULL) are ignored.
1283
+ * crash-step signal. Any closed run that is NOT `failed`
1284
+ * (ok/no_work/released/skipped) breaks the streak; still-open runs (outcome
1285
+ * NULL) are ignored. `released` breaks it exactly as `no_work` did before the
1286
+ * two were split, so the crash-step signal is unchanged by that split.
966
1287
  */
967
1288
  recentFailedRuns(workflow, step, key = '') {
968
1289
  const rows = this.db
@@ -42,6 +42,32 @@ export type RejectKind = 'judgment' | 'structural' | 'validation' | 'invalidated
42
42
  export type ReasonAction = 'reject' | 'retract' | 'skip' | 'reopen' | 'retry' | 'ask' | 'born-rejected' | 'schema-reject' | 'pinned';
43
43
  /** A JSON Schema, as authored in a definition: an object, or a boolean (allow/deny all). */
44
44
  export type JsonSchema = Record<string, unknown> | boolean;
45
+ /** A versioned external interface coordinate. Names and versions are opaque. */
46
+ export interface WorkflowInterfaceClaim {
47
+ name: string;
48
+ version: string;
49
+ }
50
+ /** A named input or public output and the schema that defines its values. */
51
+ export interface WorkflowInterfaceArtifact {
52
+ name: string;
53
+ schema?: JsonSchema;
54
+ }
55
+ /** The typed portion of an external workflow interface. */
56
+ export interface WorkflowInterfaceSignature {
57
+ inputs: WorkflowInterfaceArtifact[];
58
+ outputs: WorkflowInterfaceArtifact[];
59
+ }
60
+ /**
61
+ * One hub-selected implementation pinned when an instance starts. The engine
62
+ * validates the exact coordinate, bundle digest, nominal claim, and structural
63
+ * signature before persisting this immutable mapping.
64
+ */
65
+ export interface InterfaceCallBinding {
66
+ interface: WorkflowInterfaceClaim;
67
+ target: string;
68
+ digest: string;
69
+ signature: WorkflowInterfaceSignature;
70
+ }
45
71
  /** One entry in an artifact's append-only reason thread (design §4). */
46
72
  export interface ReasonEntry {
47
73
  at: number;
@@ -170,6 +196,12 @@ export interface Order {
170
196
  * (`wise` → `wise:deep`), or the authored names verbatim when the run
171
197
  * carries no modifier. Absent when the step authored none.
172
198
  *
199
+ * A caller may also supply a capability MAPPING, which substitutes its own
200
+ * capability name for the authored one before the modifier is attached. Such
201
+ * an order carries no in-band marker — unlike a reroute, nothing here says a
202
+ * mapping fired. The authored name stays recoverable through `defDigest`,
203
+ * which pins the def that wrote it.
204
+ *
173
205
  * This is the value a claiming crew's bindings are matched against and the
174
206
  * value the shift's settings map is keyed by. It is a snapshot of the offer:
175
207
  * an already-claimed order is never recomposed, so re-reading it later
@@ -263,11 +295,12 @@ export interface Order {
263
295
  * stalls the step. This closes that: the requirement is stated up front,
264
296
  * from the same declaration the refusal will be measured against.
265
297
  *
266
- * It is a COPY, not a reference. The order is immutable once written
267
- * (`RunData.order`), so this is the schema as it stood at claim time; a def
268
- * edited mid-run leaves the projected schema and the enforced one able to
269
- * disagree, exactly as `defDigest` already records for the rest of the
270
- * order.
298
+ * It is a COPY, not a reference. Nothing rewrites the schema on a persisted
299
+ * order — `Store.restampOrderTarget`, the one post-claim writer, touches
300
+ * only `owes[].version` — so this is the schema as it stood at claim time;
301
+ * a def edited mid-run leaves the projected schema and the enforced one
302
+ * able to disagree, exactly as `defDigest` already records for the rest of
303
+ * the order.
271
304
  */
272
305
  schema?: JsonSchema;
273
306
  /**
@@ -299,7 +332,31 @@ export interface RunData {
299
332
  workflow: string;
300
333
  step: string;
301
334
  key?: string;
302
- outcome?: 'ok' | 'no_work' | 'failed' | 'skipped';
335
+ /**
336
+ * How the run ended, or `undefined` while it is still open.
337
+ *
338
+ * `no_work` and `released` are NOT the same thing, and the difference is
339
+ * load-bearing for the daily budget and the cadence gate:
340
+ *
341
+ * - `no_work` — the step RAN and had nothing to produce. A `merge-gate` that
342
+ * polled CI and found it still pending, an `ask` that handed the question
343
+ * to a human, a holder that rejected its input. Work happened; these runs
344
+ * spend budget and restart the cadence clock, which is exactly how a
345
+ * `cadenceSecs` poll stays throttled.
346
+ * - `released` — the LEASE WAS RETURNED UNUSED. Nothing ran. A server already
347
+ * at its agent cap handing the claim straight back or a pickup window that
348
+ * lapsed with no first contact increments the task's lease-churn
349
+ * `attempts`, while a private born-reject re-arm does not. All remain
350
+ * outside the daily budget and cadence: they are not firings, they are
351
+ * claims that were withdrawn.
352
+ *
353
+ * Conflating them stalled a live run. Six capacity handbacks against a step
354
+ * declaring `maxRunsPerDay: 6` spent the whole allowance before it executed
355
+ * once; the engine then deferred it `daily-budget` until local midnight while
356
+ * its artifact still read `attemptsUsed: 0`. Lease-churn attempts are status
357
+ * telemetry, not the rework budget (`judgmentRejects`) and not a run.
358
+ */
359
+ outcome?: 'ok' | 'no_work' | 'released' | 'failed' | 'skipped';
303
360
  summary?: string;
304
361
  sessionId?: string;
305
362
  /** the version of every consumed input at claim time (§12.2 commit CAS) */
@@ -308,8 +365,10 @@ export interface RunData {
308
365
  cause?: FiringTrigger;
309
366
  /** The flattened order packet issued at claim time (§8 / Gap 1) — the exact
310
367
  * Order buildOrder emitted, written in the SAME transaction that created
311
- * this run. Immutable after insert: updateRun never touches it. The
312
- * replay/eval/paper-trail record (buildOrder is deterministic modulo run
368
+ * this run. `updateRun` never touches it, so no close/outcome write can
369
+ * clobber it; `Store.restampOrderTarget` is the single narrow exception,
370
+ * rewriting one `owes[].version` when a reject re-arms a still-open claim.
371
+ * The replay/eval/paper-trail record (buildOrder is deterministic modulo run
313
372
  * id). Absent on runs created before schema v7. */
314
373
  order?: Order;
315
374
  }
@@ -331,6 +390,12 @@ export interface WorkflowData {
331
390
  modifier?: string;
332
391
  /** Engine-written, non-routing metadata populated by artifact binds. */
333
392
  meta?: Record<string, unknown>;
393
+ /**
394
+ * Complete, normalized start-time interface-call bindings inherited by every
395
+ * calls child. Immutable instance state: routing/meta updates and adopt never
396
+ * rewrite it, and legacy rows map SQL NULL to true property absence.
397
+ */
398
+ interfaceBindings?: InterfaceCallBinding[];
334
399
  /** Instance-to-definition pinning (§28): the compiled def this instance was
335
400
  * created against, snapshotted verbatim as JSON. Absent on rows created
336
401
  * before this feature shipped — those instances fall back to today's
@@ -577,6 +642,8 @@ export interface StepDef {
577
642
  body: string;
578
643
  /** Mode 2 foundation: name of the child workflow this step delegates to. Machine-handled, never a worker firing. */
579
644
  calls?: string;
645
+ /** Versioned interface delegated to through the instance's immutable start-time binding. */
646
+ callsInterface?: WorkflowInterfaceClaim;
580
647
  /** Mode 2 foundation: child input name → parent artifact name wiring for a calls: step. */
581
648
  callsInputs?: Record<string, string>;
582
649
  /** §24 judges: marker naming the produce stem this synthesized step judges. Mirrors `calls?`. */
@@ -588,6 +655,8 @@ export interface StepDef {
588
655
  * `buildOrder` onto the Order for an external runner/tooling to read. */
589
656
  x?: Record<string, unknown>;
590
657
  }
658
+ /** True for either statically-targeted or start-bound machine call steps. */
659
+ export declare function isCallStep(step: Pick<StepDef, 'calls' | 'callsInterface'>): boolean;
591
660
  /** A workflow definition: a set of steps plus declared external inputs. */
592
661
  export interface WorkflowDef {
593
662
  name: string;
@@ -803,11 +872,20 @@ export interface CheckReport {
803
872
  bounded: boolean;
804
873
  /** Which bounds were hit, for honest reporting. */
805
874
  boundsHit: ('maxDepth' | 'maxStates')[];
875
+ /**
876
+ * True when the search expanded at least one reachable `emit-seal` outcome.
877
+ * This describes the search shape, not a BFS stop condition, and does not
878
+ * contribute to `bounded`.
879
+ */
880
+ collectionCapApplied: boolean;
881
+ /** Effective per-seal member-count cap, including the default when unspecified. */
882
+ maxCollectionSize: number;
806
883
  /**
807
884
  * Reachable non-done states with zero eligible firings that have NO path to
808
- * completion even at unlimited attempts — i.e. recomputing eligibility with
809
- * all freezes lifted (a human `retry` = unlimited attempts) STILL yields
810
- * zero firings. A genuine structural dead-end (TRUE deadlock). A definite
885
+ * completion even after unlimited attempts and elapsed idle time — i.e.
886
+ * recomputing eligibility with all freezes lifted (a human `retry` =
887
+ * unlimited attempts) and eventual idle time STILL yields zero firings. A
888
+ * genuine structural dead-end (TRUE deadlock). A definite
811
889
  * defect only when the search was exhaustive (`!bounded`) — the
812
890
  * maxCollectionSize cap can otherwise manufacture a spurious no-moves
813
891
  * state. Always present ([] when none).
@@ -815,12 +893,14 @@ export interface CheckReport {
815
893
  deadlocks: CheckFinding[];
816
894
  /**
817
895
  * Reachable non-done states with zero eligible firings whose ONLY blocker
818
- * is a frozen/stalled debt (maxAttempts / maxSchemaFailures / held).
819
- * Recomputing eligibility with all freezes lifted (a human `retry` =
820
- * unlimited attempts) yields >= 1 firing, so a producer would re-arm and
821
- * the line could move. These are the DESIGNED human-escalation brakes —
822
- * EXPECTED, never a defect; they do not affect the exit code. Always
823
- * present ([] when none).
896
+ * is a frozen/stalled debt (maxAttempts / maxSchemaFailures / held) or an
897
+ * idle trigger whose threshold has not yet elapsed. Recomputing eligibility
898
+ * with all freezes lifted (a human `retry` = unlimited attempts) and
899
+ * eventual idle time yields >= 1 firing, so a producer would re-arm or an
900
+ * idle step would become eligible. These are expected brakes/waits — never
901
+ * a defect; they do not affect the exit code. This classification does not
902
+ * itself make an idle successor reachable in the timeless BFS, so
903
+ * `completable` can remain false. Always present ([] when none).
824
904
  */
825
905
  stallStates: CheckFinding[];
826
906
  /**
package/dist/src/types.js CHANGED
@@ -25,3 +25,7 @@ export const OUTSTANDING_STATES = new Set([
25
25
  ...DEBT_STATES,
26
26
  'submitted',
27
27
  ]);
28
+ /** True for either statically-targeted or start-bound machine call steps. */
29
+ export function isCallStep(step) {
30
+ return step.calls !== undefined || step.callsInterface !== undefined;
31
+ }
package/dist/src/util.js CHANGED
@@ -138,7 +138,10 @@ export function parseDurationMs(spec) {
138
138
  const m = DUR_RE.exec(String(spec).trim());
139
139
  if (!m)
140
140
  throw new Error(`bad duration: ${spec} (use 90m, 2h, or seconds)`);
141
- return Number(m[1]) * UNIT_MS[m[2]];
141
+ const milliseconds = Number(m[1]) * UNIT_MS[m[2]];
142
+ if (!Number.isFinite(milliseconds))
143
+ throw new Error(`bad duration: ${spec} (duration is too large)`);
144
+ return milliseconds;
142
145
  }
143
146
  /** "30m" → 1800 seconds. */
144
147
  export function parseDurationSecs(spec) {