owenloop 0.5.0 → 0.5.2

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 (229) hide show
  1. package/CHANGELOG.md +67 -0
  2. package/README.md +144 -35
  3. package/bin/owenloop.mjs +49 -1
  4. package/dist/packages/work/src/agent/brief.d.ts +29 -4
  5. package/dist/packages/work/src/agent/brief.js +49 -4
  6. package/dist/packages/work/src/agent/capability-model.d.ts +123 -0
  7. package/dist/packages/work/src/agent/capability-model.js +148 -0
  8. package/dist/packages/work/src/agent/loop.d.ts +56 -7
  9. package/dist/packages/work/src/agent/loop.js +166 -9
  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 +29 -1
  20. package/dist/packages/work/src/exec/loop.js +313 -35
  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 +84 -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 +30 -10
  38. package/dist/packages/work/src/harness/session-store.js +317 -89
  39. package/dist/packages/work/src/hold/mcp.d.ts +25 -5
  40. package/dist/packages/work/src/hold/mcp.js +134 -12
  41. package/dist/packages/work/src/hub/client.d.ts +8 -1
  42. package/dist/packages/work/src/hub/client.js +15 -1
  43. package/dist/packages/work/src/hub/types.d.ts +137 -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 +115 -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 +6 -0
  53. package/dist/packages/work/src/roles/hold.js +83 -13
  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 +19 -2
  57. package/dist/packages/work/src/roles/shift.d.ts +1 -0
  58. package/dist/packages/work/src/roles/shift.js +36 -2
  59. package/dist/packages/work/src/settings/settings.d.ts +70 -1
  60. package/dist/packages/work/src/settings/settings.js +90 -4
  61. package/dist/packages/work/src/shift/logretention.d.ts +253 -0
  62. package/dist/packages/work/src/shift/logretention.js +407 -0
  63. package/dist/packages/work/src/shift/logsink.d.ts +14 -0
  64. package/dist/packages/work/src/shift/logsink.js +98 -0
  65. package/dist/packages/work/src/shift/loop.d.ts +32 -4
  66. package/dist/packages/work/src/shift/loop.js +687 -166
  67. package/dist/packages/work/src/shift/protocol.d.ts +128 -1
  68. package/dist/packages/work/src/shift/protocol.js +14 -0
  69. package/dist/packages/work/src/shift/runtime.d.ts +16 -0
  70. package/dist/packages/work/src/shift/runtime.js +291 -5
  71. package/dist/packages/work/src/shift/server.d.ts +13 -0
  72. package/dist/packages/work/src/shift/server.js +61 -36
  73. package/dist/packages/work/src/shift/spawn.d.ts +115 -19
  74. package/dist/packages/work/src/shift/spawn.js +234 -30
  75. package/dist/packages/work/src/shift/state.d.ts +76 -49
  76. package/dist/packages/work/src/shift/state.js +350 -103
  77. package/dist/packages/work/src/shift/truncate.d.ts +35 -0
  78. package/dist/packages/work/src/shift/truncate.js +73 -0
  79. package/dist/packages/work/src/submit-proof.d.ts +61 -0
  80. package/dist/packages/work/src/submit-proof.js +119 -0
  81. package/dist/packages/work/src/submit-value.d.ts +48 -0
  82. package/dist/packages/work/src/submit-value.js +118 -0
  83. package/dist/packages/work/src/usage.d.ts +1 -1
  84. package/dist/packages/work/src/usage.js +11 -0
  85. package/dist/src/add.d.ts +64 -259
  86. package/dist/src/add.js +81 -615
  87. package/dist/src/archive.d.ts +97 -0
  88. package/dist/src/archive.js +591 -0
  89. package/dist/src/bundle/index.d.ts +64 -0
  90. package/dist/src/bundle/index.js +508 -0
  91. package/dist/src/bundle/manifest.d.ts +50 -0
  92. package/dist/src/bundle/manifest.js +435 -0
  93. package/dist/src/bundle/runtime.d.ts +26 -0
  94. package/dist/src/bundle/runtime.js +64 -0
  95. package/dist/src/bundle/tar.d.ts +62 -0
  96. package/dist/src/bundle/tar.js +238 -0
  97. package/dist/src/bundle/types.d.ts +105 -0
  98. package/dist/src/bundle/types.js +21 -0
  99. package/dist/src/capabilities.d.ts +93 -0
  100. package/dist/src/capabilities.js +101 -0
  101. package/dist/src/cli.d.ts +90 -20
  102. package/dist/src/cli.js +2421 -374
  103. package/dist/src/credentials.d.ts +4 -3
  104. package/dist/src/credentials.js +21 -19
  105. package/dist/src/crypto/allowed-signers.d.ts +68 -0
  106. package/dist/src/crypto/allowed-signers.js +307 -0
  107. package/dist/src/crypto/canonical.d.ts +8 -0
  108. package/dist/src/crypto/canonical.js +92 -0
  109. package/dist/src/crypto/chain.d.ts +65 -0
  110. package/dist/src/crypto/chain.js +377 -0
  111. package/dist/src/crypto/dsse.d.ts +209 -0
  112. package/dist/src/crypto/dsse.js +282 -0
  113. package/dist/src/crypto/enrollment.d.ts +78 -0
  114. package/dist/src/crypto/enrollment.js +186 -0
  115. package/dist/src/crypto/index.d.ts +48 -0
  116. package/dist/src/crypto/index.js +44 -0
  117. package/dist/src/crypto/keys.d.ts +258 -0
  118. package/dist/src/crypto/keys.js +908 -0
  119. package/dist/src/crypto/org-root.d.ts +33 -0
  120. package/dist/src/crypto/org-root.js +78 -0
  121. package/dist/src/crypto/origin-rules.d.ts +56 -0
  122. package/dist/src/crypto/origin-rules.js +143 -0
  123. package/dist/src/crypto/policy-floor.d.ts +98 -0
  124. package/dist/src/crypto/policy-floor.js +353 -0
  125. package/dist/src/crypto/records.d.ts +319 -0
  126. package/dist/src/crypto/records.js +168 -0
  127. package/dist/src/crypto/scope.d.ts +49 -0
  128. package/dist/src/crypto/scope.js +83 -0
  129. package/dist/src/crypto/ssh.d.ts +171 -0
  130. package/dist/src/crypto/ssh.js +396 -0
  131. package/dist/src/crypto/submission.d.ts +33 -0
  132. package/dist/src/crypto/submission.js +47 -0
  133. package/dist/src/crypto/trust-roots.d.ts +29 -0
  134. package/dist/src/crypto/trust-roots.js +39 -0
  135. package/dist/src/crypto/verify-consumed.d.ts +67 -0
  136. package/dist/src/crypto/verify-consumed.js +259 -0
  137. package/dist/src/crypto/verify-origin.d.ts +50 -0
  138. package/dist/src/crypto/verify-origin.js +151 -0
  139. package/dist/src/crypto/verify-publication.d.ts +60 -0
  140. package/dist/src/crypto/verify-publication.js +150 -0
  141. package/dist/src/defs.d.ts +24 -1
  142. package/dist/src/defs.js +335 -27
  143. package/dist/src/engine.d.ts +211 -6
  144. package/dist/src/engine.js +459 -59
  145. package/dist/src/factory.d.ts +16 -0
  146. package/dist/src/factory.js +16 -4
  147. package/dist/src/global-config.d.ts +59 -0
  148. package/dist/src/global-config.js +84 -0
  149. package/dist/src/hub.d.ts +102 -32
  150. package/dist/src/hub.js +147 -58
  151. package/dist/src/index.d.ts +19 -2
  152. package/dist/src/index.js +23 -2
  153. package/dist/src/install.d.ts +538 -0
  154. package/dist/src/install.js +1981 -0
  155. package/dist/src/lock.d.ts +15 -57
  156. package/dist/src/lock.js +251 -143
  157. package/dist/src/mcp/serve.d.ts +46 -22
  158. package/dist/src/mcp/serve.js +174 -44
  159. package/dist/src/mcp/server.js +12 -1
  160. package/dist/src/model.d.ts +51 -0
  161. package/dist/src/model.js +157 -1
  162. package/dist/src/order-resolver.d.ts +184 -0
  163. package/dist/src/order-resolver.js +252 -0
  164. package/dist/src/package-version.d.ts +10 -0
  165. package/dist/src/package-version.js +42 -0
  166. package/dist/src/paths.d.ts +14 -1
  167. package/dist/src/paths.js +18 -0
  168. package/dist/src/schemas/enrollment-grant.v1.schema.json +90 -0
  169. package/dist/src/schemas/index.d.ts +1433 -0
  170. package/dist/src/schemas/index.js +31 -0
  171. package/dist/src/schemas/order.v1.schema.json +120 -0
  172. package/dist/src/schemas/origin.v1.schema.json +68 -0
  173. package/dist/src/schemas/policy-floor.v1.schema.json +29 -0
  174. package/dist/src/schemas/publication.v1.schema.json +31 -0
  175. package/dist/src/schemas/revocation.v1.schema.json +39 -0
  176. package/dist/src/schemas/submission.v1.schema.json +61 -0
  177. package/dist/src/store/def-source.d.ts +52 -0
  178. package/dist/src/store/def-source.js +335 -0
  179. package/dist/src/store/index-file.d.ts +69 -0
  180. package/dist/src/store/index-file.js +151 -0
  181. package/dist/src/store/index.d.ts +27 -0
  182. package/dist/src/store/index.js +22 -0
  183. package/dist/src/store/ingestor.d.ts +43 -0
  184. package/dist/src/store/ingestor.js +211 -0
  185. package/dist/src/store/install.d.ts +228 -0
  186. package/dist/src/store/install.js +555 -0
  187. package/dist/src/store/instruction-source.d.ts +49 -0
  188. package/dist/src/store/instruction-source.js +298 -0
  189. package/dist/src/store/origin-evidence.d.ts +21 -0
  190. package/dist/src/store/origin-evidence.js +66 -0
  191. package/dist/src/store/pre-commit-verifier.d.ts +68 -0
  192. package/dist/src/store/pre-commit-verifier.js +418 -0
  193. package/dist/src/store/resolve.d.ts +138 -0
  194. package/dist/src/store/resolve.js +363 -0
  195. package/dist/src/store/types.d.ts +288 -0
  196. package/dist/src/store/types.js +356 -0
  197. package/dist/src/store.d.ts +33 -1
  198. package/dist/src/store.js +57 -4
  199. package/dist/src/types.d.ts +146 -12
  200. package/dist/src/untar.d.ts +8 -23
  201. package/dist/src/untar.js +10 -136
  202. package/docs/agent-runner.md +86 -0
  203. package/docs/authoring.md +64 -6
  204. package/docs/bundles.md +350 -0
  205. package/docs/cli.md +1298 -106
  206. package/docs/crypto.md +832 -0
  207. package/docs/design.md +342 -20
  208. package/docs/embedding.md +132 -25
  209. package/docs/shift-logs.md +642 -0
  210. package/docs/wire-contracts.md +395 -0
  211. package/package.json +6 -1
  212. package/plugins/claude-code/.claude-plugin/marketplace.json +14 -0
  213. package/plugins/claude-code/plugin/.claude-plugin/plugin.json +8 -0
  214. package/plugins/claude-code/plugin/.mcp.json +14 -0
  215. package/plugins/claude-code/plugin/hooks/hooks.json +26 -0
  216. package/plugins/claude-code/plugin/hooks/session-end.sh +40 -0
  217. package/plugins/claude-code/plugin/hooks/session-start.sh +52 -0
  218. package/plugins/claude-code/plugin/skills/author/SKILL.md +181 -0
  219. package/plugins/claude-code/plugin/skills/conduct/SKILL.md +106 -0
  220. package/plugins/claude-code/plugin/skills/shift/SKILL.md +105 -0
  221. package/plugins/codex/.agents/plugins/marketplace.json +21 -0
  222. package/plugins/codex/plugins/owenloop/.codex-plugin/plugin.json +7 -0
  223. package/plugins/codex/plugins/owenloop/.mcp.json +20 -0
  224. package/plugins/codex/plugins/owenloop/hooks/hooks.json +26 -0
  225. package/plugins/codex/plugins/owenloop/hooks/session-end.sh +40 -0
  226. package/plugins/codex/plugins/owenloop/hooks/session-start.sh +52 -0
  227. package/plugins/codex/plugins/owenloop/skills/author/SKILL.md +181 -0
  228. package/plugins/codex/plugins/owenloop/skills/conduct/SKILL.md +106 -0
  229. package/plugins/codex/plugins/owenloop/skills/shift/SKILL.md +105 -0
