owenloop 0.5.0 → 0.5.1

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 (211) hide show
  1. package/CHANGELOG.md +45 -0
  2. package/README.md +137 -35
  3. package/bin/owenloop.mjs +49 -1
  4. package/dist/packages/work/src/agent/brief.d.ts +8 -4
  5. package/dist/packages/work/src/agent/brief.js +7 -3
  6. package/dist/packages/work/src/agent/loop.d.ts +13 -7
  7. package/dist/packages/work/src/agent/loop.js +136 -9
  8. package/dist/packages/work/src/agent/model-policy.d.ts +49 -0
  9. package/dist/packages/work/src/agent/model-policy.js +138 -0
  10. package/dist/packages/work/src/bundle/cache.d.ts +7 -5
  11. package/dist/packages/work/src/bundle/cache.js +20 -6
  12. package/dist/packages/work/src/bundle/fetch.d.ts +7 -5
  13. package/dist/packages/work/src/bundle/fetch.js +27 -7
  14. package/dist/packages/work/src/bundle/types.d.ts +8 -4
  15. package/dist/packages/work/src/consumed-verifier.d.ts +45 -0
  16. package/dist/packages/work/src/consumed-verifier.js +205 -0
  17. package/dist/packages/work/src/exec/instructions.d.ts +99 -0
  18. package/dist/packages/work/src/exec/instructions.js +323 -0
  19. package/dist/packages/work/src/exec/loop.d.ts +12 -1
  20. package/dist/packages/work/src/exec/loop.js +137 -20
  21. package/dist/packages/work/src/exec/payload.d.ts +29 -0
  22. package/dist/packages/work/src/exec/payload.js +54 -0
  23. package/dist/packages/work/src/exec/receipt.d.ts +9 -6
  24. package/dist/packages/work/src/exec/receipt.js +12 -1
  25. package/dist/packages/work/src/exec/runner.d.ts +7 -1
  26. package/dist/packages/work/src/exec/runner.js +74 -3
  27. package/dist/packages/work/src/harness/child-env.js +7 -0
  28. package/dist/packages/work/src/harness/claude.d.ts +20 -8
  29. package/dist/packages/work/src/harness/claude.js +260 -58
  30. package/dist/packages/work/src/harness/codex.d.ts +5 -4
  31. package/dist/packages/work/src/harness/codex.js +169 -41
  32. package/dist/packages/work/src/harness/contract.d.ts +36 -11
  33. package/dist/packages/work/src/harness/fake.js +1 -0
  34. package/dist/packages/work/src/harness/jsonrpc-stdio.js +7 -0
  35. package/dist/packages/work/src/harness/permissions.d.ts +16 -3
  36. package/dist/packages/work/src/harness/permissions.js +102 -13
  37. package/dist/packages/work/src/harness/session-store.d.ts +27 -9
  38. package/dist/packages/work/src/harness/session-store.js +271 -67
  39. package/dist/packages/work/src/hold/mcp.d.ts +25 -5
  40. package/dist/packages/work/src/hold/mcp.js +126 -11
  41. package/dist/packages/work/src/hub/client.d.ts +2 -1
  42. package/dist/packages/work/src/hub/client.js +14 -1
  43. package/dist/packages/work/src/hub/types.d.ts +69 -33
  44. package/dist/packages/work/src/hub/types.js +8 -10
  45. package/dist/packages/work/src/mcp/server.js +1 -1
  46. package/dist/packages/work/src/owenloop-bin.d.ts +1 -0
  47. package/dist/packages/work/src/owenloop-bin.js +18 -0
  48. package/dist/packages/work/src/roles/agent-run.d.ts +12 -6
  49. package/dist/packages/work/src/roles/agent-run.js +116 -34
  50. package/dist/packages/work/src/roles/exec.d.ts +8 -0
  51. package/dist/packages/work/src/roles/exec.js +27 -2
  52. package/dist/packages/work/src/roles/hold.d.ts +4 -0
  53. package/dist/packages/work/src/roles/hold.js +44 -5
  54. package/dist/packages/work/src/roles/lint.d.ts +3 -4
  55. package/dist/packages/work/src/roles/lint.js +41 -7
  56. package/dist/packages/work/src/roles/settings.js +5 -0
  57. package/dist/packages/work/src/roles/shift.d.ts +1 -0
  58. package/dist/packages/work/src/roles/shift.js +23 -1
  59. package/dist/packages/work/src/settings/settings.d.ts +17 -1
  60. package/dist/packages/work/src/settings/settings.js +39 -0
  61. package/dist/packages/work/src/shift/loop.d.ts +14 -3
  62. package/dist/packages/work/src/shift/loop.js +447 -164
  63. package/dist/packages/work/src/shift/protocol.d.ts +4 -0
  64. package/dist/packages/work/src/shift/runtime.d.ts +2 -0
  65. package/dist/packages/work/src/shift/runtime.js +66 -3
  66. package/dist/packages/work/src/shift/spawn.d.ts +41 -18
  67. package/dist/packages/work/src/shift/spawn.js +89 -31
  68. package/dist/packages/work/src/shift/state.d.ts +53 -51
  69. package/dist/packages/work/src/shift/state.js +325 -102
  70. package/dist/packages/work/src/submit-proof.d.ts +36 -0
  71. package/dist/packages/work/src/submit-proof.js +93 -0
  72. package/dist/src/add.d.ts +64 -259
  73. package/dist/src/add.js +81 -615
  74. package/dist/src/archive.d.ts +97 -0
  75. package/dist/src/archive.js +591 -0
  76. package/dist/src/bundle/index.d.ts +64 -0
  77. package/dist/src/bundle/index.js +508 -0
  78. package/dist/src/bundle/manifest.d.ts +50 -0
  79. package/dist/src/bundle/manifest.js +435 -0
  80. package/dist/src/bundle/runtime.d.ts +26 -0
  81. package/dist/src/bundle/runtime.js +64 -0
  82. package/dist/src/bundle/tar.d.ts +62 -0
  83. package/dist/src/bundle/tar.js +238 -0
  84. package/dist/src/bundle/types.d.ts +105 -0
  85. package/dist/src/bundle/types.js +21 -0
  86. package/dist/src/cli.d.ts +90 -20
  87. package/dist/src/cli.js +2407 -365
  88. package/dist/src/credentials.d.ts +4 -3
  89. package/dist/src/credentials.js +21 -19
  90. package/dist/src/crypto/allowed-signers.d.ts +68 -0
  91. package/dist/src/crypto/allowed-signers.js +307 -0
  92. package/dist/src/crypto/canonical.d.ts +8 -0
  93. package/dist/src/crypto/canonical.js +92 -0
  94. package/dist/src/crypto/chain.d.ts +65 -0
  95. package/dist/src/crypto/chain.js +377 -0
  96. package/dist/src/crypto/dsse.d.ts +209 -0
  97. package/dist/src/crypto/dsse.js +282 -0
  98. package/dist/src/crypto/enrollment.d.ts +78 -0
  99. package/dist/src/crypto/enrollment.js +186 -0
  100. package/dist/src/crypto/index.d.ts +48 -0
  101. package/dist/src/crypto/index.js +44 -0
  102. package/dist/src/crypto/keys.d.ts +258 -0
  103. package/dist/src/crypto/keys.js +908 -0
  104. package/dist/src/crypto/org-root.d.ts +33 -0
  105. package/dist/src/crypto/org-root.js +78 -0
  106. package/dist/src/crypto/origin-rules.d.ts +56 -0
  107. package/dist/src/crypto/origin-rules.js +143 -0
  108. package/dist/src/crypto/policy-floor.d.ts +98 -0
  109. package/dist/src/crypto/policy-floor.js +353 -0
  110. package/dist/src/crypto/records.d.ts +316 -0
  111. package/dist/src/crypto/records.js +157 -0
  112. package/dist/src/crypto/scope.d.ts +49 -0
  113. package/dist/src/crypto/scope.js +83 -0
  114. package/dist/src/crypto/ssh.d.ts +171 -0
  115. package/dist/src/crypto/ssh.js +396 -0
  116. package/dist/src/crypto/submission.d.ts +33 -0
  117. package/dist/src/crypto/submission.js +47 -0
  118. package/dist/src/crypto/trust-roots.d.ts +29 -0
  119. package/dist/src/crypto/trust-roots.js +39 -0
  120. package/dist/src/crypto/verify-consumed.d.ts +67 -0
  121. package/dist/src/crypto/verify-consumed.js +259 -0
  122. package/dist/src/crypto/verify-origin.d.ts +50 -0
  123. package/dist/src/crypto/verify-origin.js +151 -0
  124. package/dist/src/crypto/verify-publication.d.ts +60 -0
  125. package/dist/src/crypto/verify-publication.js +150 -0
  126. package/dist/src/defs.d.ts +24 -1
  127. package/dist/src/defs.js +145 -25
  128. package/dist/src/engine.d.ts +99 -3
  129. package/dist/src/engine.js +238 -34
  130. package/dist/src/factory.d.ts +16 -0
  131. package/dist/src/factory.js +16 -4
  132. package/dist/src/global-config.d.ts +59 -0
  133. package/dist/src/global-config.js +84 -0
  134. package/dist/src/hub.d.ts +75 -21
  135. package/dist/src/hub.js +123 -40
  136. package/dist/src/index.d.ts +17 -2
  137. package/dist/src/index.js +20 -2
  138. package/dist/src/install.d.ts +538 -0
  139. package/dist/src/install.js +1981 -0
  140. package/dist/src/lock.d.ts +15 -57
  141. package/dist/src/lock.js +251 -143
  142. package/dist/src/mcp/serve.d.ts +46 -22
  143. package/dist/src/mcp/serve.js +167 -44
  144. package/dist/src/mcp/server.js +12 -1
  145. package/dist/src/model.d.ts +15 -0
  146. package/dist/src/model.js +111 -1
  147. package/dist/src/order-resolver.d.ts +184 -0
  148. package/dist/src/order-resolver.js +252 -0
  149. package/dist/src/package-version.d.ts +10 -0
  150. package/dist/src/package-version.js +42 -0
  151. package/dist/src/paths.d.ts +14 -1
  152. package/dist/src/paths.js +18 -0
  153. package/dist/src/schemas/enrollment-grant.v1.schema.json +90 -0
  154. package/dist/src/schemas/index.d.ts +1416 -0
  155. package/dist/src/schemas/index.js +31 -0
  156. package/dist/src/schemas/order.v1.schema.json +106 -0
  157. package/dist/src/schemas/origin.v1.schema.json +68 -0
  158. package/dist/src/schemas/policy-floor.v1.schema.json +29 -0
  159. package/dist/src/schemas/publication.v1.schema.json +31 -0
  160. package/dist/src/schemas/revocation.v1.schema.json +39 -0
  161. package/dist/src/schemas/submission.v1.schema.json +61 -0
  162. package/dist/src/store/def-source.d.ts +52 -0
  163. package/dist/src/store/def-source.js +335 -0
  164. package/dist/src/store/index-file.d.ts +69 -0
  165. package/dist/src/store/index-file.js +151 -0
  166. package/dist/src/store/index.d.ts +27 -0
  167. package/dist/src/store/index.js +22 -0
  168. package/dist/src/store/ingestor.d.ts +43 -0
  169. package/dist/src/store/ingestor.js +211 -0
  170. package/dist/src/store/install.d.ts +228 -0
  171. package/dist/src/store/install.js +555 -0
  172. package/dist/src/store/instruction-source.d.ts +49 -0
  173. package/dist/src/store/instruction-source.js +298 -0
  174. package/dist/src/store/origin-evidence.d.ts +21 -0
  175. package/dist/src/store/origin-evidence.js +66 -0
  176. package/dist/src/store/pre-commit-verifier.d.ts +68 -0
  177. package/dist/src/store/pre-commit-verifier.js +418 -0
  178. package/dist/src/store/resolve.d.ts +138 -0
  179. package/dist/src/store/resolve.js +363 -0
  180. package/dist/src/store/types.d.ts +288 -0
  181. package/dist/src/store/types.js +356 -0
  182. package/dist/src/types.d.ts +45 -11
  183. package/dist/src/untar.d.ts +8 -23
  184. package/dist/src/untar.js +10 -136
  185. package/docs/agent-runner.md +86 -0
  186. package/docs/authoring.md +57 -6
  187. package/docs/bundles.md +250 -0
  188. package/docs/cli.md +1171 -97
  189. package/docs/crypto.md +816 -0
  190. package/docs/design.md +342 -20
  191. package/docs/embedding.md +132 -25
  192. package/docs/wire-contracts.md +380 -0
  193. package/package.json +6 -1
  194. package/plugins/claude-code/.claude-plugin/marketplace.json +14 -0
  195. package/plugins/claude-code/plugin/.claude-plugin/plugin.json +8 -0
  196. package/plugins/claude-code/plugin/.mcp.json +14 -0
  197. package/plugins/claude-code/plugin/hooks/hooks.json +26 -0
  198. package/plugins/claude-code/plugin/hooks/session-end.sh +40 -0
  199. package/plugins/claude-code/plugin/hooks/session-start.sh +52 -0
  200. package/plugins/claude-code/plugin/skills/author/SKILL.md +181 -0
  201. package/plugins/claude-code/plugin/skills/conduct/SKILL.md +106 -0
  202. package/plugins/claude-code/plugin/skills/shift/SKILL.md +105 -0
  203. package/plugins/codex/.agents/plugins/marketplace.json +21 -0
  204. package/plugins/codex/plugins/owenloop/.codex-plugin/plugin.json +7 -0
  205. package/plugins/codex/plugins/owenloop/.mcp.json +20 -0
  206. package/plugins/codex/plugins/owenloop/hooks/hooks.json +26 -0
  207. package/plugins/codex/plugins/owenloop/hooks/session-end.sh +40 -0
  208. package/plugins/codex/plugins/owenloop/hooks/session-start.sh +52 -0
  209. package/plugins/codex/plugins/owenloop/skills/author/SKILL.md +181 -0
  210. package/plugins/codex/plugins/owenloop/skills/conduct/SKILL.md +106 -0
  211. package/plugins/codex/plugins/owenloop/skills/shift/SKILL.md +105 -0
