blun-king-cli 9.1.567 → 9.1.569

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 (262) hide show
  1. package/agent-spine-plugin/.claude-plugin/marketplace.json +1 -1
  2. package/agent-spine-plugin/.claude-plugin/plugin.json +1 -1
  3. package/agent-spine-plugin/.codex-plugin/plugin.json +2 -1
  4. package/agent-spine-plugin/CHANGELOG.md +1581 -0
  5. package/agent-spine-plugin/README.md +30 -4
  6. package/agent-spine-plugin/blun.plugin.json +3 -3
  7. package/agent-spine-plugin/docs/acceptance.md +61 -0
  8. package/agent-spine-plugin/docs/assignment-continuation.md +48 -0
  9. package/agent-spine-plugin/docs/host-integration.md +178 -0
  10. package/agent-spine-plugin/docs/preflight-recall.md +69 -0
  11. package/agent-spine-plugin/docs/preservation-contract.md +53 -0
  12. package/agent-spine-plugin/docs/quality-gates.md +50 -0
  13. package/agent-spine-plugin/docs/releasing.md +85 -0
  14. package/agent-spine-plugin/docs/session-timeline.md +251 -0
  15. package/agent-spine-plugin/docs/source-roots.md +113 -0
  16. package/agent-spine-plugin/docs/structured-completion.md +67 -0
  17. package/agent-spine-plugin/docs/world-model.md +94 -0
  18. package/agent-spine-plugin/hooks/codex.json +2 -2
  19. package/agent-spine-plugin/hooks/hooks.json +1 -1
  20. package/agent-spine-plugin/hooks/version.json +1 -1
  21. package/agent-spine-plugin/package.json +13 -3
  22. package/agent-spine-plugin/scripts/check-codex-install.js +226 -0
  23. package/agent-spine-plugin/scripts/check-hosts.js +14 -5
  24. package/agent-spine-plugin/scripts/check-install-hook.js +226 -0
  25. package/agent-spine-plugin/scripts/check-install-selfstarter.js +154 -0
  26. package/agent-spine-plugin/scripts/check-install.js +478 -0
  27. package/agent-spine-plugin/scripts/check-line-budget.js +58 -0
  28. package/agent-spine-plugin/scripts/check-syntax.js +29 -0
  29. package/agent-spine-plugin/scripts/github-actions.js +11 -0
  30. package/agent-spine-plugin/scripts/hermetic-process.js +183 -0
  31. package/agent-spine-plugin/scripts/release-check.js +145 -0
  32. package/agent-spine-plugin/scripts/run-acceptance.js +19 -0
  33. package/agent-spine-plugin/scripts/run-checks.js +47 -0
  34. package/agent-spine-plugin/scripts/run-tests-hermetic.js +89 -0
  35. package/agent-spine-plugin/skills/agent-spine/SKILL.md +16 -2
  36. package/agent-spine-plugin/spine-example/1-identity.md +12 -0
  37. package/agent-spine-plugin/spine-example/2-voice.md +6 -0
  38. package/agent-spine-plugin/spine-example/3-conduct.md +8 -0
  39. package/agent-spine-plugin/spine-example/4-history.md +4 -0
  40. package/agent-spine-plugin/src/cli-agent.js +296 -0
  41. package/agent-spine-plugin/src/cli-attention.js +95 -0
  42. package/agent-spine-plugin/src/cli-autonomy.js +36 -0
  43. package/agent-spine-plugin/src/cli-common.js +71 -0
  44. package/agent-spine-plugin/src/cli-continuity.js +116 -0
  45. package/agent-spine-plugin/src/cli-core.js +128 -0
  46. package/agent-spine-plugin/src/cli-diagnostics.js +291 -0
  47. package/agent-spine-plugin/src/cli-host.js +21 -0
  48. package/agent-spine-plugin/src/cli-learning.js +305 -0
  49. package/agent-spine-plugin/src/cli-premortem.js +16 -0
  50. package/agent-spine-plugin/src/cli-sharing.js +230 -0
  51. package/agent-spine-plugin/src/cli.js +40 -1350
  52. package/agent-spine-plugin/src/codex-reader-launcher.js +182 -0
  53. package/agent-spine-plugin/src/hook.js +185 -567
  54. package/agent-spine-plugin/src/index.js +16 -2
  55. package/agent-spine-plugin/src/lib/acceptance.js +113 -11
  56. package/agent-spine-plugin/src/lib/action-lesson-recall.js +53 -0
  57. package/agent-spine-plugin/src/lib/attention-context.js +167 -0
  58. package/agent-spine-plugin/src/lib/attention-events.js +113 -0
  59. package/agent-spine-plugin/src/lib/attention-privacy.js +72 -0
  60. package/agent-spine-plugin/src/lib/attention-schema.js +164 -0
  61. package/agent-spine-plugin/src/lib/attention-storage.js +93 -0
  62. package/agent-spine-plugin/src/lib/attention.js +9 -600
  63. package/agent-spine-plugin/src/lib/audit-premortem.js +223 -0
  64. package/agent-spine-plugin/src/lib/audit.js +56 -6
  65. package/agent-spine-plugin/src/lib/autonomy-policy.js +110 -0
  66. package/agent-spine-plugin/src/lib/autonomy-store.js +202 -0
  67. package/agent-spine-plugin/src/lib/autonomy.js +8 -0
  68. package/agent-spine-plugin/src/lib/briefing.js +67 -4
  69. package/agent-spine-plugin/src/lib/catalog-document-read.js +51 -0
  70. package/agent-spine-plugin/src/lib/catalog.js +1 -1
  71. package/agent-spine-plugin/src/lib/codex-installation.js +231 -0
  72. package/agent-spine-plugin/src/lib/codex-skill-installation.js +211 -0
  73. package/agent-spine-plugin/src/lib/context.js +3 -1
  74. package/agent-spine-plugin/src/lib/delivery-agent-usage.js +224 -0
  75. package/agent-spine-plugin/src/lib/delivery-assignment.js +220 -0
  76. package/agent-spine-plugin/src/lib/delivery-command-actions.js +453 -0
  77. package/agent-spine-plugin/src/lib/delivery-knowledge.js +78 -0
  78. package/agent-spine-plugin/src/lib/delivery-premortem-binding.js +107 -0
  79. package/agent-spine-plugin/src/lib/delivery-premortem-closure.js +171 -0
  80. package/agent-spine-plugin/src/lib/delivery-premortem-codec.js +45 -0
  81. package/agent-spine-plugin/src/lib/delivery-premortem-correction.js +101 -0
  82. package/agent-spine-plugin/src/lib/delivery-premortem-file.js +21 -0
  83. package/agent-spine-plugin/src/lib/delivery-premortem-index.js +493 -0
  84. package/agent-spine-plugin/src/lib/delivery-premortem-inspection.js +37 -0
  85. package/agent-spine-plugin/src/lib/delivery-premortem-recovery.js +120 -0
  86. package/agent-spine-plugin/src/lib/delivery-premortem-rejection.js +65 -0
  87. package/agent-spine-plugin/src/lib/delivery-premortem-results.js +28 -0
  88. package/agent-spine-plugin/src/lib/delivery-premortem-session-guard.js +46 -0
  89. package/agent-spine-plugin/src/lib/delivery-premortem-write-ledger.js +285 -0
  90. package/agent-spine-plugin/src/lib/delivery-premortem.js +499 -0
  91. package/agent-spine-plugin/src/lib/delivery-shell-heredoc.js +115 -0
  92. package/agent-spine-plugin/src/lib/delivery-shell-substitutions.js +111 -0
  93. package/agent-spine-plugin/src/lib/delivery-shell-wrapper.js +64 -0
  94. package/agent-spine-plugin/src/lib/delivery-target.js +73 -0
  95. package/agent-spine-plugin/src/lib/delivery-verification.js +445 -0
  96. package/agent-spine-plugin/src/lib/documents.js +27 -5
  97. package/agent-spine-plugin/src/lib/filesystem-retry.js +2 -0
  98. package/agent-spine-plugin/src/lib/gateway-common.js +68 -0
  99. package/agent-spine-plugin/src/lib/gateway-control.js +302 -0
  100. package/agent-spine-plugin/src/lib/gateway-delivery.js +103 -0
  101. package/agent-spine-plugin/src/lib/gateway-execution.js +350 -0
  102. package/agent-spine-plugin/src/lib/gateway-host-lifecycle.js +185 -0
  103. package/agent-spine-plugin/src/lib/gateway-inspection.js +85 -0
  104. package/agent-spine-plugin/src/lib/gateway-knowledge.js +129 -0
  105. package/agent-spine-plugin/src/lib/gateway-policy-provenance.js +197 -0
  106. package/agent-spine-plugin/src/lib/gateway-premortem-disposition.js +82 -0
  107. package/agent-spine-plugin/src/lib/gateway-premortem.js +363 -0
  108. package/agent-spine-plugin/src/lib/gateway-runs.js +300 -0
  109. package/agent-spine-plugin/src/lib/gateway-runtime-identity.js +31 -0
  110. package/agent-spine-plugin/src/lib/gateway-runtime-records.js +21 -0
  111. package/agent-spine-plugin/src/lib/gateway-runtime.js +18 -1623
  112. package/agent-spine-plugin/src/lib/gateway-state-transaction.js +356 -0
  113. package/agent-spine-plugin/src/lib/gateway-state.js +342 -0
  114. package/agent-spine-plugin/src/lib/hook-artifact-guards.js +356 -0
  115. package/agent-spine-plugin/src/lib/hook-audit.js +16 -2
  116. package/agent-spine-plugin/src/lib/hook-briefing-use.js +68 -0
  117. package/agent-spine-plugin/src/lib/hook-context.js +424 -0
  118. package/agent-spine-plugin/src/lib/hook-final-message.js +26 -0
  119. package/agent-spine-plugin/src/lib/hook-input.js +27 -0
  120. package/agent-spine-plugin/src/lib/hook-output.js +140 -0
  121. package/agent-spine-plugin/src/lib/hook-premortem.js +257 -0
  122. package/agent-spine-plugin/src/lib/hook-process-advisory.js +37 -0
  123. package/agent-spine-plugin/src/lib/hook-protection.js +95 -0
  124. package/agent-spine-plugin/src/lib/hook-stop-verification.js +84 -0
  125. package/agent-spine-plugin/src/lib/hook-timeline.js +91 -0
  126. package/agent-spine-plugin/src/lib/identifier-analysis.js +446 -0
  127. package/agent-spine-plugin/src/lib/indexed-memory.js +23 -6
  128. package/agent-spine-plugin/src/lib/knowledge-evidence.js +431 -0
  129. package/agent-spine-plugin/src/lib/learning-applications.js +441 -0
  130. package/agent-spine-plugin/src/lib/learning-candidates.js +274 -0
  131. package/agent-spine-plugin/src/lib/learning-context.js +130 -0
  132. package/agent-spine-plugin/src/lib/learning-delivery-contracts.js +310 -0
  133. package/agent-spine-plugin/src/lib/learning-evaluation-contracts.js +350 -0
  134. package/agent-spine-plugin/src/lib/learning-evaluation-registration.js +372 -0
  135. package/agent-spine-plugin/src/lib/learning-evaluation-revocation.js +292 -0
  136. package/agent-spine-plugin/src/lib/learning-evidence-contracts.js +321 -0
  137. package/agent-spine-plugin/src/lib/learning-findings.js +458 -0
  138. package/agent-spine-plugin/src/lib/learning-measurement-contracts.js +285 -0
  139. package/agent-spine-plugin/src/lib/learning-measurements.js +265 -0
  140. package/agent-spine-plugin/src/lib/learning-outcome-contracts.js +165 -0
  141. package/agent-spine-plugin/src/lib/learning-outcomes.js +343 -0
  142. package/agent-spine-plugin/src/lib/learning-reconciliation.js +290 -0
  143. package/agent-spine-plugin/src/lib/learning-retry-contracts.js +188 -0
  144. package/agent-spine-plugin/src/lib/learning-schema.js +229 -0
  145. package/agent-spine-plugin/src/lib/learning-scope-targets.js +424 -0
  146. package/agent-spine-plugin/src/lib/learning-state-upgrade.js +477 -0
  147. package/agent-spine-plugin/src/lib/learning-status-configuration.js +476 -0
  148. package/agent-spine-plugin/src/lib/learning-storage.js +203 -0
  149. package/agent-spine-plugin/src/lib/learning-trial-recovery.js +218 -0
  150. package/agent-spine-plugin/src/lib/learning-validation-contracts.js +375 -0
  151. package/agent-spine-plugin/src/lib/learning-validation-renewal.js +298 -0
  152. package/agent-spine-plugin/src/lib/learning-validation-runtime.js +234 -0
  153. package/agent-spine-plugin/src/lib/learning.js +36 -6923
  154. package/agent-spine-plugin/src/lib/lesson-recall-session.js +172 -0
  155. package/agent-spine-plugin/src/lib/mcp-autonomy-tools.js +37 -0
  156. package/agent-spine-plugin/src/lib/mcp-delivery-completion.js +124 -0
  157. package/agent-spine-plugin/src/lib/mcp-delivery-tools.js +45 -0
  158. package/agent-spine-plugin/src/lib/mcp-premortem.js +68 -0
  159. package/agent-spine-plugin/src/lib/mcp-runtime.js +269 -0
  160. package/agent-spine-plugin/src/lib/mcp-source-context.js +51 -0
  161. package/agent-spine-plugin/src/lib/mcp-timeline-tools.js +164 -0
  162. package/agent-spine-plugin/src/lib/mcp-world-tools.js +52 -0
  163. package/agent-spine-plugin/src/lib/owned-file-lock.js +30 -10
  164. package/agent-spine-plugin/src/lib/project-portfolio.js +176 -0
  165. package/agent-spine-plugin/src/lib/selfstarter-core.js +382 -0
  166. package/agent-spine-plugin/src/lib/selfstarter-jobs.js +149 -0
  167. package/agent-spine-plugin/src/lib/selfstarter-lease.js +204 -0
  168. package/agent-spine-plugin/src/lib/selfstarter-policy.js +90 -0
  169. package/agent-spine-plugin/src/lib/selfstarter-workspace.js +111 -0
  170. package/agent-spine-plugin/src/lib/selfstarter.js +11 -911
  171. package/agent-spine-plugin/src/lib/session-timeline-auth.js +316 -0
  172. package/agent-spine-plugin/src/lib/session-timeline-codex.js +58 -0
  173. package/agent-spine-plugin/src/lib/session-timeline-contract.js +48 -0
  174. package/agent-spine-plugin/src/lib/session-timeline-enrollment-source.js +41 -0
  175. package/agent-spine-plugin/src/lib/session-timeline-enrollment-storage.js +132 -0
  176. package/agent-spine-plugin/src/lib/session-timeline-enrollment-transport.js +17 -0
  177. package/agent-spine-plugin/src/lib/session-timeline-enrollment.js +500 -0
  178. package/agent-spine-plugin/src/lib/session-timeline-event-extract.js +157 -0
  179. package/agent-spine-plugin/src/lib/session-timeline-host-origin.js +74 -0
  180. package/agent-spine-plugin/src/lib/session-timeline-host-receipt.js +117 -0
  181. package/agent-spine-plugin/src/lib/session-timeline-invocation.js +201 -0
  182. package/agent-spine-plugin/src/lib/session-timeline-king.js +79 -0
  183. package/agent-spine-plugin/src/lib/session-timeline-prior.js +59 -0
  184. package/agent-spine-plugin/src/lib/session-timeline-provider.js +34 -0
  185. package/agent-spine-plugin/src/lib/session-timeline-query.js +55 -0
  186. package/agent-spine-plugin/src/lib/session-timeline-results.js +31 -0
  187. package/agent-spine-plugin/src/lib/session-timeline-root.js +11 -0
  188. package/agent-spine-plugin/src/lib/session-timeline-search.js +82 -0
  189. package/agent-spine-plugin/src/lib/session-timeline-sid-acl.js +217 -0
  190. package/agent-spine-plugin/src/lib/session-timeline-source.js +83 -0
  191. package/agent-spine-plugin/src/lib/session-timeline-state.js +45 -0
  192. package/agent-spine-plugin/src/lib/session-timeline-transport.js +50 -0
  193. package/agent-spine-plugin/src/lib/session-timeline-windows-acl.js +148 -0
  194. package/agent-spine-plugin/src/lib/session-timeline.js +453 -0
  195. package/agent-spine-plugin/src/lib/source-roots.js +69 -136
  196. package/agent-spine-plugin/src/lib/source-tree-scan.js +178 -0
  197. package/agent-spine-plugin/src/lib/task-knowledge-context.js +78 -0
  198. package/agent-spine-plugin/src/lib/timeline-tool-guard.js +202 -0
  199. package/agent-spine-plugin/src/lib/world-knowledge.js +249 -0
  200. package/agent-spine-plugin/src/lib/world-model.js +278 -0
  201. package/agent-spine-plugin/src/mcp.js +20 -161
  202. package/agent-spine-plugin/src/version.js +1 -1
  203. package/agent-spine-plugin/src/worker.js +22 -5
  204. package/bin/agent-resume-snapshot.cjs +2 -2
  205. package/bin/agentspine-king-goal-inbox.mjs +111 -0
  206. package/bin/agentspine-king-goal-intake.mjs +106 -0
  207. package/bin/baseline-skill-performance-policy.cjs +1 -16
  208. package/bin/core-bootstrap.js +2 -0
  209. package/bin/curiosity-scout-policy.cjs +5 -1
  210. package/bin/input-draft-persistence.cjs +2 -2
  211. package/bin/king-tui-function-contract.json +33 -0
  212. package/bin/launcher-restart-policy.cjs +150 -0
  213. package/bin/launcher-runtime.js +56 -44
  214. package/bin/managed-context-startup-policy.cjs +27 -0
  215. package/bin/managed-plugin-selection.cjs +116 -0
  216. package/bin/mistake-relevance-policy.cjs +1 -1
  217. package/bin/observer-hooks.cjs +14 -0
  218. package/bin/oversized-context-offload-policy.cjs +86 -0
  219. package/bin/plugin-bootstrap.js +7 -40
  220. package/bin/proactive-compaction-policy.cjs +1 -1
  221. package/bin/provider-model-refresh-deadline.cjs +53 -0
  222. package/bin/provider-model-refresh-policy.cjs +107 -0
  223. package/bin/release-artifact-freeze-policy.cjs +30 -0
  224. package/bin/repeated-user-message-projection.cjs +3 -126
  225. package/bin/research-page-result.cjs +74 -0
  226. package/bin/runtime-exit-ledger.cjs +1 -0
  227. package/bin/session-compaction-policy.cjs +84 -0
  228. package/bin/skill-listing-performance-policy.cjs +2 -2
  229. package/bin/standard-tools-bootstrap.js +0 -37
  230. package/bin/subagent-skill-policy.cjs +3 -1
  231. package/bin/telegram-approval-relay.cjs +12 -7
  232. package/bin/telegram-private-conversation-policy.cjs +3 -2
  233. package/bin/telegram-queue-handoff-policy.cjs +24 -0
  234. package/bin/thinking-activity-status-policy.cjs +1 -1
  235. package/bin/thinking-only-guard.cjs +16 -12
  236. package/bin/tool-call-loop-policy.cjs +0 -2
  237. package/bin/tool-result-offload-policy.cjs +11 -2
  238. package/bin/tui-functional-contract.cjs +55 -0
  239. package/bin/update-notice.js +18 -14
  240. package/bin/user-message-offload-policy.cjs +1 -1
  241. package/bin/user-prompt-hook-origin-policy.cjs +34 -0
  242. package/bin/windows-node-crash-dump.cjs +110 -0
  243. package/blun.mjs +2517 -1048
  244. package/codebase-index/codebase_index.py +4 -3
  245. package/package.json +3 -17
  246. package/standard-skills/research-evidence/SKILL.md +39 -0
  247. package/standard-skills/research-evidence/references/evidence-format.md +82 -0
  248. package/standard-skills/research-evidence/scripts/evidence-collection.cjs +254 -0
  249. package/standard-skills/research-evidence/scripts/score-report.cjs +112 -0
  250. package/standard-skills/web-lesen/SKILL.md +37 -22
  251. package/standard-skills/web-lesen/scripts/crawl_public.py +376 -0
  252. package/telegram-plugin/DELIVERY.md +36 -0
  253. package/telegram-plugin/bin/telegram-approval-relay.cjs +13 -7
  254. package/telegram-plugin/bin/telegram-launcher-status-queue.cjs +122 -0
  255. package/telegram-plugin/bin/telegram-private-conversation-policy.cjs +3 -2
  256. package/telegram-plugin/bin/telegram-reply-parts.cjs +149 -0
  257. package/telegram-plugin/dist/bridge.mjs +7 -56
  258. package/telegram-plugin/dist/mcp-server.mjs +33 -4
  259. package/agent-spine-plugin/skill/SKILL.md +0 -76
  260. package/bin/mnemo-connect-heartbeat.cjs +0 -204
  261. package/bin/mnemo-tool-agent-policy.cjs +0 -22
  262. package/telegram-plugin/bin/telegram-mnemo-capture.cjs +0 -297
