owenloop 0.5.8 → 0.5.9

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 (87) hide show
  1. package/CHANGELOG.md +25 -0
  2. package/README.md +4 -2
  3. package/dist/packages/work/src/agent/loop.d.ts +23 -8
  4. package/dist/packages/work/src/agent/loop.js +48 -6
  5. package/dist/packages/work/src/consumed-verifier.js +6 -17
  6. package/dist/packages/work/src/exec/loop.d.ts +1 -1
  7. package/dist/packages/work/src/exec/loop.js +181 -32
  8. package/dist/packages/work/src/exec/receipt.d.ts +7 -7
  9. package/dist/packages/work/src/exec/receipt.js +6 -6
  10. package/dist/packages/work/src/harness/claude.js +100 -0
  11. package/dist/packages/work/src/hub/client.d.ts +19 -4
  12. package/dist/packages/work/src/hub/client.js +7 -3
  13. package/dist/packages/work/src/hub/types.d.ts +84 -0
  14. package/dist/packages/work/src/main.js +1 -0
  15. package/dist/packages/work/src/roles/agent-run.js +19 -22
  16. package/dist/packages/work/src/roles/exec.js +2 -0
  17. package/dist/packages/work/src/roles/settings.js +2 -0
  18. package/dist/packages/work/src/roles/shift.js +14 -2
  19. package/dist/packages/work/src/roles/util.d.ts +1 -0
  20. package/dist/packages/work/src/roles/util.js +10 -0
  21. package/dist/packages/work/src/settings/hub-roster-cache.d.ts +68 -0
  22. package/dist/packages/work/src/settings/hub-roster-cache.js +370 -0
  23. package/dist/packages/work/src/settings/roster.d.ts +84 -0
  24. package/dist/packages/work/src/settings/roster.js +364 -5
  25. package/dist/packages/work/src/settings/serving.d.ts +17 -0
  26. package/dist/packages/work/src/settings/serving.js +79 -0
  27. package/dist/packages/work/src/settings/settings.d.ts +14 -1
  28. package/dist/packages/work/src/settings/settings.js +14 -0
  29. package/dist/packages/work/src/shift/loop.d.ts +108 -5
  30. package/dist/packages/work/src/shift/loop.js +299 -51
  31. package/dist/packages/work/src/shift/protocol.d.ts +7 -5
  32. package/dist/packages/work/src/shift/runtime.d.ts +15 -0
  33. package/dist/packages/work/src/shift/runtime.js +94 -4
  34. package/dist/packages/work/src/shift/server.js +2 -0
  35. package/dist/packages/work/src/shift/spawn.d.ts +17 -2
  36. package/dist/packages/work/src/shift/spawn.js +16 -13
  37. package/dist/packages/work/src/shift/state.d.ts +29 -2
  38. package/dist/packages/work/src/shift/state.js +45 -15
  39. package/dist/packages/work/src/usage.d.ts +1 -1
  40. package/dist/packages/work/src/usage.js +7 -1
  41. package/dist/packages/work/src/util/modifier-init.d.ts +7 -0
  42. package/dist/packages/work/src/util/modifier-init.js +73 -0
  43. package/dist/src/bundle/tar.d.ts +9 -4
  44. package/dist/src/bundle/tar.js +9 -4
  45. package/dist/src/capabilities.d.ts +6 -0
  46. package/dist/src/cli.d.ts +14 -1
  47. package/dist/src/cli.js +687 -75
  48. package/dist/src/config-dir.d.ts +1 -1
  49. package/dist/src/config-dir.js +1 -1
  50. package/dist/src/crypto/index.d.ts +1 -1
  51. package/dist/src/crypto/index.js +1 -1
  52. package/dist/src/crypto/org-root.d.ts +30 -12
  53. package/dist/src/crypto/org-root.js +162 -14
  54. package/dist/src/crypto/records.d.ts +2 -0
  55. package/dist/src/crypto/records.js +2 -0
  56. package/dist/src/defs.d.ts +6 -1
  57. package/dist/src/defs.js +203 -8
  58. package/dist/src/engine.d.ts +42 -7
  59. package/dist/src/engine.js +158 -16
  60. package/dist/src/index.d.ts +4 -4
  61. package/dist/src/index.js +2 -2
  62. package/dist/src/mcp/serve.d.ts +22 -0
  63. package/dist/src/mcp/serve.js +88 -8
  64. package/dist/src/model.d.ts +2 -0
  65. package/dist/src/model.js +32 -25
  66. package/dist/src/order-resolver.d.ts +1 -0
  67. package/dist/src/order-resolver.js +8 -1
  68. package/dist/src/schemas/index.d.ts +11 -0
  69. package/dist/src/schemas/order.v1.schema.json +7 -1
  70. package/dist/src/store.d.ts +5 -0
  71. package/dist/src/store.js +43 -8
  72. package/dist/src/types.d.ts +40 -3
  73. package/docs/authoring.md +90 -2
  74. package/docs/bundles.md +26 -2
  75. package/docs/cli.md +170 -28
  76. package/docs/crypto.md +19 -3
  77. package/docs/design.md +70 -1
  78. package/docs/routing.md +189 -34
  79. package/docs/shift-logs.md +20 -9
  80. package/docs/wire-contracts.md +50 -7
  81. package/examples/workflows/delivery.yaml +31 -14
  82. package/examples/workflows/ship.yaml +10 -2
  83. package/package.json +1 -1
  84. package/plugins/claude-code/plugin/.claude-plugin/plugin.json +1 -1
  85. package/plugins/claude-code/plugin/.mcp.json +1 -1
  86. package/plugins/codex/plugins/owenloop/.codex-plugin/plugin.json +1 -1
  87. package/plugins/codex/plugins/owenloop/.mcp.json +1 -1
@@ -28,6 +28,7 @@ const DEFAULT_REAP_TTL_MS = 2 * 60 * 60 * 1000; // 2h
28
28
  const DEFAULT_MAX_CALL_DEPTH = 64;
29
29
  /** The artifact-history `action` written when an escalation promotes an offer. */
30
30
  const ESCALATION_ACTION = 'escalated';
31
+ const BIND_ACTION = 'bound';
31
32
  /**
32
33
  * F2: a typed refusal for a produced-value/input-value schema mismatch, thrown
33
34
  * by `createInstance` (seed provide) and `provideInput`. Distinct from a bare
@@ -221,8 +222,9 @@ export class Engine {
221
222
  wfData.params = opts.params;
222
223
  // Validated against the SNAPSHOT being pinned on this same row, not
223
224
  // 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.
225
+ // legitimizes it are stamped together. Later bound-artifact writes still
226
+ // validate against this pinned vocabulary, even if the def is republished
227
+ // with a different set.
226
228
  if (opts.modifier !== undefined) {
227
229
  const declared = def.modifiers ?? [];
228
230
  if (!declared.includes(opts.modifier)) {
@@ -986,7 +988,7 @@ export class Engine {
986
988
  tick(workflow, opts = {}) {
987
989
  // `capabilities` is passed through AS GIVEN — an omitted filter (undefined)
988
990
  // 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 ?? {}, opts.capabilityRewrites ?? {});
991
+ return this.tickInternal(workflow, opts.now ?? nowMs(), opts.deep ?? true, opts.capabilities, new Set(), 0, undefined, opts.matchModes ?? {}, opts.capabilityRewrites ?? {}, opts.crewStamps ?? {});
990
992
  }
991
993
  /**
992
994
  * The recursive tick worker. Runs this instance's own maintain → reap →
@@ -1027,7 +1029,7 @@ export class Engine {
1027
1029
  * edge it hangs from. The guard is silent (no debt/reasons/events), mirroring
1028
1030
  * the abort discipline of `publishCallsGreen`/`provisionCallsChild`.
1029
1031
  */
