owenloop 0.5.1 → 0.5.3

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 (88) hide show
  1. package/CHANGELOG.md +30 -0
  2. package/README.md +9 -2
  3. package/dist/packages/work/src/agent/brief.d.ts +21 -0
  4. package/dist/packages/work/src/agent/brief.js +42 -1
  5. package/dist/packages/work/src/agent/capability-model.d.ts +123 -0
  6. package/dist/packages/work/src/agent/capability-model.js +148 -0
  7. package/dist/packages/work/src/agent/loop.d.ts +47 -4
  8. package/dist/packages/work/src/agent/loop.js +83 -53
  9. package/dist/packages/work/src/exec/loop.d.ts +17 -0
  10. package/dist/packages/work/src/exec/loop.js +195 -34
  11. package/dist/packages/work/src/exec/runner.js +15 -5
  12. package/dist/packages/work/src/harness/claude.js +69 -9
  13. package/dist/packages/work/src/harness/codex.js +56 -8
  14. package/dist/packages/work/src/harness/contract.d.ts +65 -1
  15. package/dist/packages/work/src/harness/contract.js +56 -0
  16. package/dist/packages/work/src/harness/session-store.d.ts +3 -1
  17. package/dist/packages/work/src/harness/session-store.js +46 -22
  18. package/dist/packages/work/src/hold/mcp.js +9 -2
  19. package/dist/packages/work/src/hub/client.d.ts +7 -1
  20. package/dist/packages/work/src/hub/client.js +1 -0
  21. package/dist/packages/work/src/hub/types.d.ts +71 -3
  22. package/dist/packages/work/src/roles/agent-run.js +8 -9
  23. package/dist/packages/work/src/roles/hold.d.ts +2 -0
  24. package/dist/packages/work/src/roles/hold.js +39 -8
  25. package/dist/packages/work/src/roles/settings.js +18 -6
  26. package/dist/packages/work/src/roles/shift.js +13 -1
  27. package/dist/packages/work/src/settings/settings.d.ts +60 -7
  28. package/dist/packages/work/src/settings/settings.js +69 -22
  29. package/dist/packages/work/src/shift/logretention.d.ts +253 -0
  30. package/dist/packages/work/src/shift/logretention.js +407 -0
  31. package/dist/packages/work/src/shift/logsink.d.ts +14 -0
  32. package/dist/packages/work/src/shift/logsink.js +98 -0
  33. package/dist/packages/work/src/shift/loop.d.ts +18 -1
  34. package/dist/packages/work/src/shift/loop.js +250 -12
  35. package/dist/packages/work/src/shift/protocol.d.ts +124 -1
  36. package/dist/packages/work/src/shift/protocol.js +14 -0
  37. package/dist/packages/work/src/shift/runtime.d.ts +14 -0
  38. package/dist/packages/work/src/shift/runtime.js +229 -6
  39. package/dist/packages/work/src/shift/server.d.ts +13 -0
  40. package/dist/packages/work/src/shift/server.js +61 -36
  41. package/dist/packages/work/src/shift/spawn.d.ts +78 -5
  42. package/dist/packages/work/src/shift/spawn.js +158 -12
  43. package/dist/packages/work/src/shift/state.d.ts +25 -0
  44. package/dist/packages/work/src/shift/state.js +29 -5
  45. package/dist/packages/work/src/shift/truncate.d.ts +35 -0
  46. package/dist/packages/work/src/shift/truncate.js +73 -0
  47. package/dist/packages/work/src/submit-proof.d.ts +31 -6
  48. package/dist/packages/work/src/submit-proof.js +33 -7
  49. package/dist/packages/work/src/submit-value.d.ts +48 -0
  50. package/dist/packages/work/src/submit-value.js +118 -0
  51. package/dist/packages/work/src/usage.d.ts +1 -1
  52. package/dist/packages/work/src/usage.js +11 -0
  53. package/dist/src/bundle/runtime.d.ts +1 -1
  54. package/dist/src/bundle/runtime.js +9 -0
  55. package/dist/src/capabilities.d.ts +93 -0
  56. package/dist/src/capabilities.js +101 -0
  57. package/dist/src/cli.js +37 -11
  58. package/dist/src/crypto/records.d.ts +3 -0
  59. package/dist/src/crypto/records.js +11 -0
  60. package/dist/src/defs.js +192 -4
  61. package/dist/src/engine.d.ts +112 -3
  62. package/dist/src/engine.js +224 -28
  63. package/dist/src/hub.d.ts +27 -11
  64. package/dist/src/hub.js +24 -18
  65. package/dist/src/index.d.ts +3 -1
  66. package/dist/src/index.js +4 -1
  67. package/dist/src/mcp/serve.js +11 -4
  68. package/dist/src/model.d.ts +36 -0
  69. package/dist/src/model.js +46 -0
  70. package/dist/src/schemas/index.d.ts +17 -0
  71. package/dist/src/schemas/order.v1.schema.json +17 -3
  72. package/dist/src/store.d.ts +33 -1
  73. package/dist/src/store.js +57 -4
  74. package/dist/src/types.d.ts +102 -2
  75. package/docs/agent-runner.md +26 -1
  76. package/docs/authoring.md +7 -0
  77. package/docs/bundles.md +103 -3
  78. package/docs/cli.md +127 -9
  79. package/docs/crypto.md +23 -7
  80. package/docs/shift-logs.md +642 -0
  81. package/docs/wire-contracts.md +34 -19
  82. package/package.json +1 -1
  83. package/plugins/claude-code/plugin/.claude-plugin/plugin.json +1 -1
  84. package/plugins/claude-code/plugin/.mcp.json +1 -1
  85. package/plugins/codex/plugins/owenloop/.codex-plugin/plugin.json +1 -1
  86. package/plugins/codex/plugins/owenloop/.mcp.json +1 -1
  87. package/dist/packages/work/src/agent/model-policy.d.ts +0 -49
  88. package/dist/packages/work/src/agent/model-policy.js +0 -138
