blun-king-cli 9.1.642 → 9.1.644

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 (273) hide show
  1. package/LIESMICH.txt +18 -0
  2. package/README.md +20 -6
  3. package/bin/blun.js +3 -3
  4. package/bin/king.js +3 -3
  5. package/bin/launcher-mode.js +125 -126
  6. package/bin/launcher-runtime.js +603 -616
  7. package/bin/plugin-bootstrap.js +339 -405
  8. package/bin/rename-private-staging.cjs +2 -2
  9. package/bin/retired-bundled-plugins.cjs +84 -0
  10. package/bin/startup-security-host.cjs +105 -0
  11. package/bin/startup-security.cjs +9 -105
  12. package/bin/startup-warning-policy.cjs +22 -0
  13. package/bin/update-lease-installer.cjs +125 -0
  14. package/bin/update-lease-sockets.cjs +228 -0
  15. package/bin/update-lease.js +22 -327
  16. package/bin/verify-bundled-agent-sources.cjs +2 -4
  17. package/blun.mjs +78 -193
  18. package/bundled-agent-sources.json +1 -552
  19. package/package.json +4 -6
  20. package/tool-liveness642/index.cjs +7 -0
  21. package/tool-liveness642/queue-delivery.cjs +109 -0
  22. package/tool-liveness642/receipt.json +40 -0
  23. package/tool-liveness642/shell-yield.cjs +43 -0
  24. package/tool-liveness642/task-wait.cjs +45 -0
  25. package/versionierung/BELEG.json +43 -0
  26. package/versionierung/LIESMICH.md +5 -0
  27. package/versionierung/urspruenglicher-overlay-beleg.json +39 -0
  28. package/worker-host.mjs +48 -128
  29. package/agent-spine-plugin/.claude-plugin/marketplace.json +0 -20
  30. package/agent-spine-plugin/.claude-plugin/plugin.json +0 -14
  31. package/agent-spine-plugin/.codex-plugin/plugin.json +0 -47
  32. package/agent-spine-plugin/.mcp.json +0 -8
  33. package/agent-spine-plugin/CHANGELOG.md +0 -1614
  34. package/agent-spine-plugin/LICENSE +0 -186
  35. package/agent-spine-plugin/README.md +0 -432
  36. package/agent-spine-plugin/assets/agentspine-banner.svg +0 -32
  37. package/agent-spine-plugin/bin/agentspine-mcp.js +0 -4
  38. package/agent-spine-plugin/bin/agentspine.js +0 -7
  39. package/agent-spine-plugin/blun.plugin.json +0 -68
  40. package/agent-spine-plugin/docs/acceptance.md +0 -61
  41. package/agent-spine-plugin/docs/artifact-evaluation.md +0 -93
  42. package/agent-spine-plugin/docs/host-integration.md +0 -193
  43. package/agent-spine-plugin/docs/preflight-recall.md +0 -71
  44. package/agent-spine-plugin/docs/preservation-contract.md +0 -53
  45. package/agent-spine-plugin/docs/quality-gates.md +0 -50
  46. package/agent-spine-plugin/docs/session-timeline.md +0 -112
  47. package/agent-spine-plugin/docs/source-roots.md +0 -113
  48. package/agent-spine-plugin/docs/world-model.md +0 -119
  49. package/agent-spine-plugin/hooks/codex.json +0 -47
  50. package/agent-spine-plugin/hooks/hooks.json +0 -106
  51. package/agent-spine-plugin/hooks/version.json +0 -5
  52. package/agent-spine-plugin/package.json +0 -77
  53. package/agent-spine-plugin/scripts/check-codex-install.js +0 -226
  54. package/agent-spine-plugin/scripts/check-hosts.js +0 -208
  55. package/agent-spine-plugin/scripts/check-install-hook.js +0 -227
  56. package/agent-spine-plugin/scripts/check-install-selfstarter.js +0 -154
  57. package/agent-spine-plugin/scripts/check-install.js +0 -478
  58. package/agent-spine-plugin/scripts/check-line-budget.js +0 -58
  59. package/agent-spine-plugin/scripts/check-syntax.js +0 -29
  60. package/agent-spine-plugin/scripts/github-actions.js +0 -11
  61. package/agent-spine-plugin/scripts/hermetic-process.js +0 -191
  62. package/agent-spine-plugin/scripts/release-check.js +0 -150
  63. package/agent-spine-plugin/scripts/run-acceptance.js +0 -19
  64. package/agent-spine-plugin/scripts/run-checks.js +0 -50
  65. package/agent-spine-plugin/scripts/run-tests-hermetic.js +0 -112
  66. package/agent-spine-plugin/skills/agent-spine/SKILL.md +0 -99
  67. package/agent-spine-plugin/spine-example/1-identity.md +0 -12
  68. package/agent-spine-plugin/spine-example/2-voice.md +0 -6
  69. package/agent-spine-plugin/spine-example/3-conduct.md +0 -8
  70. package/agent-spine-plugin/spine-example/4-history.md +0 -4
  71. package/agent-spine-plugin/src/cli-agent.js +0 -315
  72. package/agent-spine-plugin/src/cli-attention.js +0 -95
  73. package/agent-spine-plugin/src/cli-autonomy.js +0 -36
  74. package/agent-spine-plugin/src/cli-common.js +0 -71
  75. package/agent-spine-plugin/src/cli-continuity.js +0 -116
  76. package/agent-spine-plugin/src/cli-core.js +0 -128
  77. package/agent-spine-plugin/src/cli-diagnostics.js +0 -291
  78. package/agent-spine-plugin/src/cli-host.js +0 -21
  79. package/agent-spine-plugin/src/cli-learning.js +0 -320
  80. package/agent-spine-plugin/src/cli-premortem.js +0 -16
  81. package/agent-spine-plugin/src/cli-sharing.js +0 -230
  82. package/agent-spine-plugin/src/cli.js +0 -181
  83. package/agent-spine-plugin/src/codex-reader-launcher.js +0 -182
  84. package/agent-spine-plugin/src/hook.js +0 -500
  85. package/agent-spine-plugin/src/index.js +0 -108
  86. package/agent-spine-plugin/src/lib/acceptance.js +0 -435
  87. package/agent-spine-plugin/src/lib/action-lesson-recall.js +0 -118
  88. package/agent-spine-plugin/src/lib/attention-context.js +0 -167
  89. package/agent-spine-plugin/src/lib/attention-events.js +0 -113
  90. package/agent-spine-plugin/src/lib/attention-privacy.js +0 -72
  91. package/agent-spine-plugin/src/lib/attention-schema.js +0 -164
  92. package/agent-spine-plugin/src/lib/attention-storage.js +0 -93
  93. package/agent-spine-plugin/src/lib/attention.js +0 -164
  94. package/agent-spine-plugin/src/lib/audit-premortem.js +0 -223
  95. package/agent-spine-plugin/src/lib/audit.js +0 -401
  96. package/agent-spine-plugin/src/lib/authentication.js +0 -515
  97. package/agent-spine-plugin/src/lib/autonomy-policy.js +0 -110
  98. package/agent-spine-plugin/src/lib/autonomy-store.js +0 -202
  99. package/agent-spine-plugin/src/lib/autonomy.js +0 -8
  100. package/agent-spine-plugin/src/lib/briefing.js +0 -493
  101. package/agent-spine-plugin/src/lib/catalog-document-read.js +0 -51
  102. package/agent-spine-plugin/src/lib/catalog.js +0 -167
  103. package/agent-spine-plugin/src/lib/channel-continuity.js +0 -19
  104. package/agent-spine-plugin/src/lib/channel-runtime.js +0 -665
  105. package/agent-spine-plugin/src/lib/codex-installation.js +0 -231
  106. package/agent-spine-plugin/src/lib/codex-skill-installation.js +0 -211
  107. package/agent-spine-plugin/src/lib/context.js +0 -156
  108. package/agent-spine-plugin/src/lib/continuity.js +0 -338
  109. package/agent-spine-plugin/src/lib/coordination.js +0 -577
  110. package/agent-spine-plugin/src/lib/delivery-agent-usage.js +0 -231
  111. package/agent-spine-plugin/src/lib/delivery-assignment.js +0 -220
  112. package/agent-spine-plugin/src/lib/delivery-command-actions.js +0 -462
  113. package/agent-spine-plugin/src/lib/delivery-knowledge.js +0 -78
  114. package/agent-spine-plugin/src/lib/delivery-premortem-binding.js +0 -107
  115. package/agent-spine-plugin/src/lib/delivery-premortem-closure.js +0 -171
  116. package/agent-spine-plugin/src/lib/delivery-premortem-codec.js +0 -45
  117. package/agent-spine-plugin/src/lib/delivery-premortem-correction.js +0 -101
  118. package/agent-spine-plugin/src/lib/delivery-premortem-file.js +0 -21
  119. package/agent-spine-plugin/src/lib/delivery-premortem-index.js +0 -493
  120. package/agent-spine-plugin/src/lib/delivery-premortem-inspection.js +0 -37
  121. package/agent-spine-plugin/src/lib/delivery-premortem-recovery.js +0 -120
  122. package/agent-spine-plugin/src/lib/delivery-premortem-rejection.js +0 -65
  123. package/agent-spine-plugin/src/lib/delivery-premortem-results.js +0 -28
  124. package/agent-spine-plugin/src/lib/delivery-premortem-session-guard.js +0 -46
  125. package/agent-spine-plugin/src/lib/delivery-premortem-write-ledger.js +0 -285
  126. package/agent-spine-plugin/src/lib/delivery-premortem.js +0 -499
  127. package/agent-spine-plugin/src/lib/delivery-shell-heredoc.js +0 -115
  128. package/agent-spine-plugin/src/lib/delivery-shell-substitutions.js +0 -111
  129. package/agent-spine-plugin/src/lib/delivery-shell-wrapper.js +0 -64
  130. package/agent-spine-plugin/src/lib/delivery-target.js +0 -73
  131. package/agent-spine-plugin/src/lib/delivery-verification.js +0 -445
  132. package/agent-spine-plugin/src/lib/documents.js +0 -239
  133. package/agent-spine-plugin/src/lib/feed-transport.js +0 -499
  134. package/agent-spine-plugin/src/lib/filesystem-retry.js +0 -34
  135. package/agent-spine-plugin/src/lib/gateway-common.js +0 -68
  136. package/agent-spine-plugin/src/lib/gateway-control.js +0 -370
  137. package/agent-spine-plugin/src/lib/gateway-delivery.js +0 -103
  138. package/agent-spine-plugin/src/lib/gateway-execution.js +0 -350
  139. package/agent-spine-plugin/src/lib/gateway-group-response.js +0 -128
  140. package/agent-spine-plugin/src/lib/gateway-host-fencing.js +0 -92
  141. package/agent-spine-plugin/src/lib/gateway-host-lifecycle.js +0 -193
  142. package/agent-spine-plugin/src/lib/gateway-inspection.js +0 -85
  143. package/agent-spine-plugin/src/lib/gateway-knowledge.js +0 -129
  144. package/agent-spine-plugin/src/lib/gateway-policy-provenance.js +0 -197
  145. package/agent-spine-plugin/src/lib/gateway-premortem-disposition.js +0 -82
  146. package/agent-spine-plugin/src/lib/gateway-premortem.js +0 -363
  147. package/agent-spine-plugin/src/lib/gateway-prepared-host.js +0 -28
  148. package/agent-spine-plugin/src/lib/gateway-runs.js +0 -345
  149. package/agent-spine-plugin/src/lib/gateway-runtime-identity.js +0 -31
  150. package/agent-spine-plugin/src/lib/gateway-runtime-records.js +0 -21
  151. package/agent-spine-plugin/src/lib/gateway-runtime.js +0 -18
  152. package/agent-spine-plugin/src/lib/gateway-state-transaction.js +0 -356
  153. package/agent-spine-plugin/src/lib/gateway-state.js +0 -344
  154. package/agent-spine-plugin/src/lib/graph.js +0 -337
  155. package/agent-spine-plugin/src/lib/hook-artifact-guards.js +0 -356
  156. package/agent-spine-plugin/src/lib/hook-audit.js +0 -43
  157. package/agent-spine-plugin/src/lib/hook-briefing-use.js +0 -78
  158. package/agent-spine-plugin/src/lib/hook-context.js +0 -441
  159. package/agent-spine-plugin/src/lib/hook-final-message.js +0 -26
  160. package/agent-spine-plugin/src/lib/hook-input.js +0 -27
  161. package/agent-spine-plugin/src/lib/hook-output.js +0 -284
  162. package/agent-spine-plugin/src/lib/hook-premortem.js +0 -257
  163. package/agent-spine-plugin/src/lib/hook-process-advisory.js +0 -36
  164. package/agent-spine-plugin/src/lib/hook-protection.js +0 -95
  165. package/agent-spine-plugin/src/lib/hook-stop-verification.js +0 -84
  166. package/agent-spine-plugin/src/lib/hook-timeline.js +0 -102
  167. package/agent-spine-plugin/src/lib/host-instruction-budget.js +0 -11
  168. package/agent-spine-plugin/src/lib/https-transport.js +0 -392
  169. package/agent-spine-plugin/src/lib/identifier-analysis.js +0 -446
  170. package/agent-spine-plugin/src/lib/indexed-memory-offline.js +0 -40
  171. package/agent-spine-plugin/src/lib/indexed-memory.js +0 -298
  172. package/agent-spine-plugin/src/lib/knowledge-evidence.js +0 -431
  173. package/agent-spine-plugin/src/lib/learning-applications.js +0 -441
  174. package/agent-spine-plugin/src/lib/learning-artifact-evaluator.js +0 -114
  175. package/agent-spine-plugin/src/lib/learning-candidates.js +0 -274
  176. package/agent-spine-plugin/src/lib/learning-context.js +0 -137
  177. package/agent-spine-plugin/src/lib/learning-delivery-contracts.js +0 -310
  178. package/agent-spine-plugin/src/lib/learning-evaluation-contracts.js +0 -350
  179. package/agent-spine-plugin/src/lib/learning-evaluation-registration.js +0 -372
  180. package/agent-spine-plugin/src/lib/learning-evaluation-revocation.js +0 -292
  181. package/agent-spine-plugin/src/lib/learning-evidence-contracts.js +0 -321
  182. package/agent-spine-plugin/src/lib/learning-findings.js +0 -458
  183. package/agent-spine-plugin/src/lib/learning-measurement-contracts.js +0 -285
  184. package/agent-spine-plugin/src/lib/learning-measurements.js +0 -265
  185. package/agent-spine-plugin/src/lib/learning-outcome-contracts.js +0 -165
  186. package/agent-spine-plugin/src/lib/learning-outcomes.js +0 -343
  187. package/agent-spine-plugin/src/lib/learning-reconciliation.js +0 -290
  188. package/agent-spine-plugin/src/lib/learning-retry-contracts.js +0 -188
  189. package/agent-spine-plugin/src/lib/learning-schema.js +0 -229
  190. package/agent-spine-plugin/src/lib/learning-scope-targets.js +0 -424
  191. package/agent-spine-plugin/src/lib/learning-state-upgrade.js +0 -477
  192. package/agent-spine-plugin/src/lib/learning-status-configuration.js +0 -476
  193. package/agent-spine-plugin/src/lib/learning-storage.js +0 -203
  194. package/agent-spine-plugin/src/lib/learning-trial-recovery.js +0 -218
  195. package/agent-spine-plugin/src/lib/learning-validation-contracts.js +0 -375
  196. package/agent-spine-plugin/src/lib/learning-validation-renewal.js +0 -298
  197. package/agent-spine-plugin/src/lib/learning-validation-runtime.js +0 -234
  198. package/agent-spine-plugin/src/lib/learning.js +0 -36
  199. package/agent-spine-plugin/src/lib/lesson-recall-session.js +0 -172
  200. package/agent-spine-plugin/src/lib/mcp-autonomy-tools.js +0 -37
  201. package/agent-spine-plugin/src/lib/mcp-delivery-completion.js +0 -124
  202. package/agent-spine-plugin/src/lib/mcp-delivery-tools.js +0 -45
  203. package/agent-spine-plugin/src/lib/mcp-premortem.js +0 -68
  204. package/agent-spine-plugin/src/lib/mcp-runtime.js +0 -355
  205. package/agent-spine-plugin/src/lib/mcp-source-context.js +0 -61
  206. package/agent-spine-plugin/src/lib/mcp-timeline-tools.js +0 -240
  207. package/agent-spine-plugin/src/lib/mcp-world-tools.js +0 -52
  208. package/agent-spine-plugin/src/lib/object-transport.js +0 -206
  209. package/agent-spine-plugin/src/lib/owned-file-lock.js +0 -182
  210. package/agent-spine-plugin/src/lib/paths.js +0 -109
  211. package/agent-spine-plugin/src/lib/peer-transport.js +0 -283
  212. package/agent-spine-plugin/src/lib/persona-runtime.js +0 -581
  213. package/agent-spine-plugin/src/lib/pre-answer-timeline-recall.js +0 -104
  214. package/agent-spine-plugin/src/lib/preflight-delivery-id.js +0 -27
  215. package/agent-spine-plugin/src/lib/preflight.js +0 -688
  216. package/agent-spine-plugin/src/lib/project-portfolio.js +0 -176
  217. package/agent-spine-plugin/src/lib/runtime.js +0 -13
  218. package/agent-spine-plugin/src/lib/selfstarter-core.js +0 -382
  219. package/agent-spine-plugin/src/lib/selfstarter-jobs.js +0 -149
  220. package/agent-spine-plugin/src/lib/selfstarter-lease.js +0 -204
  221. package/agent-spine-plugin/src/lib/selfstarter-policy.js +0 -90
  222. package/agent-spine-plugin/src/lib/selfstarter-workspace.js +0 -111
  223. package/agent-spine-plugin/src/lib/selfstarter.js +0 -11
  224. package/agent-spine-plugin/src/lib/session-timeline-auth.js +0 -316
  225. package/agent-spine-plugin/src/lib/session-timeline-codex.js +0 -69
  226. package/agent-spine-plugin/src/lib/session-timeline-contract.js +0 -56
  227. package/agent-spine-plugin/src/lib/session-timeline-enrollment-source.js +0 -38
  228. package/agent-spine-plugin/src/lib/session-timeline-enrollment-storage.js +0 -128
  229. package/agent-spine-plugin/src/lib/session-timeline-enrollment-transport.js +0 -15
  230. package/agent-spine-plugin/src/lib/session-timeline-enrollment.js +0 -478
  231. package/agent-spine-plugin/src/lib/session-timeline-event-extract.js +0 -186
  232. package/agent-spine-plugin/src/lib/session-timeline-host-origin.js +0 -73
  233. package/agent-spine-plugin/src/lib/session-timeline-host-receipt.js +0 -117
  234. package/agent-spine-plugin/src/lib/session-timeline-invocation.js +0 -201
  235. package/agent-spine-plugin/src/lib/session-timeline-king.js +0 -93
  236. package/agent-spine-plugin/src/lib/session-timeline-prior.js +0 -57
  237. package/agent-spine-plugin/src/lib/session-timeline-provider.js +0 -36
  238. package/agent-spine-plugin/src/lib/session-timeline-query.js +0 -56
  239. package/agent-spine-plugin/src/lib/session-timeline-results.js +0 -56
  240. package/agent-spine-plugin/src/lib/session-timeline-root.js +0 -11
  241. package/agent-spine-plugin/src/lib/session-timeline-search.js +0 -82
  242. package/agent-spine-plugin/src/lib/session-timeline-sid-acl.js +0 -213
  243. package/agent-spine-plugin/src/lib/session-timeline-source-open.js +0 -30
  244. package/agent-spine-plugin/src/lib/session-timeline-source.js +0 -80
  245. package/agent-spine-plugin/src/lib/session-timeline-state.js +0 -45
  246. package/agent-spine-plugin/src/lib/session-timeline-transport.js +0 -42
  247. package/agent-spine-plugin/src/lib/session-timeline-windows-acl.js +0 -145
  248. package/agent-spine-plugin/src/lib/session-timeline.js +0 -462
  249. package/agent-spine-plugin/src/lib/sharing.js +0 -969
  250. package/agent-spine-plugin/src/lib/source-roots.js +0 -475
  251. package/agent-spine-plugin/src/lib/source-tree-scan.js +0 -178
  252. package/agent-spine-plugin/src/lib/sqlite-transport.js +0 -501
  253. package/agent-spine-plugin/src/lib/task-knowledge-context.js +0 -99
  254. package/agent-spine-plugin/src/lib/telegram-adapter.js +0 -119
  255. package/agent-spine-plugin/src/lib/timeline-continuation-update.js +0 -100
  256. package/agent-spine-plugin/src/lib/timeline-tool-guard.js +0 -225
  257. package/agent-spine-plugin/src/lib/timeline-user-feedback.js +0 -216
  258. package/agent-spine-plugin/src/lib/timeline-world-capture.js +0 -233
  259. package/agent-spine-plugin/src/lib/voice-runtime.js +0 -39
  260. package/agent-spine-plugin/src/lib/world-knowledge.js +0 -306
  261. package/agent-spine-plugin/src/lib/world-model.js +0 -333
  262. package/agent-spine-plugin/src/mcp.js +0 -456
  263. package/agent-spine-plugin/src/version.js +0 -1
  264. package/agent-spine-plugin/src/worker.js +0 -257
  265. package/bin/agentspine-king-goal-inbox.mjs +0 -127
  266. package/bin/agentspine-king-goal-intake.mjs +0 -106
  267. package/bin/agentspine-king-host-runner.mjs +0 -109
  268. package/bin/agentspine-king-snapshot-policy.cjs +0 -80
  269. package/bin/agentspine-king-status-policy.mjs +0 -226
  270. package/bin/agentspine-king-worker-host.mjs +0 -160
  271. package/bin/managed-plugin-selection.cjs +0 -141
  272. package/bin/verify-agent-behavior.cjs +0 -122
  273. package/bin/verify-agent-components.cjs +0 -104