1030
- tickInternal(workflow, now, deep, capabilities, visited, depth, parentEdge, matchModes = {}, capabilityRewrites = {}) {
1032
+ tickInternal(workflow, now, deep, capabilities, visited, depth, parentEdge, matchModes = {}, capabilityRewrites = {}, crewStamps = {}) {
1031
1033
  if (depth > this.maxCallDepth) {
1032
1034
  throw new Error(`calls depth limit exceeded (maxCallDepth=${this.maxCallDepth}) ticking '${workflow}': `
1033
1035
  + `a calls: composition is deeper than the bound, which usually means a calls: cycle `
@@ -1080,7 +1082,7 @@ export class Engine {
1080
1082
  const orders = [];
1081
1083
  const allDeferred = [...deferred];
1082
1084
  for (const f of selected) {
1083
- const claimed = this.claim(workflow, def, f, arts, now, modifier, capabilityRewrites);
1085
+ const claimed = this.claim(workflow, def, f, arts, now, modifier, capabilityRewrites, crewStamps);
1084
1086
  if (claimed === 'in-flight') {
1085
1087
  const d = { step: f.step, key: f.key, inputs: f.inputs, outputs: f.outputs, reason: 'in-flight' };
1086
1088
  if (f.index !== undefined)
@@ -1115,7 +1117,7 @@ export class Engine {
1115
1117
  parentWf: workflow,
1116
1118
  step,
1117
1119
  callsStem: step.produces[0].stem,
1118
- }, matchModes, capabilityRewrites);
1120
+ }, matchModes, capabilityRewrites, crewStamps);
1119
1121
  // orders: flatten; each Order already carries its own `workflow`.
1120
1122
  result.orders.push(...cr.orders);
1121
1123
  // deferred: stamp child-originated entries with the child id, preserving
@@ -1307,7 +1309,7 @@ export class Engine {
1307
1309
  return this.staleness(task, now, ttl, maxLease) === 'fresh';
1308
1310
  }
1309
1311
  /** Claim a firing's lease via CAS, snapshot the fingerprint, open a run. */
1310
- claim(workflow, def, f, arts, now, modifier, capabilityRewrites = {}) {
1312
+ claim(workflow, def, f, arts, now, modifier, capabilityRewrites = {}, crewStamps = {}) {
1311
1313
  const existing = this.store.getTask(workflow, f.step, f.key);
1312
1314
  if (existing && existing.status === 'claimed') {
1313
1315
  const run = existing.run ? this.store.getRun(existing.run) : undefined;
@@ -1335,7 +1337,7 @@ export class Engine {
1335
1337
  // `applySchedule` so the offer and the filter read the same function on the
1336
1338
  // same in-tx `arts` snapshot; nothing between them can move.
1337
1339
  const routing = this.routingFor(this.step(def, f.step), f, arts, modifier);
1338
- const order = this.buildOrder(def, workflow, runId, f, arts, fp, routing, capabilityRewrites);
1340
+ const order = this.buildOrder(def, workflow, runId, f, arts, fp, routing, capabilityRewrites, crewStamps);
1339
1341
  if (typeof order === 'object' && 'deferred' in order)
1340
1342
  return order;
1341
1343
  // One history record per rejection episode. Written HERE, not in
@@ -1369,7 +1371,7 @@ export class Engine {
1369
1371
  * snapshot is registered under the digest (a side effect of `digestOf`),
1370
1372
  * so the order stays resolvable after the live definition map changes.
1371
1373
  */
1372
- buildOrder(def, workflow, runId, f, arts, consumedFingerprint, routing = {}, capabilityRewrites = {}) {
1374
+ buildOrder(def, workflow, runId, f, arts, consumedFingerprint, routing = {}, capabilityRewrites = {}, crewStamps = {}) {
1373
1375
  const step = this.step(def, f.step);
1374
1376
  const consumes = {};
1375
1377
  for (const p of f.inputs) {
@@ -1500,6 +1502,17 @@ export class Engine {
1500
1502
  const { offered, reroutedFrom } = applyCapabilityRewrites(composeCapabilities(step.capabilities, routing.modifier), capabilityRewrites);
1501
1503
  if (offered.length > 0)
1502
1504
  order.capabilities = offered;
1505
+ const crews = [];
1506
+ for (const capability of offered) {
1507
+ if (!Object.prototype.hasOwnProperty.call(crewStamps, capability))
1508
+ continue;
1509
+ for (const crew of crewStamps[capability] ?? []) {
1510
+ if (!crews.includes(crew))
1511
+ crews.push(crew);
1512
+ }
1513
+ }
1514
+ if (crews.length > 0)
1515
+ order.crews = crews;
1503
1516
  // Only when a rewrite actually fired. `reroutedFrom` is absent on every
1504
1517
  // ordinary offer, so its presence alone tells a reader the order is not
1505
1518
  // running on the capability its def asked for.
@@ -1535,6 +1548,101 @@ export class Engine {
1535
1548
  resolveOrder(order) {
1536
1549
  return this.resolver.resolveOrder(order);
1537
1550
  }
1551
+ /** Return the binding declaration that owns this artifact path, if any. */
1552
+ artifactBind(def, art) {
1553
+ const step = def.steps.find((candidate) => candidate.name === art.producer);
1554
+ if (step === undefined)
1555
+ return undefined;
1556
+ const element = parseElement(art.path);
1557
+ if (element !== null) {
1558
+ return step.produces.find((produce) => produce.kind === 'map'
1559
+ && produce.stem === element.stem
1560
+ && produce.suffix === element.suffix)?.bind;
1561
+ }
1562
+ return step.produces.find((produce) => produce.kind === 'singleton' && produce.stem === art.path)?.bind;
1563
+ }
1564
+ /** Resolve a declared dot-path of object keys against an accepted artifact value. */
1565
+ boundValue(path, bind, acceptedValue) {
1566
+ let current = acceptedValue;
1567
+ for (const key of bind.from.split('.')) {
1568
+ if (current === null ||
1569
+ typeof current !== 'object' ||
1570
+ Array.isArray(current) ||
1571
+ !Object.prototype.hasOwnProperty.call(current, key)) {
1572
+ throw new Error(`artifact '${path}' bind.from '${bind.from}' cannot be resolved from its accepted value`);
1573
+ }
1574
+ current = current[key];
1575
+ }
1576
+ return current;
1577
+ }
1578
+ /**
1579
+ * The bind-time and reject-time modifier gate: membership in the def's
1580
+ * declared `modifiers` set, and nothing else — byte for byte the rule the
1581
+ * start path applies in `createInstanceInTx`. One value cannot be legal to
1582
+ * start a run with and illegal to bind.
1583
+ *
1584
+ * `def` here is the PINNED snapshot, so the vocabulary checked is the one
1585
+ * stamped on this run, not a later republish.
1586
+ *
1587
+ * The SHAPE of a name is constrained where a name is authored:
1588
+ * `parseModifiers` in `src/defs.ts` refuses an empty name, a name containing
1589
+ * whitespace, a name containing `MODIFIER_SEPARATOR`, and a duplicate.
1590
+ * Re-testing shape here is what split the vocabulary in the first place — a
1591
+ * value the parser admitted and `start_run` accepted, refused at bind.
1592
+ */
1593
+ assertBoundModifier(def, value) {
1594
+ const declared = def.modifiers ?? [];
1595
+ if (typeof value !== 'string' || !declared.includes(value)) {
1596
+ const rendered = typeof value === 'string' ? value : JSON.stringify(value) ?? String(value);
1597
+ throw new ModifierRefusalError(def.name, rendered, declared);
1598
+ }
1599
+ }
1600
+ /** Validate extraction before an acceptance branch changes an artifact. */
1601
+ validateArtifactBind(def, art, acceptedValue) {
1602
+ const bind = this.artifactBind(def, art);
1603
+ if (bind === undefined)
1604
+ return;
1605
+ const value = this.boundValue(art.path, bind, acceptedValue);
1606
+ if (bind.to === 'modifier')
1607
+ this.assertBoundModifier(def, value);
1608
+ }
1609
+ /**
1610
+ * Persist a declared instance-routing write and its single artifact-level
1611
+ * audit event. Call only from an already-accepted branch inside its tx.
1612
+ */
1613
+ applyArtifactBind(workflow, def, art, acceptedValue, now) {
1614
+ const bind = this.artifactBind(def, art);
1615
+ if (bind === undefined)
1616
+ return;
1617
+ const value = this.boundValue(art.path, bind, acceptedValue);
1618
+ const routing = this.store.getWorkflow(workflow);
1619
+ if (routing === undefined)
1620
+ throw new Error(`cannot bind routing for unknown workflow '${workflow}'`);
1621
+ let prior;
1622
+ if (bind.to === 'modifier') {
1623
+ this.assertBoundModifier(def, value);
1624
+ prior = routing.modifier;
1625
+ this.store.setWorkflowRouting(workflow, { modifier: value });
1626
+ }
1627
+ else {
1628
+ const key = bind.to.slice('meta.'.length);
1629
+ prior = routing.meta?.[key];
1630
+ this.store.setWorkflowRouting(workflow, { meta: { [key]: value } });
1631
+ }
1632
+ this.store.recordArtifactEvent({
1633
+ workflow,
1634
+ path: art.path,
1635
+ version: 0,
1636
+ action: BIND_ACTION,
1637
+ actor: 'engine',
1638
+ dedupe: `${BIND_ACTION}:${art.path}:v${art.version}`,
1639
+ timestamp: now,
1640
+ reason: `artifact '${art.path}' bound ${bind.to}`,
1641
+ // JSON has no undefined value, so null faithfully records an unbound
1642
+ // target while preserving both sides of every accepted routing write.
1643
+ metadata: { from: prior ?? null, to: value },
1644
+ });
1645
+ }
1538
1646
  // ---- producer commits ------------------------------------------------------
1539
1647
  /**
1540
1648
  * Commit a singleton/map output green — or born-reject it if an input moved.
@@ -1601,7 +1709,9 @@ export class Engine {
1601
1709
  const producer = def.steps.find((l) => l.name === art.producer);
1602
1710
  if (opts.terminal || producer?.terminal)
1603
1711
  next.terminal = true;
1712
+ this.validateArtifactBind(def, next, value);
1604
1713
  this.store.putArtifact(next, { action: 'green', actor: 'human', reason: 'human green' });
1714
+ this.applyArtifactBind(workflow, def, next, value, nowMs());
1605
1715
  this.settle(workflow, def);
1606
1716
  return { path, outcome: 'green' };
1607
1717
  });
@@ -1642,7 +1752,9 @@ export class Engine {
1642
1752
  const next = { ...art, acceptance: 'green', approvals };
1643
1753
  if (producer?.terminal)
1644
1754
  next.terminal = true;
1755
+ this.validateArtifactBind(def, next, art.value);
1645
1756
  this.store.putArtifact(next, { action: 'judge-approved', actor: jName, reason: 'all judges approved' });
1757
+ this.applyArtifactBind(workflow, def, next, art.value, nowMs());
1646
1758
  this.settle(workflow, def);
1647
1759
  return { path: judgedStem, outcome: 'green' };
1648
1760
  }
@@ -1697,6 +1809,20 @@ export class Engine {
1697
1809
  return { path, outcome: 'schema-rejected', reason: text, issues: check.issues };
1698
1810
  }
1699
1811
  }
1812
+ try {
1813
+ this.validateArtifactBind(def, art, value);
1814
+ }
1815
+ catch (e) {
1816
+ const text = `artifact bind validation failed: ${e instanceof Error ? e.message : String(e)}`;
1817
+ this.store.putArtifact({
1818
+ ...art,
1819
+ acceptance: 'rejected',
1820
+ schemaRejects: art.schemaRejects + 1,
1821
+ reasons: [...art.reasons, reason('schema-reject', 'validation', 'engine', text, art.version)],
1822
+ });
1823
+ this.settle(workflow, def);
1824
+ return { path, outcome: 'schema-rejected', reason: text };
1825
+ }
1700
1826
  // §24 §4.4/§4.8: when this produce declares judges, the commit lands
1701
1827
  // `submitted` (not `green`) and the version bumps here — CAS re-arms on
1702
1828
  // resubmission, not on judge-approve. `approvals` resets so a prior
@@ -1722,6 +1848,8 @@ export class Engine {
1722
1848
  actor: r.step,
1723
1849
  reason: hasJudges ? 'submitted for judgment' : 'producer green',
1724
1850
  });
1851
+ if (!hasJudges)
1852
+ this.applyArtifactBind(workflow, def, next, value, nowMs());
1725
1853
  this.settle(workflow, def);
1726
1854
  return { path, outcome: hasJudges ? 'submitted' : 'green' };
1727
1855
  });
@@ -1895,7 +2023,7 @@ export class Engine {
1895
2023
  * See `docs/design.md` §24.9 for the full writeup and operator mitigations
1896
2024
  * (`parallel: 1`, a generous `reapTtl:` on slow judge steps).
1897
2025
  */
1898
- reject(workflow, path, by, text) {
2026
+ reject(workflow, path, by, text, requested) {
1899
2027
  const def = this.defFor(workflow);
1900
2028
  this.assertAuthority(def, by, path, 'reject');
1901
2029
  // F4: a reject on an artifact produced by a `calls:` step is a verdict on
@@ -1906,7 +2034,14 @@ export class Engine {
1906
2034
  // verb-guard rule below that a verdict needs a built version).
1907
2035
  const producingStep = def.steps.find((s) => s.produces.some((p) => p.stem === path));
1908
2036
  if (producingStep?.calls) {
1909
- return this.rejectCallsArtifact(workflow, def, producingStep, path, by, text);
2037
+ const bind = producingStep.produces.find((p) => p.stem === path)?.bind;
2038
+ if (requested !== undefined) {
2039
+ if (bind?.to !== 'modifier') {
2040
+ throw new Error(`requested modifier is only valid when artifact '${path}' binds to modifier`);
2041
+ }
2042
+ this.assertBoundModifier(def, requested);
2043
+ }
2044
+ return this.rejectCallsArtifact(workflow, def, producingStep, path, by, text, requested);
1910
2045
  }
1911
2046
  const judgeStep = def.steps.find((s) => s.name === by);
1912
2047
  const judgedStem = judgeStep?.judges;
@@ -1915,6 +2050,13 @@ export class Engine {
1915
2050
  const art = this.store.getArtifact(workflow, path);
1916
2051
  if (!art)
1917
2052
  throw new Error(`cannot reject unknown artifact: ${path}`);
2053
+ if (requested !== undefined) {
2054
+ const bind = this.artifactBind(def, art);
2055
+ if (bind?.to !== 'modifier') {
2056
+ throw new Error(`requested modifier is only valid when artifact '${path}' binds to modifier`);
2057
+ }
2058
+ this.assertBoundModifier(def, requested);
2059
+ }
1918
2060
  if (judgedStem !== undefined) {
1919
2061
  // A judge's reject targets the judged stem, mirroring green()'s
1920
2062
  // judge-approve branch (§24.4): CAS-guard against a stale verdict
@@ -1958,7 +2100,7 @@ export class Engine {
1958
2100
  acceptance: 'rejected',
1959
2101
  judgmentRejects: art.judgmentRejects + 1,
1960
2102
  approvals: undefined,
1961
- reasons: [...art.reasons, reason('reject', 'judgment', by, text, art.version)],
2103
+ reasons: [...art.reasons, reason('reject', 'judgment', by, text, art.version, requested)],
1962
2104
  });
1963
2105
  this.settle(workflow, def);
1964
2106
  return { outcome: 'rejected' };
@@ -1989,7 +2131,7 @@ export class Engine {
1989
2131
  * reasons entry is `parent:<by>` to make the indirection visible in its
1990
2132
  * audit thread.
1991
2133
  */
1992
- rejectCallsArtifact(parentWf, def, producingStep, callsStem, by, text) {
2134
+ rejectCallsArtifact(parentWf, def, producingStep, callsStem, by, text, requested) {
1993
2135
  const child = this.store.findChildByParent(parentWf, callsStem);
1994
2136
  if (!child) {
1995
2137
  throw new Error(`cannot reject '${callsStem}': no child instance has been spawned yet (a verdict requires a built version)`);
@@ -2012,7 +2154,7 @@ export class Engine {
2012
2154
  acceptance: 'rejected',
2013
2155
  judgmentRejects: childArt.judgmentRejects + 1,
2014
2156
  approvals: undefined,
2015
- reasons: [...childArt.reasons, reason('reject', 'judgment', `parent:${by}`, text, childArt.version)],
2157
+ reasons: [...childArt.reasons, reason('reject', 'judgment', `parent:${by}`, text, childArt.version, requested)],
2016
2158
  });
2017
2159
  this.settle(child.id, childDef);
2018
2160
  // Parent calls artifact → reopened to owed (not left rejected), pinned
@@ -3023,8 +3165,8 @@ export class Engine {
3023
3165
  }
3024
3166
  }
3025
3167
  // ---- helpers -----------------------------------------------------------------
3026
- function reason(action, kind, by, text, fromVersion) {
3027
- return { at: nowMs(), action, kind, by, text, fromVersion };
3168
+ function reason(action, kind, by, text, fromVersion, requested) {
3169
+ return { at: nowMs(), action, kind, by, text, fromVersion, ...(requested !== undefined ? { requested } : {}) };
3028
3170
  }
3029
3171
  function nextIndex(arts, stem) {
3030
3172
  let max = -1;
@@ -14,7 +14,7 @@
14
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
16
  export { applyCapabilityRewrites, capabilityName, claimMatches, composeCapabilities, DEFAULT_MATCH_MODE, MODIFIER_SEPARATOR, } from './capabilities.ts';
17
- export type { CapabilityRewrites, MatchMode } from './capabilities.ts';
17
+ export type { CapabilityRewrites, CrewStamps, MatchMode } from './capabilities.ts';
18
18
  export { createEngine } from './factory.ts';
19
19
  export type { CreateEngineOpts, CreatedEngine } from './factory.ts';
20
20
  export { createDefInstructionSource, defInstructionDigest, OrderResolver, substituteOrderVars, UnknownDefDigestError, UnknownInstructionError, } from './order-resolver.ts';
@@ -23,13 +23,13 @@ export { Store, openStore, StoreVersionError } from './store.ts';
23
23
  export type { ArtifactRow, RunRow, TaskRow, WorkflowRow } from './store.ts';
24
24
  export { defDigest, emptyWorkflowStoreIndex, globalStoreRoot, hardenObjectModes, installWorkflowBundle, inspectCasDefs, isDefDigest, loadCasDefs, 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, CasDefInspectionResult, CasDefRegistration, DefDigest, LoadCasDefsArgs, InstallWorkflowBundleArgs, PreCommitVerifier, ExecutionOriginVerifierInput, RecoverWorkflowStoreArgs, ResolvedWorkflowObject, ResolveWorkflowCoordinateArgs, ResolveWorkflowDigestArgs, ResolutionLevel, StoreLevel, WorkflowCoordinate, WorkflowStoreIndex, WorkflowStoreIndexEntry, WorkflowStoreStatePaths, } from './store/index.ts';
26
- export { buildDef, 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, lintDef, loadDefFile, loadDefs, loadDefsRaw, parseDef, resolveCallsTarget, SUPPORTED_ENGINE_VERSION, validateDef } from './defs.ts';
27
27
  export { credentialSlot, hashDefForHub, keychainServiceFor, normalizeOrigin, readStoredCredential } from './hub.ts';
28
28
  export type { Credential, CredentialSlotSelector, Keychain, ReadStoredCredentialOpts } from './hub.ts';
29
29
  export type { DefLoadFailure } from './defs.ts';
30
30
  export { deleteCredential, ensureFreshOAuth, storeCredential } from './credentials.ts';
31
31
  export type { CredentialIO } from './credentials.ts';
32
- export { DSSE_SSH_NAMESPACE, DSSE_VERSION, DSSE_RECORD_PAYLOAD_TYPES, DsseEnvelopeError, isDsseRecordPayloadType, PAYLOAD_TYPE_ENROLLMENT_GRANT, PAYLOAD_TYPE_ORIGIN, PAYLOAD_TYPE_POLICY_FLOOR, PAYLOAD_TYPE_PUBLICATION, PAYLOAD_TYPE_REVOCATION, PAYLOAD_TYPE_SUBMISSION, PrincipalKeyManager, SshSigner, SshSignerError, assertEd25519PubText, assertKeyRef, canonicalKeyRef, createSshSigner, decodeBase64Strict, dsseSignEnrollmentGrant, dsseSignEnvelope, dsseSignOrigin, dsseSignPolicyFloor, dsseSignPublication, dsseSignRecord, dsseSignRevocation, dsseSignSubmission, dsseVerifyEnrollmentGrant, dsseVerifyEnvelope, dsseVerifyOrigin, dsseVerifyPolicyFloor, dsseVerifyPublication, dsseVerifyRecord, dsseVerifyRevocation, dsseVerifySubmission, encodeBase64, keyidFromBlob, keyRefHash, parseAllowedSigners, preAuthEncode, publicKeyDescriptor, allowedSignersPath, resolveAllowedSigners, resolveAllowedSignersFile, isDefPolicy, verifyOrigin, verifyOriginSidecar, verifyPublication, verifyPublicationSidecar, verifyConsumed, verifyConsumedArtifact, DEFAULT_MACHINE_SCOPE, buildEnrollmentGrant, verifyRosterEntry, validateEnrollmentChain, validateProducer, revocationTemporalConsistency, attenuate, axisPermits, delegationPermits, ORG_ROOT_SCOPE, scopePermits, loadRoster, loadRevocations, orgRootPrivateKeyPath, orgRootPublicKeyPath, resolveOrgRoot, revocationsDir, rosterDir, ENROLLMENT_GRANT_FIELDS, ENROLLMENT_KEY_FIELDS, GRANT_DELEGATION_ALLOWED_FIELDS, GRANT_DELEGATION_DENIED_FIELDS, GRANT_SCOPE_FIELDS, ORDER_FIELDS, ORDER_OWED_FIELDS, ORDER_REASON_FIELDS, ORIGIN_FIELDS, ORIGIN_SOURCE_AGENT_FIELDS, ORIGIN_SOURCE_CONSOLE_FIELDS, ORIGIN_SOURCE_GIT_FIELDS, POLICY_FLOOR_FIELDS, POLICY_FLOOR_RECORD_FIELDS, PRINCIPAL_REFERENCE_FIELDS, PUBLICATION_FIELDS, RECORD_PAYLOAD_TYPES, REVOCATION_FIELDS, SUBMISSION_FIELDS, SUBMISSION_PRODUCED_FIELDS, } from './crypto/index.ts';
32
+ export { DSSE_SSH_NAMESPACE, DSSE_VERSION, DSSE_RECORD_PAYLOAD_TYPES, DsseEnvelopeError, isDsseRecordPayloadType, PAYLOAD_TYPE_ENROLLMENT_GRANT, PAYLOAD_TYPE_ORIGIN, PAYLOAD_TYPE_POLICY_FLOOR, PAYLOAD_TYPE_PUBLICATION, PAYLOAD_TYPE_REVOCATION, PAYLOAD_TYPE_SUBMISSION, PrincipalKeyManager, SshSigner, SshSignerError, assertEd25519PubText, assertKeyRef, canonicalKeyRef, createSshSigner, decodeBase64Strict, dsseSignEnrollmentGrant, dsseSignEnvelope, dsseSignOrigin, dsseSignPolicyFloor, dsseSignPublication, dsseSignRecord, dsseSignRevocation, dsseSignSubmission, dsseVerifyEnrollmentGrant, dsseVerifyEnvelope, dsseVerifyOrigin, dsseVerifyPolicyFloor, dsseVerifyPublication, dsseVerifyRecord, dsseVerifyRevocation, dsseVerifySubmission, encodeBase64, keyidFromBlob, keyRefHash, parseAllowedSigners, preAuthEncode, publicKeyDescriptor, allowedSignersPath, resolveAllowedSigners, resolveAllowedSignersFile, isDefPolicy, verifyOrigin, verifyOriginSidecar, verifyPublication, verifyPublicationSidecar, verifyConsumed, verifyConsumedArtifact, DEFAULT_MACHINE_SCOPE, buildEnrollmentGrant, verifyRosterEntry, validateEnrollmentChain, validateProducer, revocationTemporalConsistency, attenuate, axisPermits, delegationPermits, ORG_ROOT_SCOPE, scopePermits, loadGrants, loadRevocations, orgRootPrivateKeyPath, orgRootPublicKeyPath, resolveOrgRoot, revocationsDir, grantsDir, StrandedLegacyGrantsError, ENROLLMENT_GRANT_FIELDS, ENROLLMENT_KEY_FIELDS, GRANT_DELEGATION_ALLOWED_FIELDS, GRANT_DELEGATION_DENIED_FIELDS, GRANT_SCOPE_FIELDS, ORDER_FIELDS, ORDER_OWED_FIELDS, ORDER_REASON_FIELDS, ORIGIN_FIELDS, ORIGIN_SOURCE_AGENT_FIELDS, ORIGIN_SOURCE_CONSOLE_FIELDS, ORIGIN_SOURCE_GIT_FIELDS, POLICY_FLOOR_FIELDS, POLICY_FLOOR_RECORD_FIELDS, PRINCIPAL_REFERENCE_FIELDS, PUBLICATION_FIELDS, RECORD_PAYLOAD_TYPES, REVOCATION_FIELDS, SUBMISSION_FIELDS, SUBMISSION_PRODUCED_FIELDS, } from './crypto/index.ts';
33
33
  export type { AllowedSignerEntry, AllowedSignerOptions, AllowedSignersFile, AllowedSignersParseError, AllowedSignersResolution, AllowedSignersPresent, AllowedSignersAbsent, DefPolicy, DefVerdict, OriginVerdict, VerifyOriginInput, VerifyOriginOptions, ConsumedVerdict, VerifyConsumedInput, VerifyConsumedOptions, VerifyPublicationInput, VerifyPublicationOptions, BuildEnrollmentGrantArgs, EnrollmentChainValidator, RosterVerdict, VerifyRosterEntryInput, VerifyRosterEntryOptions, ChainInput, ChainOptions, ChainVerdict, ScopeAxis, OrgRootAbsent, OrgRootPresent, OrgRootResolution, DetachedSignature, DsseEnvelope, DsseRecordPayloadType, DsseSignature, DsseVerifyResult, EnsureKeyResult, InspectKeyResult, KeyStorageBackendKind, PrincipalKeyRef, PrincipalKind, PublicKeyDescriptor, EnrollmentGrantRecord, EnrollmentKeyDescriptor, FieldManifest, GrantDelegation, GrantDelegationAllowed, GrantDelegationDenied, GrantScope, OptionalKeys, OriginRecord, OriginSource, OriginSourceAgent, OriginSourceConsole, OriginSourceGit, PolicyFloor, PolicyFloorRecord, PrincipalReference, PublicationRecord, RequiredKeys, RevocationRecord, SubmissionProducedArtifact, SubmissionRecord, Signer, SshProcessAdapter, SshSignerConfig, VerifiedSignature, } from './crypto/index.ts';
34
34
  export { DEF_POLICY_RANK, POLICY_FLOOR_PRESETS, artifactPolicyMinimum, floorDefPolicyMinimum, mergePolicyFloorWithLocal, originRulesMinimum, policyFloorGaps, stricterDefPolicy, verifyPolicyFloorRecord, } from './crypto/index.ts';
35
35
  export type { PolicyFloorGap, PolicyFloorMergeResult, PolicyFloorVerdict, VerifyPolicyFloorInput, VerifyPolicyFloorOptions, } from './crypto/index.ts';
@@ -44,6 +44,6 @@ export { enrollmentGrantSchema, orderSchema, originSchema, policyFloorSchema, pu
44
44
  export { BundleError, DEFAULT_BUNDLE_LIMITS, digestBundle, inspectBundle, packBundle, unpackBundle } from './bundle/index.ts';
45
45
  export type { BundleEntryInfo, BundleErrorCode, BundleLimits, BundleManifest, BundleRuntimeRequirements, InspectOptions, InspectResult, PackOptions, PackResult, } from './bundle/index.ts';
46
46
  export { DEBT_STATES, SETTLED_STATES } from './types.ts';
47
- export type { Acceptance, ArtifactBiography, ArtifactData, Author, CheckFinding, CheckOptions, CheckReport, CheckStep, ConsumePattern, FiringTrigger, Fingerprint, GraphEdge, GraphNode, GraphNodeState, InputDef, InvariantDef, InvariantPredicate, InvariantViolation, JsonSchema, StepDef, ProducePattern, ReasonEntry, RejectKind, RunData, TaskData, TimelineEvent, WorkflowDef, WorkflowGraph, WorkflowTrace, } from './types.ts';
47
+ 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
48
  export { canonicalValueBytes, valueDigestHex, buildSubmissionRecord, signSubmission } from './crypto/index.ts';
49
49
  export type { BuildSubmissionRecordInput, SubmissionProducedInput } from './crypto/index.ts';
package/dist/src/index.js CHANGED
@@ -22,10 +22,10 @@ export { Store, openStore, StoreVersionError } from "./store.js";
22
22
  // store above): two-level digest-addressed workflow objects + coordinate
23
23
  // index, `.wnlp` bundle installation, and fail-closed resolution.
24
24
  export { defDigest, emptyWorkflowStoreIndex, globalStoreRoot, hardenObjectModes, installWorkflowBundle, inspectCasDefs, isDefDigest, loadCasDefs, 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.js";
25
- export { buildDef, DefError, expandIncludes, finalizeDefs, hashDef, lintDef, loadDefFile, loadDefs, loadDefsRaw, parseDef, resolveCallsTarget, SUPPORTED_ENGINE_VERSION, validateDef } from "./defs.js";
25
+ export { buildDef, cancelCleanupSteps, DefError, expandIncludes, finalizeDefs, hashDef, lintDef, loadDefFile, loadDefs, loadDefsRaw, parseDef, resolveCallsTarget, SUPPORTED_ENGINE_VERSION, validateDef } from "./defs.js";
26
26
  export { credentialSlot, hashDefForHub, keychainServiceFor, normalizeOrigin, readStoredCredential } from "./hub.js";
27
27
  export { deleteCredential, ensureFreshOAuth, storeCredential } from "./credentials.js";
28
- export { DSSE_SSH_NAMESPACE, DSSE_VERSION, DSSE_RECORD_PAYLOAD_TYPES, DsseEnvelopeError, isDsseRecordPayloadType, PAYLOAD_TYPE_ENROLLMENT_GRANT, PAYLOAD_TYPE_ORIGIN, PAYLOAD_TYPE_POLICY_FLOOR, PAYLOAD_TYPE_PUBLICATION, PAYLOAD_TYPE_REVOCATION, PAYLOAD_TYPE_SUBMISSION, PrincipalKeyManager, SshSigner, SshSignerError, assertEd25519PubText, assertKeyRef, canonicalKeyRef, createSshSigner, decodeBase64Strict, dsseSignEnrollmentGrant, dsseSignEnvelope, dsseSignOrigin, dsseSignPolicyFloor, dsseSignPublication, dsseSignRecord, dsseSignRevocation, dsseSignSubmission, dsseVerifyEnrollmentGrant, dsseVerifyEnvelope, dsseVerifyOrigin, dsseVerifyPolicyFloor, dsseVerifyPublication, dsseVerifyRecord, dsseVerifyRevocation, dsseVerifySubmission, encodeBase64, keyidFromBlob, keyRefHash, parseAllowedSigners, preAuthEncode, publicKeyDescriptor, allowedSignersPath, resolveAllowedSigners, resolveAllowedSignersFile, isDefPolicy, verifyOrigin, verifyOriginSidecar, verifyPublication, verifyPublicationSidecar, verifyConsumed, verifyConsumedArtifact, DEFAULT_MACHINE_SCOPE, buildEnrollmentGrant, verifyRosterEntry, validateEnrollmentChain, validateProducer, revocationTemporalConsistency, attenuate, axisPermits, delegationPermits, ORG_ROOT_SCOPE, scopePermits, loadRoster, loadRevocations, orgRootPrivateKeyPath, orgRootPublicKeyPath, resolveOrgRoot, revocationsDir, rosterDir, ENROLLMENT_GRANT_FIELDS, ENROLLMENT_KEY_FIELDS, GRANT_DELEGATION_ALLOWED_FIELDS, GRANT_DELEGATION_DENIED_FIELDS, GRANT_SCOPE_FIELDS, ORDER_FIELDS, ORDER_OWED_FIELDS, ORDER_REASON_FIELDS, ORIGIN_FIELDS, ORIGIN_SOURCE_AGENT_FIELDS, ORIGIN_SOURCE_CONSOLE_FIELDS, ORIGIN_SOURCE_GIT_FIELDS, POLICY_FLOOR_FIELDS, POLICY_FLOOR_RECORD_FIELDS, PRINCIPAL_REFERENCE_FIELDS, PUBLICATION_FIELDS, RECORD_PAYLOAD_TYPES, REVOCATION_FIELDS, SUBMISSION_FIELDS, SUBMISSION_PRODUCED_FIELDS, } from "./crypto/index.js";
28
+ export { DSSE_SSH_NAMESPACE, DSSE_VERSION, DSSE_RECORD_PAYLOAD_TYPES, DsseEnvelopeError, isDsseRecordPayloadType, PAYLOAD_TYPE_ENROLLMENT_GRANT, PAYLOAD_TYPE_ORIGIN, PAYLOAD_TYPE_POLICY_FLOOR, PAYLOAD_TYPE_PUBLICATION, PAYLOAD_TYPE_REVOCATION, PAYLOAD_TYPE_SUBMISSION, PrincipalKeyManager, SshSigner, SshSignerError, assertEd25519PubText, assertKeyRef, canonicalKeyRef, createSshSigner, decodeBase64Strict, dsseSignEnrollmentGrant, dsseSignEnvelope, dsseSignOrigin, dsseSignPolicyFloor, dsseSignPublication, dsseSignRecord, dsseSignRevocation, dsseSignSubmission, dsseVerifyEnrollmentGrant, dsseVerifyEnvelope, dsseVerifyOrigin, dsseVerifyPolicyFloor, dsseVerifyPublication, dsseVerifyRecord, dsseVerifyRevocation, dsseVerifySubmission, encodeBase64, keyidFromBlob, keyRefHash, parseAllowedSigners, preAuthEncode, publicKeyDescriptor, allowedSignersPath, resolveAllowedSigners, resolveAllowedSignersFile, isDefPolicy, verifyOrigin, verifyOriginSidecar, verifyPublication, verifyPublicationSidecar, verifyConsumed, verifyConsumedArtifact, DEFAULT_MACHINE_SCOPE, buildEnrollmentGrant, verifyRosterEntry, validateEnrollmentChain, validateProducer, revocationTemporalConsistency, attenuate, axisPermits, delegationPermits, ORG_ROOT_SCOPE, scopePermits, loadGrants, loadRevocations, orgRootPrivateKeyPath, orgRootPublicKeyPath, resolveOrgRoot, revocationsDir, grantsDir, StrandedLegacyGrantsError, ENROLLMENT_GRANT_FIELDS, ENROLLMENT_KEY_FIELDS, GRANT_DELEGATION_ALLOWED_FIELDS, GRANT_DELEGATION_DENIED_FIELDS, GRANT_SCOPE_FIELDS, ORDER_FIELDS, ORDER_OWED_FIELDS, ORDER_REASON_FIELDS, ORIGIN_FIELDS, ORIGIN_SOURCE_AGENT_FIELDS, ORIGIN_SOURCE_CONSOLE_FIELDS, ORIGIN_SOURCE_GIT_FIELDS, POLICY_FLOOR_FIELDS, POLICY_FLOOR_RECORD_FIELDS, PRINCIPAL_REFERENCE_FIELDS, PUBLICATION_FIELDS, RECORD_PAYLOAD_TYPES, REVOCATION_FIELDS, SUBMISSION_FIELDS, SUBMISSION_PRODUCED_FIELDS, } from "./crypto/index.js";
29
29
  // ---- policy floors ----
30
30
  export { DEF_POLICY_RANK, POLICY_FLOOR_PRESETS, artifactPolicyMinimum, floorDefPolicyMinimum, mergePolicyFloorWithLocal, originRulesMinimum, policyFloorGaps, stricterDefPolicy, verifyPolicyFloorRecord, } from "./crypto/index.js";
31
31
  // ---- WP-E2a origin execution policy ----
@@ -44,9 +44,20 @@ import type { LineStream } from './server.ts';
44
44
  * command falls back to `process.stdin`).
45
45
  */
46
46
  export interface McpIo extends CredentialIO {
47
+ /** The session's working directory — the repo the MCP host was launched in. */
48
+ cwd: string;
47
49
  out: (line: string) => void;
48
50
  err: (line: string) => void;
49
51
  stdinStream?: LineStream;
52
+ /**
53
+ * Local command runner, used only to read the git `origin` remote for the
54
+ * `start_run` scope default. Without it the default cannot be resolved.
55
+ */
56
+ runCommand?: (cmd: string, args: string[]) => {
57
+ status: number | null;
58
+ stdout: string;
59
+ stderr: string;
60
+ };
50
61
  principalKeys?: Pick<PrincipalKeyManager, 'inspect' | 'resolveRef' | 'withSigningKey'>;
51
62
  /** Injectable ssh-keygen seam for hermetic submit-proof tests. */
52
63
  sshProcess?: SshProcessAdapter;
@@ -95,6 +106,17 @@ export interface McpIo extends CredentialIO {
95
106
  * tool error instead of a dead server.
96
107
  */
97
108
  export declare function resolveMcpOrigin(io: McpIo, hubFlag: string | undefined): string;
109
+ /**
110
+ * The default `scope` for a run started from inside a repo session: the repo
111
+ * name, taken from the `origin` remote's URL (last path segment, trailing
112
+ * `.git` removed). Worktree-stable by construction — every checkout of one repo
113
+ * reports the same remote, whereas the directory name differs per worktree.
114
+ *
115
+ * Returns `undefined` — meaning "send no scope at all" — for every failure:
116
+ * no runner seam, not a git repo, no `origin` remote, empty or unparseable URL,
117
+ * or a segment outside the legal charset. Never guesses a label.
118
+ */
119
+ export declare function resolveRepoScope(io: McpIo): string | undefined;
98
120
  /**
99
121
  * Run the `owenloop mcp` command: resolve the origin, decide the enrollment
100
122
  * gate, build the tool list, construct the JSON-RPC server, and pump stdin until
@@ -109,6 +109,30 @@ export function resolveMcpOrigin(io, hubFlag) {
109
109
  }
110
110
  return DEFAULT_HUB;
111
111
  }
112
+ /** Repo-name charset — kept local so this module does not depend on the installer. */
113
+ const REPO_SEGMENT_RE = /^[A-Za-z0-9._-]+$/;
114
+ /**
115
+ * The default `scope` for a run started from inside a repo session: the repo
116
+ * name, taken from the `origin` remote's URL (last path segment, trailing
117
+ * `.git` removed). Worktree-stable by construction — every checkout of one repo
118
+ * reports the same remote, whereas the directory name differs per worktree.
119
+ *
120
+ * Returns `undefined` — meaning "send no scope at all" — for every failure:
121
+ * no runner seam, not a git repo, no `origin` remote, empty or unparseable URL,
122
+ * or a segment outside the legal charset. Never guesses a label.
123
+ */
124
+ export function resolveRepoScope(io) {
125
+ if (io.runCommand === undefined)
126
+ return undefined;
127
+ const r = io.runCommand('git', ['-C', io.cwd, 'remote', 'get-url', 'origin']);
128
+ if (r.status !== 0)
129
+ return undefined;
130
+ const url = r.stdout.trim().replace(/\/+$/, '');
131
+ if (url === '')
132
+ return undefined;
133
+ const segment = (url.split(/[/:]/).pop() ?? '').replace(/\.git$/, '');
134
+ return REPO_SEGMENT_RE.test(segment) ? segment : undefined;
135
+ }
112
136
  // ---- the authenticated hub client -------------------------------------------
113
137
  /** The non-interactive "you are not authenticated" instruction (Decision 8). */
114
138
  function loginHint(origin) {
@@ -322,13 +346,13 @@ function warnMcpUnsigned(deps, reason) {
322
346
  deps.io.err(`owenloop mcp: ${reason}`);
323
347
  }
324
348
  /**
325
- * The 17 baseline tools — names, descriptions, and schemas mirror the hub's own
349
+ * The 20 baseline tools — names, descriptions, and schemas mirror the hub's own
326
350
  * HTTP-MCP toolset (owenloop-service `apps/hub-edge/src/mcp/tools.ts`); each maps
327
351
  * to an H3 `/api/*` REST mirror. Descriptions say "Scoped Identity" for the identity
328
352
  * (wire names keep `agent`), never "tool" (model-doc §0/§10).
329
353
  *
330
354
  * This is not the server's whole tool list. `runMcpCommand` assembles the full
331
- * set: these 17, plus `createAgentTool`, plus the four crew tools from
355
+ * set: these 20, plus `createAgentTool`, plus the four crew tools from
332
356
  * `buildCrewTools` (below — deliberately NOT folded in here, since they do not
333
357
  * mirror the hub's own MCP toolset), plus the conditionally-registered
334
358
  * `stageEnrollmentTool`.
@@ -340,7 +364,16 @@ function buildBaselineTools(deps) {
340
364
  description: 'THE verb. With workflow: ticks it and returns the next work order(s), or a status summary if none. Without workflow: the inbox of started instances. Serves only YOUR OWN runs by default. Pass serve_crews to partition your own runs further (intersects with each step\'s capabilities; absent or [] = no capability filter). serve_crews is ignored in inbox mode (no workflow).',
341
365
  inputSchema: {
342
366
  type: 'object',
343
- properties: { workflow: { type: 'string' }, serve_crews: { type: 'array', items: { type: 'string' } } },
367
+ properties: {
368
+ workflow: { type: 'string' },
369
+ serve_crews: { type: 'array', items: { type: 'string' } },
370
+ serve_capabilities: {
371
+ type: 'array',
372
+ items: { type: 'string' },
373
+ description: 'Capability keys this caller serves, raw (bare names and exact compounds). ' +
374
+ 'Shifts compute this from their effective rosters; other callers normally omit it.',
375
+ },
376
+ },
344
377
  additionalProperties: false,
345
378
  },
346
379
  handler: passthrough(deps, (a) => ({ method: 'POST', path: '/api/whats_next', body: a })),
@@ -389,6 +422,19 @@ function buildBaselineTools(deps) {
389
422
  },
390
423
  handler: passthrough(deps, (a) => ({ method: 'POST', path: '/api/reject_artifact', body: a })),
391
424
  },
425
+ {
426
+ name: 'retry_artifact',
427
+ description: "The human stall-clearing lever: re-arm a stalled or rejected artifact to 'owed', resetting its " +
428
+ 'reject counters. This is also the answer path for a worker that escalated with `ask` — `text` ' +
429
+ "rides to the next producer on the artifact's reason thread. Omit `text` for a bare stall-clear.",
430
+ inputSchema: {
431
+ type: 'object',
432
+ properties: { workflow: { type: 'string' }, path: { type: 'string' }, text: { type: 'string' } },
433
+ required: ['workflow', 'path'],
434
+ additionalProperties: false,
435
+ },
436
+ handler: passthrough(deps, (a) => ({ method: 'POST', path: '/api/retry_artifact', body: a })),
437
+ },
392
438
  {
393
439
  name: 'provide_input',
394
440
  description: 'The human-gate answer path: provide a value for a seeded/owed input.',
@@ -406,14 +452,30 @@ function buildBaselineTools(deps) {
406
452
  },
407
453
  {
408
454
  name: 'start_run',
409
- description: 'Create a new workflow instance from a definition name, optionally seeding provided inputs.',
455
+ description: 'Create a new workflow instance from a definition name, optionally seeding provided inputs. ' +
456
+ '`scope` is a free routing label recorded on the run; when omitted it defaults to this ' +
457
+ "session's repository name (the `origin` remote's last path segment) when one can be " +
458
+ 'determined, and is sent as nothing otherwise. `priority` is the rate-limit band; omit it ' +
459
+ 'and the hub applies `normal`.',
410
460
  inputSchema: {
411
461
  type: 'object',
412
- properties: { workflow_name: { type: 'string' }, provide: { type: 'object', additionalProperties: true } },
462
+ properties: {
463
+ workflow_name: { type: 'string' },
464
+ provide: { type: 'object', additionalProperties: true },
465
+ scope: { type: 'string' },
466
+ // Unlike crew `kind`/`principalKind`, this is a fixed local wire
467
+ // contract, so the MCP schema rejects an out-of-set value too.
468
+ priority: { type: 'string', enum: ['low', 'normal', 'high'] },
469
+ },
413
470
  required: ['workflow_name'],
414
471
  additionalProperties: false,
415
472
  },
416
- handler: passthrough(deps, (a) => ({ method: 'POST', path: '/api/start_run', body: a })),
473
+ handler: passthrough(deps, (a) => ({
474
+ method: 'POST',
475
+ path: '/api/start_run',
476
+ // A default, never an override: explicit `scope`, including '', wins.
477
+ body: deps.repoScope !== undefined && !('scope' in a) ? { ...a, scope: deps.repoScope } : a,
478
+ })),
417
479
  },
418
480
  {
419
481
  name: 'create_workflow',
@@ -532,6 +594,12 @@ function buildBaselineTools(deps) {
532
594
  properties: {
533
595
  name: { type: 'string' },
534
596
  serve_crews: { type: 'array', items: { type: 'string' } },
597
+ serve_capabilities: {
598
+ type: 'array',
599
+ items: { type: 'string' },
600
+ description: 'Capability keys this caller serves, raw (bare names and exact compounds). ' +
601
+ 'Shifts compute this from their effective rosters; other callers normally omit it.',
602
+ },
535
603
  shift_id: { type: 'string' },
536
604
  started_at: { type: 'number' },
537
605
  },
@@ -546,6 +614,18 @@ function buildBaselineTools(deps) {
546
614
  inputSchema: { type: 'object', properties: {}, additionalProperties: false },
547
615
  handler: passthrough(deps, () => ({ method: 'GET', path: '/api/shifts' })),
548
616
  },
617
+ {
618
+ name: 'get_rosters',
619
+ description: "The org's roster cascade: one org-global capability table plus optional per-crew tables. These rows select harness/model/effort after the hub has already routed work to a crew.",
620
+ inputSchema: { type: 'object', properties: {}, additionalProperties: false },
621
+ handler: passthrough(deps, () => ({ method: 'GET', path: '/api/rosters' })),
622
+ },
623
+ {
624
+ name: 'list_harness_models',
625
+ description: "The hub's known harnesses and model snapshots, including each model's supported effort values. Read-only; roster writes stay in the terminal CLI.",
626
+ inputSchema: { type: 'object', properties: {}, additionalProperties: false },
627
+ handler: passthrough(deps, () => ({ method: 'GET', path: '/api/harness_models' })),
628
+ },
549
629
  {
550
630
  name: 'wake',
551
631
  description: 'A cheap "has anything relevant to you changed since cursor X" pre-check for a polling loop — returns { cursor, changed }. Keep the returned cursor and pass it next time; call whats_next ONLY when changed is true. Omit cursor to bootstrap. NOT a substitute for whats_next — it never returns work orders, only whether to ask.',
@@ -636,7 +716,7 @@ function createAgentTool(deps) {
636
716
  },
637
717
  };
638
718
  }
639
- /** Tool 19 (gated) — `stage_enrollment`: a plain passthrough (join codes are transcript-legal per model-doc §6). */
719
+ /** Tool 20 (gated) — `stage_enrollment`: a plain passthrough (join codes are transcript-legal per model-doc §6). */
640
720
  function stageEnrollmentTool(deps) {
641
721
  return {
642
722
  name: 'stage_enrollment',
@@ -814,7 +894,7 @@ async function shouldRegisterEnrollment(deps) {
814
894
  */
815
895
  export async function runMcpCommand(io, opts) {
816
896
  const origin = resolveMcpOrigin(io, opts.hubFlag);
817
- const deps = { io, origin };
897
+ const deps = { io, origin, repoScope: resolveRepoScope(io) };
818
898
  const tools = [...buildBaselineTools(deps), createAgentTool(deps), ...buildCrewTools(deps)];
819
899
  if (await shouldRegisterEnrollment(deps))
820
900
  tools.push(stageEnrollmentTool(deps));
@@ -79,6 +79,8 @@ export declare function stepMode(step: StepDef): StepMode;
79
79
  */
80
80
  export declare function judgeNameOf(step: StepDef): string;
81
81
  export declare function mapProduce(step: StepDef): ProducePattern | undefined;
82
+ /** All per-element outputs a map step owns for each input index. */
83
+ export declare function mapProduces(step: StepDef): ProducePattern[];
82
84
  /**
83
85
  * The concrete input artifact a map element binds on for index `i`. Normally the
84
86
  * bare collection member `stem[i]`. But when the map consume carries a suffix