blun-king-cli 9.1.643 → 9.1.645

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 (268) hide show
  1. package/CHANGELOG.md +19 -123
  2. package/LIESMICH.txt +17 -45
  3. package/README.md +15 -76
  4. package/RELEASE-9.1.645.md +29 -0
  5. package/bin/blun.js +3 -3
  6. package/bin/king.js +3 -3
  7. package/bin/launcher-mode.js +125 -126
  8. package/bin/launcher-runtime.js +603 -616
  9. package/bin/plugin-bootstrap.js +339 -405
  10. package/bin/rename-private-staging.cjs +2 -2
  11. package/bin/retired-bundled-plugins.cjs +84 -0
  12. package/bin/startup-security-host.cjs +105 -0
  13. package/bin/startup-security.cjs +9 -105
  14. package/bin/startup-warning-policy.cjs +22 -0
  15. package/bin/update-lease-installer.cjs +125 -0
  16. package/bin/update-lease-sockets.cjs +228 -0
  17. package/bin/update-lease.js +22 -327
  18. package/bin/verify-bundled-agent-sources.cjs +2 -4
  19. package/blun.mjs +77 -180
  20. package/bundled-agent-sources.json +1 -552
  21. package/package.json +3 -6
  22. package/tool-liveness642/receipt.json +1 -1
  23. package/worker-host.mjs +62 -120
  24. package/agent-spine-plugin/.claude-plugin/marketplace.json +0 -20
  25. package/agent-spine-plugin/.claude-plugin/plugin.json +0 -14
  26. package/agent-spine-plugin/.codex-plugin/plugin.json +0 -47
  27. package/agent-spine-plugin/.mcp.json +0 -8
  28. package/agent-spine-plugin/CHANGELOG.md +0 -1614
  29. package/agent-spine-plugin/LICENSE +0 -186
  30. package/agent-spine-plugin/README.md +0 -432
  31. package/agent-spine-plugin/assets/agentspine-banner.svg +0 -32
  32. package/agent-spine-plugin/bin/agentspine-mcp.js +0 -4
  33. package/agent-spine-plugin/bin/agentspine.js +0 -7
  34. package/agent-spine-plugin/blun.plugin.json +0 -68
  35. package/agent-spine-plugin/docs/acceptance.md +0 -61
  36. package/agent-spine-plugin/docs/artifact-evaluation.md +0 -93
  37. package/agent-spine-plugin/docs/host-integration.md +0 -193
  38. package/agent-spine-plugin/docs/preflight-recall.md +0 -71
  39. package/agent-spine-plugin/docs/preservation-contract.md +0 -53
  40. package/agent-spine-plugin/docs/quality-gates.md +0 -50
  41. package/agent-spine-plugin/docs/session-timeline.md +0 -112
  42. package/agent-spine-plugin/docs/source-roots.md +0 -113
  43. package/agent-spine-plugin/docs/world-model.md +0 -119
  44. package/agent-spine-plugin/hooks/codex.json +0 -47
  45. package/agent-spine-plugin/hooks/hooks.json +0 -106
  46. package/agent-spine-plugin/hooks/version.json +0 -5
  47. package/agent-spine-plugin/package.json +0 -77
  48. package/agent-spine-plugin/scripts/check-codex-install.js +0 -226
  49. package/agent-spine-plugin/scripts/check-hosts.js +0 -208
  50. package/agent-spine-plugin/scripts/check-install-hook.js +0 -227
  51. package/agent-spine-plugin/scripts/check-install-selfstarter.js +0 -154
  52. package/agent-spine-plugin/scripts/check-install.js +0 -478
  53. package/agent-spine-plugin/scripts/check-line-budget.js +0 -58
  54. package/agent-spine-plugin/scripts/check-syntax.js +0 -29
  55. package/agent-spine-plugin/scripts/github-actions.js +0 -11
  56. package/agent-spine-plugin/scripts/hermetic-process.js +0 -191
  57. package/agent-spine-plugin/scripts/release-check.js +0 -150
  58. package/agent-spine-plugin/scripts/run-acceptance.js +0 -19
  59. package/agent-spine-plugin/scripts/run-checks.js +0 -50
  60. package/agent-spine-plugin/scripts/run-tests-hermetic.js +0 -112
  61. package/agent-spine-plugin/skills/agent-spine/SKILL.md +0 -99
  62. package/agent-spine-plugin/spine-example/1-identity.md +0 -12
  63. package/agent-spine-plugin/spine-example/2-voice.md +0 -6
  64. package/agent-spine-plugin/spine-example/3-conduct.md +0 -8
  65. package/agent-spine-plugin/spine-example/4-history.md +0 -4
  66. package/agent-spine-plugin/src/cli-agent.js +0 -315
  67. package/agent-spine-plugin/src/cli-attention.js +0 -95
  68. package/agent-spine-plugin/src/cli-autonomy.js +0 -36
  69. package/agent-spine-plugin/src/cli-common.js +0 -71
  70. package/agent-spine-plugin/src/cli-continuity.js +0 -116
  71. package/agent-spine-plugin/src/cli-core.js +0 -128
  72. package/agent-spine-plugin/src/cli-diagnostics.js +0 -291
  73. package/agent-spine-plugin/src/cli-host.js +0 -21
  74. package/agent-spine-plugin/src/cli-learning.js +0 -320
  75. package/agent-spine-plugin/src/cli-premortem.js +0 -16
  76. package/agent-spine-plugin/src/cli-sharing.js +0 -230
  77. package/agent-spine-plugin/src/cli.js +0 -181
  78. package/agent-spine-plugin/src/codex-reader-launcher.js +0 -182
  79. package/agent-spine-plugin/src/hook.js +0 -500
  80. package/agent-spine-plugin/src/index.js +0 -108
  81. package/agent-spine-plugin/src/lib/acceptance.js +0 -435
  82. package/agent-spine-plugin/src/lib/action-lesson-recall.js +0 -118
  83. package/agent-spine-plugin/src/lib/attention-context.js +0 -167
  84. package/agent-spine-plugin/src/lib/attention-events.js +0 -113
  85. package/agent-spine-plugin/src/lib/attention-privacy.js +0 -72
  86. package/agent-spine-plugin/src/lib/attention-schema.js +0 -164
  87. package/agent-spine-plugin/src/lib/attention-storage.js +0 -93
  88. package/agent-spine-plugin/src/lib/attention.js +0 -164
  89. package/agent-spine-plugin/src/lib/audit-premortem.js +0 -223
  90. package/agent-spine-plugin/src/lib/audit.js +0 -401
  91. package/agent-spine-plugin/src/lib/authentication.js +0 -515
  92. package/agent-spine-plugin/src/lib/autonomy-policy.js +0 -110
  93. package/agent-spine-plugin/src/lib/autonomy-store.js +0 -202
  94. package/agent-spine-plugin/src/lib/autonomy.js +0 -8
  95. package/agent-spine-plugin/src/lib/briefing.js +0 -493
  96. package/agent-spine-plugin/src/lib/catalog-document-read.js +0 -51
  97. package/agent-spine-plugin/src/lib/catalog.js +0 -167
  98. package/agent-spine-plugin/src/lib/channel-continuity.js +0 -19
  99. package/agent-spine-plugin/src/lib/channel-runtime.js +0 -665
  100. package/agent-spine-plugin/src/lib/codex-installation.js +0 -231
  101. package/agent-spine-plugin/src/lib/codex-skill-installation.js +0 -211
  102. package/agent-spine-plugin/src/lib/context.js +0 -156
  103. package/agent-spine-plugin/src/lib/continuity.js +0 -338
  104. package/agent-spine-plugin/src/lib/coordination.js +0 -577
  105. package/agent-spine-plugin/src/lib/delivery-agent-usage.js +0 -231
  106. package/agent-spine-plugin/src/lib/delivery-assignment.js +0 -220
  107. package/agent-spine-plugin/src/lib/delivery-command-actions.js +0 -462
  108. package/agent-spine-plugin/src/lib/delivery-knowledge.js +0 -78
  109. package/agent-spine-plugin/src/lib/delivery-premortem-binding.js +0 -107
  110. package/agent-spine-plugin/src/lib/delivery-premortem-closure.js +0 -171
  111. package/agent-spine-plugin/src/lib/delivery-premortem-codec.js +0 -45
  112. package/agent-spine-plugin/src/lib/delivery-premortem-correction.js +0 -101
  113. package/agent-spine-plugin/src/lib/delivery-premortem-file.js +0 -21
  114. package/agent-spine-plugin/src/lib/delivery-premortem-index.js +0 -493
  115. package/agent-spine-plugin/src/lib/delivery-premortem-inspection.js +0 -37
  116. package/agent-spine-plugin/src/lib/delivery-premortem-recovery.js +0 -120
  117. package/agent-spine-plugin/src/lib/delivery-premortem-rejection.js +0 -65
  118. package/agent-spine-plugin/src/lib/delivery-premortem-results.js +0 -28
  119. package/agent-spine-plugin/src/lib/delivery-premortem-session-guard.js +0 -46
  120. package/agent-spine-plugin/src/lib/delivery-premortem-write-ledger.js +0 -285
  121. package/agent-spine-plugin/src/lib/delivery-premortem.js +0 -499
  122. package/agent-spine-plugin/src/lib/delivery-shell-heredoc.js +0 -115
  123. package/agent-spine-plugin/src/lib/delivery-shell-substitutions.js +0 -111
  124. package/agent-spine-plugin/src/lib/delivery-shell-wrapper.js +0 -64
  125. package/agent-spine-plugin/src/lib/delivery-target.js +0 -73
  126. package/agent-spine-plugin/src/lib/delivery-verification.js +0 -445
  127. package/agent-spine-plugin/src/lib/documents.js +0 -239
  128. package/agent-spine-plugin/src/lib/feed-transport.js +0 -499
  129. package/agent-spine-plugin/src/lib/filesystem-retry.js +0 -34
  130. package/agent-spine-plugin/src/lib/gateway-common.js +0 -68
  131. package/agent-spine-plugin/src/lib/gateway-control.js +0 -370
  132. package/agent-spine-plugin/src/lib/gateway-delivery.js +0 -103
  133. package/agent-spine-plugin/src/lib/gateway-execution.js +0 -350
  134. package/agent-spine-plugin/src/lib/gateway-group-response.js +0 -128
  135. package/agent-spine-plugin/src/lib/gateway-host-fencing.js +0 -92
  136. package/agent-spine-plugin/src/lib/gateway-host-lifecycle.js +0 -193
  137. package/agent-spine-plugin/src/lib/gateway-inspection.js +0 -85
  138. package/agent-spine-plugin/src/lib/gateway-knowledge.js +0 -129
  139. package/agent-spine-plugin/src/lib/gateway-policy-provenance.js +0 -197
  140. package/agent-spine-plugin/src/lib/gateway-premortem-disposition.js +0 -82
  141. package/agent-spine-plugin/src/lib/gateway-premortem.js +0 -363
  142. package/agent-spine-plugin/src/lib/gateway-prepared-host.js +0 -28
  143. package/agent-spine-plugin/src/lib/gateway-runs.js +0 -345
  144. package/agent-spine-plugin/src/lib/gateway-runtime-identity.js +0 -31
  145. package/agent-spine-plugin/src/lib/gateway-runtime-records.js +0 -21
  146. package/agent-spine-plugin/src/lib/gateway-runtime.js +0 -18
  147. package/agent-spine-plugin/src/lib/gateway-state-transaction.js +0 -356
  148. package/agent-spine-plugin/src/lib/gateway-state.js +0 -344
  149. package/agent-spine-plugin/src/lib/graph.js +0 -337
  150. package/agent-spine-plugin/src/lib/hook-artifact-guards.js +0 -356
  151. package/agent-spine-plugin/src/lib/hook-audit.js +0 -43
  152. package/agent-spine-plugin/src/lib/hook-briefing-use.js +0 -78
  153. package/agent-spine-plugin/src/lib/hook-context.js +0 -441
  154. package/agent-spine-plugin/src/lib/hook-final-message.js +0 -26
  155. package/agent-spine-plugin/src/lib/hook-input.js +0 -27
  156. package/agent-spine-plugin/src/lib/hook-output.js +0 -284
  157. package/agent-spine-plugin/src/lib/hook-premortem.js +0 -257
  158. package/agent-spine-plugin/src/lib/hook-process-advisory.js +0 -36
  159. package/agent-spine-plugin/src/lib/hook-protection.js +0 -95
  160. package/agent-spine-plugin/src/lib/hook-stop-verification.js +0 -84
  161. package/agent-spine-plugin/src/lib/hook-timeline.js +0 -102
  162. package/agent-spine-plugin/src/lib/host-instruction-budget.js +0 -11
  163. package/agent-spine-plugin/src/lib/https-transport.js +0 -392
  164. package/agent-spine-plugin/src/lib/identifier-analysis.js +0 -446
  165. package/agent-spine-plugin/src/lib/indexed-memory-offline.js +0 -40
  166. package/agent-spine-plugin/src/lib/indexed-memory.js +0 -298
  167. package/agent-spine-plugin/src/lib/knowledge-evidence.js +0 -431
  168. package/agent-spine-plugin/src/lib/learning-applications.js +0 -441
  169. package/agent-spine-plugin/src/lib/learning-artifact-evaluator.js +0 -114
  170. package/agent-spine-plugin/src/lib/learning-candidates.js +0 -274
  171. package/agent-spine-plugin/src/lib/learning-context.js +0 -137
  172. package/agent-spine-plugin/src/lib/learning-delivery-contracts.js +0 -310
  173. package/agent-spine-plugin/src/lib/learning-evaluation-contracts.js +0 -350
  174. package/agent-spine-plugin/src/lib/learning-evaluation-registration.js +0 -372
  175. package/agent-spine-plugin/src/lib/learning-evaluation-revocation.js +0 -292
  176. package/agent-spine-plugin/src/lib/learning-evidence-contracts.js +0 -321
  177. package/agent-spine-plugin/src/lib/learning-findings.js +0 -458
  178. package/agent-spine-plugin/src/lib/learning-measurement-contracts.js +0 -285
  179. package/agent-spine-plugin/src/lib/learning-measurements.js +0 -265
  180. package/agent-spine-plugin/src/lib/learning-outcome-contracts.js +0 -165
  181. package/agent-spine-plugin/src/lib/learning-outcomes.js +0 -343
  182. package/agent-spine-plugin/src/lib/learning-reconciliation.js +0 -290
  183. package/agent-spine-plugin/src/lib/learning-retry-contracts.js +0 -188
  184. package/agent-spine-plugin/src/lib/learning-schema.js +0 -229
  185. package/agent-spine-plugin/src/lib/learning-scope-targets.js +0 -424
  186. package/agent-spine-plugin/src/lib/learning-state-upgrade.js +0 -477
  187. package/agent-spine-plugin/src/lib/learning-status-configuration.js +0 -476
  188. package/agent-spine-plugin/src/lib/learning-storage.js +0 -203
  189. package/agent-spine-plugin/src/lib/learning-trial-recovery.js +0 -218
  190. package/agent-spine-plugin/src/lib/learning-validation-contracts.js +0 -375
  191. package/agent-spine-plugin/src/lib/learning-validation-renewal.js +0 -298
  192. package/agent-spine-plugin/src/lib/learning-validation-runtime.js +0 -234
  193. package/agent-spine-plugin/src/lib/learning.js +0 -36
  194. package/agent-spine-plugin/src/lib/lesson-recall-session.js +0 -172
  195. package/agent-spine-plugin/src/lib/mcp-autonomy-tools.js +0 -37
  196. package/agent-spine-plugin/src/lib/mcp-delivery-completion.js +0 -124
  197. package/agent-spine-plugin/src/lib/mcp-delivery-tools.js +0 -45
  198. package/agent-spine-plugin/src/lib/mcp-premortem.js +0 -68
  199. package/agent-spine-plugin/src/lib/mcp-runtime.js +0 -355
  200. package/agent-spine-plugin/src/lib/mcp-source-context.js +0 -61
  201. package/agent-spine-plugin/src/lib/mcp-timeline-tools.js +0 -240
  202. package/agent-spine-plugin/src/lib/mcp-world-tools.js +0 -52
  203. package/agent-spine-plugin/src/lib/object-transport.js +0 -206
  204. package/agent-spine-plugin/src/lib/owned-file-lock.js +0 -182
  205. package/agent-spine-plugin/src/lib/paths.js +0 -109
  206. package/agent-spine-plugin/src/lib/peer-transport.js +0 -283
  207. package/agent-spine-plugin/src/lib/persona-runtime.js +0 -581
  208. package/agent-spine-plugin/src/lib/pre-answer-timeline-recall.js +0 -104
  209. package/agent-spine-plugin/src/lib/preflight-delivery-id.js +0 -27
  210. package/agent-spine-plugin/src/lib/preflight.js +0 -688
  211. package/agent-spine-plugin/src/lib/project-portfolio.js +0 -176
  212. package/agent-spine-plugin/src/lib/runtime.js +0 -13
  213. package/agent-spine-plugin/src/lib/selfstarter-core.js +0 -382
  214. package/agent-spine-plugin/src/lib/selfstarter-jobs.js +0 -149
  215. package/agent-spine-plugin/src/lib/selfstarter-lease.js +0 -204
  216. package/agent-spine-plugin/src/lib/selfstarter-policy.js +0 -90
  217. package/agent-spine-plugin/src/lib/selfstarter-workspace.js +0 -111
  218. package/agent-spine-plugin/src/lib/selfstarter.js +0 -11
  219. package/agent-spine-plugin/src/lib/session-timeline-auth.js +0 -316
  220. package/agent-spine-plugin/src/lib/session-timeline-codex.js +0 -69
  221. package/agent-spine-plugin/src/lib/session-timeline-contract.js +0 -56
  222. package/agent-spine-plugin/src/lib/session-timeline-enrollment-source.js +0 -38
  223. package/agent-spine-plugin/src/lib/session-timeline-enrollment-storage.js +0 -128
  224. package/agent-spine-plugin/src/lib/session-timeline-enrollment-transport.js +0 -15
  225. package/agent-spine-plugin/src/lib/session-timeline-enrollment.js +0 -478
  226. package/agent-spine-plugin/src/lib/session-timeline-event-extract.js +0 -186
  227. package/agent-spine-plugin/src/lib/session-timeline-host-origin.js +0 -73
  228. package/agent-spine-plugin/src/lib/session-timeline-host-receipt.js +0 -117
  229. package/agent-spine-plugin/src/lib/session-timeline-invocation.js +0 -201
  230. package/agent-spine-plugin/src/lib/session-timeline-king.js +0 -93
  231. package/agent-spine-plugin/src/lib/session-timeline-prior.js +0 -57
  232. package/agent-spine-plugin/src/lib/session-timeline-provider.js +0 -36
  233. package/agent-spine-plugin/src/lib/session-timeline-query.js +0 -56
  234. package/agent-spine-plugin/src/lib/session-timeline-results.js +0 -56
  235. package/agent-spine-plugin/src/lib/session-timeline-root.js +0 -11
  236. package/agent-spine-plugin/src/lib/session-timeline-search.js +0 -82
  237. package/agent-spine-plugin/src/lib/session-timeline-sid-acl.js +0 -213
  238. package/agent-spine-plugin/src/lib/session-timeline-source-open.js +0 -30
  239. package/agent-spine-plugin/src/lib/session-timeline-source.js +0 -80
  240. package/agent-spine-plugin/src/lib/session-timeline-state.js +0 -45
  241. package/agent-spine-plugin/src/lib/session-timeline-transport.js +0 -42
  242. package/agent-spine-plugin/src/lib/session-timeline-windows-acl.js +0 -145
  243. package/agent-spine-plugin/src/lib/session-timeline.js +0 -462
  244. package/agent-spine-plugin/src/lib/sharing.js +0 -969
  245. package/agent-spine-plugin/src/lib/source-roots.js +0 -475
  246. package/agent-spine-plugin/src/lib/source-tree-scan.js +0 -178
  247. package/agent-spine-plugin/src/lib/sqlite-transport.js +0 -501
  248. package/agent-spine-plugin/src/lib/task-knowledge-context.js +0 -99
  249. package/agent-spine-plugin/src/lib/telegram-adapter.js +0 -119
  250. package/agent-spine-plugin/src/lib/timeline-continuation-update.js +0 -100
  251. package/agent-spine-plugin/src/lib/timeline-tool-guard.js +0 -225
  252. package/agent-spine-plugin/src/lib/timeline-user-feedback.js +0 -216
  253. package/agent-spine-plugin/src/lib/timeline-world-capture.js +0 -233
  254. package/agent-spine-plugin/src/lib/voice-runtime.js +0 -39
  255. package/agent-spine-plugin/src/lib/world-knowledge.js +0 -306
  256. package/agent-spine-plugin/src/lib/world-model.js +0 -333
  257. package/agent-spine-plugin/src/mcp.js +0 -456
  258. package/agent-spine-plugin/src/version.js +0 -1
  259. package/agent-spine-plugin/src/worker.js +0 -257
  260. package/bin/agentspine-king-goal-inbox.mjs +0 -127
  261. package/bin/agentspine-king-goal-intake.mjs +0 -106
  262. package/bin/agentspine-king-host-runner.mjs +0 -109
  263. package/bin/agentspine-king-snapshot-policy.cjs +0 -80
  264. package/bin/agentspine-king-status-policy.mjs +0 -226
  265. package/bin/agentspine-king-worker-host.mjs +0 -160
  266. package/bin/managed-plugin-selection.cjs +0 -141
  267. package/bin/verify-agent-behavior.cjs +0 -122
  268. package/bin/verify-agent-components.cjs +0 -104