@@ -59,8 +59,10 @@
59
59
  import { existsSync } from 'node:fs';
60
60
  import { createLeaseLoop } from "../lease/loop.js";
61
61
  import { isResumeUnavailable } from "../harness/contract.js";
62
+ import { preflightStepPermissions } from "../harness/permissions.js";
62
63
  import { orderId } from "../harness/session-store.js";
63
64
  import { buildOwenloopMcp, renderBrief, renderRejection, renderReplayBrief, } from "./brief.js";
65
+ import { pickModel, } from "./model-policy.js";
64
66
  /** Default confirm-phase cadence: one `get_order` per second. */
65
67
  export const DEFAULT_CONFIRM_INTERVAL_MS = 1_000;
66
68
  /** Default confirm-phase bound: give the hub 15s to show the submit's outcome. */
@@ -68,6 +70,61 @@ export const DEFAULT_SUBMIT_GRACE_MS = 15_000;
68
70
  function errMsg(e) {
69
71
  return e instanceof Error ? e.message : String(e);
70
72
  }
73
+ function laneFromPacket(packet) {
74
+ const plan = packet.consumes?.['plan'];
75
+ if (plan === null || typeof plan !== 'object' || Array.isArray(plan))
76
+ return undefined;
77
+ const lane = plan['lane'];
78
+ return lane === 'express' || lane === 'standard' || lane === 'deep' ? lane : undefined;
79
+ }
80
+ function escalationFromPacket(packet, extensionKey) {
81
+ const extension = packet.x?.[extensionKey];
82
+ if (extension === null || typeof extension !== 'object' || Array.isArray(extension))
83
+ return undefined;
84
+ if (!('escalation' in extension))
85
+ return undefined;
86
+ const raw = extension['escalation'];
87
+ if (raw === null || typeof raw !== 'object' || Array.isArray(raw))
88
+ return undefined;
89
+ const bag = raw;
90
+ const model = typeof bag['model'] === 'string' && bag['model'] !== '' ? bag['model'] : undefined;
91
+ const attempts = typeof bag['attempts'] === 'number' && Number.isInteger(bag['attempts']) && bag['attempts'] > 0
92
+ ? bag['attempts']
93
+ : undefined;
94
+ return {
95
+ ...(model !== undefined ? { model } : {}),
96
+ ...(attempts !== undefined ? { attempts } : {}),
97
+ };
98
+ }
99
+ /**
100
+ * The reject depth driving retry escalation: the max across the step's owed
101
+ * outputs, with consult paths excluded.
102
+ *
103
+ * The exclusion matters. A consult artifact's rejects are the mentor handing
104
+ * advice back for another round, not a signal that this producer is stuck — and
105
+ * they ride a separate per-produce attempt budget for exactly that reason.
106
+ * Counting them would let one ordinary mentor round escalate the model on every
107
+ * later firing of the step, permanently, on a producer that was never failing.
108
+ */
109
+ function judgmentRejectsFromPacket(packet) {
110
+ let max = 0;
111
+ for (const owed of packet.owes) {
112
+ const path = String(owed.path ?? '');
113
+ if (path === 'consultRequest' || path.endsWith('Consult'))
114
+ continue;
115
+ const rejects = owed.judgmentRejects;
116
+ if (typeof rejects === 'number' && Number.isFinite(rejects) && rejects > max)
117
+ max = rejects;
118
+ }
119
+ return max;
120
+ }
121
+ function modelForPacket(packet, policy) {
122
+ if (packet.model === undefined)
123
+ return undefined;
124
+ if (policy === undefined)
125
+ return { model: packet.model };
126
+ return pickModel(packet.model, laneFromPacket(packet), judgmentRejectsFromPacket(packet), policy, undefined, escalationFromPacket(packet, policy.escalationExtensionKey));
127
+ }
71
128
  /**
72
129
  * Poll `get_order` at `intervalMs` for at most `graceMs`, answering ONE
73
130
  * question: did the hub see the agent's `submit`?
@@ -128,6 +185,8 @@ export function createAgentRunLoop(opts) {
128
185
  * `SessionRecord.deliveredReasonAt`. Carried forward from the prior record
129
186
  * when this firing delivered no new reasons, so it can never regress. */