@@ -10,9 +10,10 @@
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, isGreen, judgeNameOf, maintainDecisions, pendingOwed, plainConsumes, requiredInputs, workflowStatus, } from "./model.js";
13
+ import { collectionStem, computeFingerprint, eligibleFirings, fingerprintMatches, groupBlockingWinner, isEscalated, isGreen, judgeNameOf, maintainDecisions, pendingOwed, plainConsumes, rejectionEpisode, requiredInputs, workflowStatus, } from "./model.js";
14
14
  import { summarizeIssues, validateValue } from "./schema.js";
15
15
  import { hashDef } from "./defs.js";
16
+ import { claimMatches, composeCapabilities } from "./capabilities.js";
16
17
  import { localMidnightMs, nowMs, randId } from "./util.js";
17
18
  import { createDefInstructionSource, OrderResolver } from "./order-resolver.js";
18
19
  const DEFAULT_REAP_TTL_MS = 2 * 60 * 60 * 1000; // 2h
@@ -25,6 +26,8 @@ const DEFAULT_REAP_TTL_MS = 2 * 60 * 60 * 1000; // 2h
25
26
  * `maintainCalls` (spawn-time refusal) and `tickInternal` (descent guard).
26
27
  */
27
28
  const DEFAULT_MAX_CALL_DEPTH = 64;