@@ -1,193 +0,0 @@
1
- import { exactHeldGeneration, heldExecution } from "./gateway-host-fencing.js";
2
-
3
- export const AMBIGUOUS_HOST_OUTCOME =
4
- "Host execution may have produced an effect before restart; manual owner review is required.";
5
-
6
- const EXECUTION_MODES = new Set(["host-effect", "read-only"]);
7
-
8
- function validTimestamp(value) {
9
- return typeof value === "string" && Number.isFinite(new Date(value).getTime());
10
- }
11
-
12
- export function normalizeGatewayExecutionMode(value = "host-effect") {
13
- if (!EXECUTION_MODES.has(value)) {
14
- throw new Error("executionMode must be host-effect or read-only");
15
- }
16
- return value;
17
- }
18
-
19
- export function newGatewayLease(workerId, current, seconds, executionMode) {
20
- return { workerId, claimedAt: current, executionMode,
21
- expiresAt: new Date(new Date(current).getTime() + seconds * 1000).toISOString(),
22
- ...(executionMode === "host-effect" ? { effectMayStartAt: current } : {}) };
23
- }
24
-
25
- export function assertGatewayCompletionMode(lease, result) {
26
- if (lease.executionMode === "read-only") {
27
- if (result?.readOnly !== true) {
28
- throw new Error("read-only gateway lease completion requires result.readOnly: true");
29
- }
30
- return false;
31
- }
32
- if (!validTimestamp(lease?.hostStartedAt)) {
33
- throw new Error("gateway lease with possible host effects requires markGatewayHostStarted before completion");
34
- }
35
- return true;
36
- }
37
-
38
- export function matchesGatewayLaneLease(lane, queue) {
39
- return queue?.status === "leased" && queue.lease?.workerId === lane.workerId
40
- && queue.lease.claimedAt === lane.claimedAt && queue.lease.expiresAt === lane.expiresAt;
41
- }
42
-
43
- export function exactGatewayLeaseGeneration(claimedAt, attempt, action) {
44
- if (!validTimestamp(claimedAt) || !Number.isInteger(attempt) || attempt < 1) {
45
- throw new Error(`${action} requires claimedAt and attempt from the exact active queue lease`);
46
- }
47
- return new Date(claimedAt).toISOString();
48
- }
49
-
50
- export function requireExactGatewayLease(runtime, item, { workerId, claimedAt, attempt, current, action, allowHeld = false }) {
51
- if (allowHeld && heldExecution(item)?.hostSessionId
52
- && exactHeldGeneration(item, { workerId, claimedAt, attempt })) {
53
- const lane = runtime.lanes.find((entry) => entry.queueId === item.queueId && entry.workerId === workerId
54
- && entry.claimedAt === claimedAt && ["leased", "expired"].includes(entry.status));
55
- if (lane) return lane;
56
- }
57
- if (!item || item.status !== "leased" || item.attempts !== attempt
58
- || item.lease?.workerId !== workerId || item.lease.claimedAt !== claimedAt
59
- || new Date(item.lease.expiresAt) <= new Date(current)) {
60
- throw new Error(`${action} requires the exact active queue lease`);
61
- }
62
- const lane = runtime.lanes.find((entry) => entry.queueId === item.queueId && entry.workerId === workerId
63
- && entry.claimedAt === claimedAt && entry.expiresAt === item.lease.expiresAt && entry.status === "leased");
64
- if (!lane) throw new Error("agent lane lease is missing");
65
- return lane;
66
- }
67
-
68
- export function validGatewayLeaseExecution(lease) {
69
- if (lease?.executionMode === undefined) {
70
- return lease?.effectMayStartAt === undefined
71
- && (lease.hostStartedAt === undefined || validTimestamp(lease.hostStartedAt));
72
- }
73
- if (lease.executionMode === "host-effect") {
74
- return validTimestamp(lease.effectMayStartAt)
75
- && (lease.hostStartedAt === undefined || validTimestamp(lease.hostStartedAt));
76
- }
77
- return lease.executionMode === "read-only" && lease.effectMayStartAt === undefined
78
- && lease.hostStartedAt === undefined;
79
- }
80
-
81
- export function leaseMayHaveHostEffect(lease) {
82
- return lease?.executionMode !== "read-only";
83
- }
84
-
85
- export function hasAmbiguousHostOutcome(runtime) {
86
- return runtime.receipts.some((receipt) => receipt.kind === "host-outcome-ambiguous");
87
- }
88
-
89
- export function gatewayHostHealthFindings(runtime) {
90
- if (runtime.health.host !== "failed") return [];
91
- return ["host-not-healthy", ...(hasAmbiguousHostOutcome(runtime) ? ["host-outcome-ambiguous"] : [])];
92
- }
93
-
94
- function markAmbiguousHostHealth(runtime, current) {
95
- runtime.health.host = "failed";
96
- runtime.health.worker = "degraded";
97
- runtime.health.lastTickAt = current;
98
- }
99
-
100
- export function requireExactHostLease(runtime, item, { workerId, claimedAt, attempt, current }) {
101
- const lane = requireExactGatewayLease(runtime, item,
102
- { workerId, claimedAt, attempt, current, action: "host start" });
103
- if (item.lease.executionMode !== "host-effect") {
104
- throw new Error("host start requires a host-effect lease");
105
- }
106
- if (item.lease.hostStartedAt) throw new Error("the exact queue lease already started host execution");
107
- return lane;
108
- }
109
-
110
- export function markHostStarted(runtime, item, lane, workerId, current, { preserve, appendReceipt }) {
111
- preserve(runtime, "queue", item, "host-started", current);
112
- item.lease.hostStartedAt = current;
113
- item.updatedAt = current;
114
- lane.updatedAt = current;
115
- runtime.revision += 1;
116
- return appendReceipt(runtime, "host-started", item.queueId, current,
117
- { workerId, attempt: item.attempts });
118
- }
119
-
120
- function blockBoundGoal(policy, item, current) {
121
- const goal = item.goalId ? policy.goals.find((entry) => entry.goalId === item.goalId) : null;
122
- if (!goal || goal.status !== "active") return false;
123
- const step = item.goalStepId && goal.plan
124
- ? goal.plan.steps.find((entry) => entry.stepId === item.goalStepId) : null;
125
- if (goal.plan && (step?.stepId !== goal.plan.currentStepId || step.status !== "active")) return false;
126
- policy.history.push({ kind: "goal", at: current, value: structuredClone(goal),
127
- authority: "authenticated-goal-policy" });
128
- goal.status = "blocked";
129
- goal.blocker = AMBIGUOUS_HOST_OUTCOME;
130
- goal.heartbeatAt = current;
131
- goal.updatedAt = current;
132
- if (step) {
133
- step.status = "blocked";
134
- step.blocker = AMBIGUOUS_HOST_OUTCOME;
135
- step.updatedAt = current;
136
- goal.plan.revision += 1;
137
- }
138
- policy.revision += 1;
139
- return true;
140
- }
141
-
142
- export function expireGatewayLane(policy, runtime, lane, current, { preserve, appendReceipt }) {
143
- const item = runtime.queue.find((entry) => entry.queueId === lane.queueId && entry.status === "leased");
144
- if (item?.lease && leaseMayHaveHostEffect(item.lease)) {
145
- const { hostStartedAt = null, effectMayStartAt = null, executionMode = "legacy-unknown" } = item.lease;
146
- preserve(runtime, "queue", item, "host-outcome-ambiguous", current);
147
- item.status = "blocked";
148
- item.lease = null;
149
- item.lastError = AMBIGUOUS_HOST_OUTCOME;
150
- item.completedAt = current;
151
- item.updatedAt = current;
152
- appendReceipt(runtime, "host-outcome-ambiguous", item.queueId, current,
153
- { attempt: item.attempts, hostStartedAt, effectMayStartAt, executionMode });
154
- lane.status = "expired";
155
- lane.updatedAt = current;
156
- markAmbiguousHostHealth(runtime, current);
157
- return blockBoundGoal(policy, item, current);
158
- }
159
- if (item) {
160
- preserve(runtime, "queue", item, "lease-expired", current);
161
- item.status = item.attempts >= 3 ? "dead-letter" : "pending";
162
- item.lease = null;
163
- item.updatedAt = current;
164
- }
165
- lane.status = "expired";
166
- lane.updatedAt = current;
167
- return false;
168
- }
169
-
170
- export function failGatewayLane(policy, runtime, item, lane, current,
171
- { error, retryAfterMs, preserve, appendReceipt }) {
172
- if (leaseMayHaveHostEffect(item.lease)) {
173
- expireGatewayLane(policy, runtime, lane, current, { preserve, appendReceipt });
174
- runtime.revision += 1;
175
- return { ambiguous: true, receipt: runtime.receipts.at(-1) };
176
- }
177
- preserve(runtime, "queue", item, "run-failed", current);
178
- item.status = item.attempts >= 3 ? "dead-letter" : "pending";
179
- item.lease = null;
180
- item.lastError = error;
181
- item.updatedAt = current;
182
- item.availableAt = new Date(new Date(current).getTime() + retryAfterMs).toISOString();
183
- if (item.status === "dead-letter") item.completedAt = current;
184
- lane.status = "completed";
185
- lane.updatedAt = current;
186
- runtime.health.host = "failed";
187
- runtime.health.worker = "degraded";
188
- runtime.health.lastTickAt = current;
189
- runtime.revision += 1;
190
- return { ambiguous: false, receipt: appendReceipt(runtime,
191
- item.status === "dead-letter" ? "run-dead-letter" : "run-retry",
192
- item.queueId, current, { attempt: item.attempts }) };
193
- }
@@ -1,85 +0,0 @@
1
- import { gatewayHostHealthFindings } from "./gateway-host-lifecycle.js";
2
- import { emptyPolicy, emptyRuntime, exactId } from "./gateway-common.js";
3
- import { executionAttemptForStep } from "./gateway-execution.js";
4
- import {
5
- conflictingResources, currentPlanStep, gatewayRuntimeFindings, normalizePolicy,
6
- normalizeRuntime, pathsFor, planStepAgentId, readJson, withLock
7
- } from "./gateway-state.js";
8
-
9
- export async function loadGatewayRuntime(root = process.cwd(), catalog = null) {
10
- const paths = await pathsFor(root, catalog);
11
- return withLock(paths, async () => {
12
- const [policy, runtime] = await Promise.all([
13
- readJson(paths.gatewayPolicyPath, paths.catalog.root, normalizePolicy, emptyPolicy),
14
- readJson(paths.gatewayRuntimePath, paths.catalog.root, normalizeRuntime, emptyRuntime)
15
- ]);
16
- return { policy, runtime, ...paths };
17
- });
18
- }
19
-
20
- export async function inspectGatewayRuntime(root = process.cwd(), catalog = null) {
21
- const paths = await pathsFor(root, catalog); const errors = [];
22
- let policy = emptyPolicy(paths.catalog.root); let runtime = emptyRuntime(paths.catalog.root);
23
- try {
24
- await withLock(paths, async () => {
25
- try { policy = await readJson(paths.gatewayPolicyPath, paths.catalog.root, normalizePolicy, emptyPolicy); }
26
- catch (error) { errors.push("policy:" + error.message); }
27
- try { runtime = await readJson(paths.gatewayRuntimePath, paths.catalog.root, normalizeRuntime, emptyRuntime); }
28
- catch (error) { errors.push("runtime:" + error.message); }
29
- });
30
- } catch (error) { errors.push("transaction:" + error.message); }
31
- return { policy, runtime, errors, ...paths };
32
- }
33
-
34
-
35
- export { gatewayRuntimeFindings } from "./gateway-state.js";
36
-
37
- export function gatewayHealthFindings(policy, runtime, { now = new Date(), staleAfterMs = 180000 } = {}) {
38
- if (!policy.enabled || policy.killSwitch) return [];
39
- const findings = [];
40
- if (runtime.health.gateway !== "running") findings.push("gateway-not-running");
41
- if (runtime.health.scheduler !== "healthy") findings.push("scheduler-not-healthy");
42
- if (runtime.health.queue !== "healthy") findings.push("queue-not-healthy");
43
- if (!new Set(["healthy", "degraded"]).has(runtime.health.worker)) findings.push("worker-not-healthy");
44
- if (!new Set(["healthy", "degraded"]).has(runtime.health.adapter)) findings.push("adapter-not-healthy");
45
- findings.push(...gatewayHostHealthFindings(runtime));
46
- const current = now instanceof Date ? now : new Date(now);
47
- const tick = runtime.health.lastTickAt === null ? null : new Date(runtime.health.lastTickAt);
48
- const reconciliation = runtime.health.lastReconciledAt === null ? null : new Date(runtime.health.lastReconciledAt);
49
- if (!tick || current.getTime() - tick.getTime() > staleAfterMs) findings.push("worker-heartbeat-stale");
50
- if (!reconciliation || current.getTime() - reconciliation.getTime() > staleAfterMs) findings.push("scheduler-heartbeat-stale");
51
- return findings;
52
- }
53
-
54
- export async function gatewayContext({ root = process.cwd(), agentId = null } = {}) {
55
- const { policy, runtime } = await loadGatewayRuntime(root);
56
- const findings = gatewayRuntimeFindings(policy, runtime);
57
- if (findings.length) throw new Error("gateway runtime failed closed: " + findings.join(", "));
58
- const exactAgentId = agentId === null ? null : exactId(agentId, "agentId");
59
- const goals = policy.goals.filter((item) => exactAgentId === null || item.agentId === exactAgentId
60
- || item.plan?.steps.some((step) => planStepAgentId(item, step) === exactAgentId));
61
- const executionAttempts = goals.map((goal) => {
62
- const step = currentPlanStep(goal); const attempt = executionAttemptForStep(step);
63
- return attempt && (exactAgentId === null || planStepAgentId(goal, step) === exactAgentId)
64
- ? { goalId: goal.goalId, goalStepId: step.stepId, ...attempt } : null;
65
- }).filter(Boolean);
66
- const queue = runtime.queue.filter((item) => exactAgentId === null || item.agentId === exactAgentId);
67
- const queueIds = new Set(queue.map((item) => item.queueId));
68
- const leased = runtime.queue.filter((item) => item.status === "leased");
69
- const resourceWaits = queue.filter((item) => item.status === "pending").map((item) => {
70
- const blockers = leased.map((entry) => ({ entry, resources: conflictingResources(policy, item, entry) }))
71
- .filter(({ resources }) => resources.length > 0);
72
- return blockers.length ? {
73
- queueId: item.queueId,
74
- resources: [...new Set(blockers.flatMap(({ resources }) => resources))].sort(),
75
- blockedByQueueIds: blockers.map(({ entry }) => entry.queueId).sort(),
76
- authority: "execution-state-only"
77
- } : null;
78
- }).filter(Boolean);
79
- return { schema: "agentspine.gateway-context/v1", enabled: policy.enabled, killSwitch: policy.killSwitch,
80
- goals: structuredClone(goals), queue: structuredClone(queue),
81
- outbox: structuredClone(runtime.outbox.filter((item) => queueIds.has(item.queueId))),
82
- resourceWaits, executionAttempts,
83
- health: structuredClone(runtime.health), healthFindings: gatewayHealthFindings(policy, runtime),
84
- authority: "execution-state-only" };
85
- }
@@ -1,129 +0,0 @@
1
- import {
2
- createKnowledgeGap, createSelfHelpRequirement, createSelfHelpResolution,
3
- pendingSelfHelpRequirement
4
- } from "./knowledge-evidence.js";
5
-
6
- function blockKnowledgeLimit({ goal, step, item, runtime, current, appendReceipt }, kind) {
7
- const reason = `Goal step reached the bounded limit of 16 ${kind}; local review is required.`;
8
- item.status = "blocked"; item.lastError = reason; item.completedAt = current;
9
- step.status = "blocked"; step.blocker = reason; step.updatedAt = current;
10
- goal.status = "blocked"; goal.blocker = reason; goal.updatedAt = current;
11
- appendReceipt(runtime, "self-help-limit-exhausted", item.queueId, current,
12
- { goalStepId: step.stepId, limit: 16, category: kind });
13
- return null;
14
- }
15
-
16
- function resolvedSelfHelp({ goal, step, item, runtime, current, request,
17
- appendReceipt, newGoalQueue, planQueueKey }) {
18
- if (!Array.isArray(step.knowledgeGaps)) step.knowledgeGaps = [];
19
- if (!Array.isArray(step.selfHelpReports)) step.selfHelpReports = [];
20
- const resolved = createSelfHelpResolution({ goal, step, queueId: item.queueId,
21
- report: request, agentId: item.agentId, now: current });
22
- const existingGap = step.knowledgeGaps.find((gap) => gap.gapId === resolved.gap.gapId);
23
- if (existingGap) {
24
- goal.blocker = "The host repeated an already resolved self-help question.";
25
- step.status = "blocked"; step.blocker = goal.blocker; goal.status = "blocked";
26
- appendReceipt(runtime, "self-help-research-regression", item.queueId, current,
27
- { goalStepId: step.stepId, reportId: resolved.report.reportId, gapId: existingGap.gapId });
28
- return null;
29
- }
30
- if (step.knowledgeGaps.length >= 16 || step.selfHelpReports.length >= 16) {
31
- return blockKnowledgeLimit({ goal, step, item, runtime, current, appendReceipt },
32
- "self-help research resolutions");
33
- }
34
- step.knowledgeGaps.push(resolved.gap); step.selfHelpReports.push(resolved.report);
35
- if (resolved.status === "needs-owner-input") {
36
- item.status = "blocked"; step.status = "blocked"; step.blocker = resolved.gap.question;
37
- goal.status = "blocked"; goal.blocker = resolved.gap.question;
38
- appendReceipt(runtime, "self-help-research-exhausted", item.queueId, current,
39
- { goalStepId: step.stepId, reportId: resolved.report.reportId, gapId: resolved.gap.gapId });
40
- appendReceipt(runtime, "knowledge-gap-opened", item.queueId, current,
41
- { goalStepId: step.stepId, gapId: resolved.gap.gapId, requiredEvidence: "owner-input" });
42
- return { clarification: structuredClone(resolved.gap), report: structuredClone(resolved.report) };
43
- }
44
- step.status = "active"; step.blocker = null; goal.status = "active"; goal.blocker = null;
45
- goal.nextSafeStep = step.title;
46
- const key = planQueueKey(goal.goalId, step.stepId, "self-help", resolved.report.reportDigest.slice(0, 20));
47
- let queued = runtime.queue.find((entry) => entry.dedupeKey === key);
48
- if (!queued) { queued = newGoalQueue(goal, step, "follow-up", key, current); runtime.queue.push(queued); }
49
- appendReceipt(runtime, "self-help-research-resolved", queued.queueId, current,
50
- { goalStepId: step.stepId, reportId: resolved.report.reportId, gapId: resolved.gap.gapId });
51
- return { report: structuredClone(resolved.report), queueId: queued.queueId };
52
- }
53
-
54
- function requireSelfHelp({ goal, step, item, runtime, current, request,
55
- appendReceipt, newGoalQueue, planQueueKey }) {
56
- if (!Array.isArray(step.selfHelpRequirements)) step.selfHelpRequirements = [];
57
- const pending = pendingSelfHelpRequirement(step);
58
- if (pending) {
59
- const same = pending.question === request.question?.trim().replace(/\s+/g, " ")
60
- && pending.reason === request.reason?.trim().replace(/\s+/g, " ");
61
- goal.blocker = same
62
- ? "The host repeated a question before completing required repository-first self-help."
63
- : "The host changed an objective question before completing required repository-first self-help.";
64
- item.status = "blocked"; step.status = "blocked"; step.blocker = goal.blocker; goal.status = "blocked";
65
- appendReceipt(runtime, "self-help-requirement-regression", item.queueId, current,
66
- { goalStepId: step.stepId, requirementId: pending.requirementId, repeated: same });
67
- return null;
68
- }
69
- if (step.selfHelpRequirements.length >= 16) {
70
- return blockKnowledgeLimit({ goal, step, item, runtime, current, appendReceipt },
71
- "self-help requirements");
72
- }
73
- const requirement = createSelfHelpRequirement(goal, step, item.queueId, request, current);
74
- step.selfHelpRequirements.push(requirement); item.status = "completed";
75
- step.status = "active"; step.blocker = null; goal.status = "active"; goal.blocker = null;
76
- goal.nextSafeStep = step.title;
77
- const key = planQueueKey(goal.goalId, step.stepId, "self-help-required",
78
- requirement.requirementDigest.slice(0, 20));
79
- let queued = runtime.queue.find((entry) => entry.dedupeKey === key);
80
- if (!queued) { queued = newGoalQueue(goal, step, "follow-up", key, current); runtime.queue.push(queued); }
81
- appendReceipt(runtime, "self-help-required", queued.queueId, current,
82
- { goalStepId: step.stepId, requirementId: requirement.requirementId });
83
- return { requirement: structuredClone(requirement), queueId: queued.queueId };
84
- }
85
-
86
- function openOwnerGap({ goal, step, item, runtime, current, request, appendReceipt }) {
87
- const pending = pendingSelfHelpRequirement(step);
88
- if (pending) {
89
- goal.blocker = "The host asked the owner before completing required repository-first self-help.";
90
- item.status = "blocked"; step.status = "blocked"; step.blocker = goal.blocker; goal.status = "blocked";
91
- appendReceipt(runtime, "self-help-requirement-regression", item.queueId, current,
92
- { goalStepId: step.stepId, requirementId: pending.requirementId, prematureOwnerQuestion: true });
93
- return null;
94
- }
95
- if (!Array.isArray(step.knowledgeGaps)) step.knowledgeGaps = [];
96
- const proposed = createKnowledgeGap(goal, step, item.queueId, request, current);
97
- const existing = step.knowledgeGaps.find((gap) => gap.gapId === proposed.gapId);
98
- if (!existing && step.knowledgeGaps.length >= 16) {
99
- return blockKnowledgeLimit({ goal, step, item, runtime, current, appendReceipt }, "knowledge gaps");
100
- }
101
- if (existing?.status === "resolved") {
102
- goal.blocker = "The host repeated an already resolved knowledge gap.";
103
- step.status = "blocked"; step.blocker = goal.blocker; goal.status = "blocked";
104
- appendReceipt(runtime, "knowledge-gap-regression", item.queueId, current,
105
- { goalStepId: step.stepId, gapId: existing.gapId });
106
- return null;
107
- }
108
- const gap = existing || proposed;
109
- if (!existing) step.knowledgeGaps.push(gap);
110
- goal.blocker = gap.question; step.status = "blocked"; step.blocker = gap.question; goal.status = "blocked";
111
- appendReceipt(runtime, "knowledge-gap-opened", item.queueId, current,
112
- { goalStepId: step.stepId, gapId: gap.gapId, requiredEvidence: gap.requiredEvidence });
113
- return structuredClone(gap);
114
- }
115
-
116
- export function handlePlanKnowledge(options) {
117
- const { goal, step, item, runtime, current, selfHelpRequest, knowledgeGapRequest } = options;
118
- if (!selfHelpRequest && !knowledgeGapRequest) return null;
119
- let result;
120
- if (selfHelpRequest) {
121
- const handled = resolvedSelfHelp({ ...options, request: selfHelpRequest });
122
- result = handled?.clarification ? handled : { selfHelp: handled };
123
- }
124
- else if (knowledgeGapRequest.requiredEvidence === "objective-observation") {
125
- result = { selfHelpRequired: requireSelfHelp({ ...options, request: knowledgeGapRequest }) };
126
- } else result = { clarification: openOwnerGap({ ...options, request: knowledgeGapRequest }) };
127
- goal.plan.revision += 1;
128
- return result;
129
- }
@@ -1,197 +0,0 @@
1
- import { createHash, randomUUID } from "node:crypto";
2
- import { readFile, stat, unlink, writeFile } from "node:fs/promises";
3
- import { basename, dirname, join } from "node:path";
4
- import { replaceFileWithRetry } from "./filesystem-retry.js";
5
-
6
- const PROVENANCE_SCHEMA = "agentspine.gateway-policy-provenance/v1";
7
- const REGISTRY_AUTHORITY = "context-only-contract-provenance";
8
- const POLICY_SCHEMA = "agentspine.gateway-policy/v2";
9
- const POLICY_BYTES = 8 * 1024 * 1024;
10
- const PROVENANCE_BYTES = 8 * 1024;
11
- const DIGEST_RE = /^[a-f0-9]{64}$/;
12
- const PROVENANCE_FILE_DIGEST = Symbol("gateway-policy-provenance-file-digest");
13
- export const GOAL_PREMORTEM_CONTRACT = "agentspine.goal-premortem/v1";
14
-
15
- function canonical(value) {
16
- if (value === null || typeof value !== "object") return JSON.stringify(value);
17
- if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`;
18
- return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${canonical(value[key])}`).join(",")}}`;
19
- }
20
- function sha256(value) {
21
- return createHash("sha256").update(typeof value === "string" ? value : canonical(value)).digest("hex");
22
- }
23
- function exactKeys(value, keys) {
24
- return value && canonical(Object.keys(value).sort()) === canonical([...keys].sort());
25
- }
26
- function seal(value) {
27
- return { ...value, digest: sha256(value) };
28
- }
29
- function validSeal(value) {
30
- if (!value || !DIGEST_RE.test(value.digest || "")) return false;
31
- const material = { ...value };
32
- delete material.digest;
33
- return value.digest === sha256(material);
34
- }
35
- function policyProvenance(root, policySchema, state, previousPolicyDigest, nextPolicyDigest) {
36
- return seal({ schema: PROVENANCE_SCHEMA, projectRootDigest: sha256(root), policySchema,
37
- contract: GOAL_PREMORTEM_CONTRACT, state, previousPolicyDigest, nextPolicyDigest,
38
- authority: REGISTRY_AUTHORITY });
39
- }
40
-
41
- export function validGatewayPolicyProvenance(value, root, policySchema) {
42
- return exactKeys(value, ["schema", "projectRootDigest", "policySchema", "contract", "state",
43
- "previousPolicyDigest", "nextPolicyDigest", "authority", "digest"])
44
- && value.schema === PROVENANCE_SCHEMA && value.projectRootDigest === sha256(root)
45
- && value.policySchema === policySchema && value.contract === GOAL_PREMORTEM_CONTRACT
46
- && new Set(["prepared", "committed"]).has(value.state)
47
- && (value.previousPolicyDigest === null || DIGEST_RE.test(value.previousPolicyDigest || ""))
48
- && DIGEST_RE.test(value.nextPolicyDigest || "")
49
- && value.authority === REGISTRY_AUTHORITY && validSeal(value);
50
- }
51
-
52
- async function readPolicyProvenance(path) {
53
- const provenancePath = join(dirname(path), "gateway-policy-provenance.json");
54
- try {
55
- const metadata = await stat(provenancePath);
56
- if (metadata.size > PROVENANCE_BYTES) throw new Error("gateway policy provenance exceeds 8 KiB");
57
- const text = await readFile(provenancePath, "utf8");
58
- if (Buffer.byteLength(text) > PROVENANCE_BYTES) throw new Error("gateway policy provenance exceeds 8 KiB");
59
- const value = JSON.parse(text);
60
- if (value && typeof value === "object") {
61
- Object.defineProperty(value, PROVENANCE_FILE_DIGEST, { value: sha256(text) });
62
- }
63
- return value;
64
- } catch (error) {
65
- if (error.code === "ENOENT") return null;
66
- throw error;
67
- }
68
- }
69
- async function currentGatewayDigest(path) {
70
- try { return sha256(await readFile(path, "utf8")); }
71
- catch (error) { if (error.code === "ENOENT") return null; throw error; }
72
- }
73
- async function atomicGatewayWrite(path, content, maximum = POLICY_BYTES, guard = {}) {
74
- if (Buffer.byteLength(content) > maximum) throw new Error("gateway state exceeds its byte limit");
75
- const temporary = `${path}.${process.pid}.${randomUUID()}.tmp`;
76
- try {
77
- await writeFile(temporary, content, { mode: 0o600 });
78
- await replaceFileWithRetry(temporary, path, { beforeAttempt: async () => {
79
- await guard.assertOwned?.();
80
- if (Object.hasOwn(guard, "expectedDigest")
81
- && await currentGatewayDigest(path) !== guard.expectedDigest) {
82
- throw new Error("gateway state predecessor changed before atomic replace");
83
- }
84
- await guard.assertRelated?.();
85
- await guard.assertOwned?.();
86
- } });
87
- } finally {
88
- await unlink(temporary).catch((error) => { if (error.code !== "ENOENT") throw error; });
89
- }
90
- }
91
- async function commitObservedPolicyProvenance(path, root, provenance, match, policyDigest, assertOwned) {
92
- if (provenance.state !== "prepared" || typeof assertOwned !== "function") return;
93
- const provenancePath = join(dirname(path), "gateway-policy-provenance.json");
94
- const priorDigest = match === "next" ? provenance.previousPolicyDigest : provenance.nextPolicyDigest;
95
- const committed = policyProvenance(root, provenance.policySchema, "committed", priorDigest, policyDigest);
96
- const assertObserved = async () => {
97
- if (await currentGatewayDigest(path) !== policyDigest) {
98
- throw new Error("gateway policy changed before prepared provenance recovery");
99
- }
100
- };
101
- await atomicGatewayWrite(provenancePath, `${JSON.stringify(committed, null, 2)}\n`, PROVENANCE_BYTES, {
102
- assertOwned, assertRelated: assertObserved, expectedDigest: provenance[PROVENANCE_FILE_DIGEST]
103
- });
104
- }
105
-
106
- export async function readGatewayJson(path, root, normalize, empty, guard = {}) {
107
- const policyFile = basename(path) === "gateway-policy.json";
108
- for (let attempt = 0; attempt < (policyFile ? 4 : 1); attempt += 1) {
109
- const provenance = policyFile ? await readPolicyProvenance(path) : null;
110
- let text;
111
- try {
112
- const metadata = await stat(path);
113
- if (metadata.size > POLICY_BYTES) throw new Error("gateway state exceeds 8 MiB");
114
- text = await readFile(path, "utf8");
115
- if (Buffer.byteLength(text) > POLICY_BYTES) throw new Error("gateway state exceeds 8 MiB");
116
- } catch (error) {
117
- if (error.code !== "ENOENT") throw error;
118
- const after = policyFile ? await readPolicyProvenance(path) : null;
119
- if (canonical(provenance) !== canonical(after)) continue;
120
- if (provenance && (!validGatewayPolicyProvenance(provenance, root, POLICY_SCHEMA)
121
- || provenance.state !== "prepared" || provenance.previousPolicyDigest !== null)) {
122
- throw new Error("gateway policy is missing while provenance exists");
123
- }
124
- if (provenance && typeof guard.assertOwned === "function") {
125
- const value = normalize(empty(root), root, { record: provenance, match: "previous" });
126
- await writeGatewayJson(path, value, { assertOwned: guard.assertOwned,
127
- afterWrite: guard.afterWrite, expectedDigest: null });
128
- return value;
129
- }
130
- return empty(root);
131
- }
132
- const after = policyFile ? await readPolicyProvenance(path) : null;
133
- if (canonical(provenance) !== canonical(after)) continue;
134
- let anchored = null;
135
- if (provenance) {
136
- if (!validGatewayPolicyProvenance(provenance, root, POLICY_SCHEMA)) {
137
- throw new Error("gateway policy provenance is invalid");
138
- }
139
- const policyDigest = sha256(text);
140
- const match = policyDigest === provenance.nextPolicyDigest ? "next"
141
- : policyDigest === provenance.previousPolicyDigest ? "previous" : null;
142
- if (!match) throw new Error("gateway policy does not match its persisted provenance");
143
- anchored = { record: provenance, match };
144
- }
145
- const parsed = JSON.parse(text);
146
- const legacyPolicy = policyFile && parsed?.schema === "agentspine.gateway-policy/v1";
147
- const value = normalize(parsed, root, anchored);
148
- if (legacyPolicy && typeof guard.assertOwned === "function") {
149
- await writeGatewayJson(path, value, { assertOwned: guard.assertOwned,
150
- afterWrite: guard.afterWrite, expectedDigest: sha256(text) });
151
- return value;
152
- }
153
- if (anchored) await commitObservedPolicyProvenance(path, root, provenance,
154
- anchored.match, sha256(text), guard.assertOwned);
155
- return value;
156
- }
157
- throw new Error("gateway policy changed during bounded provenance read");
158
- }
159
-
160
- export async function writeGatewayJson(path, value, guard = {}) {
161
- const content = `${JSON.stringify(value, null, 2)}\n`;
162
- if (basename(path) === "gateway-policy.json" && value.schema === POLICY_SCHEMA) {
163
- const provenancePath = join(dirname(path), "gateway-policy-provenance.json");
164
- const previousPolicyDigest = await currentGatewayDigest(path);
165
- if (Object.hasOwn(guard, "expectedDigest") && previousPolicyDigest !== guard.expectedDigest) {
166
- throw new Error("gateway state predecessor changed before policy provenance");
167
- }
168
- const nextPolicyDigest = sha256(content);
169
- const prepared = policyProvenance(value.root, value.schema, "prepared",
170
- previousPolicyDigest, nextPolicyDigest);
171
- const preparedContent = `${JSON.stringify(prepared, null, 2)}\n`;
172
- const previousProvenanceDigest = await currentGatewayDigest(provenancePath);
173
- const assertPreviousPolicy = async () => {
174
- if (await currentGatewayDigest(path) !== previousPolicyDigest) {
175
- throw new Error("gateway state predecessor changed before policy provenance");
176
- }
177
- };
178
- await atomicGatewayWrite(provenancePath, preparedContent, PROVENANCE_BYTES,
179
- { assertOwned: guard.assertOwned, assertRelated: assertPreviousPolicy,
180
- expectedDigest: previousProvenanceDigest });
181
- await atomicGatewayWrite(path, content, POLICY_BYTES, guard);
182
- const committed = policyProvenance(value.root, value.schema, "committed",
183
- previousPolicyDigest, nextPolicyDigest);
184
- const assertNextPolicy = async () => {
185
- if (await currentGatewayDigest(path) !== nextPolicyDigest) {
186
- throw new Error("gateway policy changed before provenance commit");
187
- }
188
- };
189
- await atomicGatewayWrite(provenancePath, `${JSON.stringify(committed, null, 2)}\n`, PROVENANCE_BYTES,
190
- { assertOwned: guard.assertOwned, assertRelated: assertNextPolicy,
191
- expectedDigest: sha256(preparedContent) });
192
- await guard.afterWrite?.(nextPolicyDigest);
193
- return;
194
- }
195
- await atomicGatewayWrite(path, content, POLICY_BYTES, guard);
196
- await guard.afterWrite?.(sha256(content));
197
- }