130
187
  let deliveredReasonAt;
188
+ /** Captures a thrown safety-gate append from the synchronous `started` event. */
189
+ let activePersistenceFailure;
131
190
  let resolveOrder;
132
191
  const orderReady = new Promise((r) => {
133
192
  resolveOrder = r;
@@ -230,9 +289,17 @@ export function createAgentRunLoop(opts) {
230
289
  case 'started':
231
290
  sessionRef = e.ref;
232
291
  opts.err(`owenloop work agent-run: session started for ${order} (harness '${e.ref.harness}')`);
233
- // Persist on the EVENT, not on the start() resolve, so a mid-turn crash
234
- // still leaves a resumable record behind (the contract requires this).
235
- record('active');
292
+ // This synchronous event is the cold-start gate. The adapter must not
293
+ // begin provider work until the callback returns. A thrown durable append
294
+ // therefore aborts the turn before delivery and is handled separately
295
+ // from an ordinary harness failure below.
296
+ try {
297
+ record('active');
298
+ }
299
+ catch (error) {
300
+ activePersistenceFailure = error;
301
+ throw error;
302
+ }
236
303
  return;
237
304
  case 'progress':
238
305
  opts.err(`owenloop work agent-run: ${e.text}`);
@@ -267,11 +334,39 @@ export function createAgentRunLoop(opts) {
267
334
  ]);
268
335
  if (first.t === 'lease')
269
336
  return mapNoHold(first.o);
270
- const packet = first.res.order;
271
- if (packet === null || packet.executor === 'command' || (typeof packet.command === 'string' && packet.command !== '')) {
337
+ let packet = first.res.order;
338
+ if (packet === null || packet.worker === 'command') {
272
339
  opts.err(`owenloop work agent-run: ${order} is not an agent order (misroute) — releasing`);
273
340
  return releaseWith('misroute', 'misroute');
274
341
  }
342
+ // Consume-side verification is the prompt boundary. Do this before loading
343
+ // or rendering any step brief: `owes[].reasons` is dynamic text supplied by
344
+ // the transport, and an unverified rejection thread must never reach a
345
+ // provider session. The same whole-order gate also protects `consumes`.
346
+ const hasConsumedData = Object.keys(packet.consumes).length > 0
347
+ || packet.owes.some((owed) => owed.reasons.length > 0 || owed.proof !== undefined);
348
+ if (hasConsumedData) {
349
+ if (opts.consumedVerifier === undefined) {
350
+ const detail = `consume-side verifier is not configured; dynamic values cannot be admitted to an agent prompt`;
351
+ opts.err(`owenloop work agent-run: consumed artifact refusal (prerequisite) for ${order}: ${detail}`);
352
+ return releaseWith('unverified-consumed', 'unverified-consumed');
353
+ }
354
+ try {
355
+ const checked = await opts.consumedVerifier(packet, { hardRule: false });
356
+ if (!checked.ok) {
357
+ opts.err(`owenloop work agent-run: ${checked.reason} — releasing ${order}`);
358
+ return releaseWith('unverified-consumed', 'unverified-consumed');
359
+ }
360
+ packet = checked.order;
361
+ for (const warning of checked.warnings)
362
+ opts.err(warning);
363
+ }
364
+ catch (error) {
365
+ const detail = error instanceof Error ? error.message : String(error);
366
+ opts.err(`owenloop work agent-run: consumed artifact refusal (prerequisite) for ${order}: ${detail} — releasing`);
367
+ return releaseWith('unverified-consumed', 'unverified-consumed');
368
+ }
369
+ }
275
370
  stepName = packet.step;
276
371
  recordCwd = packet.workdir ?? opts.cwd;
277
372
  // The step spec. No bundle / no spec ⇒ we cannot brief anybody; release so
@@ -315,6 +410,20 @@ export function createAgentRunLoop(opts) {
315
410
  // time, so this loop never looks inside an extension bag and never has a bag
316
411
  // key — vendor-keyed lookup does not exist in neutral code any more.
317
412
  const permissions = step.permissions;
413
+ // Mandatory final-boundary preflight. Common checks run first, followed by
414
+ // the selected adapter's exact capability check. A refusal starts neither a
415
+ // cold session nor a resumed provider process; the held claim is released.
416
+ const policyIssues = [
417
+ ...preflightStepPermissions(permissions),
418
+ ...active.preflight(permissions),
419
+ ];
420
+ if (policyIssues.length > 0) {
421
+ for (const issue of policyIssues) {
422
+ opts.err(`owenloop work agent-run: harness policy refusal for ${order} on '${resolution.id}'` +
423
+ `${issue.field !== undefined ? ` (${issue.field})` : ''}: ${issue.message}`);
424
+ }
425
+ return releaseWith('incompatible-harness-policy', 'incompatible-harness-policy');
426
+ }
318
427
  // ---- PHASE 4: resume or cold replay? -----------------------------------
319
428
  //
320
429
  // The delta first, because "is there anything new to say?" is one of the
@@ -376,11 +485,12 @@ export function createAgentRunLoop(opts) {
376
485
  deliveredReasonAt = delta.deliveredReasonAt;
377
486
  }
378
487
  const owenloopMcp = buildOwenloopMcp(spec);
488
+ const resolvedModel = modelForPacket(packet, opts.modelPolicy);
379
489
  const deliverArgs = {
380
490
  cwd: recordCwd,
381
491
  owenloopMcp,
382
492
  permissions,
383
- ...(packet.model !== undefined ? { model: packet.model } : {}),
493
+ ...(resolvedModel ?? {}),
384
494
  };
385
495
  /** Built lazily: a cold start after a refused resume needs a FRESH one. */
386
496
  const coldArgs = () => ({
@@ -395,12 +505,13 @@ export function createAgentRunLoop(opts) {
395
505
  cwd: recordCwd,
396
506
  owenloopMcp,
397
507
  permissions,
398
- ...(packet.model !== undefined ? { model: packet.model } : {}),
508
+ ...(resolvedModel ?? {}),
399
509
  });
400
510
  const path = resumable ? 'resume' : delta.message !== '' ? 'cold replay' : 'cold start';
401
511
  opts.out(`owenloop work agent-run: hosting ${order} (step '${packet.step}', harness '${resolution.id}', attempt ${attempt}, ${path})`);
402
512
  /** Cold-start this firing. Shared by the ordinary path and the fallback. */
403
513
  async function coldStart() {
514
+ activePersistenceFailure = undefined;
404
515
  try {
405
516
  const ref = await active.start(coldArgs(), onEvent);
406
517
  sessionRef = ref;
@@ -413,6 +524,10 @@ export function createAgentRunLoop(opts) {
413
524
  return { t: 'turn' };
414
525
  }
415
526
  catch (e) {
527
+ if (activePersistenceFailure !== undefined) {
528
+ await teardown();
529
+ return { t: 'turn', persistenceFailure: activePersistenceFailure };
530
+ }
416
531
  return { t: 'turn', failure: e };
417
532
  }
418
533
  }
@@ -434,8 +549,15 @@ export function createAgentRunLoop(opts) {
434
549
  opts.err(`owenloop work agent-run: resuming session ${prev.token} for ${order} with ${delta.count} new rejection reason${delta.count === 1 ? '' : 's'} (no brief re-sent)`);
435
550
  // Deliberately written with the PRIOR watermark: nothing has been delivered
436
551
  // yet, and this row is what the next firing reads if this turn never
437
- // completes. See `markDelivered`.
438
- record('active');
552
+ // completes. See `markDelivered`. This durable write is also the resume
553
+ // delivery gate; failure stops the old provider session without delivery.
554
+ try {
555
+ record('active');
556
+ }
557
+ catch (error) {
558
+ await teardown();
559
+ return { t: 'turn', persistenceFailure: error };
560
+ }
439
561
  try {
440
562
  await active.deliver(sessionRef, delta.message, deliverArgs, onEvent);
441
563
  markDelivered();
@@ -473,6 +595,11 @@ export function createAgentRunLoop(opts) {
473
595
  opts.err(`owenloop work agent-run: lease ${raced.o} mid-turn — tore the session down, no outcome observed`);
474
596
  return mapLeaseDuringTurn(raced.o);
475
597
  }
598
+ if (raced.persistenceFailure !== undefined) {
599
+ opts.err(`owenloop work agent-run: durable active-session persistence failed before provider delivery for ${order}: ` +
600
+ `${errMsg(raced.persistenceFailure)} — releasing`);
601
+ return releaseWith('session-store-failed', 'session-store-failed');
602
+ }
476
603
  // TURN END — NOT task end. Log the failure shape for humans, then confirm.
477
604
  if (raced.failure !== undefined) {
478
605
  const why = isResumeUnavailable(raced.failure)
@@ -0,0 +1,49 @@
1
+ /** Quality-tier resolution and retry escalation for agent orders. */
2
+ /** Shipped quality tiers. A settings tierMap may override any entry. */
3
+ export declare const DEFAULT_TIER_MAP: {
4
+ readonly fast: "haiku";
5
+ readonly standard: "sonnet";
6
+ readonly strong: "opus";
7
+ readonly strongest: "fable";
8
+ };
9
+ /** Reasoning rungs accepted by the neutral start contract. */
10
+ export declare const EFFORT_LADDER: readonly ["low", "medium", "high", "xhigh", "max"];
11
+ export type ModelLane = 'express' | 'standard' | 'deep';
12
+ export interface ModelEscalation {
13
+ model?: string;
14
+ attempts?: number;
15
+ }
16
+ export interface ModelPolicy {
17
+ /** Resolved tier names; this map is merged with DEFAULT_TIER_MAP by createModelPolicy. */
18
+ tierMap: Readonly<Record<string, string>>;
19
+ /** Reject count at which the default policy escalates. */
20
+ escalateAt: number;
21
+ /** Extension namespace containing the authored escalation object. */
22
+ escalationExtensionKey: string;
23
+ }
24
+ export interface PickModelResult {
25
+ model: string;
26
+ effort?: string;
27
+ }
28
+ export interface ModelPolicyOptions {
29
+ tierMap?: Record<string, string>;
30
+ escalateAt?: number;
31
+ escalationExtensionKey?: string;
32
+ }
33
+ export declare const DEFAULT_MODEL_POLICY: ModelPolicy;
34
+ /** Build a normalized policy from optional machine-local settings. */
35
+ export declare function createModelPolicy(options?: ModelPolicyOptions): ModelPolicy;
36
+ /** Resolve a tier name, passing through a literal model id unchanged. */
37
+ export declare function resolveModelTier(model: string, tierMap?: Readonly<Record<string, string>>): string;
38
+ /** Split a trailing positive integer effort suffix from a model string. */
39
+ export declare function parseModelEffort(raw: string): {
40
+ modelPart: string;
41
+ effortIndex?: number;
42
+ };
43
+ /**
44
+ * Pick the model and effort for one agent order.
45
+ *
46
+ * The fourth argument accepts a ModelPolicy. A numeric value is also accepted as
47
+ * the reject threshold for compatibility with the reference function's shape.
48
+ */
49
+ export declare function pickModel(stepYamlModel: string, lane: ModelLane | undefined, judgmentRejects: number, policyOrAt?: ModelPolicy | number, override?: string, escalation?: ModelEscalation): PickModelResult;
@@ -0,0 +1,138 @@
1
+ /** Quality-tier resolution and retry escalation for agent orders. */
2
+ /** Shipped quality tiers. A settings tierMap may override any entry. */
3
+ export const DEFAULT_TIER_MAP = {
4
+ fast: 'haiku',
5
+ standard: 'sonnet',
6
+ strong: 'opus',
7
+ strongest: 'fable',
8
+ };
9
+ /** Reasoning rungs accepted by the neutral start contract. */
10
+ export const EFFORT_LADDER = ['low', 'medium', 'high', 'xhigh', 'max'];
11
+ const TIER_INDEX = {
12
+ fast: 0,
13
+ standard: 1,
14
+ strong: 2,
15
+ strongest: 3,
16
+ };
17
+ /** Tier index -> tier name, so a clamp can resolve to an id at the very end. */
18
+ const TIER_NAMES = ['fast', 'standard', 'strong', 'strongest'];
19
+ export const DEFAULT_MODEL_POLICY = {
20
+ tierMap: DEFAULT_TIER_MAP,
21
+ escalateAt: 3,
22
+ escalationExtensionKey: 'delivery',
23
+ };
24
+ /** Build a normalized policy from optional machine-local settings. */
25
+ export function createModelPolicy(options = {}) {
26
+ return {
27
+ tierMap: { ...DEFAULT_TIER_MAP, ...(options.tierMap ?? {}) },
28
+ escalateAt: options.escalateAt ?? DEFAULT_MODEL_POLICY.escalateAt,
29
+ escalationExtensionKey: options.escalationExtensionKey ?? DEFAULT_MODEL_POLICY.escalationExtensionKey,
30
+ };
31
+ }
32
+ /** Resolve a tier name, passing through a literal model id unchanged. */
33
+ export function resolveModelTier(model, tierMap = DEFAULT_TIER_MAP) {
34
+ return tierMap[model] ?? model;
35
+ }
36
+ /** Split a trailing positive integer effort suffix from a model string. */
37
+ export function parseModelEffort(raw) {
38
+ const separator = raw.lastIndexOf(':');
39
+ if (separator === -1)
40
+ return { modelPart: raw };
41
+ const tail = raw.slice(separator + 1);
42
+ if (!/^[1-9]\d*$/.test(tail))
43
+ return { modelPart: raw };
44
+ return { modelPart: raw.slice(0, separator), effortIndex: Number(tail) };
45
+ }
46
+ function tierForInput(modelPart) {
47
+ return TIER_INDEX[modelPart];
48
+ }
49
+ /**
50
+ * Apply the lane to a tier index, in tier space.
51
+ *
52
+ * express caps at `standard` and deep floors at `strong`, with one exception:
53
+ * the express cap never touches the TOP tier. A step authored at the top tier
54
+ * is there because the judgment it makes is hard, so the lane's cost heuristic
55
+ * must not downgrade it — the lane scales cost, it does not overrule an
56
+ * explicit escalation of quality. The reference implementation gets this for
57
+ * free by leaving the top tier out of its rank table; ranking in tier space
58
+ * gives the top tier a rank, so the exclusion has to be stated here.
59
+ */
60
+ function clampTierForLane(tier, lane) {
61
+ if (lane === 'express' && tier > TIER_INDEX['standard'] && tier !== TIER_INDEX['strongest']) {
62
+ return TIER_INDEX['standard'];
63
+ }
64
+ if (lane === 'deep' && tier < TIER_INDEX['strong'])
65
+ return TIER_INDEX['strong'];
66
+ return tier;
67
+ }
68
+ /** Resolve a tier index back to a concrete model id through the policy map. */
69
+ function modelForTier(tier, tierMap) {
70
+ const name = TIER_NAMES[tier];
71
+ return tierMap[name] ?? name;
72
+ }
73
+ function effortName(index) {
74
+ const clamped = Math.min(Math.max(index, 1), EFFORT_LADDER.length) - 1;
75
+ return EFFORT_LADDER[clamped];
76
+ }
77
+ function withEffort(model, effortIndex) {
78
+ return effortIndex === undefined ? { model } : { model, effort: effortName(effortIndex) };
79
+ }
80
+ function normalizePolicy(policyOrAt) {
81
+ if (typeof policyOrAt === 'number') {
82
+ return createModelPolicy({ escalateAt: policyOrAt });
83
+ }
84
+ if (policyOrAt === undefined)
85
+ return DEFAULT_MODEL_POLICY;
86
+ return createModelPolicy({
87
+ tierMap: { ...policyOrAt.tierMap },
88
+ escalateAt: policyOrAt.escalateAt,
89
+ escalationExtensionKey: policyOrAt.escalationExtensionKey,
90
+ });
91
+ }
92
+ /**
93
+ * Pick the model and effort for one agent order.
94
+ *
95
+ * The fourth argument accepts a ModelPolicy. A numeric value is also accepted as
96
+ * the reject threshold for compatibility with the reference function's shape.
97
+ */
98
+ export function pickModel(stepYamlModel, lane, judgmentRejects, policyOrAt = DEFAULT_MODEL_POLICY, override, escalation) {
99
+ const policy = normalizePolicy(policyOrAt);
100
+ const pinned = typeof override === 'string' && override !== '';
101
+ const rawInput = pinned ? override : stepYamlModel;
102
+ const { modelPart, effortIndex } = parseModelEffort(rawInput);
103
+ let model = resolveModelTier(modelPart, policy.tierMap);
104
+ const inputTier = tierForInput(modelPart);
105
+ if (escalation !== undefined) {
106
+ const attempts = escalation.attempts ?? policy.escalateAt;
107
+ if (judgmentRejects >= attempts) {
108
+ const rung2Raw = typeof escalation.model === 'string' && escalation.model !== '' ? escalation.model : 'strong';
109
+ const { modelPart: rung2Part, effortIndex: rung2Effort } = parseModelEffort(rung2Raw);
110
+ return withEffort(resolveModelTier(rung2Part, policy.tierMap), rung2Effort);
111
+ }
112
+ if (inputTier !== undefined && !pinned) {
113
+ model = modelForTier(clampTierForLane(inputTier, lane), policy.tierMap);
114
+ }
115
+ return withEffort(model, effortIndex);
116
+ }
117
+ const escalate = judgmentRejects >= policy.escalateAt;
118
+ const nextEffort = effortIndex === undefined ? undefined : escalate ? effortIndex + 1 : effortIndex;
119
+ // The lane adjusts the BASE. Track the resulting tier, because escalation
120
+ // below is decided on the CLAMPED tier, not the authored one.
121
+ let currentTier = inputTier;
122
+ if (inputTier !== undefined && !pinned) {
123
+ currentTier = clampTierForLane(inputTier, lane);
124
+ model = modelForTier(currentTier, policy.tierMap);
125
+ }
126
+ // Model escalation fires when there was no effort suffix to bump instead, or
127
+ // once the reject count reaches twice the threshold. It is upward-only and
128
+ // ALWAYS wins over an express cap: a producer stuck on repeated rejects needs
129
+ // more capability more than the lane needs the cheaper tier. Gating this on
130
+ // the POST-clamp tier is what makes escalation beat the cap — gating it on
131
+ // the authored tier would let an express-clamped `strong` step sit at the
132
+ // standard tier forever, however many rejects accumulate.
133
+ const modelEscalates = escalate && (effortIndex === undefined || judgmentRejects >= policy.escalateAt * 2);
134
+ if (modelEscalates && currentTier !== undefined && currentTier < TIER_INDEX['strong']) {
135
+ model = policy.tierMap['strong'] ?? 'strong';
136
+ }
137
+ return withEffort(model, nextEffort);
138
+ }
@@ -30,11 +30,13 @@ export declare function readLatestBundle(cacheDir: string, name: string): Cached
30
30
  * absent, unreadable, or not valid JSON. Layout mirrors `writeBundle`:
31
31
  * `<cacheDir>/bundles/<name>/<hash>/steps/<step>.json`.
32
32
  *
33
- * Never throws — a missing spec is a normal case the caller reports and moves
34
- * past (a command step has no spec by design, and a hash dir prepared before
35
- * Phase 5 has none at all). There is deliberately NO fallback to the legacy
36
- * `templates/<step>.md`: silently running a stale compiled template would be
37
- * worse than an honest "re-run `owenloop work prepare`".
33
+ * A missing or corrupt spec returns `null` — a command step has no spec by
34
+ * design, and a hash dir prepared before Phase 5 has none at all. The one
35
+ * deliberate exception is a structurally valid old normalized spec that leaves
36
+ * `filesystem` or `network` buried under `permissions.extensions`: that cache
37
+ * throws with an explicit `owenloop work prepare` repair because returning it
38
+ * would silently discard an authored restriction. There is no fallback to the
39
+ * legacy `templates/<step>.md`.
38
40
  */
39
41
  export declare function readStepSpec(cacheDir: string, name: string, hash: string, step: string): NormalizedStepSpec | null;
40
42
  /**
@@ -147,16 +147,20 @@ export function readLatestBundle(cacheDir, name) {
147
147
  }
148
148
  return best;
149
149
  }
150
+ class StaleStepSpecError extends Error {
151
+ }
150
152
  /**
151
153
  * Read the normalized step spec for `(name, hash, step)`, or `null` when it is
152
154
  * absent, unreadable, or not valid JSON. Layout mirrors `writeBundle`:
153
155
  * `<cacheDir>/bundles/<name>/<hash>/steps/<step>.json`.
154
156
  *
155
- * Never throws — a missing spec is a normal case the caller reports and moves
156
- * past (a command step has no spec by design, and a hash dir prepared before
157
- * Phase 5 has none at all). There is deliberately NO fallback to the legacy
158
- * `templates/<step>.md`: silently running a stale compiled template would be
159
- * worse than an honest "re-run `owenloop work prepare`".
157
+ * A missing or corrupt spec returns `null` — a command step has no spec by
158
+ * design, and a hash dir prepared before Phase 5 has none at all. The one
159
+ * deliberate exception is a structurally valid old normalized spec that leaves
160
+ * `filesystem` or `network` buried under `permissions.extensions`: that cache
161
+ * throws with an explicit `owenloop work prepare` repair because returning it
162
+ * would silently discard an authored restriction. There is no fallback to the
163
+ * legacy `templates/<step>.md`.
160
164
  */
161
165
  export function readStepSpec(cacheDir, name, hash, step) {
162
166
  try {
@@ -172,9 +176,19 @@ export function readStepSpec(cacheDir, name, hash, step) {
172
176
  const parsed = JSON.parse(readFileSync(file, 'utf8'));
173
177
  if (typeof parsed?.step !== 'string' || typeof parsed?.brief !== 'string')
174
178
  return null;
179
+ const extensions = parsed.permissions?.extensions;
180
+ if (extensions !== null && typeof extensions === 'object' && !Array.isArray(extensions)) {
181
+ const stale = ['filesystem', 'network'].filter((key) => key in extensions);
182
+ if (stale.length > 0) {
183
+ throw new StaleStepSpecError(`cached step '${step}' has restriction(s) ${stale.join(', ')} buried in permissions.extensions; ` +
184
+ 'rerun `owenloop work prepare`');
185
+ }
186
+ }
175
187
  return parsed;
176
188
  }
177
- catch {
189
+ catch (error) {
190
+ if (error instanceof StaleStepSpecError)
191
+ throw error;
178
192
  return null;
179
193
  }
180
194
  }
@@ -50,11 +50,13 @@ export interface HarnessCarrier {
50
50
  * forward compat for the day the grammar promotes the field, and it means the
51
51
  * promotion needs no owenloop change.
52
52
  *
53
- * Validation is loose but HONEST: a non-map `x.harness`, a non-string
54
- * `x.harness.id`, a non-string top-level `harness`, or a surviving legacy
55
- * `x.claude-code` bag is a def error naming the step, never a silent drop.
56
- * Absent keys are simply absent — a step with no harness declaration is
57
- * completely normal.
53
+ * Validation is loose but HONEST: a non-map `x.harness`, a non-string or
54
+ * blank `x.harness.id`, a non-string or blank top-level `harness`, or a
55
+ * surviving legacy `x.claude-code` bag is a def error naming the step, never a
56
+ * silent drop. Absent keys are simply absent — a step with no harness
57
+ * declaration is completely normal. Blank is not absent: accepting an explicit
58
+ * empty id would let adapter resolution treat an invalid declaration as though
59
+ * the author had selected the default harness.
58
60
  *
59
61
  * `label` names the def, `stepName` the step, so an error in a pinned child is
60
62
  * attributable. Shared with `owenloop work lint`, which parses raw YAML defs.
@@ -20,6 +20,7 @@
20
20
  * a broken closure fails at fetch, never mid-run — see `validateFetchedDef`.
21
21
  */
22
22
  import { HubError } from "../hub/types.js";
23
+ import { validateHarnessOptions } from "../harness/permissions.js";
23
24
  /** A step is an agent step (spec candidate) when it is not a command/calls step. */
24
25
  function isAgentStep(s) {
25
26
  return s.executor !== 'command' && s.calls === undefined;
@@ -61,11 +62,13 @@ function isPlainMap(v) {
61
62
  * forward compat for the day the grammar promotes the field, and it means the
62
63
  * promotion needs no owenloop change.
63
64
  *
64
- * Validation is loose but HONEST: a non-map `x.harness`, a non-string
65
- * `x.harness.id`, a non-string top-level `harness`, or a surviving legacy
66
- * `x.claude-code` bag is a def error naming the step, never a silent drop.
67
- * Absent keys are simply absent — a step with no harness declaration is
68
- * completely normal.
65
+ * Validation is loose but HONEST: a non-map `x.harness`, a non-string or
66
+ * blank `x.harness.id`, a non-string or blank top-level `harness`, or a
67
+ * surviving legacy `x.claude-code` bag is a def error naming the step, never a
68
+ * silent drop. Absent keys are simply absent — a step with no harness
69
+ * declaration is completely normal. Blank is not absent: accepting an explicit
70
+ * empty id would let adapter resolution treat an invalid declaration as though
71
+ * the author had selected the default harness.
69
72
  *
70
73
  * `label` names the def, `stepName` the step, so an error in a pinned child is
71
74
  * attributable. Shared with `owenloop work lint`, which parses raw YAML defs.
@@ -73,8 +76,13 @@ function isPlainMap(v) {
73
76
  export function parseHarnessCarrier(s, label, stepName) {
74
77
  const where = `hub workflow '${label}': step '${stepName}'`;
75
78
  const topLevel = s['harness'];
76
- if (topLevel !== undefined && typeof topLevel !== 'string') {
77
- throw new Error(`${where} has a non-string harness`);
79
+ if (topLevel !== undefined) {
80
+ if (typeof topLevel !== 'string') {
81
+ throw new Error(`${where} has a non-string harness`);
82
+ }
83
+ if (topLevel.trim() === '') {
84
+ throw new Error(`${where} has an empty or whitespace-only harness`);
85
+ }
78
86
  }
79
87
  const x = s['x'];
80
88
  // A def still carrying the OLD bag key fails HARD here, before anything else
@@ -106,6 +114,9 @@ export function parseHarnessCarrier(s, label, stepName) {
106
114
  if (typeof v !== 'string') {
107
115
  throw new Error(`${where} has a non-string x.${HARNESS_BAG_KEY}.id`);
108
116
  }
117
+ if (v.trim() === '') {
118
+ throw new Error(`${where} has an empty or whitespace-only x.${HARNESS_BAG_KEY}.id`);
119
+ }
109
120
  bagId = v;
110
121
  continue;
111
122
  }
@@ -154,6 +165,15 @@ function validateDefEnvelope(data, label) {
154
165
  // still carried through verbatim — `x.owenloop` is a separate live
155
166
  // namespace that `src/shift/routing.ts` reads.
156
167
  const carrier = parseHarnessCarrier(s, label, s['name']);
168
+ if (carrier.harnessOptions !== undefined) {
169
+ const errors = validateHarnessOptions(carrier.harnessOptions, s['name'])
170
+ .filter((finding) => finding.severity === 'error');
171
+ if (errors.length > 0) {
172
+ throw new Error(errors
173
+ .map((finding) => `hub workflow '${label}': step '${finding.step}' x.harness.${finding.field ?? '<bag>'}: ${finding.message}`)
174
+ .join('; '));
175
+ }
176
+ }
157
177
  return {
158
178
  name: s['name'],
159
179
  consumes: Array.isArray(s['consumes']) ? s['consumes'] : undefined,
@@ -123,9 +123,10 @@ export interface FetchedBundle extends FetchedDef {
123
123
  children?: Record<string, FetchedDef>;
124
124
  }
125
125
  /**
126
- * The normalized per-step spec `prepare` writes to `steps/<step>.json`, one file
127
- * per dispatchable agent step (D4). It replaces the legacy `templates/<step>.md`
128
- * compiled frontmatter entirely.
126
+ * The prepare cache may persist routing metadata for `steps/<step>.json`, but
127
+ * cached instruction text is not authoritative for execution. Runtime workers
128
+ * resolve the verified step body from the local workflow store. The cache
129
+ * replaces the legacy `templates/<step>.md` compiled frontmatter entirely.
129
130
  *
130
131
  * What is DELIBERATELY not in here: the four substitution tokens
131
132
  * (`ORDER_TOKEN`, `ORIGIN_TOKEN`, `ACCOUNT_TOKEN`, `SHIFT_TOKEN`) and the
@@ -138,7 +139,10 @@ export interface FetchedBundle extends FetchedDef {
138
139
  *
139
140
  * There is no format version and no migration. A hash dir cached before Phase 5
140
141
  * simply has no `steps/*.json`; `readStepSpec` fails honestly and the fix is to
141
- * re-run `owenloop work prepare`.
142
+ * re-run `owenloop work prepare`. A cache normalized before filesystem/network
143
+ * became neutral fields may carry those restrictions under
144
+ * `permissions.extensions`; runtime preflight refuses that shape rather than
145
+ * ignoring the restriction and tells the operator to rerun prepare.
142
146
  */
143
147
  export interface NormalizedStepSpec {
144
148
  /** The step name — the same string that names the file. */
@@ -0,0 +1,45 @@
1
+ /**
2
+ * Driver-side binding for consume-side artifact verification.
3
+ *
4
+ * This module resolves local trust material from injected environment state and
5
+ * gates a complete order before the order reaches an agent prompt or command
6
+ * execution. A failed path refuses the whole order; the gate never removes only
7
+ * the offending value and continues with a partial packet.
8
+ */
9
+ import type { DefPolicy } from '../../../src/crypto/verify-publication.ts';
10
+ import type { PolicyFloor } from '../../../src/crypto/records.ts';
11
+ import { type VerifyConsumedOptions } from '../../../src/crypto/verify-consumed.ts';
12
+ import type { OrderPacket } from './hub/types.ts';
13
+ export interface ConsumedGateResult {
14
+ ok: true;
15
+ order: OrderPacket;
16
+ warnings: string[];
17
+ }
18
+ export interface ConsumedGateRefusal {
19
+ ok: false;
20
+ reason: string;
21
+ }
22
+ export interface CreateConsumedVerifierArgs {
23
+ env: Record<string, string | undefined>;
24
+ now: () => number;
25
+ artifactPolicy?: DefPolicy;
26
+ policyFloor?: PolicyFloor;
27
+ /** Explicit producer scope demand; the default is no additional demand. */
28
+ demand?: {
29
+ pool?: string;
30
+ label?: string;
31
+ namespace?: string;
32
+ };
33
+ /** Cryptographic seam for hermetic tests and alternate signer backends. */
34
+ signerForPrincipal?: VerifyConsumedOptions['signerForPrincipal'];
35
+ namespace?: string;
36
+ maxChainDepth?: number;
37
+ /** Optional warning sink; the returned warnings remain authoritative for callers. */
38
+ warn?: (line: string) => void;
39
+ }
40
+ export type ConsumedVerifier = (order: OrderPacket, opts: {
41
+ hardRule: boolean;
42
+ }) => Promise<ConsumedGateResult | ConsumedGateRefusal>;
43
+ /** Create a verifier bound to one injected local environment and clock. */
44
+ export declare function createConsumedVerifier(args: CreateConsumedVerifierArgs): ConsumedVerifier;
45
+ export declare function resetConsumedVerifierWarningsForTests(): void;