29
+ /** The artifact-history `action` written when an escalation promotes an offer. */
30
+ const ESCALATION_ACTION = 'escalated';
28
31
  /**
29
32
  * F2: a typed refusal for a produced-value/input-value schema mismatch, thrown
30
33
  * by `createInstance` (seed provide) and `provideInput`. Distinct from a bare
@@ -123,6 +126,27 @@ function callsPinViolation(parentDef, childDef, target) {
123
126
  }
124
127
  return undefined;
125
128
  }
129
+ /**
130
+ * Thrown by `createInstance` when the requested modifier is not in the def's
131
+ * declared `modifiers` set (including the case of a def that declares none).
132
+ * Its own class so the hub can map it to a 400 instead of an opaque 500 —
133
+ * this is a caller mistake, not an engine fault.
134
+ */
135
+ export class ModifierRefusalError extends Error {
136
+ defName;
137
+ modifier;
138
+ /** The def's declared modifier set — empty when the def declares none. */
139
+ declared;
140
+ constructor(defName, modifier, declared) {
141
+ super(declared.length === 0
142
+ ? `workflow '${defName}' declares no modifiers:, so it cannot be started with modifier '${modifier}'`
143
+ : `modifier '${modifier}' is not declared by workflow '${defName}' (declared: ${declared.join(', ')})`);
144
+ this.name = 'ModifierRefusalError';
145
+ this.defName = defName;
146
+ this.modifier = modifier;
147
+ this.declared = declared;
148
+ }
149
+ }
126
150
  export class Engine {
127
151
  store;
128
152
  resolveDef;
@@ -195,6 +219,17 @@ export class Engine {
195
219
  wfData.title = opts.title;
196
220
  if (opts.params !== undefined)
197
221
  wfData.params = opts.params;
222
+ // Validated against the SNAPSHOT being pinned on this same row, not
223
+ // against a live re-resolution — the modifier and the vocabulary that
224
+ // legitimizes it are stamped together and stay consistent for the life of
225
+ // the instance, even if the def is republished with a different set.
226
+ if (opts.modifier !== undefined) {
227
+ const declared = def.modifiers ?? [];
228
+ if (!declared.includes(opts.modifier)) {
229
+ throw new ModifierRefusalError(defName, opts.modifier, declared);
230
+ }
231
+ wfData.modifier = opts.modifier;
232
+ }
198
233
  this.store.insertWorkflow(id, wfData, opts.producedBy);
199
234
  for (const input of def.inputs) {
200
235
  const provided = opts.provide?.[input.name];
@@ -949,7 +984,9 @@ export class Engine {
949
984
  * only this instance's own orders. See `TickResult` for the fold semantics.
950
985
  */
951
986
  tick(workflow, opts = {}) {
952
- return this.tickInternal(workflow, opts.now ?? nowMs(), opts.deep ?? true, opts.capabilities ?? [], new Set(), 0);
987
+ // `capabilities` is passed through AS GIVEN — an omitted filter (undefined)
988
+ // and an empty list are different claims. See `claimMatches`.
989
+ return this.tickInternal(workflow, opts.now ?? nowMs(), opts.deep ?? true, opts.capabilities, new Set(), 0, undefined, opts.matchModes ?? {});
953
990
  }
954
991
  /**
955
992
  * The recursive tick worker. Runs this instance's own maintain → reap →
@@ -990,7 +1027,7 @@ export class Engine {
990
1027
  * edge it hangs from. The guard is silent (no debt/reasons/events), mirroring
991
1028
  * the abort discipline of `publishCallsGreen`/`provisionCallsChild`.
992
1029
  */
993
- tickInternal(workflow, now, deep, capabilities, visited, depth, parentEdge) {
1030
+ tickInternal(workflow, now, deep, capabilities, visited, depth, parentEdge, matchModes = {}) {
994
1031
  if (depth > this.maxCallDepth) {
995
1032
  throw new Error(`calls depth limit exceeded (maxCallDepth=${this.maxCallDepth}) ticking '${workflow}': `
996
1033
  + `a calls: composition is deeper than the bound, which usually means a calls: cycle `
@@ -999,7 +1036,10 @@ export class Engine {
999
1036
  if (visited.has(workflow))
1000
1037
  return { workflow, orders: [], reaped: 0, deferred: [] };
1001
1038
  visited.add(workflow);
1002
- const def = this.defFor(workflow);
1039
+ // ONE run-record read per frame yields both the pinned def and the run's
1040
+ // routing modifier. Each frame reads its OWN instance, so a calls: child is
1041
+ // composed against the child's modifier, never the parent's.
1042
+ const { def, modifier } = this.instanceFor(workflow);
1003
1043
  // M2B: maintain calls: child instances before the normal tick/reap/claim cycle.
1004
1044
  this.maintainCalls(workflow, def, now);
1005
1045
  // B1: set inside the frame tx when the parent↔child consistency guard fires;
@@ -1036,11 +1076,11 @@ export class Engine {
1036
1076
  // Compute time facts for idle eligibility (clock-read boundary).
1037
1077
  const timeFacts = this.computeTimeFacts(def, workflow, arts, now);
1038
1078
  const firings = eligibleFirings(def, arts, timeFacts);
1039
- const { selected, deferred } = this.applySchedule(workflow, def, firings, now, capabilities);
1079
+ const { selected, deferred } = this.applySchedule(workflow, def, firings, now, arts, capabilities, modifier, matchModes);
1040
1080
  const orders = [];
1041
1081
  const allDeferred = [...deferred];
1042
1082
  for (const f of selected) {
1043
- const claimed = this.claim(workflow, def, f, arts, now);
1083
+ const claimed = this.claim(workflow, def, f, arts, now, modifier);
1044
1084
  if (claimed === 'in-flight') {
1045
1085
  const d = { step: f.step, key: f.key, inputs: f.inputs, outputs: f.outputs, reason: 'in-flight' };
1046
1086
  if (f.index !== undefined)
@@ -1075,7 +1115,7 @@ export class Engine {
1075
1115
  parentWf: workflow,
1076
1116
  step,
1077
1117
  callsStem: step.produces[0].stem,
1078
- });
1118
+ }, matchModes);
1079
1119
  // orders: flatten; each Order already carries its own `workflow`.
1080
1120
  result.orders.push(...cr.orders);
1081
1121
  // deferred: stamp child-originated entries with the child id, preserving
@@ -1145,13 +1185,25 @@ export class Engine {
1145
1185
  }
1146
1186
  /**
1147
1187
  * Per-step cadence + daily budget + parallel cap over the eligible firings.
1148
- * A2: `capabilities` is the tick caller's optional claim filter — when non-empty, a
1149
- * step whose own `capabilities` are also non-empty is only schedulable when the two
1150
- * intersect; a disjoint step's firings are deferred as `'capability-mismatch'`.
1188
+ *
1189
+ * A2: `capabilities` is the tick caller's claim filter, matched against the
1190
+ * step's OFFERED capabilities — the authored list composed with the modifier
1191
+ * this firing will actually be offered under (`wise` + `deep` → `wise:deep`),
1192
+ * which is the same list the order will carry. `claimMatches` owns the rule;
1193
+ * see it for the four cases (no filter presented, capability-silent step,
1194
+ * empty caller list, both non-empty) and for what `matchModes` changes.
1195
+ * A firing this caller may not claim is deferred as `'capability-mismatch'`.
1151
1196
  * Filtering here (before cadence/budget) means a mismatched firing never
1152
1197
  * consumes the caller's slots and never perturbs cadence math.
1198
+ *
1199
+ * The filter is per FIRING, not per step, because §7 escalation is per firing:
1200
+ * on a map step one element may have escalated to `build:deep` while its
1201
+ * siblings are still offered at `build:standard`, and a crew bound to only one
1202
+ * of those must be judged against the compound its own firing carries. With no
1203
+ * escalation authored every firing of a step composes identically, so this
1204
+ * behaves exactly as a per-step filter would.
1153
1205
  */
1154
- applySchedule(workflow, def, firings, now, capabilities) {
1206
+ applySchedule(workflow, def, firings, now, arts, capabilities, modifier, matchModes) {
1155
1207
  const midnight = localMidnightMs(now);
1156
1208
  const selected = [];
1157
1209
  const deferred = [];
@@ -1162,18 +1214,23 @@ export class Engine {
1162
1214
  deferred.push(d);
1163
1215
  };
1164
1216
  for (const step of def.steps) {
1165
- const stepFirings = firings.filter((f) => f.step === step.name);
1166
- if (stepFirings.length === 0)
1217
+ const all = firings.filter((f) => f.step === step.name);
1218
+ if (all.length === 0)
1167
1219
  continue;
1168
- // A2: caller capability filter vs. step capabilities. Both non-empty and disjoint →
1169
- // this caller must not claim the step; defer every firing and skip it
1170
- // before it touches cadence/budget/slot math.
1171
- if (capabilities.length > 0 && step.capabilities && step.capabilities.length > 0 &&
1172
- !step.capabilities.some((l) => capabilities.includes(l))) {
1173
- for (const f of stepFirings)
1220
+ // A2: caller capability filter vs. this firing's COMPOSED offer. Composed
1221
+ // here, not authored, so a caller bound to `wise:deep` is judged against
1222
+ // what the order will actually carry — including when `deep` came from the
1223
+ // escalation rule rather than the run.
1224
+ const stepFirings = [];
1225
+ for (const f of all) {
1226
+ const offered = composeCapabilities(step.capabilities, this.routingFor(step, f, arts, modifier).modifier);
1227
+ if (claimMatches(offered, capabilities, matchModes))
1228
+ stepFirings.push(f);
1229
+ else
1174
1230
  defer(f, 'capability-mismatch');
1175
- continue;
1176
1231
  }
1232
+ if (stepFirings.length === 0)
1233
+ continue;
1177
1234
  const latest = this.store.latestRun(workflow, step.name);
1178
1235
  if (latest && now - latest.createdAt < step.cadenceSecs * 1000) {
1179
1236
  for (const f of stepFirings)
@@ -1247,7 +1304,7 @@ export class Engine {
1247
1304
  return this.staleness(task, now, ttl, maxLease) === 'fresh';
1248
1305
  }
1249
1306
  /** Claim a firing's lease via CAS, snapshot the fingerprint, open a run. */
1250
- claim(workflow, def, f, arts, now) {
1307
+ claim(workflow, def, f, arts, now, modifier) {
1251
1308
  const existing = this.store.getTask(workflow, f.step, f.key);
1252
1309
  if (existing && existing.status === 'claimed') {
1253
1310
  const run = existing.run ? this.store.getRun(existing.run) : undefined;
@@ -1270,9 +1327,21 @@ export class Engine {
1270
1327
  // CONFLICT DO UPDATE, no history table), so the issued order is unrecoverable
1271
1328
  // later unless captured here; this persisted packet is the replay/eval/paper
1272
1329
  // trail record (buildOrder is deterministic modulo run id).
1273
- const order = this.buildOrder(def, workflow, runId, f, arts, fp);
1330
+ // §7: the modifier THIS offer composes with — the run's, or the step's
1331
+ // escalation target. Recomputed here rather than passed down from
1332
+ // `applySchedule` so the offer and the filter read the same function on the
1333
+ // same in-tx `arts` snapshot; nothing between them can move.
1334
+ const routing = this.routingFor(this.step(def, f.step), f, arts, modifier);
1335
+ const order = this.buildOrder(def, workflow, runId, f, arts, fp, routing);
1274
1336
  if (typeof order === 'object' && 'deferred' in order)
1275
1337
  return order;
1338
+ // One history record per rejection episode. Written HERE, not in
1339
+ // `buildOrder` (which is store-pure) and not on the deferred path (an offer
1340
+ // that never became an order promoted nothing). Idempotence is the store's:
1341
+ // the row id is derived from the episode, so the recomputation this rule
1342
+ // performs on every subsequent offer of the same episode inserts nothing.
1343
+ if (routing.escalation)
1344
+ this.recordEscalation(workflow, f, routing.escalation, now);
1276
1345
  // Stamp the run with the tick's clock so cadence/budget compare on one clock.
1277
1346
  this.store.insertRun(runId, { workflow, step: f.step, key: f.key, fingerprint: fp, order, ...(f.cause ? { cause: f.cause } : {}) }, now);
1278
1347
  this.store.putTask({
@@ -1297,7 +1366,7 @@ export class Engine {
1297
1366
  * snapshot is registered under the digest (a side effect of `digestOf`),
1298
1367
  * so the order stays resolvable after the live definition map changes.
1299
1368
  */
1300
- buildOrder(def, workflow, runId, f, arts, consumedFingerprint) {
1369
+ buildOrder(def, workflow, runId, f, arts, consumedFingerprint, routing = {}) {
1301
1370
  const step = this.step(def, f.step);
1302
1371
  const consumes = {};
1303
1372
  for (const p of f.inputs) {
@@ -1359,7 +1428,17 @@ export class Engine {
1359
1428
  const a = arts.get(p);
1360
1429
  return {
1361
1430
  path: p,
1362
- version: a?.version ?? 0,
1431
+ // The TARGET version this claim's next successful producer commit will
1432
+ // land, not the currently-committed one: `green()` writes
1433
+ // `art.version + 1`, so that is the version a consumer will later see
1434
+ // and check a submission proof against. Issued by the engine inside the
1435
+ // claim transaction and persisted with the immutable order, so every
1436
+ // retry of the same claim reads the same target. Refusal paths that
1437
+ // leave the run open (schema-reject) do NOT bump the artifact, so the
1438
+ // target stays correct across in-claim retries; a path that does commit
1439
+ // closes the run, and a stale target then fails the consumer's version
1440
+ // check — a refusal, never an admitted unverified value.
1441
+ version: (a?.version ?? 0) + 1,
1363
1442
  judgmentRejects: a?.judgmentRejects ?? 0,
1364
1443
  schemaRejects: a?.schemaRejects ?? 0,
1365
1444
  reasons: a?.reasons ?? [],
@@ -1380,6 +1459,22 @@ export class Engine {
1380
1459
  };
1381
1460
  if (f.index !== undefined)
1382
1461
  order.index = f.index;
1462
+ // The routing snapshot of THIS offer. `capabilities` is the composed list —
1463
+ // absent on a capability-silent step, since there is nothing to compose
1464
+ // onto. `modifier` is stamped whenever the offer carries one, even for a
1465
+ // capability-silent step, so the brief can surface the grade of service
1466
+ // regardless of how the step routes; on an escalated offer it is the
1467
+ // escalation target, and `escalated` marks it as such so the hub does not
1468
+ // have to diff it against the run record. A claimed order is never
1469
+ // recomposed: composition happens per offer, and this record is what the
1470
+ // shift resolved against.
1471
+ const offered = composeCapabilities(step.capabilities, routing.modifier);
1472
+ if (offered.length > 0)
1473
+ order.capabilities = offered;
1474
+ if (routing.modifier !== undefined)
1475
+ order.modifier = routing.modifier;
1476
+ if (routing.escalation !== undefined)
1477
+ order.escalated = true;
1383
1478
  if (step.model !== undefined)
1384
1479
  order.model = step.model;
1385
1480
  if (step.executor !== undefined)
@@ -2622,7 +2717,16 @@ export class Engine {
2622
2717
  }
2623
2718
  return { workflow: childWf, def: childDef.name, done: cs.done, stalled, debts: cs.debts.length };
2624
2719
  }
2625
- defFor(workflow) {
2720
+ /**
2721
+ * The two per-instance facts a tick needs, from ONE run-record read: the def
2722
+ * this instance is pinned to, and the routing modifier it carries.
2723
+ *
2724
+ * Offer-time composition needs the modifier inside the claim path, where the
2725
+ * run record was not previously in scope. Reading it here — in the same
2726
+ * `getWorkflow` the def resolution already performs, once per tick frame —
2727
+ * keeps that cost at zero extra reads rather than one per claim.
2728
+ */
2729
+ instanceFor(workflow) {
2626
2730
  const wf = this.store.getWorkflow(workflow);
2627
2731
  if (!wf)
2628
2732
  throw new Error(`no such workflow instance: ${workflow}`);
@@ -2630,9 +2734,101 @@ export class Engine {
2630
2734
  // Rows created before this feature shipped have no snapshot — fall back
2631
2735
  // to today's name-resolution, unchanged. This is the compatibility path,
2632
2736
  // not an error: an un-pinned instance behaves exactly as it always has.
2633
- if (wf.defSnapshot !== undefined)
2634
- return wf.defSnapshot;
2635
- return this.resolveDef(wf.def);
2737
+ const def = wf.defSnapshot !== undefined ? wf.defSnapshot : this.resolveDef(wf.def);
2738
+ return wf.modifier !== undefined ? { def, modifier: wf.modifier } : { def };
2739
+ }
2740
+ defFor(workflow) {
2741
+ return this.instanceFor(workflow).def;
2742
+ }
2743
+ /**
2744
+ * §7: the modifier ONE offer of ONE firing composes with — the run's, or the
2745
+ * step's escalation target when the escalation rule has tripped.
2746
+ *
2747
+ * Derived, never stored. Every offer re-evaluates it from the artifact
2748
+ * counters, which is what makes the transition atomic (there is no separate
2749
+ * write that could half-apply), idempotent (recomputing it changes nothing),
2750
+ * and self-reversing (a human `retry` zeroes `judgmentRejects`, and the very
2751
+ * next offer composes with the run's modifier again).
2752
+ *
2753
+ * The trigger is per OUTPUT PATH: the firing escalates when any path it owes
2754
+ * has taken `escalation.after` judgment rejections. For a plain step that is
2755
+ * its single produce; for a map step each element firing escalates on its own
2756
+ * element's count, so one bad element does not promote the whole step.
2757
+ *
2758
+ * Three cases return the run's modifier untouched:
2759
+ * - the step authors no `escalation:` block — rejections run the normal
2760
+ * retry path at the same compound until the stall brake;
2761
+ * - no owed path has reached the threshold yet;
2762
+ * - the run's modifier ALREADY equals the escalation target — there is
2763
+ * nothing to promote, so no `escalated` flag and no history record. A
2764
+ * `deep` run whose builder escalates to `deep` is a no-op, not an event.
2765
+ *
2766
+ * `escalation` on the result is set ONLY in the case that actually changed
2767
+ * the routing; `claim` writes the history record from it.
2768
+ */
2769
+ routingFor(step, f, arts, runModifier) {
2770
+ const rule = step.escalation;
2771
+ if (rule === undefined || rule.modifier === runModifier) {
2772
+ return runModifier !== undefined ? { modifier: runModifier } : {};
2773
+ }
2774
+ // `f.outputs` order is the def's produce order, so the reported path is
2775
+ // deterministic when more than one output has crossed the threshold.
2776
+ const path = f.outputs.find((p) => isEscalated(arts.get(p), rule.after));
2777
+ if (path === undefined)
2778
+ return runModifier !== undefined ? { modifier: runModifier } : {};
2779
+ const art = arts.get(path);
2780
+ const escalation = {
2781
+ path,
2782
+ to: rule.modifier,
2783
+ after: rule.after,
2784
+ judgmentRejects: art?.judgmentRejects ?? 0,
2785
+ episode: rejectionEpisode(art),
2786
+ atVersion: art?.version ?? 0,
2787
+ };
2788
+ if (runModifier !== undefined)
2789
+ escalation.from = runModifier;
2790
+ return { modifier: rule.modifier, escalation };
2791
+ }
2792
+ /**
2793
+ * Write the ONE artifact-history record for an escalation promotion.
2794
+ *
2795
+ * `version: 0` on purpose. The promotion belongs to the artifact across a
2796
+ * whole rejection episode, not to any single produced version — the episode
2797
+ * spans every attempt from the crossing rejection to the human `retry` that
2798
+ * ends it, and those attempts each produce their own version. Anchoring the
2799
+ * record to a version would either mislabel it or (since the row id mixes in
2800
+ * the version) write one row per version, breaking the once-per-episode
2801
+ * guarantee. `getArtifactHistory` collects version-0 events in its
2802
+ * artifact-level `events` bucket, which is exactly where this belongs; the
2803
+ * version the promotion took effect at is in `metadata.atVersion`.
2804
+ *
2805
+ * The dedupe key is `(step, firing key, episode)`. Step and key are in it
2806
+ * because two different steps can owe the same path in different firings; the
2807
+ * episode ordinal is what makes a SECOND promotion, after a human `retry` and
2808
+ * three fresh rejections, a distinct row rather than a swallowed duplicate.
2809
+ */
2810
+ recordEscalation(workflow, f, e, now) {
2811
+ this.store.recordArtifactEvent({
2812
+ workflow,
2813
+ path: e.path,
2814
+ version: 0,
2815
+ action: ESCALATION_ACTION,
2816
+ actor: 'engine',
2817
+ dedupe: `${ESCALATION_ACTION}:${f.step}:${f.key}:${e.episode}`,
2818
+ timestamp: now,
2819
+ reason: `step '${f.step}' escalated to modifier '${e.to}' after ${e.judgmentRejects} judgment rejection(s)`
2820
+ + ` (threshold ${e.after})`,
2821
+ metadata: {
2822
+ step: f.step,
2823
+ key: f.key,
2824
+ to: e.to,
2825
+ after: e.after,
2826
+ judgmentRejects: e.judgmentRejects,
2827
+ episode: e.episode,
2828
+ atVersion: e.atVersion,
2829
+ ...(e.from !== undefined ? { from: e.from } : {}),
2830
+ },
2831
+ });
2636
2832
  }
2637
2833
  step(def, name) {
2638
2834
  const l = def.steps.find((x) => x.name === name);
package/dist/src/hub.d.ts CHANGED
@@ -687,28 +687,38 @@ export interface CapabilityRouteWire {
687
687
  /**
688
688
  * `POST /api/add_capability_route`'s 200 body, narrowed.
689
689
  *
690
- * NESTED exactly as the wire nests it: the row lives under `route`, while
691
- * `alreadyRouted` and `routedCrewCount` live at the BODY's top level. A flat
690
+ * THE FIELD NAMES ARE THE HUB'S, NOT THIS CLI'S. The hub verb
691
+ * (`hub-core/src/verbs/manage-capability-routes.ts`) returns `binding`,
692
+ * `alreadyBound` and `boundCrewCount`; it does NOT return `route`,
693
+ * `alreadyRouted` or `routedCrewCount`, which is what this narrower demanded
694
+ * until now — so `capability bind` failed against every live hub with
695
+ * `malformed success response — missing route`. Both repos migrated their
696
+ * routing vocabulary on the same day and disagreed on the payload names. The
697
+ * hub is the server of record, so the client mirrors it verbatim: an operator
698
+ * correlating stdout against the hub's audit log never has to translate.
699
+ *
700
+ * NESTED exactly as the wire nests it: the row lives under `binding`, while
701
+ * `alreadyBound` and `boundCrewCount` live at the BODY's top level. A flat
692
702
  * interface would blur where each field actually sits.
693
703
  *
694
- * - `alreadyRouted` — was this exact `(capability, crew)` pair already present? The add
704
+ * - `alreadyBound` — was this exact `(capability, crew)` pair already present? The add
695
705
  * is ADDITIVE and idempotent per pair, so a repeat is a 200 no-op, not an
696
- * error, and `route.createdBy`/`createdAt` then echo the ORIGINAL row.
697
- * - `routedCrewCount` — how many **LIVE** crews the capability binds AFTER the write. A
706
+ * error, and `binding.createdBy`/`createdAt` then echo the ORIGINAL row.
707
+ * - `boundCrewCount` — how many **LIVE** crews the capability binds AFTER the write. A
698
708
  * route whose crew row was deleted routes nothing and is not counted.
699
709
  */
700
710
  export interface CapabilityRouteAddedWire {
701
- route: CapabilityRouteWire;
702
- alreadyRouted: boolean;
703
- routedCrewCount: number;
711
+ binding: CapabilityRouteWire;
712
+ alreadyBound: boolean;
713
+ boundCrewCount: number;
704
714
  }
705
715
  /**
706
716
  * Narrow `POST /api/add_capability_route`'s 200 body
707
- * (`{ text, route, alreadyRouted, routedCrewCount }`). Throws on anything
717
+ * (`{ text, binding, alreadyBound, boundCrewCount }`). Throws on anything
708
718
  * malformed, naming the offending FIELD only — same discipline as
709
719
  * `asAgentIdentities`, so no body value is echoed.
710
720
  *
711
- * `route.crewName` is required to be a NON-NULL non-empty string here, on top
721
+ * `binding.crewName` is required to be a NON-NULL non-empty string here, on top
712
722
  * of `asCapabilityRouteRow`'s lenient check. That is not a contradiction: an add
713
723
  * resolves its crew BY NAME, so the crew is live by construction and a `null`
714
724
  * name in THIS response is genuinely malformed — whereas a `null` name in a
@@ -755,10 +765,16 @@ export declare function asCapabilityRouteRemoved(body: unknown): {
755
765
  remainingCrewIds: string[];
756
766
  };
757
767
  /**
758
- * Narrow `GET /api/capability_routes`'s 200 body (`{ text, routes: [...] }`) to a
768
+ * Narrow `GET /api/capability_routes`'s 200 body (`{ text, bindings: [...] }`) to a
759
769
  * typed array. An EMPTY array is valid — that is the "this org has no routes
760
770
  * yet" case, not an error.
761
771
  *
772
+ * THE ARRAY KEY IS `bindings`, WHICH IS THE HUB'S NAME — the endpoint PATH is
773
+ * `capability_routes` but its payload key is not. This narrower demanded
774
+ * `routes` until now, so `capability list` failed against every live hub with
775
+ * `malformed response — expected a \`routes\` array` even on a perfectly good
776
+ * 200. See `CapabilityRouteAddedWire` for why the client mirrors the hub.
777
+ *
762
778
  * Rows are plain `CapabilityRouteWire`, ONE per `(capability, crew)` pair ordered by
763
779
  * `capability, crew_id`, so a capability bound to many crews yields MANY rows — the array
764
780
  * is forwarded as-is and must never be collapsed into a per-capability map. A row
package/dist/src/hub.js CHANGED
@@ -968,7 +968,7 @@ export function asAgentIdentities(body) {
968
968
  * Validate the five common `CapabilityRouteWire` fields on one row. `prefix` is the
969
969
  * endpoint-qualified lead-in the caller wants (e.g.
970
970
  * `add_capability_route: malformed success response`) and `where` names the
971
- * offending position (`route`, or `routes[2]`) — a FIELD/INDEX name only,
971
+ * offending position (`binding`, or `bindings[2]`) — a FIELD/INDEX name only,
972
972
  * never a value.
973
973
  *
974
974
  * `crewName` is validated LENIENTLY here, unlike the other four fields: absent or
@@ -1008,11 +1008,11 @@ function asCapabilityRouteRow(entry, prefix, where) {
1008
1008
  }
1009
1009
  /**
1010
1010
  * Narrow `POST /api/add_capability_route`'s 200 body
1011
- * (`{ text, route, alreadyRouted, routedCrewCount }`). Throws on anything
1011
+ * (`{ text, binding, alreadyBound, boundCrewCount }`). Throws on anything
1012
1012
  * malformed, naming the offending FIELD only — same discipline as
1013
1013
  * `asAgentIdentities`, so no body value is echoed.
1014
1014
  *
1015
- * `route.crewName` is required to be a NON-NULL non-empty string here, on top
1015
+ * `binding.crewName` is required to be a NON-NULL non-empty string here, on top
1016
1016
  * of `asCapabilityRouteRow`'s lenient check. That is not a contradiction: an add
1017
1017
  * resolves its crew BY NAME, so the crew is live by construction and a `null`
1018
1018
  * name in THIS response is genuinely malformed — whereas a `null` name in a
@@ -1026,20 +1026,20 @@ export function asCapabilityRouteAdded(body) {
1026
1026
  throw new Error(`${prefix} — not an object`);
1027
1027
  }
1028
1028
  const b = body;
1029
- if (b.route === undefined) {
1030
- throw new Error(`${prefix} — missing route`);
1029
+ if (b.binding === undefined) {
1030
+ throw new Error(`${prefix} — missing binding`);
1031
1031
  }
1032
- const route = asCapabilityRouteRow(b.route, prefix, 'route');
1033
- if (route.crewName === null) {
1034
- throw new Error(`${prefix} — route missing non-empty string crewName`);
1032
+ const binding = asCapabilityRouteRow(b.binding, prefix, 'binding');
1033
+ if (binding.crewName === null) {
1034
+ throw new Error(`${prefix} — binding missing non-empty string crewName`);
1035
1035
  }
1036
- if (typeof b.alreadyRouted !== 'boolean') {
1037
- throw new Error(`${prefix} — missing boolean alreadyRouted`);
1036
+ if (typeof b.alreadyBound !== 'boolean') {
1037
+ throw new Error(`${prefix} — missing boolean alreadyBound`);
1038
1038
  }
1039
- if (typeof b.routedCrewCount !== 'number') {
1040
- throw new Error(`${prefix} — missing number routedCrewCount`);
1039
+ if (typeof b.boundCrewCount !== 'number') {
1040
+ throw new Error(`${prefix} — missing number boundCrewCount`);
1041
1041
  }
1042
- return { route, alreadyRouted: b.alreadyRouted, routedCrewCount: b.routedCrewCount };
1042
+ return { binding, alreadyBound: b.alreadyBound, boundCrewCount: b.boundCrewCount };
1043
1043
  }
1044
1044
  /**
1045
1045
  * Narrow `POST /api/remove_capability_route`'s 200 body
@@ -1103,21 +1103,27 @@ export function asCapabilityRouteRemoved(body) {
1103
1103
  return { capability: b.capability, crewId, removed: b.removed, remainingCrewIds };
1104
1104
  }
1105
1105
  /**
1106
- * Narrow `GET /api/capability_routes`'s 200 body (`{ text, routes: [...] }`) to a
1106
+ * Narrow `GET /api/capability_routes`'s 200 body (`{ text, bindings: [...] }`) to a
1107
1107
  * typed array. An EMPTY array is valid — that is the "this org has no routes
1108
1108
  * yet" case, not an error.
1109
1109
  *
1110
+ * THE ARRAY KEY IS `bindings`, WHICH IS THE HUB'S NAME — the endpoint PATH is
1111
+ * `capability_routes` but its payload key is not. This narrower demanded
1112
+ * `routes` until now, so `capability list` failed against every live hub with
1113
+ * `malformed response — expected a \`routes\` array` even on a perfectly good
1114
+ * 200. See `CapabilityRouteAddedWire` for why the client mirrors the hub.
1115
+ *
1110
1116
  * Rows are plain `CapabilityRouteWire`, ONE per `(capability, crew)` pair ordered by
1111
1117
  * `capability, crew_id`, so a capability bound to many crews yields MANY rows — the array
1112
1118
  * is forwarded as-is and must never be collapsed into a per-capability map. A row
1113
1119
  * whose `crewName` is `null` is a dangling route and is kept, not dropped.
1114
1120
  */
1115
1121
  export function asCapabilityRoutes(body) {
1116
- if (typeof body !== 'object' || body === null || !Array.isArray(body.routes)) {
1117
- throw new Error('capability_routes: malformed response — expected a `routes` array');
1122
+ if (typeof body !== 'object' || body === null || !Array.isArray(body.bindings)) {
1123
+ throw new Error('capability_routes: malformed response — expected a `bindings` array');
1118
1124
  }
1119
- const list = body.routes;
1120
- return list.map((entry, i) => asCapabilityRouteRow(entry, 'capability_routes: malformed response', `routes[${i}]`));
1125
+ const list = body.bindings;
1126
+ return list.map((entry, i) => asCapabilityRouteRow(entry, 'capability_routes: malformed response', `bindings[${i}]`));
1121
1127
  }
1122
1128
  /**
1123
1129
  * The `orphan:` prefix the hub uses to name its reserved orphan crew
@@ -11,8 +11,10 @@
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 } from './engine.ts';
14
+ export { CallsPinError, Engine, 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
+ export { capabilityName, claimMatches, composeCapabilities, DEFAULT_MATCH_MODE, MODIFIER_SEPARATOR, } from './capabilities.ts';
17
+ export type { MatchMode } from './capabilities.ts';
16
18
  export { createEngine } from './factory.ts';
17
19
  export type { CreateEngineOpts, CreatedEngine } from './factory.ts';
18
20
  export { createDefInstructionSource, defInstructionDigest, OrderResolver, substituteOrderVars, UnknownDefDigestError, UnknownInstructionError, } from './order-resolver.ts';
package/dist/src/index.js CHANGED
@@ -11,7 +11,10 @@
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 } from "./engine.js";
14
+ export { CallsPinError, Engine, ModifierRefusalError } from "./engine.js";
15
+ // Routing capabilities: offer-time composition and the claim-side match. The
16
+ // hub imports these to reason about the same compounds the engine composes.
17
+ export { capabilityName, claimMatches, composeCapabilities, DEFAULT_MATCH_MODE, MODIFIER_SEPARATOR, } from "./capabilities.js";
15
18
  export { createEngine } from "./factory.js";
16
19
  export { createDefInstructionSource, defInstructionDigest, OrderResolver, substituteOrderVars, UnknownDefDigestError, UnknownInstructionError, } from "./order-resolver.js";
17
20
  export { Store, openStore, StoreVersionError } from "./store.js";
@@ -299,14 +299,21 @@ function submissionFingerprint(order, deps) {
299
299
  }
300
300
  /**
301
301
  * Resolve a signed submit version from authoritative immutable metadata only.
302
- * Judge claims name the already-submitted version in their fingerprint. Producer
303
- * claims do not name a retry-safe target: `owes[].version` is claim-time state and
304
- * can be stale after a refinement, lost response, unsigned commit, or restart.
302
+ * Judge claims name the already-submitted version in their fingerprint; the
303
+ * judge-approve commit does not increment it. Producer claims name
304
+ * `owes[].version`, the target the engine issued for this owed output inside
305
+ * the claim transaction — the version the next successful commit lands, and
306
+ * the version the consumer checks the proof against. See
307
+ * `outputVersionForSubmission` in packages/work/src/submit-proof.ts for the
308
+ * retry-safety argument; this is the same rule on the local MCP path.
305
309
  */
306
310
  function outputVersion(order, path) {
307
311
  if (order.judge === path)
308
312
  return order.consumedFingerprint?.[path];
309
- return undefined;
313
+ const target = order.owes.find((owed) => owed.path === path)?.version;
314
+ // Only a positive integer is a target this protocol issued; see
315
+ // outputVersionForSubmission for why 0 submits unsigned instead.
316
+ return typeof target === 'number' && Number.isInteger(target) && target > 0 ? target : undefined;
310
317
  }
311
318
  function warnMcpUnsigned(deps, reason) {
312
319
  if (warnedMcpUnsigned)
@@ -134,6 +134,42 @@ export declare function isSchemaStalled(a: ArtifactData | undefined, cap: number
134
134
  * entry, which clears the held condition automatically.
135
135
  */
136
136
  export declare function isHeld(a: ArtifactData | undefined): boolean;
137
+ /**
138
+ * §7 escalation trigger: has this artifact been judgment-rejected at least
139
+ * `after` times in the CURRENT rejection episode?
140
+ *
141
+ * Reads `judgmentRejects`, the same counter `isStalled` reads and the same one
142
+ * `retry` zeroes — so "current episode" needs no separate bookkeeping: a human
143
+ * `retry` resets the counter and the trigger goes false again by itself.
144
+ *
145
+ * The state this tests is derived, never stored. Every offer of the step
146
+ * re-evaluates it, so the transition cannot half-apply, cannot be lost, and
147
+ * cannot be applied twice to one offer. It is deliberately independent of
148
+ * `acceptance`: unlike `isStalled` (which describes a FROZEN artifact and must
149
+ * only be true while it is sitting rejected), this describes the routing of the
150
+ * NEXT offer, and by the time that offer is built the artifact has been re-armed
151
+ * to `owed`.
152
+ *
153
+ * `after` comes from the step's authored `escalation.after`. Install validation
154
+ * (`defs.ts` R2) guarantees `after < effectiveMaxAttempts`, so there is always a
155
+ * window between "escalate" and "freeze" in which the escalated attempt runs.
156
+ */
157
+ export declare function isEscalated(a: ArtifactData | undefined, after: number): boolean;
158
+ /**
159
+ * Which rejection episode this artifact is in: 0 before any human `retry`, 1
160
+ * after the first, and so on.
161
+ *
162
+ * `retry` is the only lever that ends an episode (it zeroes `judgmentRejects`),
163
+ * and it appends a `'retry'` entry to the append-only reason thread — so
164
+ * counting those entries yields a monotonic episode ordinal with no new column
165
+ * and no new state to keep consistent.
166
+ *
167
+ * Used to key an escalation's ONE history record per episode. It is not used to
168
+ * decide anything: the trigger above reads the counter, which is authoritative.
169
+ * If the thread and the counter ever disagreed, the ordinal would only mislabel
170
+ * a history row, never change routing.
171
+ */
172
+ export declare function rejectionEpisode(a: ArtifactData | undefined): number;
137
173
  /** Bare elements (no further suffix) of a collection stem, in index order. */
138
174
  export declare function members(arts: ArtifactMap, stem: string): ArtifactData[];
139
175
  /**