@sema-agent/core 7.62.0 → 7.64.0

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 (320) hide show
  1. package/CHANGELOG.md +936 -0
  2. package/dist/agents/cc-peer-directory.js +1 -0
  3. package/dist/agents/cc-peer-wire.d.ts +4 -0
  4. package/dist/agents/cc-peer-wire.js +1 -0
  5. package/dist/agents/cc-uds-peer-channel.js +5 -0
  6. package/dist/agents/cross-session-judge.d.ts +3 -1
  7. package/dist/agents/cross-session-judge.js +4 -1
  8. package/dist/agents/peer-directory.d.ts +8 -0
  9. package/dist/agents/peer-directory.js +4 -0
  10. package/dist/agents/peer-held-queue.d.ts +9 -3
  11. package/dist/agents/peer-held-queue.js +12 -9
  12. package/dist/agents/peer-idle.d.ts +20 -1
  13. package/dist/agents/peer-idle.js +23 -12
  14. package/dist/agents/peer-notice-route.d.ts +16 -5
  15. package/dist/agents/peer-notice-route.js +11 -9
  16. package/dist/agents/peer-notices.d.ts +25 -8
  17. package/dist/agents/peer-notices.js +6 -1
  18. package/dist/agents/peer-session-drain.d.ts +32 -6
  19. package/dist/agents/peer-session-drain.js +100 -26
  20. package/dist/agents/send-message-tool.d.ts +7 -0
  21. package/dist/agents/send-message-tool.js +18 -6
  22. package/dist/agents/subagent-transcript-placement.d.ts +23 -0
  23. package/dist/agents/subagent-transcript-placement.js +14 -0
  24. package/dist/agents/subagent.js +102 -54
  25. package/dist/brain/route-adjudicator.js +9 -4
  26. package/dist/core/allow-entry.d.ts +4 -0
  27. package/dist/core/approval-object.js +1 -1
  28. package/dist/core/arg-summary.js +1 -1
  29. package/dist/core/ask-origin.d.ts +1 -1
  30. package/dist/core/ask-origin.js +2 -2
  31. package/dist/core/ask-question.d.ts +2 -2
  32. package/dist/core/ask-unresolvable-notice.d.ts +13 -4
  33. package/dist/core/ask-unresolvable-notice.js +10 -3
  34. package/dist/core/auto-compaction.d.ts +7 -5
  35. package/dist/core/background-agent-store.d.ts +7 -0
  36. package/dist/core/background-agent-store.js +3 -0
  37. package/dist/core/canonical-json.d.ts +23 -13
  38. package/dist/core/canonical-json.js +4 -4
  39. package/dist/core/checkpoint-queries.d.ts +50 -4
  40. package/dist/core/checkpoint-queries.js +42 -17
  41. package/dist/core/checkpoint-requirements.d.ts +3 -3
  42. package/dist/core/checkpoint-requirements.js +2 -1
  43. package/dist/core/checkpoint-row-verdict.d.ts +15 -4
  44. package/dist/core/checkpoint-row-verdict.js +22 -2
  45. package/dist/core/checkpoint-store.d.ts +28 -11
  46. package/dist/core/checkpoint-store.js +45 -4
  47. package/dist/core/compliance.d.ts +6 -2
  48. package/dist/core/compliance.js +3 -3
  49. package/dist/core/context-settings.d.ts +40 -9
  50. package/dist/core/context-settings.js +32 -10
  51. package/dist/core/engine-attestation.d.ts +27 -7
  52. package/dist/core/engine-attestation.js +5 -1
  53. package/dist/core/engine-notice.d.ts +43 -5
  54. package/dist/core/extension-requester.d.ts +9 -0
  55. package/dist/core/extension-requester.js +7 -0
  56. package/dist/core/file-history-store.d.ts +28 -0
  57. package/dist/core/file-history-store.js +48 -5
  58. package/dist/core/fs-write-gate-policy.js +1 -1
  59. package/dist/core/gate-fold.js +2 -0
  60. package/dist/core/gate-lanes.js +2 -0
  61. package/dist/core/gate-outcome.d.ts +39 -2
  62. package/dist/core/gate-outcome.js +20 -1
  63. package/dist/core/git-worktree-env.d.ts +62 -3
  64. package/dist/core/git-worktree-env.js +91 -30
  65. package/dist/core/governance-codes.d.ts +9 -3
  66. package/dist/core/governance-codes.js +17 -3
  67. package/dist/core/leg-identity.d.ts +19 -1
  68. package/dist/core/leg-identity.js +12 -0
  69. package/dist/core/mailbox-store.d.ts +39 -4
  70. package/dist/core/mailbox-store.js +14 -2
  71. package/dist/core/memory-engine/consolidation-driver.d.ts +32 -17
  72. package/dist/core/memory-engine/consolidation-driver.js +99 -98
  73. package/dist/core/memory-engine/consolidation.d.ts +74 -10
  74. package/dist/core/memory-engine/consolidation.js +183 -11
  75. package/dist/core/memory-engine/control-objects.d.ts +25 -0
  76. package/dist/core/memory-engine/control-objects.js +151 -0
  77. package/dist/core/memory-engine/control-plane-adoption.d.ts +48 -0
  78. package/dist/core/memory-engine/control-plane-adoption.js +159 -0
  79. package/dist/core/memory-engine/data-plane.d.ts +8 -4
  80. package/dist/core/memory-engine/data-plane.js +11 -6
  81. package/dist/core/memory-engine/delegation-settlement.d.ts +58 -40
  82. package/dist/core/memory-engine/delegation-settlement.js +270 -85
  83. package/dist/core/memory-engine/dual-root.d.ts +12 -6
  84. package/dist/core/memory-engine/dual-root.js +11 -7
  85. package/dist/core/memory-engine/engine.d.ts +136 -58
  86. package/dist/core/memory-engine/engine.js +491 -394
  87. package/dist/core/memory-engine/entry-scan.d.ts +8 -0
  88. package/dist/core/memory-engine/entry-scan.js +3 -0
  89. package/dist/core/memory-engine/file-backend.d.ts +62 -60
  90. package/dist/core/memory-engine/file-backend.js +122 -198
  91. package/dist/core/memory-engine/index.d.ts +8 -7
  92. package/dist/core/memory-engine/index.js +7 -6
  93. package/dist/core/memory-engine/landing-admission.d.ts +5 -3
  94. package/dist/core/memory-engine/landing-admission.js +3 -3
  95. package/dist/core/memory-engine/layout.d.ts +127 -46
  96. package/dist/core/memory-engine/layout.js +264 -109
  97. package/dist/core/memory-engine/memory-backend-contract.d.ts +26 -1
  98. package/dist/core/memory-engine/memory-backend-contract.js +476 -0
  99. package/dist/core/memory-engine/memory-deployment.d.ts +42 -11
  100. package/dist/core/memory-engine/memory-deployment.js +54 -15
  101. package/dist/core/memory-engine/origin-clearance.d.ts +12 -3
  102. package/dist/core/memory-engine/origin-clearance.js +68 -9
  103. package/dist/core/memory-engine/scope-contract.d.ts +52 -11
  104. package/dist/core/memory-engine/scope-contract.js +68 -19
  105. package/dist/core/memory-engine/session-write-home.d.ts +37 -2
  106. package/dist/core/memory-engine/session-write-home.js +38 -11
  107. package/dist/core/memory-engine/sync-client.d.ts +3 -1
  108. package/dist/core/memory-engine/sync-client.js +7 -0
  109. package/dist/core/memory-engine/sync-report.d.ts +3 -2
  110. package/dist/core/memory-engine/sync-report.js +6 -2
  111. package/dist/core/memory-engine/tools.d.ts +2 -2
  112. package/dist/core/memory-engine/tools.js +10 -10
  113. package/dist/core/memory-engine/types.d.ts +155 -19
  114. package/dist/core/memory-engine/types.js +2 -0
  115. package/dist/core/memory.js +15 -6
  116. package/dist/core/mode-policy.js +3 -3
  117. package/dist/core/mods/agent-stations.d.ts +18 -0
  118. package/dist/core/mods/agent-stations.js +8 -6
  119. package/dist/core/mods/extension-call.d.ts +4 -0
  120. package/dist/core/mods/extension-call.js +8 -0
  121. package/dist/core/mods/stations.d.ts +20 -1
  122. package/dist/core/mods/stations.js +21 -2
  123. package/dist/core/mods/tool-call.js +3 -4
  124. package/dist/core/parent-spec-seat.d.ts +2 -2
  125. package/dist/core/park-selfcheck.js +2 -2
  126. package/dist/core/pause-registry.d.ts +2 -0
  127. package/dist/core/pause-registry.js +3 -0
  128. package/dist/core/peer-channel.d.ts +5 -0
  129. package/dist/core/permission-rule-consent.d.ts +26 -8
  130. package/dist/core/permission-rule-consent.js +76 -36
  131. package/dist/core/permission-rule-store.d.ts +72 -13
  132. package/dist/core/permission-rule-store.js +29 -8
  133. package/dist/core/read-only-shell.js +3 -2
  134. package/dist/core/redaction-marks.d.ts +8 -0
  135. package/dist/core/redaction-marks.js +6 -0
  136. package/dist/core/refusal-echo.d.ts +20 -0
  137. package/dist/core/refusal-echo.js +33 -0
  138. package/dist/core/remote-env.d.ts +12 -1
  139. package/dist/core/remote-env.js +3 -0
  140. package/dist/core/retention.d.ts +180 -10
  141. package/dist/core/retention.js +45 -0
  142. package/dist/core/retired-keys.d.ts +5 -0
  143. package/dist/core/retired-keys.js +3 -0
  144. package/dist/core/rule-offer-read.d.ts +0 -4
  145. package/dist/core/rule-offer-read.js +2 -18
  146. package/dist/core/runner/child-tree.d.ts +29 -3
  147. package/dist/core/runner/child-tree.js +39 -16
  148. package/dist/core/runner/classifier-ladder.d.ts +7 -1
  149. package/dist/core/runner/classifier-ladder.js +4 -2
  150. package/dist/core/runner/compact-session.js +10 -7
  151. package/dist/core/runner/compaction-call-options.d.ts +7 -7
  152. package/dist/core/runner/compaction-call-options.js +3 -2
  153. package/dist/core/runner/contracts.d.ts +39 -11
  154. package/dist/core/runner/delegation-owner.d.ts +10 -3
  155. package/dist/core/runner/delegation-owner.js +4 -1
  156. package/dist/core/runner/gate-exit.d.ts +6 -0
  157. package/dist/core/runner/gate-exit.js +13 -4
  158. package/dist/core/runner/inherited-ask-grants.js +1 -1
  159. package/dist/core/runner/memory-consolidation-driver.d.ts +10 -5
  160. package/dist/core/runner/memory-consolidation-driver.js +12 -9
  161. package/dist/core/runner/memory-consolidation-write-judge.d.ts +2 -1
  162. package/dist/core/runner/memory-consolidation-write-judge.js +3 -2
  163. package/dist/core/runner/person-path-rows.d.ts +8 -3
  164. package/dist/core/runner/person-path-rows.js +5 -1
  165. package/dist/core/runner/placement-fence.d.ts +12 -0
  166. package/dist/core/runner/placement-fence.js +20 -6
  167. package/dist/core/runner/prepare-ask-lane.js +5 -5
  168. package/dist/core/runner/prepare-caps-and-workflow.d.ts +7 -2
  169. package/dist/core/runner/prepare-caps-and-workflow.js +7 -4
  170. package/dist/core/runner/prepare-config-doors.js +4 -0
  171. package/dist/core/runner/prepare-delegation-surface.d.ts +3 -0
  172. package/dist/core/runner/prepare-delegation-surface.js +2 -2
  173. package/dist/core/runner/prepare-execution-env.js +17 -6
  174. package/dist/core/runner/prepare-gate-stations.d.ts +5 -0
  175. package/dist/core/runner/prepare-gate-stations.js +5 -5
  176. package/dist/core/runner/prepare-hands-readface.d.ts +2 -1
  177. package/dist/core/runner/prepare-hands-readface.js +5 -4
  178. package/dist/core/runner/prepare-inherited-gate.d.ts +13 -9
  179. package/dist/core/runner/prepare-inherited-gate.js +12 -6
  180. package/dist/core/runner/prepare-memory-engine-session.d.ts +2 -4
  181. package/dist/core/runner/prepare-memory-engine-session.js +4 -4
  182. package/dist/core/runner/prepare-memory.d.ts +7 -2
  183. package/dist/core/runner/prepare-memory.js +41 -39
  184. package/dist/core/runner/prepare-park-ask.js +4 -3
  185. package/dist/core/runner/prepare-policy-chain.js +7 -7
  186. package/dist/core/runner/prepare-prompt-inputs.js +1 -1
  187. package/dist/core/runner/prepare-task.js +26 -18
  188. package/dist/core/runner/prepare-wiring-manifest.d.ts +3 -1
  189. package/dist/core/runner/prepare-wiring-manifest.js +3 -2
  190. package/dist/core/runner/prepare-workspace-restore.js +3 -6
  191. package/dist/core/runner/resume-admission.d.ts +2 -2
  192. package/dist/core/runner/resume-admission.js +2 -23
  193. package/dist/core/runner/role-resolution-table.d.ts +98 -0
  194. package/dist/core/runner/role-resolution-table.js +62 -0
  195. package/dist/core/runner/run-compaction-machinery.js +2 -2
  196. package/dist/core/runner/run-identity-wiring.js +12 -9
  197. package/dist/core/runner/run-leg.js +9 -5
  198. package/dist/core/runner/run-notification-lane.js +22 -22
  199. package/dist/core/runner/run-recovery-lanes.js +3 -3
  200. package/dist/core/runner/run-settle-and-teardown.js +3 -2
  201. package/dist/core/runner/run-terminal-adoption.js +1 -1
  202. package/dist/core/runner/run-turn-boundary.js +14 -15
  203. package/dist/core/runner/runtask.js +1 -1
  204. package/dist/core/runner/terminal-account.js +1 -1
  205. package/dist/core/runner/tool-occurrence.d.ts +4 -2
  206. package/dist/core/runner/tool-occurrence.js +2 -2
  207. package/dist/core/runner-deps.d.ts +7 -3
  208. package/dist/core/secret-env.d.ts +1 -1
  209. package/dist/core/secret-env.js +4 -4
  210. package/dist/core/session-checkout.d.ts +168 -0
  211. package/dist/core/session-checkout.js +579 -0
  212. package/dist/core/session-store.d.ts +12 -4
  213. package/dist/core/session-store.js +23 -3
  214. package/dist/core/session.d.ts +16 -2
  215. package/dist/core/session.js +3 -0
  216. package/dist/core/shell-read-silence.js +8 -0
  217. package/dist/core/store-contracts/checkpoint-store-contract.d.ts +0 -12
  218. package/dist/core/store-contracts/checkpoint-store-contract.js +6 -7
  219. package/dist/core/store-contracts/peer-directory-contract.js +8 -1
  220. package/dist/core/store-contracts/session-store-contract.js +39 -0
  221. package/dist/core/task-event.d.ts +30 -5
  222. package/dist/core/task-notification.d.ts +119 -32
  223. package/dist/core/task-notification.js +186 -100
  224. package/dist/core/task-registry-agent.d.ts +25 -2
  225. package/dist/core/task-registry-agent.js +56 -22
  226. package/dist/core/task-registry-shared.d.ts +33 -11
  227. package/dist/core/task-registry.d.ts +33 -9
  228. package/dist/core/task-registry.js +36 -18
  229. package/dist/core/task-spec-members.js +1 -1
  230. package/dist/core/task-spec.d.ts +27 -2
  231. package/dist/core/tool-errors.d.ts +14 -6
  232. package/dist/core/tool-errors.js +1 -1
  233. package/dist/core/tool-policy.d.ts +32 -13
  234. package/dist/core/tool-policy.js +27 -17
  235. package/dist/core/tool-result-store.d.ts +20 -0
  236. package/dist/core/tool-spec.d.ts +42 -19
  237. package/dist/core/trace.d.ts +3 -2
  238. package/dist/core/types.d.ts +1 -1
  239. package/dist/core/untrusted-egress.d.ts +15 -4
  240. package/dist/core/untrusted-egress.js +23 -22
  241. package/dist/core/workflow-journal-store.d.ts +11 -0
  242. package/dist/core/workflow-journal-store.js +7 -0
  243. package/dist/core/workflow-run-store.d.ts +9 -0
  244. package/dist/core/workflow-run-store.js +6 -0
  245. package/dist/core/workspace-snapshot.d.ts +3 -1
  246. package/dist/core/workspace-snapshot.js +1 -0
  247. package/dist/engine/compaction/compaction.d.ts +2 -1
  248. package/dist/engine/harness/types.d.ts +67 -1
  249. package/dist/engine/harness/types.js +108 -0
  250. package/dist/engine/session/import-validate.js +6 -1
  251. package/dist/engine/session/session.d.ts +30 -1
  252. package/dist/engine/session/session.js +48 -1
  253. package/dist/index.d.ts +12 -7
  254. package/dist/index.js +12 -7
  255. package/dist/internal/harness-types.d.ts +1 -1
  256. package/dist/orchestration/run-workflow-tool.d.ts +8 -1
  257. package/dist/orchestration/run-workflow-tool.js +8 -0
  258. package/dist/orchestration/workflow-types.d.ts +2 -1
  259. package/dist/orchestration/workflow.d.ts +6 -0
  260. package/dist/orchestration/workflow.js +5 -2
  261. package/dist/stores/file/checkpoint-store.d.ts +6 -0
  262. package/dist/stores/file/checkpoint-store.js +4 -1
  263. package/dist/stores/file/file-history-store.d.ts +13 -0
  264. package/dist/stores/file/file-history-store.js +75 -13
  265. package/dist/stores/file/index.d.ts +11 -1
  266. package/dist/stores/file/index.js +7 -11
  267. package/dist/stores/file/permission-rule-store.d.ts +23 -0
  268. package/dist/stores/file/permission-rule-store.js +75 -7
  269. package/dist/stores/file/session-store.js +2 -1
  270. package/dist/stores/file/tool-result-store.d.ts +14 -0
  271. package/dist/stores/file/tool-result-store.js +39 -2
  272. package/dist/stores/file/workflow-journal-store.d.ts +4 -0
  273. package/dist/stores/file/workflow-journal-store.js +17 -0
  274. package/dist/stores/file/workflow-run-store.d.ts +3 -0
  275. package/dist/stores/file/workflow-run-store.js +15 -0
  276. package/dist/tools/fs/bash-program-position.js +3 -3
  277. package/dist/tools/fs/program-read-model.d.ts +34 -10
  278. package/dist/tools/fs/program-read-model.js +37 -7
  279. package/dist/tools/fs/program-read-model.rows.js +13 -2
  280. package/dist/tools/fs/read-deny.d.ts +28 -3
  281. package/dist/tools/fs/read-deny.js +18 -2
  282. package/dist/tools/fs/removal-targets.js +3 -3
  283. package/dist/tools/fs/safety.d.ts +2 -0
  284. package/dist/tools/fs/safety.js +1 -1
  285. package/dist/tools/fs/shell-read-argv.d.ts +8 -1
  286. package/dist/tools/fs/shell-read-argv.js +34 -29
  287. package/dist/tools/fs/shell-read-bindings.d.ts +2 -0
  288. package/dist/tools/fs/shell-read-bindings.js +5 -1
  289. package/dist/tools/fs/shell-read-brace.d.ts +18 -0
  290. package/dist/tools/fs/shell-read-brace.js +79 -0
  291. package/dist/tools/fs/shell-read-check.d.ts +8 -2
  292. package/dist/tools/fs/shell-read-check.js +16 -14
  293. package/dist/tools/fs/shell-read-establish.js +23 -16
  294. package/dist/tools/fs/shell-read-judge.d.ts +11 -0
  295. package/dist/tools/fs/shell-read-judge.js +3 -3
  296. package/dist/tools/fs/shell-read-plan.d.ts +10 -0
  297. package/dist/tools/fs/shell-read-plan.js +189 -93
  298. package/dist/tools/fs/shell-read-start.d.ts +19 -9
  299. package/dist/tools/fs/shell-read-start.js +20 -12
  300. package/dist/tools/fs/shell-read-word.d.ts +10 -0
  301. package/dist/tools/fs/shell-read-word.js +9 -5
  302. package/dist/tools/fs/shell-read-workdir.d.ts +26 -7
  303. package/dist/tools/fs/shell-read-workdir.js +73 -12
  304. package/dist/tools/fs/shell-read-write-targets.js +13 -8
  305. package/dist/tools/worktree.d.ts +3 -2
  306. package/dist/tools/worktree.js +7 -35
  307. package/package.json +3 -2
  308. package/test/export-surface.snapshot.json +135 -11
  309. package/wire-changes/core-stores-sql@7.63.0.json +30 -0
  310. package/wire-changes/core-stores-sql@7.64.0.json +30 -0
  311. package/wire-changes/core@7.63.0.json +3523 -0
  312. package/wire-changes/core@7.64.0.json +2653 -0
  313. package/wire-changes/mods-kernel@7.63.0.json +30 -0
  314. package/wire-changes/mods-kernel@7.64.0.json +30 -0
  315. package/wire-changes/primitives@7.63.0.json +445 -0
  316. package/wire-changes/primitives@7.64.0.json +30 -0
  317. package/dist/core/credential-vocabulary.d.ts +0 -176
  318. package/dist/core/credential-vocabulary.js +0 -190
  319. package/dist/core/redaction-passes.d.ts +0 -82
  320. package/dist/core/redaction-passes.js +0 -377