@@ -0,0 +1,342 @@
1
+ import { join } from "node:path";
2
+ import { buildCatalog } from "./catalog.js";
3
+ import { matchesGatewayLaneLease, validGatewayLeaseExecution } from "./gateway-host-lifecycle.js";
4
+ import * as goalPremortem from "./gateway-premortem.js";
5
+ import {
6
+ readGatewayStateJson, withGatewayStateLock, writeGatewayStateJson
7
+ } from "./gateway-state-transaction.js";
8
+ import { validStepKnowledgeState } from "./knowledge-evidence.js";
9
+ import { projectStateDir } from "./paths.js";
10
+ import {
11
+ GATEWAY_POLICY_SCHEMA, GATEWAY_RUNTIME_SCHEMA, GOAL_PLAN_SCHEMA, GOAL_STATUSES,
12
+ HEALTH_VALUES, ID_RE, OUTBOX_STATUSES, PLAN_STEP_STATUSES, QUEUE_STATUSES,
13
+ ROUTE_RE, SECRET_RE, WAKE_KINDS, emptyPolicy, emptyRuntime, exactId,
14
+ safeCheckpoint, safeText, sha256
15
+ } from "./gateway-common.js";
16
+ import {
17
+ createExecutionDecision, validExecutionDecision, validExecutionOutcomeSequence,
18
+ validGoalTransferProofs
19
+ } from "./gateway-execution.js";
20
+
21
+ export function validGoalPlan(plan, goal = null, root = null, premortemContractVersion = undefined) {
22
+ if (!(plan && plan.schema === GOAL_PLAN_SCHEMA && plan.authority === "context-only-plan"
23
+ && Number.isInteger(plan.revision) && plan.revision >= 0 && Array.isArray(plan.steps)
24
+ && plan.steps.length > 0 && plan.steps.length <= 32 && /^[a-f0-9]{64}$/.test(plan.definitionsDigest || "")
25
+ && (plan.currentStepId === null || ID_RE.test(plan.currentStepId || ""))
26
+ && goalPremortem.validPlanPremortemContract(plan, premortemContractVersion))) return false;
27
+ const ids = new Set(plan.steps.map((step) => step?.stepId));
28
+ if (ids.size !== plan.steps.length || ids.has(undefined)) return false;
29
+ for (const step of plan.steps) {
30
+ if (!(ID_RE.test(step.stepId || "") && typeof step.title === "string" && step.title.length > 0 && step.title.length <= 500
31
+ && (step.agentId === undefined || ID_RE.test(step.agentId || ""))
32
+ && (step.resources === undefined || (Array.isArray(step.resources) && step.resources.length <= 16
33
+ && new Set(step.resources).size === step.resources.length && step.resources.every((resource) => ID_RE.test(resource || ""))))
34
+ && (step.execution === undefined || step.execution === null || validExecutionDecision(step.execution))
35
+ && (step.executionOutcomes === undefined || (Array.isArray(step.executionOutcomes) && step.executionOutcomes.length <= 8
36
+ && new Set(step.executionOutcomes.map((outcome) => outcome.outcomeId)).size === step.executionOutcomes.length
37
+ && (step.executionOutcomes.length === 0 || (step.execution
38
+ && validExecutionOutcomeSequence(step.execution, step.executionOutcomes)))))
39
+ && typeof step.successCriterion === "string" && step.successCriterion.length > 0 && step.successCriterion.length <= 1000
40
+ && Array.isArray(step.dependsOn) && new Set(step.dependsOn).size === step.dependsOn.length
41
+ && step.dependsOn.every((dependency) => ids.has(dependency) && dependency !== step.stepId)
42
+ && PLAN_STEP_STATUSES.has(step.status)
43
+ && (step.checkpoint === null || (() => { try { safeCheckpoint(step.checkpoint); return true; } catch { return false; } })())
44
+ && (step.blocker === null || (typeof step.blocker === "string" && step.blocker.length <= 500 && !SECRET_RE.test(step.blocker)))
45
+ && (step.completedAt === null || Number.isFinite(new Date(step.completedAt).getTime()))
46
+ && (step.completedByQueueId === null || ID_RE.test(step.completedByQueueId || ""))
47
+ && goalPremortem.validGoalPremortemAttachments(step, goal, root, plan.definitionsDigest)
48
+ && validStepKnowledgeState(step, plan.definitionsDigest)
49
+ && Number.isFinite(new Date(step.updatedAt).getTime())
50
+ && (step.executionOutcomes || []).every((outcome) => new Date(outcome.observedAt) <= new Date(step.updatedAt)))) return false;
51
+ }
52
+ const visiting = new Set(); const visited = new Set();
53
+ const visit = (stepId) => {
54
+ if (visiting.has(stepId)) return false;
55
+ if (visited.has(stepId)) return true;
56
+ visiting.add(stepId);
57
+ const step = plan.steps.find((entry) => entry.stepId === stepId);
58
+ if (!step.dependsOn.every(visit)) return false;
59
+ visiting.delete(stepId); visited.add(stepId); return true;
60
+ };
61
+ if (!plan.steps.every((step) => visit(step.stepId))) return false;
62
+ const completed = new Set(plan.steps.filter((step) => step.status === "completed").map((step) => step.stepId));
63
+ if (plan.steps.some((step) => ["completed", "active", "blocked"].includes(step.status)
64
+ && !step.dependsOn.every((dependency) => completed.has(dependency)))) return false;
65
+ if (plan.steps.some((step) => (step.status === "completed") !== (step.completedAt !== null && step.completedByQueueId !== null))) return false;
66
+ if (plan.steps.some((step) => (step.status === "blocked") !== (step.blocker !== null))) return false;
67
+ if (plan.steps.some((step) => (step.knowledgeGaps || []).filter((gap) => gap.status === "open").length > 1)) return false;
68
+ if (plan.steps.some((step) => (step.knowledgeGaps || []).some((gap) => gap.status === "open")
69
+ && step.status !== "blocked")) return false;
70
+ if (plan.steps.some((step) => step.execution && step.status === "completed"
71
+ && !(step.executionOutcomes || []).some((outcome) => outcome.passed))) return false;
72
+ if (plan.definitionsDigest !== sha256(JSON.stringify(goalPremortem.planDefinitionMaterial(plan.steps)))) return false;
73
+ const current = plan.steps.filter((step) => ["active", "blocked"].includes(step.status));
74
+ return current.length <= 1 && (plan.currentStepId === null
75
+ ? current.length === 0 : current.length === 1 && current[0].stepId === plan.currentStepId);
76
+ }
77
+ export function activateNextPlanStep(plan, now) {
78
+ const completed = new Set(plan.steps.filter((step) => step.status === "completed").map((step) => step.stepId));
79
+ const next = plan.steps.find((step) => step.status === "pending" && step.dependsOn.every((dependency) => completed.has(dependency)));
80
+ if (!next) { plan.currentStepId = null; return null; }
81
+ next.status = "active"; next.updatedAt = now; plan.currentStepId = next.stepId; plan.revision += 1;
82
+ return next;
83
+ }
84
+ export function createGoalPlan(steps, now, defaultAgentId, transferContext) {
85
+ if (!Array.isArray(steps) || steps.length === 0 || steps.length > 32) throw new Error("goal plan requires 1-32 steps");
86
+ const normalized = steps.map((step, index) => ({
87
+ stepId: exactId(step?.stepId ?? step?.id, `steps[${index}].stepId`),
88
+ agentId: exactId(step?.agentId ?? defaultAgentId, `steps[${index}].agentId`),
89
+ resources: Array.isArray(step?.resources)
90
+ ? step.resources.map((resource) => exactId(resource, `steps[${index}].resources`)) : [],
91
+ execution: createExecutionDecision(step?.execution, `steps[${index}].execution`, transferContext),
92
+ ...(transferContext.premortemContractVersion === 1 ? { premortemContractVersion: 1 } : {}),
93
+ title: safeText(step?.title, `steps[${index}].title`, 500),
94
+ successCriterion: safeText(step?.successCriterion, `steps[${index}].successCriterion`),
95
+ dependsOn: Array.isArray(step?.dependsOn) ? step.dependsOn.map((dependency) => exactId(dependency, `steps[${index}].dependsOn`)) : [],
96
+ status: "pending", checkpoint: null, blocker: null, completedAt: null, completedByQueueId: null,
97
+ knowledgeGaps: [], selfHelpReports: [], selfHelpRequirements: [], executionOutcomes: [], updatedAt: now
98
+ }));
99
+ const plan = { schema: GOAL_PLAN_SCHEMA, ...(transferContext.premortemContractVersion === 1
100
+ ? { premortemContractVersion: 1, premortemContract: goalPremortem.GOAL_PREMORTEM_CONTRACT } : {}),
101
+ revision: 0, currentStepId: null, steps: normalized,
102
+ definitionsDigest: sha256(JSON.stringify(goalPremortem.planDefinitionMaterial(normalized))), authority: "context-only-plan" };
103
+ if (!validGoalPlan(plan, null, null, transferContext.premortemContractVersion)) throw new Error("goal plan must be an acyclic dependency graph with exact unique step IDs");
104
+ activateNextPlanStep(plan, now);
105
+ return plan;
106
+ }
107
+ export function currentPlanStep(goal) {
108
+ return goal.plan?.steps.find((step) => step.stepId === goal.plan.currentStepId) || null;
109
+ }
110
+ export function planStepAgentId(goal, step) {
111
+ return step?.agentId ?? goal.agentId;
112
+ }
113
+ export function planStepResources(step) {
114
+ return Array.isArray(step?.resources) ? step.resources : [];
115
+ }
116
+ export function queuePlanStep(policy, item) {
117
+ if (!item.goalStepId) return null;
118
+ return policy.goals.find((goal) => goal.goalId === item.goalId)?.plan?.steps
119
+ .find((step) => step.stepId === item.goalStepId) || null;
120
+ }
121
+ export function conflictingResources(policy, candidate, leased) {
122
+ const wanted = new Set(planStepResources(queuePlanStep(policy, candidate)));
123
+ if (!wanted.size || candidate.projectId !== leased.projectId || candidate.groupId !== leased.groupId) return [];
124
+ return planStepResources(queuePlanStep(policy, leased)).filter((resource) => wanted.has(resource));
125
+ }
126
+ export function effectiveQueuePriority(policy, item) {
127
+ if (!item.goalId) return item.priority;
128
+ return policy.goals.find((goal) => goal.goalId === item.goalId)?.priority ?? item.priority;
129
+ }
130
+ export function planQueueKey(goalId, stepId, phase, suffix = "") {
131
+ return ["goal", goalId, "step", stepId, phase, suffix].filter(Boolean).join(":");
132
+ }
133
+
134
+ export function newGoalQueue(goal, step, kind, key, current, availableAt = current) {
135
+ return { queueId: "gateway-queue:" + sha256(key).slice(0, 32), dedupeKey: key, kind,
136
+ agentId: planStepAgentId(goal, step), projectId: goal.projectId, groupId: goal.groupId, goalId: goal.goalId,
137
+ goalStepId: step?.stepId || null, channelEventId: null, priority: goal.priority, status: "pending",
138
+ attempts: 0, lease: null, availableAt, createdAt: current, updatedAt: current,
139
+ completedAt: null, lastError: null, authority: "execution-state-only" };
140
+ }
141
+
142
+ export function validGoal(goal, root = null, premortemContractVersion = undefined) {
143
+ return goal && ID_RE.test(goal.goalId || "") && ID_RE.test(goal.agentId || "")
144
+ && ID_RE.test(goal.ownerSubjectId || "") && ID_RE.test(goal.projectId || "")
145
+ && (goal.groupId === null || ID_RE.test(goal.groupId || "")) && GOAL_STATUSES.has(goal.status)
146
+ && typeof goal.successCriterion === "string" && goal.successCriterion.length > 0
147
+ && typeof goal.nextSafeStep === "string" && goal.nextSafeStep.length > 0
148
+ && (goal.deadline === null || Number.isFinite(new Date(goal.deadline).getTime()))
149
+ && Number.isInteger(goal.priority) && goal.priority >= 0 && goal.priority <= 100
150
+ && (goal.checkpoint === null || (() => { try { safeCheckpoint(goal.checkpoint); return true; } catch { return false; } })())
151
+ && (goal.blocker === null || (typeof goal.blocker === "string" && goal.blocker.length <= 500 && !SECRET_RE.test(goal.blocker)))
152
+ && (goal.heartbeatAt === null || Number.isFinite(new Date(goal.heartbeatAt).getTime()))
153
+ && goal.authority === "authenticated-goal-policy" && Number.isFinite(new Date(goal.createdAt).getTime())
154
+ && Number.isFinite(new Date(goal.updatedAt).getTime())
155
+ && (goal.plan === undefined || goal.plan === null
156
+ || (validGoalPlan(goal.plan, goal, root, premortemContractVersion)
157
+ && goal.plan.steps.every((step) => ["knowledgeGaps", "selfHelpReports", "selfHelpRequirements"]
158
+ .every((field) => (step[field] || []).every((entry) => entry.goalId === goal.goalId)))
159
+ && (goal.status !== "active" || (currentPlanStep(goal)?.status === "active" && goal.nextSafeStep === currentPlanStep(goal).title))
160
+ && (goal.status !== "blocked" || currentPlanStep(goal)?.status === "blocked")
161
+ && (goal.status !== "completed" || goal.plan.steps.every((step) => step.status === "completed"))));
162
+ }
163
+
164
+ export function validPolicyHistory(item, root = null) {
165
+ if (!item || item.authority !== "authenticated-goal-policy" || !Number.isFinite(new Date(item.at).getTime())) return false;
166
+ if (item.kind === "goal") return validGoal(item.value, root);
167
+ return item.kind === "control" && item.value && typeof item.value.enabled === "boolean" && typeof item.value.killSwitch === "boolean";
168
+ }
169
+
170
+ export function validQueue(item) {
171
+ return item && ID_RE.test(item.queueId || "") && WAKE_KINDS.has(item.kind)
172
+ && ID_RE.test(item.dedupeKey || "") && item.queueId === "gateway-queue:" + sha256(item.dedupeKey).slice(0, 32)
173
+ && ID_RE.test(item.agentId || "") && ID_RE.test(item.projectId || "")
174
+ && (item.groupId === null || ID_RE.test(item.groupId || ""))
175
+ && (item.goalId === null || ID_RE.test(item.goalId || ""))
176
+ && (item.goalStepId === undefined || item.goalStepId === null || (item.goalId !== null && ID_RE.test(item.goalStepId || "")))
177
+ && (item.channelEventId === null || ID_RE.test(item.channelEventId || ""))
178
+ && QUEUE_STATUSES.has(item.status) && Number.isInteger(item.priority) && item.priority >= 0 && item.priority <= 100
179
+ && Number.isInteger(item.attempts) && item.attempts >= 0 && item.attempts <= 20
180
+ && item.authority === "execution-state-only" && Number.isFinite(new Date(item.createdAt).getTime())
181
+ && Number.isFinite(new Date(item.availableAt).getTime()) && Number.isFinite(new Date(item.updatedAt).getTime())
182
+ && (item.completedAt === null || Number.isFinite(new Date(item.completedAt).getTime()))
183
+ && (item.lastError === null || (typeof item.lastError === "string" && item.lastError.length <= 500 && !SECRET_RE.test(item.lastError)))
184
+ && (item.lease === null || (item.status === "leased" && ID_RE.test(item.lease.workerId || "")
185
+ && Number.isFinite(new Date(item.lease.claimedAt).getTime())
186
+ && Number.isFinite(new Date(item.lease.expiresAt).getTime())
187
+ && validGatewayLeaseExecution(item.lease)));
188
+ }
189
+
190
+ export function validOutbox(item) {
191
+ return item && ID_RE.test(item.outboxId || "") && ID_RE.test(item.queueId || "")
192
+ && ID_RE.test(item.idempotencyKey || "") && ID_RE.test(item.bindingId || "")
193
+ && item.outboxId === "gateway-outbox:" + sha256(item.idempotencyKey).slice(0, 32)
194
+ && ID_RE.test(item.eventId || "") && ROUTE_RE.test(item.provider || "") && ROUTE_RE.test(item.tenantId || "")
195
+ && ROUTE_RE.test(item.accountId || "") && ROUTE_RE.test(item.chatId || "")
196
+ && (item.threadId === null || ROUTE_RE.test(item.threadId || "")) && (item.replyTo === null || ROUTE_RE.test(item.replyTo || ""))
197
+ && OUTBOX_STATUSES.has(item.status)
198
+ && typeof item.text === "string" && item.text.length > 0 && item.text.length <= 16000 && !SECRET_RE.test(item.text)
199
+ && Number.isInteger(item.attempts) && item.attempts >= 0 && item.attempts <= 20
200
+ && item.authority === "delivery-state-only" && Number.isFinite(new Date(item.createdAt).getTime())
201
+ && Number.isFinite(new Date(item.updatedAt).getTime()) && Number.isFinite(new Date(item.nextAttemptAt).getTime())
202
+ && (item.deliveredAt === null || Number.isFinite(new Date(item.deliveredAt).getTime()))
203
+ && (item.adapterReceipt === null || (typeof item.adapterReceipt === "string" && item.adapterReceipt.length <= 500))
204
+ && (item.lastError === null || (typeof item.lastError === "string" && item.lastError.length <= 500 && !SECRET_RE.test(item.lastError)));
205
+ }
206
+
207
+ export function validLane(item) {
208
+ return item && ID_RE.test(item.agentId || "") && ID_RE.test(item.queueId || "") && ID_RE.test(item.workerId || "")
209
+ && new Set(["leased", "completed", "expired"]).has(item.status)
210
+ && Number.isFinite(new Date(item.claimedAt).getTime()) && Number.isFinite(new Date(item.expiresAt).getTime())
211
+ && Number.isFinite(new Date(item.updatedAt).getTime()) && item.authority === "execution-state-only";
212
+ }
213
+
214
+ export function validReceipt(item) {
215
+ if (!(item && ID_RE.test(item.id || "") && ID_RE.test(item.kind || "") && ID_RE.test(item.objectId || "")
216
+ && Number.isFinite(new Date(item.at).getTime()) && item.details && typeof item.details === "object"
217
+ && !Array.isArray(item.details) && !SECRET_RE.test(JSON.stringify(item.details))
218
+ && item.authority === "execution-state-only" && /^[a-f0-9]{64}$/.test(item.digest || ""))) return false;
219
+ const material = { kind: item.kind, objectId: item.objectId, at: item.at, details: item.details, authority: "execution-state-only" };
220
+ return item.digest === sha256(JSON.stringify(material)) && item.id === "gateway-receipt:" + item.digest.slice(0, 24);
221
+ }
222
+
223
+ export function validHistory(item) {
224
+ if (!(item && new Set(["queue", "outbox"]).has(item.kind) && ID_RE.test(item.objectId || "")
225
+ && ID_RE.test(item.transition || "") && Number.isFinite(new Date(item.at).getTime())
226
+ && item.value && item.authority === "execution-state-only")) return false;
227
+ return item.kind === "queue" ? validQueue(item.value) && item.objectId === item.value.queueId
228
+ : validOutbox(item.value) && item.objectId === item.value.outboxId;
229
+ }
230
+
231
+ export function validHealth(health) {
232
+ return health && ["gateway", "adapter", "scheduler", "queue", "worker", "host"].every((key) => HEALTH_VALUES.has(health[key]))
233
+ && (health.lastTickAt === null || Number.isFinite(new Date(health.lastTickAt).getTime()))
234
+ && (health.lastReconciledAt === null || Number.isFinite(new Date(health.lastReconciledAt).getTime()));
235
+ }
236
+
237
+ export function normalizePolicy(value, root, provenance = null, staged = false) {
238
+ const contractValid = staged ? value?.schema === GATEWAY_POLICY_SCHEMA
239
+ && goalPremortem.ensureGoalPremortemRegistry(value) : goalPremortem.ensureGoalPremortemPolicy(value, GATEWAY_POLICY_SCHEMA, provenance);
240
+ if (!value || !contractValid || value.root !== root
241
+ || !Number.isInteger(value.revision) || typeof value.enabled !== "boolean" || typeof value.killSwitch !== "boolean"
242
+ || !Array.isArray(value.goals) || !Array.isArray(value.history)
243
+ || value.goals.some((item) => !validGoal(item, root, goalPremortem.goalPremortemContractVersion(value, item.goalId)))
244
+ || value.goals.some((item) => !validGoalTransferProofs(item, value.goals))
245
+ || value.history.some((item) => !validPolicyHistory(item, root))) {
246
+ throw new Error("gateway policy is invalid; autonomous runtime is disabled");
247
+ }
248
+ return value;
249
+ }
250
+
251
+ export function normalizeRuntime(value, root) {
252
+ const baseValid = value && value.schema === GATEWAY_RUNTIME_SCHEMA && value.root === root && Number.isInteger(value.revision)
253
+ && Array.isArray(value.queue) && Array.isArray(value.lanes) && Array.isArray(value.outbox)
254
+ && Array.isArray(value.receipts) && Array.isArray(value.history);
255
+ if (!baseValid) throw new Error("gateway runtime structure is invalid; worker is disabled");
256
+ const invalid = [];
257
+ if (!validHealth(value.health)) invalid.push("health");
258
+ const queueIndex = value.queue.findIndex((item) => !validQueue(item));
259
+ const laneIndex = value.lanes.findIndex((item) => !validLane(item));
260
+ const outboxIndex = value.outbox.findIndex((item) => !validOutbox(item));
261
+ const receiptIndex = value.receipts.findIndex((item) => !validReceipt(item));
262
+ const historyIndex = value.history.findIndex((item) => !validHistory(item));
263
+ const leaseBindingMismatch = value.lanes.some((lane) => lane?.status === "leased"
264
+ && !matchesGatewayLaneLease(lane, value.queue.find((item) => item.queueId === lane.queueId)));
265
+ if (queueIndex >= 0) invalid.push("queue:" + queueIndex);
266
+ if (laneIndex >= 0) invalid.push("lanes:" + laneIndex);
267
+ if (leaseBindingMismatch) invalid.push("lane-lease-binding");
268
+ if (outboxIndex >= 0) invalid.push("outbox:" + outboxIndex);
269
+ if (receiptIndex >= 0) invalid.push("receipts:" + receiptIndex);
270
+ if (historyIndex >= 0) invalid.push("history:" + historyIndex);
271
+ if (invalid.length) throw new Error("gateway runtime is invalid (" + invalid.join(",") + "); worker is disabled");
272
+ return value;
273
+ }
274
+
275
+ export async function pathsFor(root, catalog = null) {
276
+ catalog ||= await buildCatalog(root);
277
+ const directory = await projectStateDir(catalog.root);
278
+ return { catalog, directory, gatewayPolicyPath: join(directory, "gateway-policy.json"), gatewayRuntimePath: join(directory, "gateway-runtime.json") };
279
+ }
280
+
281
+ export const readJson = readGatewayStateJson;
282
+ export const writeJson = writeGatewayStateJson;
283
+
284
+ export async function withLock(paths, task) {
285
+ return withGatewayStateLock(paths, task, { validatePair: (policy, runtime) => {
286
+ normalizePolicy(policy, paths.catalog.root, null, true); normalizeRuntime(runtime, paths.catalog.root);
287
+ const findings = gatewayRuntimeFindings(policy, runtime);
288
+ if (findings.length) throw new Error("gateway state pair is invalid (" + findings.slice(0, 16).join(",") + ")");
289
+ } });
290
+ }
291
+
292
+
293
+ export function gatewayRuntimeFindings(policy, runtime) {
294
+ const findings = [];
295
+ const active = new Set();
296
+ const goalIds = new Set();
297
+ for (const goal of policy.goals) {
298
+ if (!validGoal(goal, policy.root)) findings.push("invalid-goal:" + (goal?.goalId || "unknown"));
299
+ else if (!validGoalTransferProofs(goal, policy.goals)) findings.push("invalid-strategy-transfer:" + goal.goalId);
300
+ if (goalIds.has(goal.goalId)) findings.push("duplicate-goal:" + goal.goalId);
301
+ goalIds.add(goal.goalId);
302
+ if (goal.status === "active" && active.has(goal.agentId)) findings.push("multiple-active-goals:" + goal.agentId);
303
+ if (goal.status === "active") active.add(goal.agentId);
304
+ }
305
+ for (const item of policy.history) if (!validPolicyHistory(item, policy.root)) findings.push("invalid-gateway-policy-history");
306
+ const queueIds = new Set(); const dedupeKeys = new Set();
307
+ for (const item of runtime.queue) {
308
+ if (!validQueue(item)) findings.push("invalid-queue-item:" + (item?.queueId || "unknown"));
309
+ if (queueIds.has(item.queueId)) findings.push("duplicate-queue-item:" + item.queueId);
310
+ if (dedupeKeys.has(item.dedupeKey)) findings.push("duplicate-queue-dedupe:" + item.dedupeKey);
311
+ queueIds.add(item.queueId); dedupeKeys.add(item.dedupeKey);
312
+ if (item.goalStepId) {
313
+ const goal = policy.goals.find((entry) => entry.goalId === item.goalId);
314
+ const step = goal?.plan?.steps.find((entry) => entry.stepId === item.goalStepId);
315
+ if (!step) findings.push("orphan-goal-step:" + item.queueId);
316
+ else if (item.agentId !== planStepAgentId(goal, step)) findings.push("goal-step-agent-mismatch:" + item.queueId);
317
+ }
318
+ }
319
+ const outboxIds = new Set(); const idempotencyKeys = new Set();
320
+ for (const item of runtime.outbox) {
321
+ if (!validOutbox(item)) findings.push("invalid-outbox-item:" + (item?.outboxId || "unknown"));
322
+ if (!queueIds.has(item.queueId)) findings.push("orphan-outbox-item:" + item.outboxId);
323
+ if (outboxIds.has(item.outboxId)) findings.push("duplicate-outbox-item:" + item.outboxId);
324
+ if (idempotencyKeys.has(item.idempotencyKey)) findings.push("duplicate-outbox-idempotency:" + item.idempotencyKey);
325
+ outboxIds.add(item.outboxId); idempotencyKeys.add(item.idempotencyKey);
326
+ }
327
+ for (const item of runtime.receipts) if (!validReceipt(item)
328
+ || (!queueIds.has(item.objectId) && !outboxIds.has(item.objectId))) findings.push("invalid-gateway-receipt:" + (item?.id || "unknown"));
329
+ for (const item of runtime.history) if (!validHistory(item)) findings.push("invalid-gateway-history:" + (item?.objectId || "unknown"));
330
+ const leased = runtime.lanes.filter((item) => item.status === "leased");
331
+ for (const lane of runtime.lanes) {
332
+ if (!validLane(lane)) findings.push("invalid-agent-lane:" + (lane?.queueId || "unknown"));
333
+ const queue = runtime.queue.find((item) => item.queueId === lane.queueId);
334
+ if (!queue || (lane.status === "leased" && !matchesGatewayLaneLease(lane, queue))) {
335
+ findings.push("agent-lane-queue-mismatch:" + (lane.queueId || "unknown"));
336
+ }
337
+ }
338
+ if (new Set(leased.map((item) => item.agentId)).size !== leased.length) findings.push("duplicate-agent-lane");
339
+ if (!validHealth(runtime.health)) findings.push("invalid-gateway-health");
340
+ return findings;
341
+ }
342
+