@@ -1,688 +0,0 @@
1
- import { createHash, createHmac, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
2
- import { constants as fsConstants } from "node:fs";
3
- import { spawn } from "node:child_process";
4
- import { lstat, mkdir, open, readFile, realpath, stat, unlink, writeFile } from "node:fs/promises";
5
- import { basename, dirname, isAbsolute, join, relative, resolve } from "node:path";
6
- import { isFileLockContention, replaceFileWithRetry } from "./filesystem-retry.js";
7
- import { ancestorsBetween, isInside, stateRoot } from "./paths.js";
8
- import { preflightDeliveryId } from "./preflight-delivery-id.js";
9
- import { resolveHostSourceCatalog } from "./source-roots.js";
10
- import { instructionBudget } from "./host-instruction-budget.js";
11
-
12
- export const PREFLIGHT_SCHEMA = "agentspine.preflight/v2";
13
- export const PREFLIGHT_POLICY_SCHEMA = "agentspine.preflight-policy/v1";
14
- export const RETRIEVAL_QUERY_SCHEMA = "agentspine.retrieval-query/v1";
15
- export const RETRIEVAL_RESULT_SCHEMA = "agentspine.retrieval-result/v1";
16
- export const MUST_REMEMBER_SCHEMA = "agentspine.must-remember/v1";
17
-
18
- const CONFIRM_POLICY = "local-owner-confirmed";
19
- const CONFIRM_MEMORY = "local-user-confirmed";
20
- const ID_RE = /^[A-Za-z0-9][A-Za-z0-9:_.@/+~-]{0,255}$/;
21
- const DIGEST_RE = /^[a-f0-9]{64}$/;
22
- const ENV_RE = /^[A-Z_][A-Z0-9_]{0,127}$/;
23
- const MAX_POLICY_BYTES = 1024 * 1024;
24
- const MAX_STATE_BYTES = 8 * 1024 * 1024;
25
- const MAX_PROVIDER_BYTES = 1024 * 1024;
26
- const MAX_REQUIRED_MEMORY_BYTES = 6 * 1024;
27
- const RECEIPT_TTL_MS = 60_000;
28
- const FORBIDDEN_MEMORY = /-----BEGIN [A-Z ]*PRIVATE KEY-----|\b(?:sk|gh[opusu])_[A-Za-z0-9_-]{20,}\b|\b(?:password|passwort|secret|token|api[-_ ]?key|credential|permission|rights?|roles?|delegat|authoriz|berechtig|freigabe|approval|tool access|file access|network|production|payment|zahlung|policy)\b/i;
29
-
30
- function sha256(value) { return createHash("sha256").update(value).digest("hex"); }
31
- function canonical(value) {
32
- if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`;
33
- if (value && typeof value === "object") return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${canonical(value[key])}`).join(",")}}`;
34
- return JSON.stringify(value);
35
- }
36
- function digestObject(value) { return sha256(canonical(value)); }
37
- function timestamp(value = new Date()) {
38
- const date = value instanceof Date ? value : new Date(value);
39
- if (!Number.isFinite(date.getTime())) throw new Error("preflight timestamp is invalid");
40
- return date.toISOString();
41
- }
42
- function exactId(value, field, fallback = null) {
43
- const selected = value === null || value === undefined || value === "" ? fallback : value;
44
- if (typeof selected !== "string" || !ID_RE.test(selected) || selected.includes("*")) throw new Error(`${field} must be one exact ID`);
45
- return selected;
46
- }
47
- function nullableId(value, field) { return value === null || value === undefined || value === "" ? null : exactId(value, field); }
48
- function storagePaths(env = process.env) {
49
- const root = stateRoot(env);
50
- return {
51
- directory: join(root, "preflight"), policy: join(root, "policy", "preflight-policy.json"),
52
- state: join(root, "preflight", "preflight-state.json"), memories: join(root, "context", "must-remember.json"),
53
- key: join(root, "policy", "preflight-signing.key"), lock: join(root, "preflight", "preflight.lock")
54
- };
55
- }
56
- function emptyPolicy() { return { schema: PREFLIGHT_POLICY_SCHEMA, revision: 0, profiles: [], history: [] }; }
57
- function emptyState() { return { schema: PREFLIGHT_SCHEMA, revision: 0, receipts: [], history: [], lastTurn: null }; }
58
- function emptyMemories() { return { schema: MUST_REMEMBER_SCHEMA, revision: 0, candidates: [], entries: [], history: [] }; }
59
-
60
- async function readJson(path, maximum, fallback) {
61
- try {
62
- const metadata = await stat(path);
63
- if (!metadata.isFile() || metadata.size > maximum) throw new Error(`${basename(path)} is invalid or too large`);
64
- return JSON.parse(await readFile(path, "utf8"));
65
- } catch (error) {
66
- if (error.code === "ENOENT") return fallback();
67
- throw error;
68
- }
69
- }
70
- async function writeJson(path, value, maximum = MAX_STATE_BYTES) {
71
- const body = `${JSON.stringify(value, null, 2)}\n`;
72
- if (Buffer.byteLength(body) > maximum) throw new Error(`${basename(path)} exceeds its state limit`);
73
- await mkdir(dirname(path), { recursive: true, mode: 0o700 });
74
- const temporary = `${path}.${process.pid}.${randomUUID()}.tmp`;
75
- try {
76
- await writeFile(temporary, body, { mode: 0o600 });
77
- await replaceFileWithRetry(temporary, path);
78
- } finally {
79
- await unlink(temporary).catch((error) => { if (error.code !== "ENOENT") throw error; });
80
- }
81
- }
82
- async function withLock(paths, task) {
83
- await mkdir(paths.directory, { recursive: true, mode: 0o700 });
84
- let handle;
85
- for (let attempt = 0; attempt < 120; attempt += 1) {
86
- try { handle = await open(paths.lock, "wx", 0o600); break; } catch (error) {
87
- if (!isFileLockContention(error)) throw error;
88
- try {
89
- const metadata = await stat(paths.lock);
90
- if (Date.now() - metadata.mtimeMs > 90_000) await unlink(paths.lock);
91
- } catch (lockError) { if (lockError.code !== "ENOENT") throw lockError; }
92
- await new Promise((resolvePromise) => setTimeout(resolvePromise, 25));
93
- }
94
- }
95
- if (!handle) throw new Error("preflight state is busy; turn blocked");
96
- try { return await task(); } finally {
97
- await handle.close();
98
- await unlink(paths.lock).catch((error) => { if (error.code !== "ENOENT") throw error; });
99
- }
100
- }
101
-
102
- function normalizeProvider(provider) {
103
- if (!provider || provider.schema !== "agentspine.retrieval-provider/v1") throw new Error("retrieval provider schema is invalid");
104
- const value = {
105
- schema: provider.schema, id: exactId(provider.id, "providerId"), adapter: provider.adapter,
106
- required: provider.required === true, failClosed: provider.failClosed === true,
107
- timeoutMs: Number(provider.timeoutMs ?? 5000), command: provider.command, args: provider.args || [],
108
- credentialEnv: provider.credentialEnv || []
109
- };
110
- if (value.adapter !== "mnemo-command/v1" || !isAbsolute(value.command || "") || !Array.isArray(value.args)
111
- || value.args.some((item) => typeof item !== "string" || item.length > 500)
112
- || !Number.isInteger(value.timeoutMs) || value.timeoutMs < 100 || value.timeoutMs > 10_000
113
- || !Array.isArray(value.credentialEnv) || value.credentialEnv.some((item) => !ENV_RE.test(item))) {
114
- throw new Error("retrieval provider configuration is unsafe");
115
- }
116
- if (value.required && !value.failClosed) throw new Error("required retrieval providers must fail closed");
117
- return value;
118
- }
119
- function normalizeProfile(profile) {
120
- return {
121
- id: exactId(profile.id, "profilePolicyId"), agentId: exactId(profile.agentId, "agentId"),
122
- host: exactId(profile.host, "host"), profileId: exactId(profile.profileId, "profileId"),
123
- tenantId: exactId(profile.tenantId, "tenantId"), enabled: profile.enabled === true,
124
- providers: (profile.providers || []).map(normalizeProvider), authority: "authenticated-local-policy"
125
- };
126
- }
127
- function validatePolicy(value) {
128
- if (!value || value.schema !== PREFLIGHT_POLICY_SCHEMA || !Number.isInteger(value.revision)
129
- || !Array.isArray(value.profiles) || !Array.isArray(value.history)
130
- || value.history.some((item) => item?.authority !== "authenticated-local-policy")) throw new Error("preflight policy is corrupt; required turns are blocked");
131
- value.profiles = value.profiles.map(normalizeProfile);
132
- if (new Set(value.profiles.map((item) => item.id)).size !== value.profiles.length) throw new Error("preflight policy contains duplicate profiles");
133
- return value;
134
- }
135
- function validateMemories(value) {
136
- if (!value || value.schema !== MUST_REMEMBER_SCHEMA || !Number.isInteger(value.revision)
137
- || !Array.isArray(value.candidates) || !Array.isArray(value.entries) || !Array.isArray(value.history)
138
- || value.history.some((item) => item?.authority !== "context-only")
139
- || [...value.candidates, ...value.entries].some((item) => !item || !ID_RE.test(item.id || "")
140
- || typeof item.claim !== "string" || !item.claim || FORBIDDEN_MEMORY.test(item.claim)
141
- || item.authority !== "context-only" || !ID_RE.test(item.userId || "") || !ID_RE.test(item.tenantId || ""))
142
- || value.entries.some((item) => !DIGEST_RE.test(item.checksum || "") || item.checksum !== sha256(item.claim)
143
- || !["active", "superseded"].includes(item.status) || !Number.isInteger(item.version) || item.version < 1)) {
144
- throw new Error("must-remember state is corrupt; required recall is blocked");
145
- }
146
- return value;
147
- }
148
- function validateState(value) {
149
- if (!value || value.schema !== PREFLIGHT_SCHEMA || !Number.isInteger(value.revision)
150
- || !Array.isArray(value.receipts) || !Array.isArray(value.history)
151
- || value.receipts.some((envelope) => {
152
- const receipt = envelope?.receipt;
153
- if (!receipt || receipt.schema !== PREFLIGHT_SCHEMA || receipt.status !== "ready"
154
- || !ID_RE.test(receipt.id || "") || !DIGEST_RE.test(receipt.bodyDigest || "") || !DIGEST_RE.test(receipt.signature || "")
155
- || !DIGEST_RE.test(envelope.stateSignature || "")
156
- || (envelope.consumedAt !== null && !Number.isFinite(new Date(envelope.consumedAt).getTime()))
157
- || (envelope.invalidatedAt !== null && envelope.invalidatedAt !== undefined
158
- && !Number.isFinite(new Date(envelope.invalidatedAt).getTime()))) return true;
159
- const { id, bodyDigest, signature: _signature, ...body } = receipt;
160
- return id !== `preflight:${bodyDigest.slice(0, 32)}` || digestObject(body) !== bodyDigest;
161
- })) throw new Error("preflight receipt state is corrupt; turn blocked");
162
- return value;
163
- }
164
- function envelopeBody(envelope) {
165
- return canonical({ bodyDigest: envelope.receipt.bodyDigest, consumedAt: envelope.consumedAt,
166
- invalidatedAt: envelope.invalidatedAt ?? null });
167
- }
168
- async function signingKey(paths) {
169
- await mkdir(dirname(paths.key), { recursive: true, mode: 0o700 });
170
- try {
171
- const value = await readFile(paths.key);
172
- if (value.byteLength !== 32) throw new Error("preflight signing key is corrupt; turn blocked");
173
- return value;
174
- } catch (error) {
175
- if (error.code !== "ENOENT") throw error;
176
- const value = randomBytes(32);
177
- const handle = await open(paths.key, "wx", 0o600);
178
- try { await handle.writeFile(value); } finally { await handle.close(); }
179
- return value;
180
- }
181
- }
182
-
183
- async function readVerifiedState(paths) {
184
- const state = validateState(await readJson(paths.state, MAX_STATE_BYTES, emptyState));
185
- if (!state.receipts.length) return state;
186
- const key = await signingKey(paths);
187
- for (const envelope of state.receipts) {
188
- const expected = createHmac("sha256", key).update(envelope.receipt.bodyDigest).digest();
189
- const actual = Buffer.from(envelope.receipt.signature, "hex");
190
- if (actual.length !== expected.length || !timingSafeEqual(actual, expected)) {
191
- throw new Error("preflight receipt authentication failed; turn blocked");
192
- }
193
- const expectedState = createHmac("sha256", key).update(envelopeBody(envelope)).digest();
194
- const actualState = Buffer.from(envelope.stateSignature, "hex");
195
- if (actualState.length !== expectedState.length || !timingSafeEqual(actualState, expectedState)) {
196
- throw new Error("preflight receipt lifecycle authentication failed; turn blocked");
197
- }
198
- }
199
- return state;
200
- }
201
-
202
- export async function configurePreflightPolicy({ profile, confirmation, env = process.env }) {
203
- if (confirmation !== CONFIRM_POLICY) throw new Error("preflight policy changes require explicit local owner confirmation");
204
- const paths = storagePaths(env);
205
- return withLock(paths, async () => {
206
- const policy = validatePolicy(await readJson(paths.policy, MAX_POLICY_BYTES, emptyPolicy));
207
- const normalized = normalizeProfile(profile);
208
- policy.profiles = [...policy.profiles.filter((item) => item.id !== normalized.id), normalized];
209
- policy.revision += 1;
210
- policy.history.push({ event: "profile-configured", profileId: normalized.id, at: timestamp(), authority: "authenticated-local-policy" });
211
- await writeJson(paths.policy, policy, MAX_POLICY_BYTES);
212
- return { profile: normalized, revision: policy.revision, policyPath: paths.policy };
213
- });
214
- }
215
-
216
- function memoryScope(input) {
217
- return {
218
- userId: exactId(input.userId, "userId"), tenantId: exactId(input.tenantId, "tenantId"),
219
- projectId: nullableId(input.projectId, "projectId"), groupId: nullableId(input.groupId, "groupId"),
220
- taskId: nullableId(input.taskId, "taskId")
221
- };
222
- }
223
- function safeClaim(value) {
224
- if (typeof value !== "string" || !value.trim() || Buffer.byteLength(value) > 4096 || FORBIDDEN_MEMORY.test(value)) {
225
- throw new Error("must-remember claim is empty, too large, secret-shaped, or authority-shaped");
226
- }
227
- return value.trim().replace(/\s+/g, " ");
228
- }
229
- export async function proposeMustRemember({ claim, kind = "critical", sourceDigest, ...scope }, env = process.env) {
230
- const paths = storagePaths(env);
231
- const exactScope = memoryScope(scope);
232
- const normalized = safeClaim(claim);
233
- const id = `remember-candidate:${sha256(canonical({ claim: normalized, ...exactScope })).slice(0, 32)}`;
234
- return withLock(paths, async () => {
235
- const state = validateMemories(await readJson(paths.memories, MAX_STATE_BYTES, emptyMemories));
236
- const existing = state.candidates.find((item) => item.id === id);
237
- if (existing) return { candidate: existing, duplicate: true };
238
- const candidate = { id, kind, claim: normalized, ...exactScope, sourceDigest: DIGEST_RE.test(sourceDigest || "") ? sourceDigest : null,
239
- status: "pending-confirmation", observedAt: timestamp(), authority: "context-only" };
240
- state.candidates.push(candidate); state.revision += 1;
241
- state.history.push({ event: "proposed", id, at: candidate.observedAt, authority: "context-only" });
242
- await writeJson(paths.memories, state);
243
- return { candidate, duplicate: false };
244
- });
245
- }
246
- export async function captureMustRememberPrompt({ prompt, receipt, env = process.env }) {
247
- if (typeof prompt !== "string" || Buffer.byteLength(prompt) > 64 * 1024 || !receipt || receipt.schema !== PREFLIGHT_SCHEMA) return null;
248
- const match = prompt.trim().match(/^(?:merk dir(?: bitte)?(?: dauerhaft)?(?: das)?|das ist wichtig|vergiss das niemals|remember (?:this|that)(?: permanently)?|never forget this)\s*[:,-]?\s*(.+)$/i);
249
- if (!match?.[1]?.trim()) return null;
250
- try {
251
- return await proposeMustRemember({ claim: match[1], kind: "critical", userId: receipt.userId,
252
- tenantId: receipt.tenantId, projectId: receipt.projectId, groupId: receipt.groupId,
253
- taskId: receipt.taskId, sourceDigest: receipt.promptDigest }, env);
254
- } catch (error) {
255
- return { rejected: true, reason: error.message };
256
- }
257
- }
258
- export async function confirmMustRemember({ candidateId, confirmation, supersedes = null }, env = process.env) {
259
- if (confirmation !== CONFIRM_MEMORY) throw new Error("must-remember activation requires explicit local user confirmation");
260
- const paths = storagePaths(env);
261
- return withLock(paths, async () => {
262
- const state = validateMemories(await readJson(paths.memories, MAX_STATE_BYTES, emptyMemories));
263
- const candidate = state.candidates.find((item) => item.id === candidateId && item.status === "pending-confirmation");
264
- if (!candidate) throw new Error("pending must-remember candidate not found");
265
- const previous = supersedes ? state.entries.find((item) => item.id === supersedes && item.status === "active") : null;
266
- if (supersedes && !previous) throw new Error("active must-remember entry to supersede was not found");
267
- if (previous && ["userId", "tenantId", "projectId", "groupId", "taskId"].some((key) => previous[key] !== candidate[key])) {
268
- throw new Error("must-remember supersession cannot cross scope");
269
- }
270
- const version = previous ? previous.version + 1 : 1;
271
- const id = `remember:${sha256(`${candidate.id}\0${version}\0${timestamp()}`).slice(0, 32)}`;
272
- const entry = { ...candidate, id, candidateId: candidate.id, version, supersedes: previous?.id || null,
273
- checksum: sha256(candidate.claim), status: "active", confirmedAt: timestamp(), retention: "until-local-user-deletes",
274
- confirmation: "explicit-local-user", authority: "context-only" };
275
- delete entry.observedAt;
276
- candidate.status = "confirmed";
277
- if (previous) previous.status = "superseded";
278
- state.entries.push(entry); state.revision += 1;
279
- state.history.push({ event: "confirmed", id, supersedes: entry.supersedes, at: entry.confirmedAt, authority: "context-only" });
280
- await writeJson(paths.memories, state);
281
- return { entry, revision: state.revision };
282
- });
283
- }
284
- export async function rollbackMustRemember({ id, confirmation }, env = process.env) {
285
- if (confirmation !== CONFIRM_MEMORY) throw new Error("must-remember rollback requires explicit local user confirmation");
286
- const paths = storagePaths(env);
287
- return withLock(paths, async () => {
288
- const state = validateMemories(await readJson(paths.memories, MAX_STATE_BYTES, emptyMemories));
289
- const target = state.entries.find((item) => item.id === id);
290
- if (!target) throw new Error("must-remember entry not found");
291
- for (const item of state.entries) if (item.userId === target.userId && item.tenantId === target.tenantId
292
- && item.projectId === target.projectId && item.groupId === target.groupId && item.taskId === target.taskId
293
- && item.kind === target.kind && item.status === "active") item.status = "superseded";
294
- target.status = "active"; state.revision += 1;
295
- state.history.push({ event: "rolled-back", id, at: timestamp(), authority: "context-only" });
296
- await writeJson(paths.memories, state);
297
- return { entry: target, revision: state.revision };
298
- });
299
- }
300
- export async function purgeMustRemember({ id, confirmation }, env = process.env) {
301
- if (confirmation !== "local-user-purge-confirmed") throw new Error("permanent must-remember deletion requires explicit local user purge confirmation");
302
- const paths = storagePaths(env);
303
- return withLock(paths, async () => {
304
- const state = validateMemories(await readJson(paths.memories, MAX_STATE_BYTES, emptyMemories));
305
- const removed = state.entries.find((item) => item.id === id);
306
- if (!removed) throw new Error("must-remember entry not found");
307
- state.entries = state.entries.filter((item) => item.id !== id);
308
- state.candidates = state.candidates.filter((item) => item.id !== removed.candidateId);
309
- state.revision += 1; state.history.push({ event: "purged", idDigest: sha256(id), at: timestamp(), authority: "context-only" });
310
- await writeJson(paths.memories, state);
311
- return { purged: true, idDigest: sha256(id), revision: state.revision };
312
- });
313
- }
314
-
315
- async function assertNoSymlinkParents(path, allowedRoot) {
316
- const root = await realpath(allowedRoot);
317
- const target = resolve(path);
318
- if (!isInside(root, target)) throw new Error("required instruction escaped its allowed scope");
319
- let cursor = target;
320
- const chain = [];
321
- while (cursor !== root) { chain.push(cursor); cursor = dirname(cursor); if (!isInside(root, cursor)) throw new Error("required instruction escaped its allowed scope"); }
322
- chain.reverse();
323
- for (const item of chain) {
324
- const metadata = await lstat(item);
325
- if (metadata.isSymbolicLink()) throw new Error("required instruction path contains a symlink");
326
- }
327
- return { root, target };
328
- }
329
- async function safeReadRequired(path, allowedRoot, maximum = STANDARD_REQUIRED_INSTRUCTIONS_BYTES, fileHooks = null) {
330
- const checked = await assertNoSymlinkParents(path, allowedRoot);
331
- const flags = fsConstants.O_RDONLY | (fsConstants.O_NOFOLLOW || 0);
332
- const handle = await open(checked.target, flags);
333
- try {
334
- const before = await handle.stat();
335
- if (!before.isFile()) throw new Error(`required instruction ${basename(path)} is not a regular file`);
336
- if (before.size > maximum) {
337
- throw new Error(`required instruction ${basename(path)} is ${before.size} bytes; mandatory limit is ${maximum} bytes`);
338
- }
339
- const buffer = Buffer.alloc(Number(before.size));
340
- let offset = 0;
341
- while (offset < buffer.length) {
342
- const result = await handle.read(buffer, offset, buffer.length - offset, offset);
343
- if (!result.bytesRead) break;
344
- offset += result.bytesRead;
345
- }
346
- if (fileHooks?.afterRead) await fileHooks.afterRead(checked.target);
347
- const after = await handle.stat();
348
- if (offset !== buffer.length || before.dev !== after.dev || before.ino !== after.ino || before.size !== after.size
349
- || before.mtimeMs !== after.mtimeMs || before.ctimeMs !== after.ctimeMs) throw new Error(`required instruction ${basename(path)} changed during preflight`);
350
- const finalPath = await assertNoSymlinkParents(checked.target, checked.root);
351
- const current = await lstat(finalPath.target);
352
- if (!current.isFile() || current.isSymbolicLink() || current.dev !== before.dev || current.ino !== before.ino
353
- || current.size !== before.size || current.mtimeMs !== before.mtimeMs || current.ctimeMs !== before.ctimeMs) {
354
- throw new Error(`required instruction ${basename(path)} was replaced during preflight`);
355
- }
356
- return { content: buffer.toString("utf8"), bytes: buffer.length, sha256: sha256(buffer),
357
- identity: sha256(`${before.dev}\0${before.ino}\0${before.size}\0${before.mtimeMs}\0${before.ctimeMs}`) };
358
- } finally { await handle.close(); }
359
- }
360
-
361
- function scopeFromInput({ input, scope, resolvedSources, env = process.env }) {
362
- const supplied = input.agent_spine_scope && typeof input.agent_spine_scope === "object" ? input.agent_spine_scope : input;
363
- return {
364
- agentId: exactId(supplied.agent_id ?? supplied.agentId ?? scope.entityId, "agentId", "host-agent:default"),
365
- personaId: nullableId(supplied.persona_id ?? supplied.personaId, "personaId"),
366
- userId: exactId(supplied.user_id ?? supplied.userId ?? env.AGENTSPINE_USER_ID, "userId", "local-user"),
367
- tenantId: exactId(supplied.tenant_id ?? supplied.tenantId ?? env.AGENTSPINE_TENANT_ID, "tenantId", "local-tenant"),
368
- profileId: exactId(supplied.profile_id ?? supplied.profileId ?? env.AGENTSPINE_PROFILE_ID, "profileId", "default"),
369
- sessionId: exactId(input.session_id ?? input.sessionId, "sessionId"), host: scope.host,
370
- projectId: exactId(scope.projectId, "projectId", `project:${sha256(resolvedSources.projectRoot).slice(0, 20)}`),
371
- groupId: nullableId(scope.groupId, "groupId"), taskId: nullableId(scope.currentTaskId, "taskId"),
372
- cwd: resolvedSources.cwd, projectRoot: resolvedSources.projectRoot
373
- };
374
- }
375
- function instructionDocuments(catalog, host) {
376
- const pattern = host === "claude" ? /(?:^|\/)CLAUDE(?:\.local)?\.md$/ : /(?:^|\/)AGENTS(?:\.override)?\.md$/;
377
- return catalog.documents.filter((item) => item.layer === "constitution" && pattern.test(item.relativePath))
378
- .sort((left, right) => left.precedence - right.precedence || left.relativePath.localeCompare(right.relativePath));
379
- }
380
- async function rejectKnownInstructionSymlinks(resolvedSources, host) {
381
- const candidates = host === "claude"
382
- ? [join(resolvedSources.hostHome, "CLAUDE.md"), ...ancestorsBetween(resolvedSources.projectRoot, resolvedSources.cwd)
383
- .flatMap((directory) => [join(directory, "CLAUDE.md"), join(directory, "CLAUDE.local.md"), join(directory, ".claude", "CLAUDE.md")])]
384
- : [join(resolvedSources.hostHome, "AGENTS.override.md"), join(resolvedSources.hostHome, "AGENTS.md"),
385
- ...ancestorsBetween(resolvedSources.projectRoot, resolvedSources.cwd)
386
- .flatMap((directory) => [join(directory, "AGENTS.override.md"), join(directory, "AGENTS.md")])];
387
- for (const path of candidates) {
388
- try {
389
- if ((await lstat(path)).isSymbolicLink()) throw new Error(`host instruction path is a symlink: ${basename(path)}`);
390
- } catch (error) { if (error.code !== "ENOENT") throw error; }
391
- }
392
- }
393
- function memoryMatches(entry, scope) {
394
- return entry.status === "active" && entry.userId === scope.userId && entry.tenantId === scope.tenantId
395
- && (entry.projectId === null || entry.projectId === scope.projectId)
396
- && (entry.groupId === null || entry.groupId === scope.groupId)
397
- && (entry.taskId === null || entry.taskId === scope.taskId);
398
- }
399
- function memoryProofs(entries) {
400
- return entries.map((entry) => ({ id: entry.id, version: entry.version, checksum: entry.checksum }))
401
- .sort((left, right) => left.id.localeCompare(right.id));
402
- }
403
- function retrievalQuery(scope, promptDigest, providerId) {
404
- const body = { schema: RETRIEVAL_QUERY_SCHEMA, providerId, agentId: scope.agentId, personaId: scope.personaId,
405
- userId: scope.userId, tenantId: scope.tenantId, host: scope.host, profileId: scope.profileId,
406
- sessionId: scope.sessionId, projectId: scope.projectId, groupId: scope.groupId, taskId: scope.taskId,
407
- cwdDigest: sha256(scope.cwd), promptDigest, requested: "current-effective-truth" };
408
- return { ...body, queryDigest: digestObject(body) };
409
- }
410
- function normalizeResult(value, providerId, query) {
411
- if (!value || value.schema !== RETRIEVAL_RESULT_SCHEMA || value.providerId !== providerId
412
- || value.queryDigest !== query.queryDigest || value.status !== "ok" || !Array.isArray(value.items)
413
- || value.items.length > 128) throw new Error(`retrieval provider ${providerId} returned an invalid or mismatched result`);
414
- const items = value.items.map((item) => {
415
- const itemScope = item?.scope;
416
- const scopeKeys = ["agentId", "personaId", "userId", "tenantId", "profileId", "sessionId", "projectId", "groupId", "taskId"];
417
- const exactScope = itemScope && typeof itemScope === "object" && !Array.isArray(itemScope)
418
- && Object.keys(itemScope).every((key) => scopeKeys.includes(key))
419
- && ["agentId", "userId", "tenantId"].every((key) => itemScope[key] === query[key])
420
- && scopeKeys.every((key) => itemScope[key] === undefined || itemScope[key] === null || itemScope[key] === query[key]);
421
- if (!item || !ID_RE.test(item.id || "") || !ID_RE.test(String(item.revision || ""))
422
- || typeof item.claim !== "string" || !item.claim.trim() || Buffer.byteLength(item.claim) > 4096
423
- || FORBIDDEN_MEMORY.test(item.claim) || !["current", "effective"].includes(item.validity)
424
- || !Number.isFinite(Number(item.confidence)) || Number(item.confidence) < 0 || Number(item.confidence) > 1
425
- || typeof item.source !== "string" || !ID_RE.test(item.source) || typeof item.whyLoaded !== "string"
426
- || !item.whyLoaded.trim() || Buffer.byteLength(item.whyLoaded) > 512 || FORBIDDEN_MEMORY.test(item.whyLoaded)
427
- || !exactScope) throw new Error(`retrieval provider ${providerId} returned an unsafe item`);
428
- return { id: item.id, revision: String(item.revision), claim: item.claim.trim(), source: item.source,
429
- scope: itemScope, validity: item.validity, confidence: Number(item.confidence), whyLoaded: item.whyLoaded.trim(), authority: "context-only" };
430
- });
431
- return { items, rejected: Number.isInteger(value.rejected) && value.rejected >= 0 ? value.rejected : 0 };
432
- }
433
- function providerInputError(provider, error) {
434
- const wrapped = new Error(`retrieval adapter ${provider.id} input failed (${error.code || "stream-error"})`);
435
- wrapped.code = error.code;
436
- return wrapped;
437
- }
438
- function commandProviderAttempt(provider, query, env, executable) {
439
- return new Promise((resolvePromise, rejectPromise) => {
440
- const childEnv = { PATH: env.PATH || "" };
441
- for (const name of provider.credentialEnv) {
442
- if (typeof env[name] !== "string" || !env[name]) return rejectPromise(new Error(`retrieval adapter credential is missing: ${name}`));
443
- childEnv[name] = env[name];
444
- }
445
- const child = spawn(executable, provider.args, { stdio: ["pipe", "pipe", "pipe"], env: childEnv, shell: false });
446
- let stdout = ""; let stderrBytes = 0; let bytes = 0; let settled = false;
447
- const finish = (error, value) => { if (settled) return; settled = true; clearTimeout(timer); error ? rejectPromise(error) : resolvePromise(value); };
448
- const timer = setTimeout(() => { child.kill("SIGKILL"); finish(new Error(`retrieval adapter ${provider.id} timed out`)); }, provider.timeoutMs);
449
- child.stdout.on("data", (chunk) => { bytes += chunk.length; if (bytes > MAX_PROVIDER_BYTES) { child.kill("SIGKILL"); finish(new Error("retrieval response exceeds 1 MiB")); } else stdout += chunk; });
450
- child.stderr.on("data", (chunk) => { stderrBytes = Math.min(2048, stderrBytes + chunk.length); });
451
- child.once("error", (error) => finish(error));
452
- child.stdin.once("error", (error) => {
453
- if (settled) return;
454
- child.kill("SIGKILL");
455
- finish(providerInputError(provider, error));
456
- });
457
- child.once("close", (code) => {
458
- if (settled) return;
459
- if (code !== 0) return finish(new Error(`retrieval adapter ${provider.id} failed (${code}; stderr-bytes<=${stderrBytes})`));
460
- try { finish(null, JSON.parse(stdout)); } catch { finish(new Error(`retrieval adapter ${provider.id} returned invalid JSON`)); }
461
- });
462
- try { child.stdin.end(JSON.stringify(query)); }
463
- catch (error) { child.kill("SIGKILL"); finish(providerInputError(provider, error)); }
464
- });
465
- }
466
- async function commandProvider(provider, query, env, runner = null) {
467
- if (runner) return runner(provider, query);
468
- const executable = await realpath(provider.command);
469
- const metadata = await lstat(executable);
470
- if (!metadata.isFile() || metadata.isSymbolicLink()) throw new Error(`retrieval adapter ${provider.id} is not a regular executable`);
471
- try { return await commandProviderAttempt(provider, query, env, executable); }
472
- catch (error) {
473
- if (error.code !== "EPIPE") throw error;
474
- return commandProviderAttempt(provider, query, env, executable);
475
- }
476
- }
477
-
478
- export async function runPreflight({ input, scope, resolvedSources, prompt, now = new Date(), env = process.env,
479
- providerRunner = null, fileHooks = null }) {
480
- if (typeof prompt !== "string" || !prompt.length || Buffer.byteLength(prompt) > 64 * 1024) throw new Error("preflight requires one bounded prompt");
481
- const exactScope = scopeFromInput({ input, scope, resolvedSources, env });
482
- const promptDigest = sha256(prompt);
483
- const deliveryId = preflightDeliveryId(input, { issue: true });
484
- if (!deliveryId) throw new Error("preflight hook invocation identity is unavailable");
485
- const paths = storagePaths(env);
486
- const policy = validatePolicy(await readJson(paths.policy, MAX_POLICY_BYTES, emptyPolicy));
487
- const profile = policy.profiles.find((item) => item.enabled && item.agentId === exactScope.agentId && item.host === exactScope.host
488
- && item.profileId === exactScope.profileId && item.tenantId === exactScope.tenantId) || null;
489
- const instructionHost = resolvedSources.host;
490
- await rejectKnownInstructionSymlinks(resolvedSources, instructionHost);
491
- const documents = instructionDocuments(resolvedSources.catalog, instructionHost);
492
- const requiredInstructions = [];
493
- let instructionBytes = 0;
494
- const maximumInstructionBytes = instructionBudget(instructionHost, 0, env).hardLimitBytes;
495
- for (const document of documents) {
496
- const allowedRoot = document.sourceScope === "user" ? resolvedSources.hostHome : resolvedSources.projectRoot;
497
- const snapshot = await safeReadRequired(document.path, allowedRoot, maximumInstructionBytes, fileHooks);
498
- if (snapshot.sha256 !== document.sha256 || snapshot.bytes !== document.bytes) throw new Error(`required instruction changed after source resolution: ${document.relativePath}`);
499
- instructionBytes += snapshot.bytes;
500
- if (instructionBytes > maximumInstructionBytes) {
501
- throw new Error(`required host instructions total ${instructionBytes} bytes; mandatory limit is ${maximumInstructionBytes} bytes`);
502
- }
503
- requiredInstructions.push({ path: document.path, displayPath: document.relativePath, scope: document.sourceScope,
504
- bytes: snapshot.bytes, sha256: snapshot.sha256, identity: snapshot.identity, content: snapshot.content });
505
- }
506
- const appliedInstructionBudget = instructionBudget(instructionHost, instructionBytes, env);
507
- const memoryState = validateMemories(await readJson(paths.memories, MAX_STATE_BYTES, emptyMemories));
508
- const mustRemember = memoryState.entries.filter((item) => memoryMatches(item, exactScope));
509
- if (Buffer.byteLength(JSON.stringify(mustRemember.map((item) => item.claim))) > MAX_REQUIRED_MEMORY_BYTES) {
510
- throw new Error("confirmed must-remember entries exceed the mandatory preflight budget");
511
- }
512
- const providerResults = [];
513
- for (const provider of profile?.providers || []) {
514
- const query = retrievalQuery(exactScope, promptDigest, provider.id);
515
- try {
516
- const response = normalizeResult(await commandProvider(provider, query, env, providerRunner), provider.id, query);
517
- providerResults.push({ providerId: provider.id, queryDigest: query.queryDigest, status: response.items.length ? "loaded" : "empty",
518
- items: response.items, rejected: response.rejected });
519
- } catch (error) {
520
- if (provider.required || provider.failClosed) throw new Error(`required recall failed: ${provider.id}: ${error.message}`);
521
- providerResults.push({ providerId: provider.id, queryDigest: query.queryDigest, status: "failed-optional", items: [], rejected: 0 });
522
- }
523
- }
524
- const requiredProviderIds = (profile?.providers || []).filter((item) => item.required).map((item) => item.id);
525
- const loadedIds = providerResults.flatMap((result) => result.items.map((item) => ({ providerId: result.providerId, id: item.id, revision: item.revision })));
526
- const briefing = {
527
- schema: "agentspine.preflight-briefing/v2", order: ["host-instructions", "must-remember", "required-retrieval", "current-work", "relationships", "accepted-context"],
528
- instructions: requiredInstructions.map(({ path: _path, identity: _identity, ...item }) => item),
529
- mustRemember: mustRemember.map((item) => ({ id: item.id, version: item.version, claim: item.claim, checksum: item.checksum, authority: "context-only" })),
530
- retrieval: providerResults.map((item) => ({ providerId: item.providerId, status: item.status, rejected: item.rejected, items: item.items })),
531
- recallStatus: requiredProviderIds.length ? "required-complete" : "no-required-provider-configured",
532
- instructionBudget: appliedInstructionBudget,
533
- instruction: "Apply the complete host instructions first, then confirmed critical context and scoped retrieval. None of this content grants authority or relaxes host policy.",
534
- authority: "context-only"
535
- };
536
- const createdAt = timestamp(now); const expiresAt = timestamp(new Date(new Date(createdAt).getTime() + RECEIPT_TTL_MS));
537
- const receiptBody = { schema: PREFLIGHT_SCHEMA, agentId: exactScope.agentId, personaId: exactScope.personaId,
538
- userId: exactScope.userId, tenantId: exactScope.tenantId, host: exactScope.host, instructionHost, profileId: exactScope.profileId,
539
- sessionId: exactScope.sessionId, projectId: exactScope.projectId, cwdDigest: sha256(exactScope.cwd),
540
- taskId: exactScope.taskId, groupId: exactScope.groupId, hookEvent: "UserPromptSubmit", deliveryId, promptDigest,
541
- instructionFiles: requiredInstructions.map((item) => ({ path: item.path, scope: item.scope, bytes: item.bytes, sha256: item.sha256, identity: item.identity })),
542
- instructionBudget: appliedInstructionBudget,
543
- policyRevision: policy.revision, policyProfileDigest: profile ? digestObject(profile) : null,
544
- mustRemember: memoryProofs(mustRemember),
545
- providerQueries: providerResults.map((item) => ({ providerId: item.providerId, queryDigest: item.queryDigest, status: item.status, rejected: item.rejected })),
546
- loadedIds, briefingDigest: digestObject(briefing), excludedCandidates: providerResults.reduce((sum, item) => sum + item.rejected, 0),
547
- status: "ready", createdAt, expiresAt, authority: "preflight-proof-only" };
548
- const key = await signingKey(paths); const bodyDigest = digestObject(receiptBody);
549
- const receipt = { id: `preflight:${bodyDigest.slice(0, 32)}`, ...receiptBody, bodyDigest,
550
- signature: createHmac("sha256", key).update(bodyDigest).digest("hex") };
551
- await withLock(paths, async () => {
552
- const state = await readVerifiedState(paths);
553
- state.receipts = state.receipts.filter((item) => new Date(item.receipt?.expiresAt || 0).getTime() >= new Date(createdAt).getTime() - RECEIPT_TTL_MS);
554
- if (state.receipts.some((item) => item.receipt?.deliveryId === receipt.deliveryId && !item.invalidatedAt)) {
555
- throw new Error("preflight delivery replay detected; turn blocked");
556
- }
557
- const envelope = { receipt, consumedAt: null, invalidatedAt: null, stateSignature: "" };
558
- envelope.stateSignature = createHmac("sha256", key).update(envelopeBody(envelope)).digest("hex");
559
- state.receipts.push(envelope); state.revision += 1;
560
- state.lastTurn = { status: "ready", receiptId: receipt.id, at: createdAt, host: exactScope.host,
561
- instructionHost, instructionFiles: receipt.instructionFiles.length, recall: receipt.providerQueries.map((item) => ({
562
- providerId: item.providerId, status: item.status, rejected: item.rejected
563
- })), cwdDigest: receipt.cwdDigest, authority: "diagnostic-only" };
564
- state.history.push({ event: "ready", receiptId: receipt.id, at: createdAt, authority: "preflight-proof-only" });
565
- await writeJson(paths.state, state);
566
- });
567
- return { receipt, briefing, policy: { configured: Boolean(profile), requiredProviderIds } };
568
- }
569
-
570
- export async function verifyPreflightReceipt({ receipt, input, scope, resolvedSources, prompt, now = new Date(), env = process.env, consume = false }) {
571
- const exactScope = scopeFromInput({ input, scope, resolvedSources, env });
572
- const current = new Date(now).getTime();
573
- if (!receipt || receipt.schema !== PREFLIGHT_SCHEMA || receipt.status !== "ready" || !DIGEST_RE.test(receipt.bodyDigest || "")
574
- || !DIGEST_RE.test(receipt.signature || "") || new Date(receipt.expiresAt).getTime() < current
575
- || receipt.promptDigest !== sha256(prompt) || receipt.agentId !== exactScope.agentId || receipt.personaId !== exactScope.personaId
576
- || receipt.userId !== exactScope.userId
577
- || receipt.tenantId !== exactScope.tenantId || receipt.host !== exactScope.host || receipt.profileId !== exactScope.profileId
578
- || receipt.sessionId !== exactScope.sessionId || receipt.projectId !== exactScope.projectId || receipt.cwdDigest !== sha256(exactScope.cwd)
579
- || receipt.taskId !== exactScope.taskId || receipt.groupId !== exactScope.groupId) return false;
580
- const deliveryId = preflightDeliveryId(input);
581
- if (receipt.deliveryId !== deliveryId) return false;
582
- const { id: _id, bodyDigest, signature, ...body } = receipt;
583
- if (digestObject(body) !== bodyDigest) return false;
584
- const key = await signingKey(storagePaths(env));
585
- const expected = createHmac("sha256", key).update(bodyDigest).digest();
586
- const actual = Buffer.from(signature, "hex");
587
- if (!(actual.length === expected.length && timingSafeEqual(actual, expected))) return false;
588
- try {
589
- const paths = storagePaths(env);
590
- const [policy, memories, freshSources, receiptState] = await Promise.all([
591
- readJson(paths.policy, MAX_POLICY_BYTES, emptyPolicy).then(validatePolicy),
592
- readJson(paths.memories, MAX_STATE_BYTES, emptyMemories).then(validateMemories),
593
- resolveHostSourceCatalog({ host: receipt.instructionHost, cwd: exactScope.cwd, input, env }),
594
- readVerifiedState(paths)
595
- ]);
596
- const storedEnvelope = receiptState.receipts.find((item) => item.receipt?.id === receipt.id
597
- && item.receipt?.bodyDigest === receipt.bodyDigest);
598
- if (!storedEnvelope || storedEnvelope.consumedAt !== null || storedEnvelope.invalidatedAt) return false;
599
- const profile = policy.profiles.find((item) => item.enabled && item.agentId === exactScope.agentId && item.host === exactScope.host
600
- && item.profileId === exactScope.profileId && item.tenantId === exactScope.tenantId) || null;
601
- if (receipt.policyRevision !== policy.revision || receipt.policyProfileDigest !== (profile ? digestObject(profile) : null)) return false;
602
- if (canonical(receipt.mustRemember) !== canonical(memoryProofs(memories.entries.filter((item) => memoryMatches(item, exactScope))))) return false;
603
- if (receipt.instructionHost !== freshSources.host) return false;
604
- await rejectKnownInstructionSymlinks(freshSources, freshSources.host);
605
- const currentDocuments = instructionDocuments(freshSources.catalog, freshSources.host);
606
- if (currentDocuments.length !== receipt.instructionFiles.length
607
- || currentDocuments.some((document, index) => document.path !== receipt.instructionFiles[index]?.path)) return false;
608
- let instructionBytes = 0;
609
- const maximumInstructionBytes = instructionBudget(receipt.instructionHost, 0, env).hardLimitBytes;
610
- for (const instruction of receipt.instructionFiles) {
611
- const allowedRoot = instruction.scope === "user" ? freshSources.hostHome : freshSources.projectRoot;
612
- const currentSnapshot = await safeReadRequired(instruction.path, allowedRoot, maximumInstructionBytes);
613
- if (currentSnapshot.sha256 !== instruction.sha256 || currentSnapshot.bytes !== instruction.bytes
614
- || currentSnapshot.identity !== instruction.identity) return false;
615
- instructionBytes += currentSnapshot.bytes;
616
- }
617
- if (instructionBytes > maximumInstructionBytes
618
- || canonical(receipt.instructionBudget) !== canonical(instructionBudget(receipt.instructionHost, instructionBytes, env))) return false;
619
- } catch { return false; }
620
- if (consume) {
621
- const paths = storagePaths(env);
622
- const consumed = await withLock(paths, async () => {
623
- const state = await readVerifiedState(paths);
624
- const stored = state.receipts.find((item) => item.receipt?.id === receipt.id && item.receipt?.bodyDigest === receipt.bodyDigest);
625
- if (!stored || stored.consumedAt !== null || stored.invalidatedAt) return false;
626
- stored.consumedAt = timestamp(now); state.revision += 1;
627
- stored.stateSignature = createHmac("sha256", key).update(envelopeBody(stored)).digest("hex");
628
- state.lastTurn = { ...(state.lastTurn || {}), status: "consumed", receiptId: receipt.id,
629
- at: stored.consumedAt, authority: "diagnostic-only" };
630
- state.history.push({ event: "consumed", receiptId: receipt.id, at: stored.consumedAt, authority: "preflight-proof-only" });
631
- await writeJson(paths.state, state);
632
- return true;
633
- });
634
- if (!consumed) return false;
635
- }
636
- return true;
637
- }
638
-
639
- function failureCode(error) {
640
- const message = String(error?.message || error || "");
641
- if (/source resolution|required instruction|host instruction/i.test(message)) return "instructions-failed";
642
- if (/required recall|retrieval provider|adapter/i.test(message)) return "provider-failed";
643
- if (/budget|injection limit|too large|cannot fit/i.test(message)) return "budget-failed";
644
- if (/receipt|replay|delivery/i.test(message)) return "receipt-failed";
645
- return "preflight-failed";
646
- }
647
-
648
- export async function recordPreflightFailure({ receiptId = null, input = {}, host = null, error,
649
- now = new Date(), env = process.env }) {
650
- const paths = storagePaths(env);
651
- return withLock(paths, async () => {
652
- const state = await readVerifiedState(paths);
653
- const at = timestamp(now);
654
- if (receiptId) {
655
- const stored = state.receipts.find((item) => item.receipt?.id === receiptId
656
- && item.consumedAt === null && !item.invalidatedAt);
657
- if (stored) {
658
- stored.invalidatedAt = at;
659
- const key = await signingKey(paths);
660
- stored.stateSignature = createHmac("sha256", key).update(envelopeBody(stored)).digest("hex");
661
- }
662
- }
663
- const code = failureCode(error);
664
- state.lastTurn = { status: "blocked", code, receiptId, at, host: host || null,
665
- deliveryDigest: sha256(String(input.event_id ?? input.hook_event_id ?? "missing")), authority: "diagnostic-only" };
666
- state.revision += 1;
667
- state.history.push({ event: "blocked", code, receiptId, at, authority: "preflight-proof-only" });
668
- await writeJson(paths.state, state);
669
- return state.lastTurn;
670
- });
671
- }
672
-
673
- export async function preflightStatus(env = process.env) {
674
- const paths = storagePaths(env);
675
- const [policy, memories, state] = await Promise.all([
676
- readJson(paths.policy, MAX_POLICY_BYTES, emptyPolicy).then(validatePolicy),
677
- readJson(paths.memories, MAX_STATE_BYTES, emptyMemories).then(validateMemories),
678
- readVerifiedState(paths)
679
- ]);
680
- return { schema: PREFLIGHT_SCHEMA, policies: policy.profiles.length, requiredProviders: policy.profiles.flatMap((item) => item.providers).filter((item) => item.required).length,
681
- pendingMemories: memories.candidates.filter((item) => item.status === "pending-confirmation").length,
682
- activeMustRemember: memories.entries.filter((item) => item.status === "active").length,
683
- readyReceipts: state.receipts.filter((item) => item.consumedAt === null && !item.invalidatedAt && item.receipt?.status === "ready"
684
- && new Date(item.receipt.expiresAt).getTime() >= Date.now()).length,
685
- status: policy.profiles.some((item) => item.providers.some((provider) => provider.required)) ? "wrapper-hard-required" : "instructions-only-no-required-provider",
686
- lastTurn: state.lastTurn,
687
- authority: "diagnostic-only" };
688
- }