@@ -1,7 +1,23 @@
1
+ /**
2
+ * The delegation's two stations over the delegating leg's bus. `agent.offer`: the agent types the model is offered — ONE set
3
+ * ({@link offeredAgents}) read by the listing and by the dispatch; a handler answers `next(e)` or `{ isOffered: false }`.
4
+ * `agent.spawn`: raised before a delegated subagent is let start, every member pinned; a handler answers `next(e)` or
5
+ * `{ deny: <reason> }` in place of `next`; any other answer, a changed member, a throw or a timeout refuses while the
6
+ * subagent has not started, after which the spawn stands. A revival and an observer leg raise no spawn.
7
+ *
8
+ * `$.agent.spawn({ prompt, ... })` is `agent.spawn` called (the table's `call` column): the host entry
9
+ * ({@link createAgentSpawnEntry}) runs the delegation tool's own per-call pipeline, as `$.tool.call` runs any other tool's — the
10
+ * whole gate, `tool.call`, the delegation (whose `agent.spawn` station is raised once, at its own place), the post-execution
11
+ * stations — as the caller's call, with the subagent in the background. The delegation reads ONE fact of the call
12
+ * ({@link AgentStations.extensionSpawn}, the extension call's own record): an extension's spawn is no offer, and it never holds the
13
+ * foreground; where the delegation lets the subagent run it writes `{ agentId, model }` on the record, and the entry answers off
14
+ * that record alone (never off the call's result, which a post-execution station may withhold after the subagent started).
15
+ */
1
16
  import { type ModCallEntry } from "./kernel/index.js";