@@ -0,0 +1,123 @@
1
+ /**
2
+ * Resolve an order's COMPOSED CAPABILITY to the model and reasoning effort this
3
+ * machine runs it at.
4
+ *
5
+ * The hub decides WHAT grade of work an order is (`builder` composed with the
6
+ * run's `deep` modifier → `builder:deep`). It never decides which model serves
7
+ * that grade. That decision is local to the operator's machine, because it is a
8
+ * statement about accounts, quotas and taste — three things a shared workflow
9
+ * definition has no business asserting.
10
+ *
11
+ * So the settings file carries a flat map from capability to `{model, effort}`:
12
+ *
13
+ * ```json
14
+ * {
15
+ * "capabilityModels": {
16
+ * "wise:deep": { "model": "<model-id>", "effort": "xhigh" },
17
+ * "build:deep": { "model": "<model-id>", "effort": "xhigh" },
18
+ * "wise": { "model": "<model-id>", "effort": "high" }
19
+ * }
20
+ * }
21
+ * ```
22
+ *
23
+ * `<model-id>` is whatever string the shift's harness accepts as a model. This
24
+ * module never enumerates real model ids: it ships as neutral runtime, and
25
+ * `test/vendor-gate.test.ts` forbids a harness vendor's names here. `README.md`
26
+ * and `docs/` carry worked examples with real ids.
27
+ *
28
+ * THIS REPLACES `tierMap`/`tierProfiles` OUTRIGHT. A tier was an abstract rung
29
+ * (`fast`/`standard`/`strong`/`strongest`) that a machine then mapped to a
30
+ * model, and the tier ladder could not express the thing the operator actually
31
+ * wanted: "Luna at low effort" and "Fable at max effort" are different routes,
32
+ * but the ladder welded model choice and depth into one ordered axis, so one
33
+ * could not vary without the other. A capability is just a name. What serves it
34
+ * is a local lookup, and depth rides on the capability's modifier suffix rather
35
+ * than on a rung.
36
+ *
37
+ * The one behavior worth carrying out of the tier code is EFFORT VALIDITY
38
+ * CHECKING, which now happens at settings load rather than at resolution time.
39
+ * It checks the effort against `EFFORT_LADDER` — the neutral start contract's
40
+ * own five rungs — and nothing else.
41
+ *
42
+ * IT DELIBERATELY DOES NOT CHECK EFFORT AGAINST THE MODEL. Doing that would
43
+ * require a table of real model ids in this file, which the vendor gate forbids
44
+ * and which this repository has no ground truth for anyway. Look at what the
45
+ * harness adapters in `src/harness/` actually enforce: one validates effort
46
+ * against a closed union that is a property of THE HARNESS — every model that
47
+ * harness runs accepts the same rungs — and the other passes effort through
48
+ * without validating it at all. Neither knows a per-model constraint, so a
49
+ * table here would be either a restatement of `EFFORT_LADDER` under
50
+ * model-shaped keys, or an invention that blocks a valid operator config. The
51
+ * real per-harness check belongs on the adapter contract; see the follow-up
52
+ * noted in `validateCapabilityModels`.
53
+ *
54
+ * The old snap-up/ceiling-refusal logic in `resolveEffort` is gone with the
55
+ * ladder it resolved through: there is no abstract rung left to snap.
56
+ */
57
+ /** Reasoning rungs the neutral start contract accepts, weakest to strongest. */
58
+ export declare const EFFORT_LADDER: readonly ["low", "medium", "high", "xhigh", "max"];
59
+ export type Effort = (typeof EFFORT_LADDER)[number];
60
+ /**
61
+ * What separates a capability's NAME PART from its MODIFIER: `wise:deep` is the
62
+ * name `wise` at the modifier `deep`. Split on the FIRST separator, matching
63
+ * the engine's own `capabilityName` — a capability name may not contain `:`
64
+ * (install-time rule), so anything after the first one is modifier territory.
65
+ */
66
+ export declare const MODIFIER_SEPARATOR = ":";
67
+ /** The bare capability name inside a composed capability. `wise:deep` → `wise`. */
68
+ export declare function capabilityNamePart(capability: string): string;
69
+ /** One settings row: the model that serves a capability, and how hard it thinks. */
70
+ export interface CapabilityModelRow {
71
+ model: string;
72
+ effort: string;
73
+ }
74
+ /** The settings map, keyed by composed capability (`wise:deep`) or bare name (`wise`). */
75
+ export type CapabilityModelMap = Readonly<Record<string, CapabilityModelRow>>;
76
+ /** Thrown when the capability map is unusable. Never silently repaired. */
77
+ export declare class CapabilityModelError extends Error {
78
+ }
79
+ /**
80
+ * Validate the map, throwing on the first unusable row. Returns nothing: every
81
+ * fault this function can see is certainly wrong.
82
+ *
83
+ * WHAT IT CATCHES — a capability key that is empty, a row that is not an object,
84
+ * a missing or empty `model`, and an `effort` that is not one of
85
+ * `EFFORT_LADDER`. Each is wrong under every harness and every model, and a
86
+ * shift that started anyway would refuse or misroute its first matching order
87
+ * hours later, far from the typo.
88
+ *
89
+ * WHAT IT DOES NOT CATCH — an effort a particular MODEL or HARNESS rejects, and
90
+ * a model id that does not exist. Neither is knowable here (see this module's
91
+ * header). FOLLOW-UP: `HarnessAdapter` is the right owner for the first one —
92
+ * an adapter that validates effort against a closed union could declare that
93
+ * union, and a composition root could check every row against every registered
94
+ * adapter at shift start. Until then those faults surface at the vendor API on
95
+ * the first order that lands on the bad row.
96
+ */
97
+ export declare function validateCapabilityModels(map: Readonly<Record<string, unknown>>, ctx?: string): void;
98
+ /** Which row served the order: its exact compound, or the bare name fallback. */
99
+ export type CapabilityMatch = 'exact' | 'bare';
100
+ export interface CapabilityResolution {
101
+ /** The capability the winning row was keyed by (`wise:deep` or `wise`). */
102
+ capability: string;
103
+ match: CapabilityMatch;
104
+ model: string;
105
+ effort: string;
106
+ }
107
+ /**
108
+ * Resolve an order's capabilities against the map: exact compound row first,
109
+ * then the bare name-part row, else `undefined` (the caller REFUSES the order —
110
+ * never a default model).
111
+ *
112
+ * TWO PASSES ACROSS ALL CAPABILITIES, NOT ONE PASS PER CAPABILITY. A step may
113
+ * author several capabilities, and the hub's claim gate is itself exact-first
114
+ * across the set (§4/§5: "lookup mirrors the claim rule"). Resolving capability
115
+ * by capability instead would let a bare row on the FIRST capability beat an
116
+ * exact row on the second — the shift would run a `builder:deep` order at the
117
+ * bare `builder` grade purely because of authoring order.
118
+ *
119
+ * The bare row is what makes a NAME-MATCH FALLBACK order resolvable at all: the
120
+ * hub stamps `wise:deep` on an order that a crew bound only to `wise:standard`
121
+ * then claims, and that shift has no `wise:deep` row by construction.
122
+ */
123
+ export declare function resolveCapabilityModel(map: CapabilityModelMap, capabilities: readonly string[]): CapabilityResolution | undefined;
@@ -0,0 +1,148 @@
1
+ /**
2
+ * Resolve an order's COMPOSED CAPABILITY to the model and reasoning effort this
3
+ * machine runs it at.
4
+ *
5
+ * The hub decides WHAT grade of work an order is (`builder` composed with the
6
+ * run's `deep` modifier → `builder:deep`). It never decides which model serves
7
+ * that grade. That decision is local to the operator's machine, because it is a
8
+ * statement about accounts, quotas and taste — three things a shared workflow
9
+ * definition has no business asserting.
10
+ *
11
+ * So the settings file carries a flat map from capability to `{model, effort}`:
12
+ *
13
+ * ```json
14
+ * {
15
+ * "capabilityModels": {
16
+ * "wise:deep": { "model": "<model-id>", "effort": "xhigh" },
17
+ * "build:deep": { "model": "<model-id>", "effort": "xhigh" },
18
+ * "wise": { "model": "<model-id>", "effort": "high" }
19
+ * }
20
+ * }
21
+ * ```
22
+ *
23
+ * `<model-id>` is whatever string the shift's harness accepts as a model. This
24
+ * module never enumerates real model ids: it ships as neutral runtime, and
25
+ * `test/vendor-gate.test.ts` forbids a harness vendor's names here. `README.md`
26
+ * and `docs/` carry worked examples with real ids.
27
+ *
28
+ * THIS REPLACES `tierMap`/`tierProfiles` OUTRIGHT. A tier was an abstract rung
29
+ * (`fast`/`standard`/`strong`/`strongest`) that a machine then mapped to a
30
+ * model, and the tier ladder could not express the thing the operator actually
31
+ * wanted: "Luna at low effort" and "Fable at max effort" are different routes,
32
+ * but the ladder welded model choice and depth into one ordered axis, so one
33
+ * could not vary without the other. A capability is just a name. What serves it
34
+ * is a local lookup, and depth rides on the capability's modifier suffix rather
35
+ * than on a rung.
36
+ *
37
+ * The one behavior worth carrying out of the tier code is EFFORT VALIDITY
38
+ * CHECKING, which now happens at settings load rather than at resolution time.
39
+ * It checks the effort against `EFFORT_LADDER` — the neutral start contract's
40
+ * own five rungs — and nothing else.
41
+ *
42
+ * IT DELIBERATELY DOES NOT CHECK EFFORT AGAINST THE MODEL. Doing that would
43
+ * require a table of real model ids in this file, which the vendor gate forbids
44
+ * and which this repository has no ground truth for anyway. Look at what the
45
+ * harness adapters in `src/harness/` actually enforce: one validates effort
46
+ * against a closed union that is a property of THE HARNESS — every model that
47
+ * harness runs accepts the same rungs — and the other passes effort through
48
+ * without validating it at all. Neither knows a per-model constraint, so a
49
+ * table here would be either a restatement of `EFFORT_LADDER` under
50
+ * model-shaped keys, or an invention that blocks a valid operator config. The
51
+ * real per-harness check belongs on the adapter contract; see the follow-up
52
+ * noted in `validateCapabilityModels`.
53
+ *
54
+ * The old snap-up/ceiling-refusal logic in `resolveEffort` is gone with the
55
+ * ladder it resolved through: there is no abstract rung left to snap.
56
+ */
57
+ /** Reasoning rungs the neutral start contract accepts, weakest to strongest. */
58
+ export const EFFORT_LADDER = ['low', 'medium', 'high', 'xhigh', 'max'];
59
+ /**
60
+ * What separates a capability's NAME PART from its MODIFIER: `wise:deep` is the
61
+ * name `wise` at the modifier `deep`. Split on the FIRST separator, matching
62
+ * the engine's own `capabilityName` — a capability name may not contain `:`
63
+ * (install-time rule), so anything after the first one is modifier territory.
64
+ */
65
+ export const MODIFIER_SEPARATOR = ':';
66
+ /** The bare capability name inside a composed capability. `wise:deep` → `wise`. */
67
+ export function capabilityNamePart(capability) {
68
+ const at = capability.indexOf(MODIFIER_SEPARATOR);
69
+ return at === -1 ? capability : capability.slice(0, at);
70
+ }
71
+ /** Thrown when the capability map is unusable. Never silently repaired. */
72
+ export class CapabilityModelError extends Error {
73
+ }
74
+ function isEffort(value) {
75
+ return EFFORT_LADDER.includes(value);
76
+ }
77
+ /**
78
+ * Validate the map, throwing on the first unusable row. Returns nothing: every
79
+ * fault this function can see is certainly wrong.
80
+ *
81
+ * WHAT IT CATCHES — a capability key that is empty, a row that is not an object,
82
+ * a missing or empty `model`, and an `effort` that is not one of
83
+ * `EFFORT_LADDER`. Each is wrong under every harness and every model, and a
84
+ * shift that started anyway would refuse or misroute its first matching order
85
+ * hours later, far from the typo.
86
+ *
87
+ * WHAT IT DOES NOT CATCH — an effort a particular MODEL or HARNESS rejects, and
88
+ * a model id that does not exist. Neither is knowable here (see this module's
89
+ * header). FOLLOW-UP: `HarnessAdapter` is the right owner for the first one —
90
+ * an adapter that validates effort against a closed union could declare that
91
+ * union, and a composition root could check every row against every registered
92
+ * adapter at shift start. Until then those faults surface at the vendor API on
93
+ * the first order that lands on the bad row.
94
+ */
95
+ export function validateCapabilityModels(map, ctx = 'capabilityModels') {
96
+ for (const [capability, raw] of Object.entries(map)) {
97
+ if (capability.trim() === '') {
98
+ throw new CapabilityModelError(`${ctx}: a capability key may not be empty`);
99
+ }
100
+ if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) {
101
+ throw new CapabilityModelError(`${ctx}['${capability}'] must be an object with 'model' and 'effort', got ${JSON.stringify(raw)}`);
102
+ }
103
+ const row = raw;
104
+ const model = row['model'];
105
+ if (typeof model !== 'string' || model.trim() === '') {
106
+ throw new CapabilityModelError(`${ctx}['${capability}'].model must be a non-empty string`);
107
+ }
108
+ const effort = row['effort'];
109
+ if (typeof effort !== 'string' || !isEffort(effort)) {
110
+ throw new CapabilityModelError(`${ctx}['${capability}'].effort must be one of ${EFFORT_LADDER.join(', ')}, got ${JSON.stringify(effort)}`);
111
+ }
112
+ }
113
+ }
114
+ /**
115
+ * Resolve an order's capabilities against the map: exact compound row first,
116
+ * then the bare name-part row, else `undefined` (the caller REFUSES the order —
117
+ * never a default model).
118
+ *
119
+ * TWO PASSES ACROSS ALL CAPABILITIES, NOT ONE PASS PER CAPABILITY. A step may
120
+ * author several capabilities, and the hub's claim gate is itself exact-first
121
+ * across the set (§4/§5: "lookup mirrors the claim rule"). Resolving capability
122
+ * by capability instead would let a bare row on the FIRST capability beat an
123
+ * exact row on the second — the shift would run a `builder:deep` order at the
124
+ * bare `builder` grade purely because of authoring order.
125
+ *
126
+ * The bare row is what makes a NAME-MATCH FALLBACK order resolvable at all: the
127
+ * hub stamps `wise:deep` on an order that a crew bound only to `wise:standard`
128
+ * then claims, and that shift has no `wise:deep` row by construction.
129
+ */
130
+ export function resolveCapabilityModel(map, capabilities) {
131
+ for (const capability of capabilities) {
132
+ const row = map[capability];
133
+ if (row !== undefined)
134
+ return { capability, match: 'exact', model: row.model, effort: row.effort };
135
+ }
136
+ for (const capability of capabilities) {
137
+ const name = capabilityNamePart(capability);
138
+ // Skip a capability that IS its own name part — the first pass already
139
+ // tried that key, and reporting it as a `bare` match would misreport an
140
+ // exact hit as a fallback in the resolution record.
141
+ if (name === capability)
142
+ continue;
143
+ const row = map[name];
144
+ if (row !== undefined)
145
+ return { capability: name, match: 'bare', model: row.model, effort: row.effort };
146
+ }
147
+ return undefined;
148
+ }
@@ -1,19 +1,21 @@
1
1
  import type { HubClient } from '../hub/client.ts';
