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,515 +0,0 @@
1
- import {
2
- createHash, createPrivateKey, createPublicKey, generateKeyPairSync, randomUUID,
3
- sign as cryptoSign, verify as cryptoVerify
4
- } from "node:crypto";
5
- import {
6
- chmod, lstat, mkdir, open, readFile, stat, unlink, writeFile
7
- } from "node:fs/promises";
8
- import { dirname, join, resolve } from "node:path";
9
- import { buildCatalog } from "./catalog.js";
10
- import { isFileLockContention, replaceFileWithRetry } from "./filesystem-retry.js";
11
- import { projectId, projectStateDir, statePathIsScanExcluded, stateRoot } from "./paths.js";
12
-
13
- const AUTH_CONFIRMATION = "local-share-confirmed";
14
- const ID_RE = /^[A-Za-z0-9][A-Za-z0-9:_.@/-]{0,127}$/;
15
- const DIGEST_RE = /^[a-f0-9]{64}$/;
16
- const SIGNATURE_RE = /^[A-Za-z0-9+/]{80,96}={0,2}$/;
17
- const MAX_AUTH_BYTES = 2 * 1024 * 1024;
18
- const MAX_PUBLIC_IDENTITY_BYTES = 16 * 1024;
19
- const SECRET_RE = /-----BEGIN [A-Z ]*PRIVATE KEY-----|\b(?:sk|gh[opusu])_[A-Za-z0-9_-]{20,}\b|\bBearer\s+[A-Za-z0-9._~+/-]{20,}|\b(?:api[-_ ]?key|token|password|secret)\s*[:=]\s*\S{8,}/i;
20
-
21
- function canonical(value) {
22
- if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`;
23
- if (value && typeof value === "object") {
24
- return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${canonical(value[key])}`).join(",")}}`;
25
- }
26
- return JSON.stringify(value);
27
- }
28
-
29
- function digest(value) {
30
- return createHash("sha256").update(canonical(value)).digest("hex");
31
- }
32
-
33
- function exactKeys(value, expected) {
34
- if (!value || typeof value !== "object" || Array.isArray(value)) return false;
35
- const actual = Object.keys(value).sort();
36
- const wanted = [...expected].sort();
37
- return actual.length === wanted.length && actual.every((key, index) => key === wanted[index]);
38
- }
39
-
40
- function validDate(value) {
41
- return typeof value === "string" && value.length > 0 && Number.isFinite(new Date(value).getTime());
42
- }
43
-
44
- function isoDate(value, field = "date") {
45
- const parsed = value instanceof Date ? value : new Date(value);
46
- if (!Number.isFinite(parsed.getTime())) throw new Error(`${field} must be a valid date`);
47
- return parsed.toISOString();
48
- }
49
-
50
- function requireConfirmation(confirmation) {
51
- if (confirmation !== AUTH_CONFIRMATION) throw new Error("signer and trust changes require explicit local owner confirmation");
52
- }
53
-
54
- function emptyRegistry() {
55
- return { schema: "agentspine.signers/v1", signers: [], history: [] };
56
- }
57
-
58
- function emptyTrust(root) {
59
- return { schema: "agentspine.sharing-trust/v1", root, records: [], history: [] };
60
- }
61
-
62
- function publicIdentityBody({ signerId, publicKey, createdAt }) {
63
- const keyBytes = Buffer.from(publicKey, "base64");
64
- return {
65
- schema: "agentspine.signer/v1",
66
- signerId,
67
- keyId: `ed25519:${createHash("sha256").update(keyBytes).digest("hex")}`,
68
- algorithm: "Ed25519",
69
- publicKey,
70
- createdAt,
71
- authority: "context-only"
72
- };
73
- }
74
-
75
- export function validatePublicIdentity(identity) {
76
- if (!identity || typeof identity !== "object" || Array.isArray(identity)
77
- || !exactKeys(identity, ["schema", "signerId", "keyId", "algorithm", "publicKey", "createdAt", "authority", "digest"])
78
- || identity.schema !== "agentspine.signer/v1" || !ID_RE.test(identity.signerId || "")
79
- || !ID_RE.test(identity.keyId || "") || identity.algorithm !== "Ed25519"
80
- || typeof identity.publicKey !== "string" || identity.publicKey.length > 1024
81
- || !validDate(identity.createdAt) || identity.authority !== "context-only"
82
- || !DIGEST_RE.test(identity.digest || "")) {
83
- throw new Error("public signing identity is invalid");
84
- }
85
- let key;
86
- try {
87
- key = createPublicKey({ key: Buffer.from(identity.publicKey, "base64"), format: "der", type: "spki" });
88
- } catch {
89
- throw new Error("public signing identity contains an invalid Ed25519 key");
90
- }
91
- if (key.asymmetricKeyType !== "ed25519") throw new Error("public signing identity must use Ed25519");
92
- const body = { ...identity };
93
- delete body.digest;
94
- const expected = publicIdentityBody({ signerId: identity.signerId, publicKey: identity.publicKey, createdAt: identity.createdAt });
95
- if (identity.keyId !== expected.keyId || identity.digest !== digest(body)) {
96
- throw new Error("public signing identity failed its fingerprint or integrity check");
97
- }
98
- return identity;
99
- }
100
-
101
- function registryFindings(registry) {
102
- const findings = [];
103
- if (!exactKeys(registry, ["schema", "signers", "history"])
104
- || registry.schema !== "agentspine.signers/v1" || !Array.isArray(registry.signers)
105
- || !Array.isArray(registry.history)) return ["invalid-signer-registry"];
106
- const ids = new Set();
107
- const keys = new Set();
108
- for (const record of registry.signers) {
109
- try { validatePublicIdentity(record.publicIdentity); } catch { findings.push(`invalid-signer:${record?.signerId || "unknown"}`); }
110
- if (!exactKeys(record, ["signerId", "keyId", "publicIdentity", "createdAt", "authority"])
111
- || record.signerId !== record.publicIdentity?.signerId || record.keyId !== record.publicIdentity?.keyId
112
- || record.createdAt !== record.publicIdentity?.createdAt || record.authority !== "context-only") {
113
- findings.push(`invalid-signer-record:${record?.signerId || "unknown"}`);
114
- }
115
- if (ids.has(record.signerId)) findings.push(`duplicate-signer:${record.signerId}`);
116
- if (keys.has(record.keyId)) findings.push(`duplicate-signer-key:${record.keyId}`);
117
- ids.add(record.signerId); keys.add(record.keyId);
118
- }
119
- for (const entry of registry.history) {
120
- if (!exactKeys(entry, ["kind", "signerId", "keyId", "replacedAt", "value", "authority"])
121
- || entry.kind !== "signer-rotation" || entry.signerId !== entry.value?.signerId
122
- || entry.keyId !== entry.value?.keyId || !validDate(entry.replacedAt)
123
- || entry.authority !== "context-only") findings.push(`invalid-signer-history:${entry?.signerId || "unknown"}`);
124
- try { validatePublicIdentity(entry.value); } catch { findings.push(`invalid-retired-signer:${entry?.signerId || "unknown"}`); }
125
- }
126
- return [...new Set(findings)];
127
- }
128
-
129
- export function trustFindings(trust) {
130
- const findings = [];
131
- if (!exactKeys(trust, ["schema", "root", "records", "history"])
132
- || trust.schema !== "agentspine.sharing-trust/v1" || typeof trust.root !== "string"
133
- || !Array.isArray(trust.records) || !Array.isArray(trust.history)) return ["invalid-sharing-trust"];
134
- const keys = new Set();
135
- for (const record of trust.records) {
136
- try { validatePublicIdentity(record.publicIdentity); } catch { findings.push(`invalid-trusted-signer:${record?.keyId || "unknown"}`); }
137
- if (!validTrustRecord(record)) findings.push(`invalid-trust-record:${record?.keyId || "unknown"}`);
138
- if (keys.has(record.keyId)) findings.push(`duplicate-trusted-key:${record.keyId}`);
139
- keys.add(record.keyId);
140
- }
141
- for (const entry of trust.history) {
142
- if (!exactKeys(entry, ["kind", "keyId", "changedAt", "value", "authority"])
143
- || entry.kind !== "trust-record" || entry.keyId !== entry.value?.keyId
144
- || !validDate(entry.changedAt) || entry.authority !== "context-only") {
145
- findings.push(`invalid-trust-history:${entry?.keyId || "unknown"}`);
146
- }
147
- if (!validTrustRecord(entry.value)) findings.push(`invalid-historical-trust:${entry?.keyId || "unknown"}`);
148
- try { validatePublicIdentity(entry.value?.publicIdentity); } catch { findings.push(`invalid-historical-trusted-signer:${entry?.keyId || "unknown"}`); }
149
- }
150
- return [...new Set(findings)];
151
- }
152
-
153
- function validTrustRecord(record) {
154
- if (!exactKeys(record, ["signerId", "keyId", "publicIdentity", "status", "addedAt", "revokedAt", "reason", "confirmation", "authority"])
155
- || record.signerId !== record.publicIdentity?.signerId || record.keyId !== record.publicIdentity?.keyId
156
- || !new Set(["trusted", "revoked"]).has(record.status) || !validDate(record.addedAt)
157
- || record.confirmation !== "local-owner" || record.authority !== "context-only") return false;
158
- if (record.status === "trusted") return record.revokedAt === null && record.reason === null;
159
- return validDate(record.revokedAt) && typeof record.reason === "string" && Boolean(record.reason.trim());
160
- }
161
-
162
- async function authPaths(root, providedCatalog = null, { allowInside = false, create = true } = {}) {
163
- const catalog = providedCatalog || await buildCatalog(root);
164
- const globalRoot = resolve(stateRoot());
165
- const signerDirectory = join(globalRoot, "signers");
166
- if (!allowInside && !statePathIsScanExcluded(catalog, signerDirectory)) {
167
- throw new Error("signing identity state must remain outside the scanned project or in an excluded home-state root");
168
- }
169
- if (create) await mkdir(join(signerDirectory, "private"), { recursive: true, mode: 0o700 });
170
- const projectDirectory = create
171
- ? await projectStateDir(catalog.root)
172
- : join(globalRoot, "projects", projectId(catalog.root));
173
- return {
174
- catalog,
175
- signerDirectory,
176
- registryPath: join(signerDirectory, "registry.json"),
177
- trustPath: join(projectDirectory, "sharing-trust.json")
178
- };
179
- }
180
-
181
- async function readBoundedJson(path, fallback, normalize) {
182
- try {
183
- const metadata = await stat(path);
184
- if (metadata.size > MAX_AUTH_BYTES) throw new Error("authentication state exceeds the 2 MiB read limit");
185
- const value = JSON.parse(await readFile(path, "utf8"));
186
- return normalize(value);
187
- } catch (error) {
188
- if (error.code !== "ENOENT") throw error;
189
- return fallback();
190
- }
191
- }
192
-
193
- async function atomicWrite(path, value, mode = 0o600) {
194
- const content = `${JSON.stringify(value, null, 2)}\n`;
195
- if (Buffer.byteLength(content) > MAX_AUTH_BYTES) throw new Error("authentication state exceeds 2 MiB");
196
- const temporary = `${path}.${process.pid}.${randomUUID()}.tmp`;
197
- await writeFile(temporary, content, { mode });
198
- await replaceFileWithRetry(temporary, path);
199
- }
200
-
201
- async function acquireLock(path) {
202
- const lockPath = `${path}.lock`;
203
- for (let attempt = 0; attempt < 80; attempt += 1) {
204
- try {
205
- return { handle: await open(lockPath, "wx", 0o600), lockPath };
206
- } catch (error) {
207
- if (!isFileLockContention(error)) throw error;
208
- try {
209
- const metadata = await stat(lockPath);
210
- if (Date.now() - metadata.mtimeMs > 15000) await unlink(lockPath);
211
- } catch (lockError) {
212
- if (lockError.code !== "ENOENT") throw lockError;
213
- }
214
- await new Promise((resolvePromise) => setTimeout(resolvePromise, 25));
215
- }
216
- }
217
- throw new Error("authentication state is busy; retry shortly");
218
- }
219
-
220
- async function mutate(path, read, findings, operation) {
221
- const { handle, lockPath } = await acquireLock(path);
222
- try {
223
- const state = await read();
224
- const before = findings(state);
225
- if (before.length) throw new Error(`authentication state failed closed: ${before.join(", ")}`);
226
- const result = await operation(state);
227
- const after = findings(state);
228
- if (after.length) throw new Error(`authentication mutation failed closed: ${after.join(", ")}`);
229
- await atomicWrite(path, state);
230
- return result;
231
- } finally {
232
- await handle.close();
233
- await unlink(lockPath).catch((error) => { if (error.code !== "ENOENT") throw error; });
234
- }
235
- }
236
-
237
- function normalizeRegistry(value) {
238
- const findings = registryFindings(value);
239
- if (findings.length) throw new Error(`signer registry is invalid: ${findings.join(", ")}`);
240
- return value;
241
- }
242
-
243
- function normalizeTrust(value, root) {
244
- if (value?.root !== root) throw new Error("sharing trust state belongs to another project");
245
- const findings = trustFindings(value);
246
- if (findings.length) throw new Error(`sharing trust state is invalid: ${findings.join(", ")}`);
247
- return value;
248
- }
249
-
250
- function privatePath(directory, keyId) {
251
- return join(directory, "private", `${createHash("sha256").update(keyId).digest("hex")}.pem`);
252
- }
253
-
254
- export async function generateSigningIdentity({
255
- root = process.cwd(), signerId, rotate = false, publicOut = null,
256
- confirmation, now = new Date()
257
- }) {
258
- requireConfirmation(confirmation);
259
- if (!ID_RE.test(signerId || "")) throw new Error("signerId must be a stable, whitespace-free identifier");
260
- const publicTarget = publicOut ? resolve(publicOut) : null;
261
- if (publicTarget) {
262
- try {
263
- await lstat(publicTarget);
264
- throw new Error(`public identity output already exists: ${publicTarget}`);
265
- } catch (error) {
266
- if (error.code !== "ENOENT") throw error;
267
- }
268
- }
269
- const paths = await authPaths(root);
270
- const createdAt = isoDate(now, "now");
271
- const result = await mutate(
272
- paths.registryPath,
273
- () => readBoundedJson(paths.registryPath, emptyRegistry, normalizeRegistry),
274
- registryFindings,
275
- async (registry) => {
276
- const existing = registry.signers.find((record) => record.signerId === signerId);
277
- if (existing && !rotate) throw new Error(`signer already exists: ${signerId}; use explicit rotation`);
278
- const { publicKey, privateKey } = generateKeyPairSync("ed25519", {
279
- publicKeyEncoding: { format: "der", type: "spki" },
280
- privateKeyEncoding: { format: "pem", type: "pkcs8" }
281
- });
282
- const body = publicIdentityBody({ signerId, publicKey: publicKey.toString("base64"), createdAt });
283
- const publicIdentity = { ...body, digest: digest(body) };
284
- validatePublicIdentity(publicIdentity);
285
- const path = privatePath(paths.signerDirectory, publicIdentity.keyId);
286
- await writeFile(path, privateKey, { flag: "wx", mode: 0o600 });
287
- await chmod(path, 0o600);
288
- if (existing) {
289
- registry.history.push({
290
- kind: "signer-rotation", signerId, keyId: existing.keyId, replacedAt: createdAt,
291
- value: existing.publicIdentity, authority: "context-only"
292
- });
293
- }
294
- const record = { signerId, keyId: publicIdentity.keyId, publicIdentity, createdAt, authority: "context-only" };
295
- registry.signers = [...registry.signers.filter((item) => item.signerId !== signerId), record]
296
- .sort((a, b) => a.signerId.localeCompare(b.signerId));
297
- return { signerId, keyId: record.keyId, publicIdentity, retiredKeyId: existing?.keyId || null };
298
- }
299
- );
300
- if (result.retiredKeyId) await unlink(privatePath(paths.signerDirectory, result.retiredKeyId)).catch((error) => {
301
- if (error.code !== "ENOENT") throw error;
302
- });
303
- if (publicOut) {
304
- await mkdir(dirname(publicTarget), { recursive: true, mode: 0o700 });
305
- await writeFile(publicTarget, `${JSON.stringify(result.publicIdentity, null, 2)}\n`, { flag: "wx", mode: 0o644 });
306
- }
307
- return { ...result, publicOut: publicTarget, authority: "context-only" };
308
- }
309
-
310
- export async function listSigningIdentities({ root = process.cwd() } = {}) {
311
- const paths = await authPaths(root);
312
- const registry = await readBoundedJson(paths.registryPath, emptyRegistry, normalizeRegistry);
313
- return {
314
- schema: registry.schema,
315
- signers: registry.signers.map((record) => record.publicIdentity),
316
- retired: registry.history.map((entry) => entry.value),
317
- authority: "context-only"
318
- };
319
- }
320
-
321
- export async function inspectSignerRegistry(root = process.cwd(), providedCatalog = null) {
322
- const paths = await authPaths(root, providedCatalog, { allowInside: true, create: false });
323
- try {
324
- const registry = await readBoundedJson(paths.registryPath, emptyRegistry, normalizeRegistry);
325
- const errors = [];
326
- for (const record of registry.signers) {
327
- const path = privatePath(paths.signerDirectory, record.keyId);
328
- try {
329
- const metadata = await lstat(path);
330
- if (!metadata.isFile() || metadata.isSymbolicLink() || metadata.size > MAX_PUBLIC_IDENTITY_BYTES) {
331
- errors.push(`invalid-private-key-file:${record.signerId}`);
332
- continue;
333
- }
334
- if (process.platform !== "win32" && (metadata.mode & 0o077) !== 0) errors.push(`unsafe-private-key-mode:${record.signerId}`);
335
- const privateKey = createPrivateKey(await readFile(path, "utf8"));
336
- const publicKey = createPublicKey(privateKey).export({ format: "der", type: "spki" }).toString("base64");
337
- if (privateKey.asymmetricKeyType !== "ed25519" || publicKey !== record.publicIdentity.publicKey) {
338
- errors.push(`private-public-key-mismatch:${record.signerId}`);
339
- }
340
- } catch (error) {
341
- errors.push(`unreadable-private-key:${record.signerId}:${error.code || "invalid"}`);
342
- }
343
- }
344
- return { registry, registryPath: paths.registryPath, signerDirectory: paths.signerDirectory, errors, catalog: paths.catalog };
345
- } catch (error) {
346
- return {
347
- registry: emptyRegistry(), registryPath: paths.registryPath, signerDirectory: paths.signerDirectory,
348
- errors: [`unreadable-registry:${error.message}`], catalog: paths.catalog
349
- };
350
- }
351
- }
352
-
353
- async function activeIdentity(root, signerId) {
354
- const paths = await authPaths(root);
355
- const registry = await readBoundedJson(paths.registryPath, emptyRegistry, normalizeRegistry);
356
- const record = registry.signers.find((item) => item.signerId === signerId);
357
- if (!record) throw new Error(`unknown local signer: ${signerId}`);
358
- const path = privatePath(paths.signerDirectory, record.keyId);
359
- const metadata = await lstat(path);
360
- if (!metadata.isFile() || metadata.isSymbolicLink()) throw new Error("signing private key must be a regular file");
361
- if (process.platform !== "win32" && (metadata.mode & 0o077) !== 0) throw new Error("signing private key permissions are too broad");
362
- const privateKey = createPrivateKey(await readFile(path, "utf8"));
363
- if (privateKey.asymmetricKeyType !== "ed25519") throw new Error("signing private key is not Ed25519");
364
- return { publicIdentity: record.publicIdentity, privateKey };
365
- }
366
-
367
- export async function signEnvelope({ root = process.cwd(), signerId, kind, payload, now = new Date() }) {
368
- if (!new Set(["manifest", "event"]).has(kind)) throw new Error("signed envelope kind must be manifest or event");
369
- const identity = await activeIdentity(root, signerId);
370
- const body = {
371
- schema: "agentspine.signed-envelope/v1",
372
- kind,
373
- signer: identity.publicIdentity,
374
- payload,
375
- signedAt: isoDate(now, "now"),
376
- authority: "context-only"
377
- };
378
- const signature = cryptoSign(null, Buffer.from(canonical(body)), identity.privateKey).toString("base64");
379
- return { ...body, signature };
380
- }
381
-
382
- export function verifyEnvelope(envelope, expectedKind = null) {
383
- if (!envelope || typeof envelope !== "object" || Array.isArray(envelope)
384
- || !exactKeys(envelope, ["schema", "kind", "signer", "payload", "signedAt", "authority", "signature"])
385
- || envelope.schema !== "agentspine.signed-envelope/v1"
386
- || !new Set(["manifest", "event"]).has(envelope.kind)
387
- || (expectedKind !== null && envelope.kind !== expectedKind)
388
- || !validDate(envelope.signedAt) || envelope.authority !== "context-only"
389
- || !SIGNATURE_RE.test(envelope.signature || "")) {
390
- throw new Error("signed envelope structure is invalid");
391
- }
392
- validatePublicIdentity(envelope.signer);
393
- const body = { ...envelope };
394
- delete body.signature;
395
- const key = createPublicKey({ key: Buffer.from(envelope.signer.publicKey, "base64"), format: "der", type: "spki" });
396
- if (!cryptoVerify(null, Buffer.from(canonical(body)), key, Buffer.from(envelope.signature, "base64"))) {
397
- throw new Error("signed envelope signature is invalid");
398
- }
399
- return {
400
- payload: envelope.payload,
401
- authentication: {
402
- mode: "signed",
403
- signerId: envelope.signer.signerId,
404
- keyId: envelope.signer.keyId,
405
- signedAt: envelope.signedAt,
406
- verifiedAt: null,
407
- signature: envelope.signature,
408
- authority: "context-only"
409
- },
410
- publicIdentity: envelope.signer
411
- };
412
- }
413
-
414
- export async function loadTrust(root = process.cwd(), providedCatalog = null) {
415
- const paths = await authPaths(root, providedCatalog);
416
- const trust = await readBoundedJson(
417
- paths.trustPath,
418
- () => emptyTrust(paths.catalog.root),
419
- (value) => normalizeTrust(value, paths.catalog.root)
420
- );
421
- return { trust, trustPath: paths.trustPath, catalog: paths.catalog };
422
- }
423
-
424
- export async function inspectTrust(root = process.cwd(), providedCatalog = null) {
425
- const paths = await authPaths(root, providedCatalog, { allowInside: true, create: false });
426
- try {
427
- const trust = await readBoundedJson(
428
- paths.trustPath, () => emptyTrust(paths.catalog.root),
429
- (value) => normalizeTrust(value, paths.catalog.root)
430
- );
431
- return { trust, trustPath: paths.trustPath, catalog: paths.catalog, error: null };
432
- } catch (error) {
433
- return { trust: emptyTrust(paths.catalog.root), trustPath: paths.trustPath, catalog: paths.catalog, error: error.message };
434
- }
435
- }
436
-
437
- async function trustMutation(root, operation) {
438
- const paths = await authPaths(root);
439
- return mutate(
440
- paths.trustPath,
441
- () => readBoundedJson(paths.trustPath, () => emptyTrust(paths.catalog.root), (value) => normalizeTrust(value, paths.catalog.root)),
442
- trustFindings,
443
- (trust) => operation(trust, paths)
444
- );
445
- }
446
-
447
- export async function trustSigner({ root = process.cwd(), publicIdentityPath, confirmation, now = new Date() }) {
448
- requireConfirmation(confirmation);
449
- if (!publicIdentityPath || typeof publicIdentityPath !== "string") throw new Error("public identity path is required");
450
- const target = resolve(publicIdentityPath);
451
- const metadata = await lstat(target);
452
- if (!metadata.isFile() || metadata.isSymbolicLink() || metadata.size > MAX_PUBLIC_IDENTITY_BYTES) {
453
- throw new Error("public identity must be a regular JSON file smaller than 16 KiB");
454
- }
455
- const publicIdentity = validatePublicIdentity(JSON.parse(await readFile(target, "utf8")));
456
- const addedAt = isoDate(now, "now");
457
- return trustMutation(root, (trust, paths) => {
458
- const existing = trust.records.find((record) => record.keyId === publicIdentity.keyId);
459
- if (existing?.status === "trusted") return { created: false, record: existing, trustPath: paths.trustPath };
460
- if (existing?.status === "revoked") throw new Error("a revoked key cannot be silently trusted again; import a rotated key");
461
- const record = {
462
- signerId: publicIdentity.signerId, keyId: publicIdentity.keyId, publicIdentity,
463
- status: "trusted", addedAt, revokedAt: null, reason: null,
464
- confirmation: "local-owner", authority: "context-only"
465
- };
466
- trust.records.push(record);
467
- trust.records.sort((a, b) => a.signerId.localeCompare(b.signerId) || a.keyId.localeCompare(b.keyId));
468
- return { created: true, record, trustPath: paths.trustPath };
469
- });
470
- }
471
-
472
- export async function revokeTrustedSigner({ root = process.cwd(), keyId, reason, confirmation, now = new Date() }) {
473
- requireConfirmation(confirmation);
474
- if (!ID_RE.test(keyId || "")) throw new Error("keyId is required");
475
- if (!reason || typeof reason !== "string" || !reason.trim()) throw new Error("revocation reason is required");
476
- if (SECRET_RE.test(reason)) throw new Error("revocation reason appears to contain a secret");
477
- const revokedAt = isoDate(now, "now");
478
- return trustMutation(root, (trust, paths) => {
479
- const record = trust.records.find((item) => item.keyId === keyId);
480
- if (!record) throw new Error(`unknown trusted key: ${keyId}`);
481
- if (record.status === "revoked") return { changed: false, record, trustPath: paths.trustPath };
482
- trust.history.push({ kind: "trust-record", keyId, changedAt: revokedAt, value: { ...record }, authority: "context-only" });
483
- const revoked = { ...record, status: "revoked", revokedAt, reason: reason.trim().slice(0, 500), authority: "context-only" };
484
- trust.records = trust.records.map((item) => item.keyId === keyId ? revoked : item);
485
- return { changed: true, record: revoked, trustPath: paths.trustPath };
486
- });
487
- }
488
-
489
- export function assertTrustedIdentity(publicIdentity, trust) {
490
- validatePublicIdentity(publicIdentity);
491
- const findings = trustFindings(trust);
492
- if (findings.length) throw new Error(`sharing trust state failed closed: ${findings.join(", ")}`);
493
- const record = trust.records.find((item) => item.keyId === publicIdentity.keyId);
494
- if (!record || record.status !== "trusted" || record.signerId !== publicIdentity.signerId
495
- || record.publicIdentity.digest !== publicIdentity.digest) {
496
- throw new Error(`untrusted or revoked signing key: ${publicIdentity.keyId}`);
497
- }
498
- return record;
499
- }
500
-
501
- export async function trustedSignerContext({ root = process.cwd(), includeRevoked = false } = {}) {
502
- const { trust, trustPath } = await loadTrust(root);
503
- return {
504
- schema: "agentspine.trusted-signers/v1",
505
- root: trust.root,
506
- signers: trust.records.filter((record) => includeRevoked || record.status === "trusted").map((record) => ({
507
- signerId: record.signerId, keyId: record.keyId, status: record.status,
508
- addedAt: record.addedAt, revokedAt: record.revokedAt, reason: record.reason,
509
- authority: "context-only"
510
- })),
511
- trustPath,
512
- authority: "context-only",
513
- note: "A trusted signature authenticates origin only. It never grants permissions, delegation, or approval of the signed content."
514
- };
515
- }
@@ -1,110 +0,0 @@
1
- import { randomUUID } from "node:crypto";
2
- import {
3
- AUTONOMY_CONFIRMATION, AUTONOMY_MODES, CAPABILITY_RE, PUBLISH_CONFIRMATION,
4
- appendHistory, canonicalLocalRoot, exactCapabilities, loadAutonomy, modeAllows,
5
- mutateAutonomy, publicRepository, safeText, signedRecord, stableId, timestamp
6
- } from "./autonomy-store.js";
7
- import { loadExecutionPolicy } from "./selfstarter.js";
8
-
9
- function confirmation(value) {
10
- if (value !== AUTONOMY_CONFIRMATION) throw new Error("autonomy changes require explicit local-owner confirmation");
11
- }
12
-
13
- export async function configureAutonomyProject({
14
- root = process.cwd(), id = `autonomy-project:${randomUUID()}`, projectId, tenantId, groupId = null,
15
- localRoot = null, publicUrl = null, mode = "observe", capabilities = [], goal = "Maintain a bounded project overview.",
16
- confirmation: ownerConfirmation, publishConfirmation = null, now = new Date()
17
- }) {
18
- confirmation(ownerConfirmation);
19
- if (!AUTONOMY_MODES.includes(mode)) throw new Error(`mode must be one of: ${AUTONOMY_MODES.join(", ")}`);
20
- if (Boolean(localRoot) === Boolean(publicUrl)) throw new Error("configure exactly one local root or public repository URL");
21
- const source = localRoot
22
- ? { kind: "local-root", value: await canonicalLocalRoot(localRoot) }
23
- : { kind: "public-repository", value: publicRepository(publicUrl) };
24
- const requestedCapabilities = exactCapabilities(capabilities);
25
- if (modeAllows(mode, "execute") && !requestedCapabilities.length) throw new Error("execute and publish modes require exact capabilities");
26
- if (mode === "publish" && publishConfirmation !== PUBLISH_CONFIRMATION) {
27
- throw new Error("publish mode requires a separate explicit local publish confirmation");
28
- }
29
- const at = timestamp(now, "now");
30
- const registrationId = stableId(id, "registrationId");
31
- return mutateAutonomy(root, (state, paths) => {
32
- const previous = state.projects.find((item) => item.id === registrationId);
33
- if (previous && (previous.projectId !== projectId || previous.tenantId !== tenantId || previous.groupId !== groupId
34
- || previous.source.kind !== source.kind || previous.source.value !== source.value)) {
35
- throw new Error("project registration identity and scope are immutable; create a new registration");
36
- }
37
- state.revision += 1;
38
- const body = {
39
- id: registrationId, projectId: stableId(projectId, "projectId"), tenantId: stableId(tenantId, "tenantId"),
40
- groupId: stableId(groupId, "groupId", true), source, mode, capabilities: requestedCapabilities,
41
- goal: safeText(goal, "goal", 500), active: true, revision: state.revision,
42
- createdAt: previous?.createdAt || at, updatedAt: at,
43
- publishConfirmedAt: mode === "publish" ? at : null,
44
- sourceAuthority: "explicit-local-owner-policy", authority: "explicit-local-autonomy-policy"
45
- };
46
- const project = signedRecord(body);
47
- if (previous) state.projects = state.projects.map((item) => item.id === registrationId ? project : item);
48
- else state.projects.push(project);
49
- state.projects.sort((a, b) => a.id.localeCompare(b.id));
50
- appendHistory(state, { kind: previous ? "project-updated" : "project-registered", projectRegistrationId: project.id, at });
51
- return { project, policyRevision: state.revision, autonomyPath: paths.autonomyPath };
52
- });
53
- }
54
-
55
- export async function revokeAutonomyProject({ root = process.cwd(), id, reason, confirmation: ownerConfirmation, now = new Date() }) {
56
- confirmation(ownerConfirmation);
57
- const registrationId = stableId(id, "registrationId");
58
- const at = timestamp(now, "now");
59
- const revokeReason = safeText(reason, "reason", 500);
60
- return mutateAutonomy(root, (state, paths) => {
61
- const previous = state.projects.find((item) => item.id === registrationId);
62
- if (!previous?.active) throw new Error("project registration is unknown or already inactive");
63
- state.revision += 1;
64
- const { recordDigest: ignored, ...body } = previous;
65
- const project = signedRecord({ ...body, active: false, updatedAt: at, revision: state.revision, revokedAt: at, revokeReason });
66
- state.projects = state.projects.map((item) => item.id === registrationId ? project : item);
67
- appendHistory(state, { kind: "project-revoked", projectRegistrationId: project.id, at });
68
- return { project, policyRevision: state.revision, autonomyPath: paths.autonomyPath };
69
- });
70
- }
71
-
72
- function exactGrant(policy, input, capability, now) {
73
- return policy.grants.find((grant) => grant.active && grant.actorId === input.actorId
74
- && grant.jobId === input.jobId && grant.taskId === input.taskId && grant.targetId === input.targetId
75
- && grant.projectId === input.projectId && grant.groupId === input.groupId && grant.host === input.host
76
- && grant.capabilities.includes(capability) && (!grant.expiresAt || new Date(grant.expiresAt) > now));
77
- }
78
-
79
- export async function evaluateAutonomyAction({
80
- root = process.cwd(), registrationId, tenantId, groupId = null, action, capability = null,
81
- actorId = null, jobId = null, taskId = null, targetId = null, projectId = null, host = null, now = new Date()
82
- }) {
83
- if (!AUTONOMY_MODES.includes(action)) throw new Error(`action must be one of: ${AUTONOMY_MODES.join(", ")}`);
84
- const { state } = await loadAutonomy(root);
85
- const project = state.projects.find((item) => item.id === stableId(registrationId, "registrationId") && item.active);
86
- const base = { schema: "agentspine.autonomy-decision/v1", registrationId, action, allowed: false,
87
- reason: "project-registration-unavailable", grantsAuthority: false, authority: "additional-autonomy-gate" };
88
- if (!project || project.tenantId !== stableId(tenantId, "tenantId") || project.groupId !== stableId(groupId, "groupId", true)) return base;
89
- if (!modeAllows(project.mode, action)) return { ...base, reason: "autonomy-mode-insufficient", configuredMode: project.mode };
90
- if (!modeAllows(action, "execute")) return { ...base, allowed: true, reason: "configured-context-action", configuredMode: project.mode };
91
- if (project.projectId !== projectId) return { ...base, reason: "action-project-mismatch", configuredMode: project.mode };
92
- if (typeof capability !== "string" || !CAPABILITY_RE.test(capability) || !project.capabilities.includes(capability)) {
93
- return { ...base, reason: "capability-not-configured", configuredMode: project.mode };
94
- }
95
- if (action === "publish" && !project.publishConfirmedAt) return { ...base, reason: "publish-not-confirmed", configuredMode: project.mode };
96
- const scope = { actorId, jobId, taskId, targetId, projectId, groupId, host };
97
- if (Object.entries(scope).some(([key, value]) => key !== "groupId" && (typeof value !== "string" || !value))) {
98
- return { ...base, reason: "execution-scope-incomplete", configuredMode: project.mode };
99
- }
100
- const { policy } = await loadExecutionPolicy(root);
101
- const grant = exactGrant(policy, scope, capability, new Date(now));
102
- if (!grant) return { ...base, reason: "execution-grant-unavailable", configuredMode: project.mode };
103
- return { ...base, allowed: true, reason: "configured-and-explicitly-granted", configuredMode: project.mode, grantId: grant.id };
104
- }
105
-
106
- export async function autonomyStatus({ root = process.cwd(), tenantId = null, groupId = null } = {}) {
107
- const { state, autonomyPath } = await loadAutonomy(root);
108
- const projects = state.projects.filter((item) => (!tenantId || item.tenantId === tenantId) && item.groupId === groupId);
109
- return { schema: AUTONOMY_SCHEMA, projects, revision: state.revision, autonomyPath, authority: "context-only" };
110
- }