2
17
  import type { HookInvocationIdentity } from "../hooks.js";
3
18
  import type { PermissionMode } from "../ask-origin.js";
4
19
  import { type LegModBus } from "./stations.js";
20
+ import type { ExtensionRequester } from "../task-event.js";
5
21
  import { type ToolCallEntryInput } from "./tool-call.js";
6
22
  /** One agent type as the model is offered it. */
7
23
  export interface OfferedAgent {
@@ -58,6 +74,8 @@ export declare function spawnedModel(model: string | undefined): string;
58
74
  export interface ExtensionSpawn {
59
75
  /** The registration that called `$.agent.spawn`. */
60
76
  readonly by: string;
77
+ /** Who asked, as the registry row and the durable record carry it ({@link ExtensionRequester}): this extension, by its registration name. */
78
+ readonly requestedBy: ExtensionRequester;
61
79
  /** The subagent was let run under `agentId` — its registry task id, which is its leg's task id and so its events' `agentId`;
62
80
  * `model` is the one the delegation settled (`undefined` ⇒ the child's prepare decides). Written once. */
63
81
  launched(agentId: string, model: string | undefined): void;
@@ -1,4 +1,3 @@
1
- import { randomUUID } from "node:crypto";
2
1
  import { ENGINE_ORIGIN } from "./kernel/index.js";
3
2
  import { isPlainRecord } from "./kernel/receive.js";
4
3
  import { NEXT_IN_FLIGHT } from "./kernel/site-rules.js";
@@ -7,7 +6,7 @@ import { extensionWords } from "../untrusted-egress.js";
7
6
  import { declaredDelegationNameOf } from "../delegation-name.js";
8
7
  import { failedHandlerClause, seatHears } from "./stations.js";
9
8
  import { agentIdOf } from "../leg-identity.js";
10
- import { extensionCallOf, noteExtensionCallLaunched, runExtensionCall } from "./extension-call.js";
9
+ import { extensionCallOf, isExtensionCallId, mintExtensionCallId, noteExtensionCallLaunched, requesterOf, runExtensionCall } from "./extension-call.js";
11
10
  import { resultText } from "./tool-call.js";
12
11
  const ENGINE_PROVIDER = Object.freeze({ plugin: ENGINE_ORIGIN.plugin, tier: ENGINE_ORIGIN.tier });
13
12
  const OFFERED = Object.freeze({ isOffered: true });
@@ -53,10 +52,13 @@ export function createAgentStations(input) {
53
52
  listens: (event) => seatHears(input, event),
54
53
  offered: (agents, signal) => offeredAgents(input, agents, signal),
55
54
  extensionSpawn: (toolCallId) => {
56
- const call = toolCallId !== undefined ? extensionCallOf(input.bus, toolCallId) : undefined;
57
- if (call === undefined || call.door !== "agent.spawn" || toolCallId === undefined)
55
+ if (!isExtensionCallId(toolCallId))
58
56
  return undefined;
59
- return { by: call.caller.origin.plugin, launched: (agentId, model) => noteExtensionCallLaunched(input.bus, toolCallId, { agentId, model: spawnedModel(model) }) };
57
+ const call = extensionCallOf(input.bus, toolCallId);
58
+ const requestedBy = requesterOf(input.bus, toolCallId).requestedBy;
59
+ if (call === undefined || call.door !== "agent.spawn" || requestedBy === undefined)
60
+ return undefined;
61
+ return { by: call.caller.origin.plugin, requestedBy, launched: (agentId, model) => noteExtensionCallLaunched(input.bus, toolCallId, { agentId, model: spawnedModel(model) }) };
60
62
  },
61
63
  spawn: async (facts, signal) => {
62
64
  if (!seatHears(input, "agent.spawn"))
@@ -141,7 +143,7 @@ export function createAgentSpawnEntry(input) {
141
143
  throw new TypeError(`${by}: $.agent.spawn: this run mounts no delegation tool`);
142
144
  if (tools.length > 1)
143
145
  throw new TypeError(`${by}: $.agent.spawn: this run mounts ${tools.length} delegation tools (${tools.map((n) => `"${extensionWords(n, 80)}"`).join(", ")}) and a spawn names none of them`);
144
- const toolCallId = `ext-${randomUUID()}`;
146
+ const toolCallId = mintExtensionCallId();
145
147
  return runExtensionCall(input.bus, toolCallId, "agent.spawn", ctx, async (call) => {
146
148
  const finalized = await input.harness.callTool({ type: "toolCall", id: toolCallId, name: tool, arguments: delegationInput(args, prompt) }, ctx.signal, () => undefined);
147
149
  if (call.launched !== undefined)
@@ -1,5 +1,9 @@
1
1
  import { type ModBottomContext, type ModBus } from "./kernel/index.js";
2
2
  import type { ExtensionRequester } from "../task-event.js";
3
+ /** The id an extension's own call (`$.tool.call`, `$.agent.spawn`) runs under: both doors mint it here. */
4
+ export declare function mintExtensionCallId(): string;
5
+ /** Whether `id` is a call id {@link mintExtensionCallId} could have minted — the one reading of "an extension's own call id". */
6
+ export declare function isExtensionCallId(id: unknown): id is string;
3
7
  /** Which `$` call made the record: the door the extension came through. */
4
8
  export type ExtensionDoor = "tool.call" | "agent.spawn";
5
9
  /** One extension's call while it runs. */
@@ -1,5 +1,13 @@
1
1
  import { AsyncLocalStorage } from "node:async_hooks";
2
+ import { randomUUID } from "node:crypto";
2
3
  import { ENGINE_ORIGIN } from "./kernel/index.js";
4
+ const EXTENSION_CALL_ID_PREFIX = "ext-";
5
+ export function mintExtensionCallId() {
6
+ return `${EXTENSION_CALL_ID_PREFIX}${randomUUID()}`;
7
+ }
8
+ export function isExtensionCallId(id) {
9
+ return typeof id === "string" && id.startsWith(EXTENSION_CALL_ID_PREFIX);
10
+ }
3
11
  const store = new AsyncLocalStorage();
4
12
  export function extensionCallOf(bus, toolCallId) {
5
13
  const c = store.getStore();
@@ -234,9 +234,28 @@ export interface TextChanges {
234
234
  * `prompt.submit`): a handler is named for the change it made — handing a different text on, or answering a different text
235
235
  * than the one that came up to it — never for carrying another handler's change up. */
236
236
  export declare function textChanges(original: string): TextChanges;
237
+ /** The stations a prompt's screen is — `prompt.submit`, and `classic.UserPromptSubmit` raised in its bottom. The one list:
238
+ * the entrances raise these and nothing else on a prompt, and every reading of "is the screen heard" reads it, so a station
239
+ * added here is heard by all of them. Both are the engine bus's (`MOD_EVENT_TABLE`). */
240
+ export declare const PROMPT_SCREEN_STATIONS: readonly ModEventName[];
237
241
  /** The four entrances' one predicate: does the leg hear a prompt's screen — `prompt.submit`, or `classic.UserPromptSubmit`
238
- * raised in its bottom? */
242
+ * raised in its bottom? The bus's reading of {@link promptScreenHeard}; {@link promptScreenDeclaredBy} is the registrations'. */
239
243
  export declare function promptScreenHasHandlers(bus: LegModBus): boolean;
244
+ /**
245
+ * Whether a set of registrations declares a prompt screen: some `uses.events` pattern — an event name or a `<prefix>.*`,
246
+ * expanded on the engine bus as admission expands it (`expandOnSide`) — selects `prompt.submit` or `classic.UserPromptSubmit`
247
+ * ({@link PROMPT_SCREEN_STATIONS}). The reading for a host that holds registrations before any bus is admitted (an acceptance
248
+ * seat that must know, before it writes a byte, whether the prompt will be screened); the bus's reading is
249
+ * {@link promptScreenHasHandlers} over what the admitted registrations hung. A declaration is the upper bound on what a
250
+ * registration hangs, so a registration that declares a station and hangs nothing on it is declared here and unheard there.
251
+ * A pattern admission would refuse (not a name, not a list, a name no bus reads) selects nothing here — admission refuses the
252
+ * registration itself, with `config.mods_invalid`.
253
+ */
254
+ export declare function promptScreenDeclaredBy(registrations: readonly {
255
+ readonly uses: {
256
+ readonly events: readonly string[];
257
+ };
258
+ }[]): boolean;
240
259
  /**
241
260
  * A prompt's screen at one of the four entrances (objective, live steer, a wake's message before its claim, a parked steer
242
261
  * redelivered): `prompt.submit` over `e` with the prompt as `text`, its bottom raising `classic.UserPromptSubmit` on the text
@@ -6,7 +6,7 @@ import { deliverEngineNotice } from "../engine-notice.js";
6
6
  import { extensionWords } from "../untrusted-egress.js";
7
7
  import { askApproverIdentity, describeThrown, ownArgs } from "../tool-policy.js";
8
8
  import { agentIdOf } from "../leg-identity.js";
9
- import { admitMods } from "./kernel/index.js";
9
+ import { admitMods, expandOnSide } from "./kernel/index.js";
10
10
  import { legBusOf } from "./extension-call.js";
11
11
  import { validateOverlay } from "../../prompt-assembly/overlay.js";
12
12
  import { modsInvalid } from "./kernel/registration.js";
@@ -221,8 +221,27 @@ export function textChanges(original) {
221
221
  rewrittenBy: () => Object.freeze([...changers]),
222
222
  };
223
223
  }
224
+ export const PROMPT_SCREEN_STATIONS = Object.freeze(["prompt.submit", "classic.UserPromptSubmit"]);
225
+ function promptScreenHeard(hears) {
226
+ return PROMPT_SCREEN_STATIONS.some(hears);
227
+ }
224
228
  export function promptScreenHasHandlers(bus) {
225
- return bus.hasHandlers("prompt.submit") || bus.hasHandlers("classic.UserPromptSubmit");
229
+ return promptScreenHeard((station) => bus.hasHandlers(station));
230
+ }
231
+ export function promptScreenDeclaredBy(registrations) {
232
+ const selected = new Set();
233
+ for (const registration of registrations) {
234
+ const patterns = registration?.uses?.events;
235
+ if (!Array.isArray(patterns))
236
+ continue;
237
+ for (const pattern of patterns) {
238
+ const expanded = expandOnSide(pattern, "engine");
239
+ if ("names" in expanded)
240
+ for (const name of expanded.names)
241
+ selected.add(name);
242
+ }
243
+ }
244
+ return promptScreenHeard((station) => selected.has(station));
226
245
  }
227
246
  const PROMPT_SUBMIT_FORM = "prompt.submit takes { text } (a string) or { drop: <reason> }";
228
247
  function readSubmitAnswer(a) {
@@ -8,9 +8,8 @@ import { ENGINE_ORIGIN } from "./kernel/index.js";
8
8
  import { isPlainRecord } from "./kernel/receive.js";
9
9
  import { NEXT_IN_FLIGHT } from "./kernel/site-rules.js";
10
10
  import { classicEventBase, failedHandlerClause, failedHandlerName, judgedInputOf } from "./stations.js";
11
- import { runExtensionCall } from "./extension-call.js";
11
+ import { mintExtensionCallId, runExtensionCall } from "./extension-call.js";
12
12
  import { settleWithheldResult } from "../frame-settlement.js";
13
- import { randomUUID } from "node:crypto";
14
13
  const FORM = "tool.call takes next(e), { deny: <reason> } or { result } (a string, or a list of text blocks)";
15
14
  const denyOf = (a) => isPlainRecord(a) && Object.keys(a).length === 1 && typeof a["deny"] === "string" && a["deny"] !== "" ? a["deny"] : undefined;
16
15
  function substituteOf(a) {
@@ -54,7 +53,7 @@ export function createToolCallStation(input) {
54
53
  const content = [{ type: "text", text: formatHookFeedback(text, input.reminderMark) }];
55
54
  if (by !== undefined) {
56
55
  if (input.occurrences.get(call.toolCallId) !== undefined) {
57
- input.occurrences.refuse(call.toolCallId, "hook", by);
56
+ input.occurrences.refuse(call.toolCallId, "hook", { extension: by });
58
57
  input.occurrences.answeredInPlace(call.toolCallId, by);
59
58
  }
60
59
  input.blockedToolCalls.add(call.toolCallId);
@@ -151,7 +150,7 @@ export function createToolCallEntry(input) {
151
150
  const { tool, ...callInput } = args;
152
151
  if (typeof tool !== "string" || tool === "")
153
152
  throw new TypeError(`${by}: $.tool.call takes the event's input: { tool, ...args }`);
154
- const toolCallId = `ext-${randomUUID()}`;
153
+ const toolCallId = mintExtensionCallId();
155
154
  return runExtensionCall(input.bus, toolCallId, "tool.call", ctx, async (call) => {
156
155
  const finalized = await input.harness.callTool({ type: "toolCall", id: toolCallId, name: tool, arguments: { ...callInput } }, ctx.signal, (t) => {
157
156
  const contractId = input.faceOf(t.name)?.contractId;
@@ -41,11 +41,11 @@ export type ParentSpecSeatFields = Pick<TaskSpec, "principal" | "oneShot" | "cli
41
41
  * · `memory` — the request-level "memory is off" FACT, `{ enabled: false }` and nothing else of the declaration (the clamp
42
42
  * table's `memory.enabled` row; present only when the parent stated `enabled: false`): a REMOVAL (floor) that
43
43
  * REWRITES the one member on the child's own memory declaration — its scopes and knobs are the child's.
44
- * · `compaction` — the request's CONTEXT-MANAGEMENT settings (enabled / withinTask / reserve / keepRecent /
44
+ * · `compaction` — the request's CONTEXT-MANAGEMENT settings (autoCompact / manualCompact / withinTask / reserve / keepRecent /
45
45
  * instructions / attachWorkingFiles / staleToolResultOffload / clampTolerance). One set of settings for the
46
46
  * whole delegation tree, measured per leg against the leg's OWN window: the numbers are repaired against the
47
47
  * child's model by the same sanitizer every leg runs (`sanitizeCompactionSettings`), so a parent's 128k-tuned
48
- * reserve does not have to be re-tuned to be legal on a 6k child. `enabled: false` is NOT a removal — the
48
+ * reserve does not have to be re-tuned to be legal on a 6k child. A seat's `false` is NOT a removal — the
49
49
  * reference implementation shares one settings object down the tree rather than flooring children, and a
50
50
  * child that authors its own settings wins the whole object (an ORDINARY seat member).
51
51
  * · `skillListingBudgetFraction` / `skillListingMaxDescChars` — the listing-budget knobs, the same shape for the
@@ -1,4 +1,4 @@
1
- import { boundInputHashOf, canonicalize } from "./canonical-json.js";
1
+ import { canonicalize, exactBoundInputHashOf } from "./canonical-json.js";
2
2
  import { mintCheckpointId, mintCheckpointToken, resolveCheckpointStore, resolveDeclaredFidelity } from "./checkpoint-store.js";
3
3
  import { stampCheckpointRequirements } from "./checkpoint-requirements.js";
4
4
  import { resolveDeclaredDurability } from "./wiring-manifest.js";
@@ -70,7 +70,7 @@ function syntheticCheckpoint(scope, fidelity) {
70
70
  toolCallId: `${scope}:call`,
71
71
  toolName: "SelfCheck",
72
72
  args: { probe: true, nested: { depth: 2, list: [1, 2, 3] } },
73
- boundInputHash: boundInputHashOf({ probe: true, nested: { depth: 2, list: [1, 2, 3] } }),
73
+ boundInputHash: exactBoundInputHashOf("SelfCheck", { probe: true, nested: { depth: 2, list: [1, 2, 3] } }),
74
74
  hasBidiControls: true,
75
75
  preview: { probe: true, note: "park wiring self-check display stub" },
76
76
  previewWithheld: "oversize",
@@ -82,6 +82,8 @@ export type PendingKind = (typeof PAUSE_REGISTRY)[GateKind]["pending"];
82
82
  export type ResumeGate = (typeof PAUSE_REGISTRY)[GateKind]["resume"] | "wake";
83
83
  /** Runtime twin of {@link GateKind}. */
84
84
  export declare function isGateKind(v: unknown): v is GateKind;
85
+ /** Runtime twin of {@link PendingKind}: a word of the registry's `pending` column. */
86
+ export declare function isPendingKind(v: unknown): v is PendingKind;
85
87
  /**
86
88
  * The approval cards whose parked row takes another deadline semantic than its gate kind's: a question parked under an
87
89
  * approval gate kind is not an approval, so its deadline voids it (`B`) instead of denying it (`A`). Read only on an
@@ -10,6 +10,9 @@ export const PAUSE_REGISTRY = {
10
10
  export function isGateKind(v) {
11
11
  return typeof v === "string" && Object.prototype.hasOwnProperty.call(PAUSE_REGISTRY, v);
12
12
  }
13
+ export function isPendingKind(v) {
14
+ return Object.values(PAUSE_REGISTRY).some((row) => row.pending === v);
15
+ }
13
16
  export const CARD_FACET_OVERRIDES = Object.freeze({ question: "B" });
14
17
  export function facetOf(gate) {
15
18
  const reading = parkedApprovalCardOf(gate);
@@ -6,6 +6,11 @@ export interface PeerChannelSelf {
6
6
  sessionId: string;
7
7
  /** The mailbox scope this session's box lives in. */
8
8
  scope: string;
9
+ /** The occupant of this session's row — its `SessionMetadata.incarnation` — or `null` when the row carries no token. REQUIRED,
10
+ * `null` included: every frame the listener appends is stamped for it (`MailboxPeerMeta.occupant`), the session's drain hands a
11
+ * record only to the occupant it names, and the published registration row carries it so a peer of this engine addresses this
12
+ * session's box the same way. An addressing fact, never a credential. */
13
+ occupant: string | null;
9
14
  /** The doorbell rang (a peer appended to this session's box). The HOST decides what to do with it —
10
15
  * start a turn now, or let the next boundary drain; the engine never starts a turn on a frame. */
11
16
  onNudge?: () => void;
@@ -32,6 +32,7 @@ import { type RuleOwner } from "./rule-owner.js";
32
32
  import type { RuleOfferShapeProblem } from "./rule-offer-read.js";
33
33
  import type { AssertAllKeysHandled } from "./ask-origin.js";
34
34
  import { type PermissionRuleStoreProvider } from "./permission-rule-provider.js";
35
+ import { type RuleRefusalCode, type RuleWriteCommitted } from "./permission-rule-store.js";
35
36
  /** One candidate rule inside an approval record: what it says (`behavior`), the exact text and where it
36
37
  * would apply. A card mints `allow` candidates only (a card is one person's yes); the settings import
37
38
  * carries all three behaviors, each entry under the list it was read from. */
@@ -516,7 +517,12 @@ export declare function precheckEditedRuleText(text: string, command: string): E
516
517
  * `rev` is the DURABLE store's revision. A session-scope redemption (design/382 §4.3) lands in the
517
518
  * session overlay and does not move it: its `rev` is a best-effort read of the store's current
518
519
  * revision (0 when the store could not be read — the landing is in the overlay either way, and the
519
- * durable revision is reporting, not the landing's identity). */
520
+ * durable revision is reporting, not the landing's identity).
521
+ *
522
+ * A refusal is one shape wherever this module refuses — the single ticket, the batch's own record-level refusals and
523
+ * (with the member's identity beside them) a batch member's row: `reason` is the sentence for a person and is never
524
+ * parsed, `code` the cause ({@link RuleRefusalCode}), `committed` what may be claimed about the bytes
525
+ * ({@link RuleWriteCommitted}). */
520
526
  export type RedeemResult = {
521
527
  status: "redeemed";
522
528
  behavior: RuleBehavior;
@@ -527,6 +533,8 @@ export type RedeemResult = {
527
533
  alreadyRedeemed: boolean;
528
534
  } | {
529
535
  status: "refused";
536
+ code: RuleRefusalCode;
537
+ committed: RuleWriteCommitted;
530
538
  reason: string;
531
539
  };
532
540
  /**
@@ -535,6 +543,9 @@ export type RedeemResult = {
535
543
  * Takes a ticket and a verified principal, and nothing else. There is deliberately no field carrying rule
536
544
  * text: what gets persisted is what the engine put in the record when it drew the card, so a host cannot
537
545
  * turn a click on `git status` into a rule for something else.
546
+ *
547
+ * This is also the one leg every member of a batch walk takes ({@link redeemRuleBatch}), so a refusal here is the
548
+ * same `code` / `committed` / `reason` a member row carries (a member's row adds the member's identity).
538
549
  */
539
550
  export declare function redeemRuleTicket(opts: {
540
551
  ticket: RuleTicket;
@@ -597,8 +608,10 @@ export interface ImportPreview {
597
608
  * independent `alreadyRedeemed` axis (the single-leg replay marker: a dot-recorded-but-unlanded
598
609
  * retry is `alreadyRedeemed: true` AND `persisted`; a rule that pre-existed in the store is
599
610
  * `false` AND `deduped` — the two axes answer different questions and neither implies the other).
600
- * A refused row always carries its `reason`. `deduped` counts as LANDED: an equivalent rule
601
- * already standing means the consent is already in effect.
611
+ * A refused row always carries its `reason` (a sentence for a person, never parsed) and two closed words: `code`, the
612
+ * cause ({@link RuleRefusalCode}), and `committed`, what may be claimed about the bytes — the one reading is
613
+ * {@link RuleWriteCommitted}'s, stated there and not here (a member whose dot a successful read finds no longer live is
614
+ * read by it too). `deduped` counts as LANDED: an equivalent rule already standing means the consent is already in effect.
602
615
  *
603
616
  * design/382 §4.3 — on a SESSION-scope member the two landed words mean the same thing about a
604
617
  * different home: landed in / already in the session's OVERLAY (a session rule's home store), never
@@ -620,6 +633,8 @@ export type RedeemedBatchMember = {
620
633
  readonly rule: string;
621
634
  readonly scope: RuleScope;
622
635
  readonly status: "refused";
636
+ readonly code: RuleRefusalCode;
637
+ readonly committed: RuleWriteCommitted;
623
638
  readonly reason: string;
624
639
  };
625
640
  /**
@@ -688,7 +703,7 @@ export declare function prepareStarterBatch(opts: {
688
703
  * dot reuse included; the walk adds no concurrency primitive of its own;
689
704
  * · a refused member does NOT fold the batch: "all or nothing" is the CONFIRMATION's semantics
690
705
  * (one yes covered the whole offer), not the landing's transaction shape — the walk continues
691
- * and the member's row says refused, with the reason;
706
+ * and the member's row says refused, with its reason, cause (`code`) and claim (`committed`);
692
707
  * · resuming a partial walk IS re-walking: already-landed members answer `alreadyRedeemed: true`
693
708
  * and reuse their recorded dots (two concurrent walkers converge on one dot set, zero double
694
709
  * mints), unlanded members mint on;
@@ -696,7 +711,11 @@ export declare function prepareStarterBatch(opts: {
696
711
  * offer's member order, no extras — so a caller's aggregate is an honest projection: all rows
697
712
  * landed (`persisted` or `deduped`, both count as the consent being in effect) is full
698
713
  * success, and ANY refused row must project to a non-success aggregate, never to a silent
699
- * partial one.
714
+ * partial one;
715
+ * · a walk that cannot start (the record is missing or cannot be read, another principal's, stale, pending,
716
+ * malformed, or the owner's store cannot be resolved) answers no table: it answers the
717
+ * {@link RedeemResult} refused arm, `code` / `committed` / `reason`, the one shape a single
718
+ * ticket's refusal and a member's row take.
700
719
  */
701
720
  export declare function redeemRuleBatch(opts: {
702
721
  approvalId: string;
@@ -706,7 +725,6 @@ export declare function redeemRuleBatch(opts: {
706
725
  }): Promise<{
707
726
  members: readonly RedeemedBatchMember[];
708
727
  rev: number;
709
- } | {
728
+ } | Extract<RedeemResult, {
710
729
  status: "refused";
711
- reason: string;
712
- }>;
730
+ }>>;
@@ -657,53 +657,79 @@ async function confirmEditedCandidate(rec, edit, deps) {
657
657
  }
658
658
  return { ok: true, mintedCandidate: { index, rule: checked.canonicalRule, ticket: mintRuleTicket(rec.id, index) } };
659
659
  }
660
+ function refusal(code, reason, committed = "no") {
661
+ return { status: "refused", code, committed, reason };
662
+ }
663
+ async function storeStep(step, failure) {
664
+ try {
665
+ return { value: await step() };
666
+ }
667
+ catch (err) {
668
+ return { refused: refusal(failure.code, `${failure.what}: ${errText(err)}`, failure.code === "store_write" ? "unknown" : "no") };
669
+ }
670
+ }
671
+ const RECORD_READ = { code: "store_read", what: "could not read the approval record" };
672
+ const RECORD_CAS = { code: "store_write", what: "the approval record store failed the compare-and-set that records this redemption's dot" };
673
+ const DOT_ALLOCATION = { code: "store_write", what: "the permission-rule store failed to allocate this redemption's dot" };
660
674
  export async function redeemRuleTicket(opts) {
661
675
  const caller = resolveCallerOwner(opts.principal, opts.owner, "redeemRuleTicket");
662
676
  const parsed = parseRuleTicket(opts.ticket);
663
677
  if (parsed === undefined)
664
- return { status: "refused", reason: "malformed ticket" };
665
- const rec = await opts.deps.approvals.get(parsed.recordId);
678
+ return refusal("ticket_invalid", "malformed ticket");
679
+ const read = await storeStep(() => opts.deps.approvals.get(parsed.recordId), RECORD_READ);
680
+ if ("refused" in read)
681
+ return read.refused;
682
+ const rec = read.value;
666
683
  if (rec === undefined)
667
- return { status: "refused", reason: "no such approval record" };
684
+ return refusal("record_missing", "no such approval record");
668
685
  const recOwner = ownerOfRecord(rec);
669
686
  if (recOwner === undefined || !sameRuleOwner(recOwner, caller))
670
- return { status: "refused", reason: "the ticket belongs to a different principal" };
687
+ return refusal("wrong_principal", "the ticket belongs to a different principal");
671
688
  if (isStale(rec))
672
- return { status: "refused", reason: `record_schema_stale: ${STALE_RECORD_MESSAGE}` };
689
+ return refusal("record_schema_stale", `record_schema_stale: ${STALE_RECORD_MESSAGE}`);
673
690
  if (rec.state === "pending")
674
- return { status: "refused", reason: "the approval record has not been confirmed" };
691
+ return refusal("not_confirmed", "the approval record has not been confirmed");
675
692
  const damage = approvalRecordDamageOf(rec);
676
693
  if (damage !== undefined)
677
- return { status: "refused", reason: `the approval record is malformed: ${damage}` };
694
+ return refusal("record_malformed", `the approval record is malformed: ${damage}`);
678
695
  const candidate = rec.candidates[parsed.index];
679
696
  if (candidate === undefined)
680
- return { status: "refused", reason: "the ticket names no candidate on this record" };
697
+ return refusal("ticket_invalid", "the ticket names no candidate on this record");
681
698
  const chosen = rec.selectedOffer;
682
699
  const chosenOffer = chosen !== undefined && Number.isInteger(chosen) ? rec.offers[chosen] : undefined;
683
700
  if (chosenOffer === undefined) {
684
- return { status: "refused", reason: "the approval record is malformed: it is settled but names no valid chosen offer" };
701
+ return refusal("record_malformed", "the approval record is malformed: it is settled but names no valid chosen offer");
685
702
  }
686
703
  if (!offerMembersOf(chosenOffer).includes(parsed.index)) {
687
- return { status: "refused", reason: "the ticket names an option the person did not choose" };
704
+ return refusal("not_chosen", "the ticket names an option the person did not choose");
688
705
  }
689
706
  const siblingsOf = candidate.behavior === "allow" ? { rec, offer: chosenOffer, index: parsed.index } : undefined;
690
707
  const parsedRule = parseRuleText(candidate.rule, candidate.behavior);
691
708
  if ("reject" in parsedRule)
692
- return { status: "refused", reason: `${parsedRule.reject.code}: ${parsedRule.reject.message}` };
709
+ return refusal("parse_rejected", `${parsedRule.reject.code}: ${parsedRule.reject.message}`);
693
710
  if (rec.kind === "import" && !importCarries(candidate.scope, parsedRule.rule))
694
- return { status: "refused", reason: LAYER_ROOT_RECORD_REASON };
711
+ return refusal("unsupported.layer_root", LAYER_ROOT_RECORD_REASON);
695
712
  let store;
696
713
  try {
697
714
  store = storeForOwner(opts.deps.provider, caller);
698
715
  }
699
716
  catch (err) {
700
- return { status: "refused", reason: errText(err) };
717
+ return refusal("store_unavailable", errText(err));
701
718
  }
702
719
  const writer = writerOf(store);
703
720
  if (writer === undefined)
704
- return { status: "refused", reason: "the resolved permission-rule store has no write face" };
721
+ return refusal("store_unavailable", "the resolved permission-rule store has no write face");
705
722
  const known = rec.redeemedDots?.[parsed.index];
706
- const dot = known ?? (await writer.nextDot());
723
+ let dot;
724
+ if (known !== undefined) {
725
+ dot = known;
726
+ }
727
+ else {
728
+ const minted = await storeStep(() => writer.nextDot(), DOT_ALLOCATION);
729
+ if ("refused" in minted)
730
+ return minted.refused;
731
+ dot = minted.value;
732
+ }
707
733
  if (known === undefined) {
708
734
  const next = {
709
735
  ...rec,
@@ -711,12 +737,17 @@ export async function redeemRuleTicket(opts) {
711
737
  state: "redeemed",
712
738
  redeemedDots: { ...(rec.redeemedDots ?? {}), [parsed.index]: dot },
713
739
  };
714
- const ok = await opts.deps.approvals.cas(rec.id, rec.rev, next);
715
- if (!ok) {
716
- const again = await opts.deps.approvals.get(rec.id);
740
+ const casted = await storeStep(() => opts.deps.approvals.cas(rec.id, rec.rev, next), RECORD_CAS);
741
+ if ("refused" in casted)
742
+ return casted.refused;
743
+ if (!casted.value) {
744
+ const reread = await storeStep(() => opts.deps.approvals.get(rec.id), RECORD_READ);
745
+ if ("refused" in reread)
746
+ return reread.refused;
747
+ const again = reread.value;
717
748
  const theirs = again === undefined || isStale(again) ? undefined : again.redeemedDots?.[parsed.index];
718
749
  if (theirs === undefined)
719
- return { status: "refused", reason: "the approval record changed state concurrently" };
750
+ return refusal("record_changed", "the approval record changed state concurrently");
720
751
  return await applyRedemption({ deps: opts.deps, owner: caller, candidate, parsedRule: parsedRule.rule, dot: theirs, recordId: rec.id, kind: rec.kind, replay: true, ...(siblingsOf !== undefined ? { siblingsOf } : {}) });
721
752
  }
722
753
  }
@@ -745,11 +776,11 @@ async function applyRedemption(args) {
745
776
  store = storeForOwner(args.deps.provider, args.owner);
746
777
  }
747
778
  catch (err) {
748
- return { status: "refused", reason: errText(err) };
779
+ return refusal("store_unavailable", errText(err));
749
780
  }
750
781
  const writer = writerOf(store);
751
782
  if (writer === undefined)
752
- return { status: "refused", reason: "the resolved permission-rule store has no write face" };
783
+ return refusal("store_unavailable", "the resolved permission-rule store has no write face");
753
784
  const origin = originOfRecordKind(args.kind);
754
785
  const siblings = args.siblingsOf;
755
786
  const landing = await landRuleAdd({
@@ -778,7 +809,7 @@ async function applyRedemption(args) {
778
809
  : {}),
779
810
  });
780
811
  if (!landing.landed)
781
- return { status: "refused", reason: landing.reason };
812
+ return refusal(landing.code, landing.reason, landing.committed);
782
813
  return { status: "redeemed", behavior: args.parsedRule.behavior, rule: args.parsedRule.rule, scope: args.candidate.scope, dot: args.dot, rev: landing.rev, alreadyRedeemed: args.replay };
783
814
  }
784
815
  function originOfRecordKind(kind) {
@@ -939,30 +970,33 @@ export async function prepareStarterBatch(opts) {
939
970
  }
940
971
  export async function redeemRuleBatch(opts) {
941
972
  const caller = resolveCallerOwner(opts.principal, opts.owner, "redeemRuleBatch");
942
- const rec = await opts.deps.approvals.get(opts.approvalId);
973
+ const read = await storeStep(() => opts.deps.approvals.get(opts.approvalId), RECORD_READ);
974
+ if ("refused" in read)
975
+ return read.refused;
976
+ const rec = read.value;
943
977
  if (rec === undefined)
944
- return { status: "refused", reason: "no such approval record" };
978
+ return refusal("record_missing", "no such approval record");
945
979
  const recOwner = ownerOfRecord(rec);
946
980
  if (recOwner === undefined || !sameRuleOwner(recOwner, caller))
947
- return { status: "refused", reason: "the record belongs to a different principal" };
981
+ return refusal("wrong_principal", "the record belongs to a different principal");
948
982
  if (isStale(rec))
949
- return { status: "refused", reason: `record_schema_stale: ${STALE_RECORD_MESSAGE}` };
983
+ return refusal("record_schema_stale", `record_schema_stale: ${STALE_RECORD_MESSAGE}`);
950
984
  if (rec.state === "pending")
951
- return { status: "refused", reason: "the approval record has not been confirmed" };
985
+ return refusal("not_confirmed", "the approval record has not been confirmed");
952
986
  const damage = approvalRecordDamageOf(rec);
953
987
  if (damage !== undefined)
954
- return { status: "refused", reason: `the approval record is malformed: ${damage}` };
988
+ return refusal("record_malformed", `the approval record is malformed: ${damage}`);
955
989
  const chosen = rec.selectedOffer;
956
990
  const chosenOffer = chosen !== undefined && Number.isInteger(chosen) ? rec.offers[chosen] : undefined;
957
991
  if (chosenOffer === undefined) {
958
- return { status: "refused", reason: "the approval record is malformed: it is settled but names no valid chosen offer" };
992
+ return refusal("record_malformed", "the approval record is malformed: it is settled but names no valid chosen offer");
959
993
  }
960
994
  let store;
961
995
  try {
962
996
  store = storeForOwner(opts.deps.provider, caller);
963
997
  }
964
998
  catch (err) {
965
- return { status: "refused", reason: errText(err) };
999
+ return refusal("store_unavailable", errText(err));
966
1000
  }
967
1001
  const members = [];
968
1002
  let rev = 0;
@@ -976,7 +1010,7 @@ export async function redeemRuleBatch(opts) {
976
1010
  const candidate = rec.candidates[candidateIndex];
977
1011
  const row = { candidateIndex, behavior: candidate.behavior, rule: candidate.rule, scope: candidate.scope };
978
1012
  if (candidate.behavior === "allow" && tighteningFailed !== undefined) {
979
- members.push({ ...row, status: "refused", reason: `withheld: candidate ${tighteningFailed} (a deny/ask member of this batch) did not land, and an allow must not stand wider than the list that was confirmed — redeem the batch again once the store accepts the tightening member` });
1013
+ members.push({ ...row, ...refusal("withheld", `withheld: candidate ${tighteningFailed} (a deny/ask member of this batch) did not land, and an allow must not stand wider than the list that was confirmed — redeem the batch again once the store accepts the tightening member`) });
980
1014
  continue;
981
1015
  }
982
1016
  let alreadyThere = false;
@@ -987,7 +1021,7 @@ export async function redeemRuleBatch(opts) {
987
1021
  alreadyThere = snap.rules.some((r) => r.behavior === candidate.behavior && r.rule === candidate.rule && sameScope(r.scope, candidate.scope));
988
1022
  }
989
1023
  catch (err) {
990
- members.push({ ...row, status: "refused", reason: `could not read the permission-rule store: ${errText(err)}` });
1024
+ members.push({ ...row, ...refusal("store_read", `could not read the permission-rule store: ${errText(err)}`) });
991
1025
  if (candidate.behavior !== "allow")
992
1026
  tighteningFailed ??= candidateIndex;
993
1027
  continue;
@@ -999,22 +1033,28 @@ export async function redeemRuleBatch(opts) {
999
1033
  deps: opts.deps,
1000
1034
  });
1001
1035
  if (res.status === "refused") {
1002
- members.push({ ...row, status: "refused", reason: res.reason });
1036
+ members.push({ ...row, ...res });
1003
1037
  if (candidate.behavior !== "allow")
1004
1038
  tighteningFailed ??= candidateIndex;
1005
1039
  continue;
1006
1040
  }
1007
1041
  if (candidate.behavior !== "allow") {
1008
1042
  let live = false;
1043
+ let unreadable;
1009
1044
  try {
1010
1045
  const snap = await effectiveOrThrow(store, candidate.scope.kind === "session" ? { sessionId: candidate.scope.sessionId } : undefined);
1011
1046
  live = snap.rules.some((r) => r.behavior === candidate.behavior && r.rule === candidate.rule && sameScope(r.scope, candidate.scope) && r.adds.some((a) => a.dot.actor === res.dot.actor && a.dot.counter === res.dot.counter));
1012
1047
  }
1013
- catch {
1014
- live = false;
1048
+ catch (err) {
1049
+ unreadable = errText(err);
1050
+ }
1051
+ if (unreadable !== undefined) {
1052
+ members.push({ ...row, ...refusal("store_read", `could not read the permission-rule store to confirm this ${candidate.behavior} member stands after its redemption: ${unreadable}`, "unknown") });
1053
+ tighteningFailed ??= candidateIndex;
1054
+ continue;
1015
1055
  }
1016
1056
  if (!live) {
1017
- members.push({ ...row, status: "refused", reason: `this ${candidate.behavior} member's redeemed dot ${res.dot.actor}#${res.dot.counter} is not live in the store (removed since it was redeemed) — a removed rule is not re-landed by replaying its record; a new consent is required` });
1057
+ members.push({ ...row, ...refusal("dot_removed", `this ${candidate.behavior} member's redeemed dot ${res.dot.actor}#${res.dot.counter} is not live in the store (removed since it was redeemed) — a removed rule is not re-landed by replaying its record; a new consent is required`) });
1018
1058
  tighteningFailed ??= candidateIndex;
1019
1059
  continue;
1020
1060
  }