2
2
  import type { ContactHolder, OrderPacket } from '../hub/types.ts';
3
+ import type { ConsumedVerifier } from '../consumed-verifier.ts';
3
4
  import type { NormalizedStepSpec } from '../bundle/types.ts';
4
5
  import type { HarnessAdapter } from '../harness/contract.ts';
5
6
  import { type SessionRecord } from '../harness/session-store.ts';
7
+ import { type CapabilityModelMap, type CapabilityResolution } from './capability-model.ts';
6
8
  /** Discriminated result of one worker life; the role maps these to exit codes. */
7
- export type AgentRunOutcome = 'submitted' | 'completed' | 'misroute' | 'no-template' | 'no-harness' | 'no-submit' | 'killed' | 'lease-lost' | 'ownership-error' | 'hub-unreachable' | 'stopped';
9
+ export type AgentRunOutcome = 'submitted' | 'completed' | 'misroute' | 'no-template' | 'no-harness' | 'incompatible-harness-policy' | 'unresolvable-capability' | 'unverified-consumed' | 'session-store-failed' | 'no-submit' | 'killed' | 'lease-lost' | 'ownership-error' | 'hub-unreachable' | 'stopped';
8
10
  /**
9
11
  * Locate the normalized step spec for an order. Injected because the lookup is
10
- * I/O (the bundle cache) and because resolving WHICH cached def serves this
11
- * instance is the role's business, not the loop's. `null` ⇒ no spec, which is
12
- * the `'no-template'` outcome (release, leave it for the pickup window).
12
+ * I/O (the verified workflow store) and because resolving the local definition
13
+ * is the role's business, not the loop's. `null` means instruction resolution
14
+ * refused; the loop releases and leaves the order for the pickup window.
13
15
  *
14
- * The spec arrives ALREADY NORMALIZED from `prepare` — brief, harness id, and
15
- * `StepPermissions`. That is what lets this loop stay vendor-neutral: it never
16
- * reaches into a step def's extension bag, so there is no key to name.
16
+ * The spec arrives already normalized from the verified `StepDef` — brief,
17
+ * harness id, and `StepPermissions`. The loop stays vendor-neutral: it never
18
+ * reaches into a step definition's extension bag, so there is no key to name.
17
19
  */
18
20
  export type StepLoader = (order: OrderPacket) => Promise<NormalizedStepSpec | null>;
19
21
  /**
@@ -52,6 +54,20 @@ export interface AgentRunLoopOptions {
52
54
  cwd: string;
53
55
  loadStep: StepLoader;
54
56
  resolveAdapter: AdapterResolver;
57
+ /**
58
+ * THIS MACHINE'S capability → `{model, effort}` map, straight from the
59
+ * settings file (plan §5). The loop resolves the order's composed capabilities
60
+ * against it before dispatch and REFUSES the order when nothing matches —
61
+ * there is no default model here, by design.
62
+ *
63
+ * Absent (or empty) means the shift declared no map at all, which makes every
64
+ * capability-bearing order unresolvable. That is deliberate: a shift that
65
+ * forgot its map should say so on the first order, not run everything on a
66
+ * hardcoded model.
67
+ */
68
+ capabilityModels?: CapabilityModelMap;
69
+ /** Gate dynamic values and rejection reasons before any prompt rendering. */
70
+ consumedVerifier?: ConsumedVerifier;
55
71
  /** Append one session record. Wired to `appendSession` by the role. */
56
72
  appendSession: (rec: SessionRecord) => void;
57
73
  /** The attempt number for this `(workflow, run, step)`. Wired to `latestFor`. */
@@ -113,6 +129,39 @@ export interface ConfirmOptions {
113
129
  */
114
130
  cancelled?: () => boolean;
115
131
  }
132
+ /**
133
+ * How this order's model was decided.
134
+ *
135
+ * `resolved` — a settings row matched; `resolution` names it, plus the model
136
+ * and effort the harness starts with.
137
+ * `refused` — the order named capabilities and NONE of them, exact or bare,
138
+ * has a row. The order is handed back; nothing launches. Plan
139
+ * §5: "never a silent default model".
140
+ * `unrouted` — the order named NO capabilities at all, so there is nothing to
141
+ * look up. This is not a failure: a def that declares no
142
+ * `modifiers:` may author capability-silent steps, and those
143
+ * have always run at the harness's own default model. The loop
144
+ * passes no model and no effort, exactly as it did for a step
145
+ * with no authored tier before this scheme existed.
146
+ */
147
+ export type OrderRouting = {
148
+ kind: 'resolved';
149
+ resolution: CapabilityResolution;
150
+ } | {
151
+ kind: 'refused';
152
+ capabilities: readonly string[];
153
+ } | {
154
+ kind: 'unrouted';
155
+ };
156
+ /**
157
+ * Resolve an order's composed capabilities against this machine's map.
158
+ *
159
+ * ONLY `packet.capabilities` is consulted. `packet.model` — the def's authored
160
+ * tier name under the retired scheme — is deliberately ignored: a tier is an
161
+ * abstract rung with no meaning left, and reading it as a model id would put a
162
+ * literal `strong` on the wire to a vendor.
163
+ */
164
+ export declare function resolveOrderRouting(packet: OrderPacket, map: CapabilityModelMap | undefined): OrderRouting;
116
165
  /**
117
166
  * Poll `get_order` at `intervalMs` for at most `graceMs`, answering ONE
118
167
  * question: did the hub see the agent's `submit`?
@@ -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 { resolveCapabilityModel, } from "./capability-model.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,21 @@ 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
+ /**
74
+ * Resolve an order's composed capabilities against this machine's map.
75
+ *
76
+ * ONLY `packet.capabilities` is consulted. `packet.model` — the def's authored
77
+ * tier name under the retired scheme — is deliberately ignored: a tier is an
78
+ * abstract rung with no meaning left, and reading it as a model id would put a
79
+ * literal `strong` on the wire to a vendor.
80
+ */
81
+ export function resolveOrderRouting(packet, map) {
82
+ const capabilities = packet.capabilities ?? [];
83
+ if (capabilities.length === 0)
84
+ return { kind: 'unrouted' };
85
+ const resolution = map === undefined ? undefined : resolveCapabilityModel(map, capabilities);
86
+ return resolution === undefined ? { kind: 'refused', capabilities } : { kind: 'resolved', resolution };
87
+ }
71
88
  /**
72
89
  * Poll `get_order` at `intervalMs` for at most `graceMs`, answering ONE
73
90
  * question: did the hub see the agent's `submit`?
@@ -128,6 +145,8 @@ export function createAgentRunLoop(opts) {
128
145
  * `SessionRecord.deliveredReasonAt`. Carried forward from the prior record
129
146
  * when this firing delivered no new reasons, so it can never regress. */
130
147
  let deliveredReasonAt;
148
+ /** Captures a thrown safety-gate append from the synchronous `started` event. */
149
+ let activePersistenceFailure;
131
150
  let resolveOrder;
132
151
  const orderReady = new Promise((r) => {
133
152
  resolveOrder = r;
@@ -230,9 +249,17 @@ export function createAgentRunLoop(opts) {
230
249
  case 'started':
231
250
  sessionRef = e.ref;
232
251
  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');
252
+ // This synchronous event is the cold-start gate. The adapter must not
253
+ // begin provider work until the callback returns. A thrown durable append
254
+ // therefore aborts the turn before delivery and is handled separately
255
+ // from an ordinary harness failure below.
256
+ try {
257
+ record('active');
258
+ }
259
+ catch (error) {
260
+ activePersistenceFailure = error;
261
+ throw error;
262
+ }
236
263
  return;
237
264
  case 'progress':
238
265
  opts.err(`owenloop work agent-run: ${e.text}`);
@@ -248,6 +275,40 @@ export function createAgentRunLoop(opts) {
248
275
  return;
249
276
  }
250
277
  }
278
+ /**
279
+ * Tell the hub what this shift resolved the order to (plan §6), before the
280
+ * harness launches.
281
+ *
282
+ * BEST EFFORT, ALWAYS. A hub that is unreachable, older than the verb, or
283
+ * simply erroring must never be able to stop work the shift is otherwise
284
+ * ready to do — the report is observability, not a gate, and the hub's own
285
+ * verb says so. A failure is logged and swallowed.
286
+ *
287
+ * An `unrouted` order is not reported at all: the payload's `capability` is
288
+ * required and non-empty on the hub side, and there is no capability to name.
289
+ */
290
+ async function reportResolution(routing, harness) {
291
+ if (routing.kind === 'unrouted')
292
+ return;
293
+ const payload = routing.kind === 'resolved'
294
+ ? {
295
+ capability: routing.resolution.capability,
296
+ match: routing.resolution.match,
297
+ model: routing.resolution.model,
298
+ effort: routing.resolution.effort,
299
+ harness,
300
+ }
301
+ : // The refusal names the capability the order was OFFERED under — the
302
+ // first one — because that is the row an operator has to add. Model
303
+ // and effort are absent: nothing was selected.
304
+ { capability: routing.capabilities[0] ?? '', match: 'refused', harness };
305
+ try {
306
+ await opts.hub.reportResolution({ workflow, run: runId, resolution: payload });
307
+ }
308
+ catch (e) {
309
+ opts.err(`owenloop work agent-run: reporting the resolution for ${order} failed (continuing): ${errMsg(e)}`);
310
+ }
311
+ }
251
312
  /** Release and finish. Used by every path that hands the order back. */
252
313
  async function releaseWith(reason, outcome) {
253
314
  lease.stop(reason);
@@ -267,11 +328,39 @@ export function createAgentRunLoop(opts) {
267
328
  ]);
268
329
  if (first.t === 'lease')
269
330
  return mapNoHold(first.o);
270
- const packet = first.res.order;
271
- if (packet === null || packet.executor === 'command' || (typeof packet.command === 'string' && packet.command !== '')) {
331
+ let packet = first.res.order;
332
+ if (packet === null || packet.worker === 'command') {
272
333
  opts.err(`owenloop work agent-run: ${order} is not an agent order (misroute) — releasing`);
273
334
  return releaseWith('misroute', 'misroute');
274
335
  }
336
+ // Consume-side verification is the prompt boundary. Do this before loading
337
+ // or rendering any step brief: `owes[].reasons` is dynamic text supplied by
338
+ // the transport, and an unverified rejection thread must never reach a
339
+ // provider session. The same whole-order gate also protects `consumes`.
340
+ const hasConsumedData = Object.keys(packet.consumes).length > 0
341
+ || packet.owes.some((owed) => owed.reasons.length > 0 || owed.proof !== undefined);
342
+ if (hasConsumedData) {
343
+ if (opts.consumedVerifier === undefined) {
344
+ const detail = `consume-side verifier is not configured; dynamic values cannot be admitted to an agent prompt`;
345
+ opts.err(`owenloop work agent-run: consumed artifact refusal (prerequisite) for ${order}: ${detail}`);
346
+ return releaseWith('unverified-consumed', 'unverified-consumed');
347
+ }
348
+ try {
349
+ const checked = await opts.consumedVerifier(packet, { hardRule: false });
350
+ if (!checked.ok) {
351
+ opts.err(`owenloop work agent-run: ${checked.reason} — releasing ${order}`);
352
+ return releaseWith('unverified-consumed', 'unverified-consumed');
353
+ }
354
+ packet = checked.order;
355
+ for (const warning of checked.warnings)
356
+ opts.err(warning);
357
+ }
358
+ catch (error) {
359
+ const detail = error instanceof Error ? error.message : String(error);
360
+ opts.err(`owenloop work agent-run: consumed artifact refusal (prerequisite) for ${order}: ${detail} — releasing`);
361
+ return releaseWith('unverified-consumed', 'unverified-consumed');
362
+ }
363
+ }
275
364
  stepName = packet.step;
276
365
  recordCwd = packet.workdir ?? opts.cwd;
277
366
  // The step spec. No bundle / no spec ⇒ we cannot brief anybody; release so
@@ -309,12 +398,60 @@ export function createAgentRunLoop(opts) {
309
398
  origin: opts.origin,
310
399
  account: opts.account,
311
400
  ...(opts.shiftId !== undefined ? { shiftId: opts.shiftId } : {}),
401
+ // Straight from the packet, not from settings: the modifier is the hub's
402
+ // statement about the RUN, and a shift has no say in it.
403
+ ...(packet.modifier !== undefined ? { modifier: packet.modifier } : {}),
404
+ ...(packet.escalated === true ? { escalated: true } : {}),
312
405
  };
313
406
  // Permissions arrive PRE-NORMALIZED in the spec. `prepare` ran
314
407
  // `normalizeStepPermissions` over the step's `x.harness` options at cache
315
408
  // time, so this loop never looks inside an extension bag and never has a bag
316
409
  // key — vendor-keyed lookup does not exist in neutral code any more.
317
410
  const permissions = step.permissions;
411
+ // Mandatory final-boundary preflight. Common checks run first, followed by
412
+ // the selected adapter's exact capability check. A refusal starts neither a
413
+ // cold session nor a resumed provider process; the held claim is released.
414
+ const policyIssues = [
415
+ ...preflightStepPermissions(permissions),
416
+ ...active.preflight(permissions),
417
+ ];
418
+ if (policyIssues.length > 0) {
419
+ for (const issue of policyIssues) {
420
+ opts.err(`owenloop work agent-run: harness policy refusal for ${order} on '${resolution.id}'` +
421
+ `${issue.field !== undefined ? ` (${issue.field})` : ''}: ${issue.message}`);
422
+ }
423
+ return releaseWith('incompatible-harness-policy', 'incompatible-harness-policy');
424
+ }
425
+ // ---- ROUTING: which model serves this order, and telling the hub --------
426
+ //
427
+ // DELIBERATELY THE LAST GATE BEFORE DISPATCH, and deliberately AFTER every
428
+ // launch gate above (misroute, consumed verification, step spec, adapter,
429
+ // harness policy). Plan §3: the launch gates block on a malformed order
430
+ // before model selection is even attempted, so a refusal never has to be
431
+ // explained in terms of a model the order was never going to reach.
432
+ const routing = resolveOrderRouting(packet, opts.capabilityModels);
433
+ // Plan §6: the record must exist BEFORE tokens are spent, which is why this
434
+ // is a dedicated verb and not a field on the next heartbeat. It is reported
435
+ // on the refusal path too — a refusal is a true observation of what this
436
+ // shift resolved, and the whole point of the report is that the hub can say
437
+ // why an order did or did not run.
438
+ await reportResolution(routing, resolution.id);
439
+ if (routing.kind === 'refused') {
440
+ opts.err(`owenloop work agent-run: no settings row for ${order} — the order's capabilities ` +
441
+ `[${routing.capabilities.join(', ')}] match neither an exact row nor a bare name row in ` +
442
+ `'capabilityModels'. Add a row for one of them (a bare row such as ` +
443
+ `'${routing.capabilities[0]?.split(':')[0] ?? ''}' covers every modifier) and restart the shift. ` +
444
+ `Releasing — this shift will not pick a model it was not told to use.`);
445
+ return releaseWith('unresolvable-capability', 'unresolvable-capability');
446
+ }
447
+ if (routing.kind === 'unrouted') {
448
+ opts.err(`owenloop work agent-run: ${order} carries no capabilities, so no settings row applies — ` +
449
+ `running on '${resolution.id}''s own default model.`);
450
+ }
451
+ else {
452
+ opts.out(`owenloop work agent-run: ${order} resolved '${routing.resolution.capability}' ` +
453
+ `(${routing.resolution.match} row) → ${routing.resolution.model} at ${routing.resolution.effort}`);
454
+ }
318
455
  // ---- PHASE 4: resume or cold replay? -----------------------------------
319
456
  //
320
457
  // The delta first, because "is there anything new to say?" is one of the
@@ -376,11 +513,14 @@ export function createAgentRunLoop(opts) {
376
513
  deliveredReasonAt = delta.deliveredReasonAt;
377
514
  }
378
515
  const owenloopMcp = buildOwenloopMcp(spec);
516
+ const resolvedModel = routing.kind === 'resolved'
517
+ ? { model: routing.resolution.model, effort: routing.resolution.effort }
518
+ : undefined;
379
519
  const deliverArgs = {
380
520
  cwd: recordCwd,
381
521
  owenloopMcp,
382
522
  permissions,
383
- ...(packet.model !== undefined ? { model: packet.model } : {}),
523
+ ...(resolvedModel ?? {}),
384
524
  };
385
525
  /** Built lazily: a cold start after a refused resume needs a FRESH one. */
386
526
  const coldArgs = () => ({
@@ -395,12 +535,13 @@ export function createAgentRunLoop(opts) {
395
535
  cwd: recordCwd,
396
536
  owenloopMcp,
397
537
  permissions,
398
- ...(packet.model !== undefined ? { model: packet.model } : {}),
538
+ ...(resolvedModel ?? {}),
399
539
  });
400
540
  const path = resumable ? 'resume' : delta.message !== '' ? 'cold replay' : 'cold start';
401
541
  opts.out(`owenloop work agent-run: hosting ${order} (step '${packet.step}', harness '${resolution.id}', attempt ${attempt}, ${path})`);
402
542
  /** Cold-start this firing. Shared by the ordinary path and the fallback. */
403
543
  async function coldStart() {
544
+ activePersistenceFailure = undefined;
404
545
  try {
405
546
  const ref = await active.start(coldArgs(), onEvent);
406
547
  sessionRef = ref;
@@ -413,6 +554,10 @@ export function createAgentRunLoop(opts) {
413
554
  return { t: 'turn' };
414
555
  }
415
556
  catch (e) {
557
+ if (activePersistenceFailure !== undefined) {
558
+ await teardown();
559
+ return { t: 'turn', persistenceFailure: activePersistenceFailure };
560
+ }
416
561
  return { t: 'turn', failure: e };
417
562
  }
418
563
  }
@@ -434,8 +579,15 @@ export function createAgentRunLoop(opts) {
434
579
  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
580
  // Deliberately written with the PRIOR watermark: nothing has been delivered
436
581
  // yet, and this row is what the next firing reads if this turn never
437
- // completes. See `markDelivered`.
438
- record('active');
582
+ // completes. See `markDelivered`. This durable write is also the resume
583
+ // delivery gate; failure stops the old provider session without delivery.
584
+ try {
585
+ record('active');
586
+ }
587
+ catch (error) {
588
+ await teardown();
589
+ return { t: 'turn', persistenceFailure: error };
590
+ }
439
591
  try {
440
592
  await active.deliver(sessionRef, delta.message, deliverArgs, onEvent);
441
593
  markDelivered();
@@ -473,6 +625,11 @@ export function createAgentRunLoop(opts) {
473
625
  opts.err(`owenloop work agent-run: lease ${raced.o} mid-turn — tore the session down, no outcome observed`);
474
626
  return mapLeaseDuringTurn(raced.o);
475
627
  }
628
+ if (raced.persistenceFailure !== undefined) {
629
+ opts.err(`owenloop work agent-run: durable active-session persistence failed before provider delivery for ${order}: ` +
630
+ `${errMsg(raced.persistenceFailure)} — releasing`);
631
+ return releaseWith('session-store-failed', 'session-store-failed');
632
+ }
476
633
  // TURN END — NOT task end. Log the failure shape for humans, then confirm.
477
634
  if (raced.failure !== undefined) {
478
635
  const why = isResumeUnavailable(raced.failure)
@@ -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
  /**