blun-king-cli 9.1.643 → 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 (266) 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 +18 -179
  18. package/bundled-agent-sources.json +1 -552
  19. package/package.json +1 -5
  20. package/tool-liveness642/receipt.json +1 -1
  21. package/worker-host.mjs +3 -119
  22. package/agent-spine-plugin/.claude-plugin/marketplace.json +0 -20
  23. package/agent-spine-plugin/.claude-plugin/plugin.json +0 -14
  24. package/agent-spine-plugin/.codex-plugin/plugin.json +0 -47
  25. package/agent-spine-plugin/.mcp.json +0 -8
  26. package/agent-spine-plugin/CHANGELOG.md +0 -1614
  27. package/agent-spine-plugin/LICENSE +0 -186
  28. package/agent-spine-plugin/README.md +0 -432
  29. package/agent-spine-plugin/assets/agentspine-banner.svg +0 -32
  30. package/agent-spine-plugin/bin/agentspine-mcp.js +0 -4
  31. package/agent-spine-plugin/bin/agentspine.js +0 -7
  32. package/agent-spine-plugin/blun.plugin.json +0 -68
  33. package/agent-spine-plugin/docs/acceptance.md +0 -61
  34. package/agent-spine-plugin/docs/artifact-evaluation.md +0 -93
  35. package/agent-spine-plugin/docs/host-integration.md +0 -193
  36. package/agent-spine-plugin/docs/preflight-recall.md +0 -71
  37. package/agent-spine-plugin/docs/preservation-contract.md +0 -53
  38. package/agent-spine-plugin/docs/quality-gates.md +0 -50
  39. package/agent-spine-plugin/docs/session-timeline.md +0 -112
  40. package/agent-spine-plugin/docs/source-roots.md +0 -113
  41. package/agent-spine-plugin/docs/world-model.md +0 -119
  42. package/agent-spine-plugin/hooks/codex.json +0 -47
  43. package/agent-spine-plugin/hooks/hooks.json +0 -106
  44. package/agent-spine-plugin/hooks/version.json +0 -5
  45. package/agent-spine-plugin/package.json +0 -77
  46. package/agent-spine-plugin/scripts/check-codex-install.js +0 -226
  47. package/agent-spine-plugin/scripts/check-hosts.js +0 -208
  48. package/agent-spine-plugin/scripts/check-install-hook.js +0 -227
  49. package/agent-spine-plugin/scripts/check-install-selfstarter.js +0 -154
  50. package/agent-spine-plugin/scripts/check-install.js +0 -478
  51. package/agent-spine-plugin/scripts/check-line-budget.js +0 -58
  52. package/agent-spine-plugin/scripts/check-syntax.js +0 -29
  53. package/agent-spine-plugin/scripts/github-actions.js +0 -11
  54. package/agent-spine-plugin/scripts/hermetic-process.js +0 -191
  55. package/agent-spine-plugin/scripts/release-check.js +0 -150
  56. package/agent-spine-plugin/scripts/run-acceptance.js +0 -19
  57. package/agent-spine-plugin/scripts/run-checks.js +0 -50
  58. package/agent-spine-plugin/scripts/run-tests-hermetic.js +0 -112
  59. package/agent-spine-plugin/skills/agent-spine/SKILL.md +0 -99
  60. package/agent-spine-plugin/spine-example/1-identity.md +0 -12
  61. package/agent-spine-plugin/spine-example/2-voice.md +0 -6
  62. package/agent-spine-plugin/spine-example/3-conduct.md +0 -8
  63. package/agent-spine-plugin/spine-example/4-history.md +0 -4
  64. package/agent-spine-plugin/src/cli-agent.js +0 -315
  65. package/agent-spine-plugin/src/cli-attention.js +0 -95
  66. package/agent-spine-plugin/src/cli-autonomy.js +0 -36
  67. package/agent-spine-plugin/src/cli-common.js +0 -71
  68. package/agent-spine-plugin/src/cli-continuity.js +0 -116
  69. package/agent-spine-plugin/src/cli-core.js +0 -128
  70. package/agent-spine-plugin/src/cli-diagnostics.js +0 -291
  71. package/agent-spine-plugin/src/cli-host.js +0 -21
  72. package/agent-spine-plugin/src/cli-learning.js +0 -320
  73. package/agent-spine-plugin/src/cli-premortem.js +0 -16
  74. package/agent-spine-plugin/src/cli-sharing.js +0 -230
  75. package/agent-spine-plugin/src/cli.js +0 -181
  76. package/agent-spine-plugin/src/codex-reader-launcher.js +0 -182
  77. package/agent-spine-plugin/src/hook.js +0 -500
  78. package/agent-spine-plugin/src/index.js +0 -108
  79. package/agent-spine-plugin/src/lib/acceptance.js +0 -435
  80. package/agent-spine-plugin/src/lib/action-lesson-recall.js +0 -118
  81. package/agent-spine-plugin/src/lib/attention-context.js +0 -167
  82. package/agent-spine-plugin/src/lib/attention-events.js +0 -113
  83. package/agent-spine-plugin/src/lib/attention-privacy.js +0 -72
  84. package/agent-spine-plugin/src/lib/attention-schema.js +0 -164
  85. package/agent-spine-plugin/src/lib/attention-storage.js +0 -93
  86. package/agent-spine-plugin/src/lib/attention.js +0 -164
  87. package/agent-spine-plugin/src/lib/audit-premortem.js +0 -223
  88. package/agent-spine-plugin/src/lib/audit.js +0 -401
  89. package/agent-spine-plugin/src/lib/authentication.js +0 -515
  90. package/agent-spine-plugin/src/lib/autonomy-policy.js +0 -110
  91. package/agent-spine-plugin/src/lib/autonomy-store.js +0 -202
  92. package/agent-spine-plugin/src/lib/autonomy.js +0 -8
  93. package/agent-spine-plugin/src/lib/briefing.js +0 -493
  94. package/agent-spine-plugin/src/lib/catalog-document-read.js +0 -51
  95. package/agent-spine-plugin/src/lib/catalog.js +0 -167
  96. package/agent-spine-plugin/src/lib/channel-continuity.js +0 -19
  97. package/agent-spine-plugin/src/lib/channel-runtime.js +0 -665
  98. package/agent-spine-plugin/src/lib/codex-installation.js +0 -231
  99. package/agent-spine-plugin/src/lib/codex-skill-installation.js +0 -211
  100. package/agent-spine-plugin/src/lib/context.js +0 -156
  101. package/agent-spine-plugin/src/lib/continuity.js +0 -338
  102. package/agent-spine-plugin/src/lib/coordination.js +0 -577
  103. package/agent-spine-plugin/src/lib/delivery-agent-usage.js +0 -231
  104. package/agent-spine-plugin/src/lib/delivery-assignment.js +0 -220
  105. package/agent-spine-plugin/src/lib/delivery-command-actions.js +0 -462
  106. package/agent-spine-plugin/src/lib/delivery-knowledge.js +0 -78
  107. package/agent-spine-plugin/src/lib/delivery-premortem-binding.js +0 -107
  108. package/agent-spine-plugin/src/lib/delivery-premortem-closure.js +0 -171
  109. package/agent-spine-plugin/src/lib/delivery-premortem-codec.js +0 -45
  110. package/agent-spine-plugin/src/lib/delivery-premortem-correction.js +0 -101
  111. package/agent-spine-plugin/src/lib/delivery-premortem-file.js +0 -21
  112. package/agent-spine-plugin/src/lib/delivery-premortem-index.js +0 -493
  113. package/agent-spine-plugin/src/lib/delivery-premortem-inspection.js +0 -37
  114. package/agent-spine-plugin/src/lib/delivery-premortem-recovery.js +0 -120
  115. package/agent-spine-plugin/src/lib/delivery-premortem-rejection.js +0 -65
  116. package/agent-spine-plugin/src/lib/delivery-premortem-results.js +0 -28
  117. package/agent-spine-plugin/src/lib/delivery-premortem-session-guard.js +0 -46
  118. package/agent-spine-plugin/src/lib/delivery-premortem-write-ledger.js +0 -285
  119. package/agent-spine-plugin/src/lib/delivery-premortem.js +0 -499
  120. package/agent-spine-plugin/src/lib/delivery-shell-heredoc.js +0 -115
  121. package/agent-spine-plugin/src/lib/delivery-shell-substitutions.js +0 -111
  122. package/agent-spine-plugin/src/lib/delivery-shell-wrapper.js +0 -64
  123. package/agent-spine-plugin/src/lib/delivery-target.js +0 -73
  124. package/agent-spine-plugin/src/lib/delivery-verification.js +0 -445
  125. package/agent-spine-plugin/src/lib/documents.js +0 -239
  126. package/agent-spine-plugin/src/lib/feed-transport.js +0 -499
  127. package/agent-spine-plugin/src/lib/filesystem-retry.js +0 -34
  128. package/agent-spine-plugin/src/lib/gateway-common.js +0 -68
  129. package/agent-spine-plugin/src/lib/gateway-control.js +0 -370
  130. package/agent-spine-plugin/src/lib/gateway-delivery.js +0 -103
  131. package/agent-spine-plugin/src/lib/gateway-execution.js +0 -350
  132. package/agent-spine-plugin/src/lib/gateway-group-response.js +0 -128
  133. package/agent-spine-plugin/src/lib/gateway-host-fencing.js +0 -92
  134. package/agent-spine-plugin/src/lib/gateway-host-lifecycle.js +0 -193
  135. package/agent-spine-plugin/src/lib/gateway-inspection.js +0 -85
  136. package/agent-spine-plugin/src/lib/gateway-knowledge.js +0 -129
  137. package/agent-spine-plugin/src/lib/gateway-policy-provenance.js +0 -197
  138. package/agent-spine-plugin/src/lib/gateway-premortem-disposition.js +0 -82
  139. package/agent-spine-plugin/src/lib/gateway-premortem.js +0 -363
  140. package/agent-spine-plugin/src/lib/gateway-prepared-host.js +0 -28
  141. package/agent-spine-plugin/src/lib/gateway-runs.js +0 -345
  142. package/agent-spine-plugin/src/lib/gateway-runtime-identity.js +0 -31
  143. package/agent-spine-plugin/src/lib/gateway-runtime-records.js +0 -21
  144. package/agent-spine-plugin/src/lib/gateway-runtime.js +0 -18
  145. package/agent-spine-plugin/src/lib/gateway-state-transaction.js +0 -356
  146. package/agent-spine-plugin/src/lib/gateway-state.js +0 -344
  147. package/agent-spine-plugin/src/lib/graph.js +0 -337
  148. package/agent-spine-plugin/src/lib/hook-artifact-guards.js +0 -356
  149. package/agent-spine-plugin/src/lib/hook-audit.js +0 -43
  150. package/agent-spine-plugin/src/lib/hook-briefing-use.js +0 -78
  151. package/agent-spine-plugin/src/lib/hook-context.js +0 -441
  152. package/agent-spine-plugin/src/lib/hook-final-message.js +0 -26
  153. package/agent-spine-plugin/src/lib/hook-input.js +0 -27
  154. package/agent-spine-plugin/src/lib/hook-output.js +0 -284
  155. package/agent-spine-plugin/src/lib/hook-premortem.js +0 -257
  156. package/agent-spine-plugin/src/lib/hook-process-advisory.js +0 -36
  157. package/agent-spine-plugin/src/lib/hook-protection.js +0 -95
  158. package/agent-spine-plugin/src/lib/hook-stop-verification.js +0 -84
  159. package/agent-spine-plugin/src/lib/hook-timeline.js +0 -102
  160. package/agent-spine-plugin/src/lib/host-instruction-budget.js +0 -11
  161. package/agent-spine-plugin/src/lib/https-transport.js +0 -392
  162. package/agent-spine-plugin/src/lib/identifier-analysis.js +0 -446
  163. package/agent-spine-plugin/src/lib/indexed-memory-offline.js +0 -40
  164. package/agent-spine-plugin/src/lib/indexed-memory.js +0 -298
  165. package/agent-spine-plugin/src/lib/knowledge-evidence.js +0 -431
  166. package/agent-spine-plugin/src/lib/learning-applications.js +0 -441
  167. package/agent-spine-plugin/src/lib/learning-artifact-evaluator.js +0 -114
  168. package/agent-spine-plugin/src/lib/learning-candidates.js +0 -274
  169. package/agent-spine-plugin/src/lib/learning-context.js +0 -137
  170. package/agent-spine-plugin/src/lib/learning-delivery-contracts.js +0 -310
  171. package/agent-spine-plugin/src/lib/learning-evaluation-contracts.js +0 -350
  172. package/agent-spine-plugin/src/lib/learning-evaluation-registration.js +0 -372
  173. package/agent-spine-plugin/src/lib/learning-evaluation-revocation.js +0 -292
  174. package/agent-spine-plugin/src/lib/learning-evidence-contracts.js +0 -321
  175. package/agent-spine-plugin/src/lib/learning-findings.js +0 -458
  176. package/agent-spine-plugin/src/lib/learning-measurement-contracts.js +0 -285
  177. package/agent-spine-plugin/src/lib/learning-measurements.js +0 -265
  178. package/agent-spine-plugin/src/lib/learning-outcome-contracts.js +0 -165
  179. package/agent-spine-plugin/src/lib/learning-outcomes.js +0 -343
  180. package/agent-spine-plugin/src/lib/learning-reconciliation.js +0 -290
  181. package/agent-spine-plugin/src/lib/learning-retry-contracts.js +0 -188
  182. package/agent-spine-plugin/src/lib/learning-schema.js +0 -229
  183. package/agent-spine-plugin/src/lib/learning-scope-targets.js +0 -424
  184. package/agent-spine-plugin/src/lib/learning-state-upgrade.js +0 -477
  185. package/agent-spine-plugin/src/lib/learning-status-configuration.js +0 -476
  186. package/agent-spine-plugin/src/lib/learning-storage.js +0 -203
  187. package/agent-spine-plugin/src/lib/learning-trial-recovery.js +0 -218
  188. package/agent-spine-plugin/src/lib/learning-validation-contracts.js +0 -375
  189. package/agent-spine-plugin/src/lib/learning-validation-renewal.js +0 -298
  190. package/agent-spine-plugin/src/lib/learning-validation-runtime.js +0 -234
  191. package/agent-spine-plugin/src/lib/learning.js +0 -36
  192. package/agent-spine-plugin/src/lib/lesson-recall-session.js +0 -172
  193. package/agent-spine-plugin/src/lib/mcp-autonomy-tools.js +0 -37
  194. package/agent-spine-plugin/src/lib/mcp-delivery-completion.js +0 -124
  195. package/agent-spine-plugin/src/lib/mcp-delivery-tools.js +0 -45
  196. package/agent-spine-plugin/src/lib/mcp-premortem.js +0 -68
  197. package/agent-spine-plugin/src/lib/mcp-runtime.js +0 -355
  198. package/agent-spine-plugin/src/lib/mcp-source-context.js +0 -61
  199. package/agent-spine-plugin/src/lib/mcp-timeline-tools.js +0 -240
  200. package/agent-spine-plugin/src/lib/mcp-world-tools.js +0 -52
  201. package/agent-spine-plugin/src/lib/object-transport.js +0 -206
  202. package/agent-spine-plugin/src/lib/owned-file-lock.js +0 -182
  203. package/agent-spine-plugin/src/lib/paths.js +0 -109
  204. package/agent-spine-plugin/src/lib/peer-transport.js +0 -283
  205. package/agent-spine-plugin/src/lib/persona-runtime.js +0 -581
  206. package/agent-spine-plugin/src/lib/pre-answer-timeline-recall.js +0 -104
  207. package/agent-spine-plugin/src/lib/preflight-delivery-id.js +0 -27
  208. package/agent-spine-plugin/src/lib/preflight.js +0 -688
  209. package/agent-spine-plugin/src/lib/project-portfolio.js +0 -176
  210. package/agent-spine-plugin/src/lib/runtime.js +0 -13
  211. package/agent-spine-plugin/src/lib/selfstarter-core.js +0 -382
  212. package/agent-spine-plugin/src/lib/selfstarter-jobs.js +0 -149
  213. package/agent-spine-plugin/src/lib/selfstarter-lease.js +0 -204
  214. package/agent-spine-plugin/src/lib/selfstarter-policy.js +0 -90
  215. package/agent-spine-plugin/src/lib/selfstarter-workspace.js +0 -111
  216. package/agent-spine-plugin/src/lib/selfstarter.js +0 -11
  217. package/agent-spine-plugin/src/lib/session-timeline-auth.js +0 -316
  218. package/agent-spine-plugin/src/lib/session-timeline-codex.js +0 -69
  219. package/agent-spine-plugin/src/lib/session-timeline-contract.js +0 -56
  220. package/agent-spine-plugin/src/lib/session-timeline-enrollment-source.js +0 -38
  221. package/agent-spine-plugin/src/lib/session-timeline-enrollment-storage.js +0 -128
  222. package/agent-spine-plugin/src/lib/session-timeline-enrollment-transport.js +0 -15
  223. package/agent-spine-plugin/src/lib/session-timeline-enrollment.js +0 -478
  224. package/agent-spine-plugin/src/lib/session-timeline-event-extract.js +0 -186
  225. package/agent-spine-plugin/src/lib/session-timeline-host-origin.js +0 -73
  226. package/agent-spine-plugin/src/lib/session-timeline-host-receipt.js +0 -117
  227. package/agent-spine-plugin/src/lib/session-timeline-invocation.js +0 -201
  228. package/agent-spine-plugin/src/lib/session-timeline-king.js +0 -93
  229. package/agent-spine-plugin/src/lib/session-timeline-prior.js +0 -57
  230. package/agent-spine-plugin/src/lib/session-timeline-provider.js +0 -36
  231. package/agent-spine-plugin/src/lib/session-timeline-query.js +0 -56
  232. package/agent-spine-plugin/src/lib/session-timeline-results.js +0 -56
  233. package/agent-spine-plugin/src/lib/session-timeline-root.js +0 -11
  234. package/agent-spine-plugin/src/lib/session-timeline-search.js +0 -82
  235. package/agent-spine-plugin/src/lib/session-timeline-sid-acl.js +0 -213
  236. package/agent-spine-plugin/src/lib/session-timeline-source-open.js +0 -30
  237. package/agent-spine-plugin/src/lib/session-timeline-source.js +0 -80
  238. package/agent-spine-plugin/src/lib/session-timeline-state.js +0 -45
  239. package/agent-spine-plugin/src/lib/session-timeline-transport.js +0 -42
  240. package/agent-spine-plugin/src/lib/session-timeline-windows-acl.js +0 -145
  241. package/agent-spine-plugin/src/lib/session-timeline.js +0 -462
  242. package/agent-spine-plugin/src/lib/sharing.js +0 -969
  243. package/agent-spine-plugin/src/lib/source-roots.js +0 -475
  244. package/agent-spine-plugin/src/lib/source-tree-scan.js +0 -178
  245. package/agent-spine-plugin/src/lib/sqlite-transport.js +0 -501
  246. package/agent-spine-plugin/src/lib/task-knowledge-context.js +0 -99
  247. package/agent-spine-plugin/src/lib/telegram-adapter.js +0 -119
  248. package/agent-spine-plugin/src/lib/timeline-continuation-update.js +0 -100
  249. package/agent-spine-plugin/src/lib/timeline-tool-guard.js +0 -225
  250. package/agent-spine-plugin/src/lib/timeline-user-feedback.js +0 -216
  251. package/agent-spine-plugin/src/lib/timeline-world-capture.js +0 -233
  252. package/agent-spine-plugin/src/lib/voice-runtime.js +0 -39
  253. package/agent-spine-plugin/src/lib/world-knowledge.js +0 -306
  254. package/agent-spine-plugin/src/lib/world-model.js +0 -333
  255. package/agent-spine-plugin/src/mcp.js +0 -456
  256. package/agent-spine-plugin/src/version.js +0 -1
  257. package/agent-spine-plugin/src/worker.js +0 -257
  258. package/bin/agentspine-king-goal-inbox.mjs +0 -127
  259. package/bin/agentspine-king-goal-intake.mjs +0 -106
  260. package/bin/agentspine-king-host-runner.mjs +0 -109
  261. package/bin/agentspine-king-snapshot-policy.cjs +0 -80
  262. package/bin/agentspine-king-status-policy.mjs +0 -226
  263. package/bin/agentspine-king-worker-host.mjs +0 -160
  264. package/bin/managed-plugin-selection.cjs +0 -141
  265. package/bin/verify-agent-behavior.cjs +0 -122
  266. package/bin/verify-agent-components.cjs +0 -104
@@ -1,581 +0,0 @@
1
- import { createHash, randomUUID } from "node:crypto";
2
- import { constants as fsConstants } from "node:fs";
3
- import { lstat, open, opendir, readFile, realpath, stat, unlink, writeFile } from "node:fs/promises";
4
- import { isAbsolute, join } from "node:path";
5
- import { buildCatalog } from "./catalog.js";
6
- import { isFileLockContention, isTransientLockMetadataError, replaceFileWithRetry } from "./filesystem-retry.js";
7
- import { linkEntities, loadGraph, unlinkEntities, upsertEntity } from "./graph.js";
8
- import { isInside, projectStateDir } from "./paths.js";
9
-
10
- export const PERSONA_POLICY_SCHEMA = "agentspine.persona-policy/v1";
11
- export const PERSONA_RUNTIME_SCHEMA = "agentspine.persona-runtime/v1";
12
- export const PERSONA_EVENT_SCHEMA = "agentspine.persona-event/v1";
13
- export const PERSONA_ROSTER_SCHEMA = "agentspine.persona-roster/v1";
14
-
15
- const CONFIRMATION = "local-owner-confirmed";
16
- const MAX_BYTES = 5 * 1024 * 1024;
17
- const ID_RE = /^[A-Za-z0-9][A-Za-z0-9:_.@/+~-]{0,255}$/;
18
- const KINDS = new Set(["person", "agent", "bot"]);
19
- const EVENTS = new Set(["join", "rename", "group-change", "leave", "deactivate", "rejoin"]);
20
- const ACTIVE = new Set(["active", "left", "deactivated"]);
21
- const AUTHENTICATORS = new Set(["host-manifest", "oauth-subject", "local-roster", "signed-roster"]);
22
- const NATIVE_HOSTS = new Set(["claude", "codex"]);
23
- const NATIVE_SCOPES = new Set(["user", "project"]);
24
- const FORBIDDEN = /\b(?:permission|rights?|roles?|owner|trusted|reports[- ]to|responsible[- ]for|delegat|token|secret|credential|api[-_ ]?key|network|production|payment|send capability|tool capability)\b/i;
25
-
26
- function emptyPolicy(root) {
27
- return { schema: PERSONA_POLICY_SCHEMA, root, revision: 0, bindings: [], history: [] };
28
- }
29
-
30
- function emptyRuntime(root) {
31
- return { schema: PERSONA_RUNTIME_SCHEMA, root, revision: 0, personas: [], events: [], receipts: [] };
32
- }
33
-
34
- function exactId(value, field, nullable = false) {
35
- if ((value === null || value === undefined || value === "") && nullable) return null;
36
- if (typeof value !== "string" || !ID_RE.test(value) || value.includes("*")) {
37
- throw new Error(field + " must be an exact stable ID without wildcards");
38
- }
39
- return value;
40
- }
41
-
42
- function exactText(value, field, maximum = 200) {
43
- if (typeof value !== "string" || !value.trim()) throw new Error(field + " is required");
44
- const text = value.trim().replace(/\s+/g, " ").slice(0, maximum);
45
- if (FORBIDDEN.test(text)) throw new Error(field + " contains authority or secret-shaped content");
46
- return text;
47
- }
48
-
49
- function sourceText(value) {
50
- if (typeof value !== "string" || !value.trim() || value.includes("\0")) throw new Error("sourceBinding is invalid");
51
- return value.trim().replaceAll("\\", "/").slice(0, 500);
52
- }
53
-
54
- function at(value = new Date()) {
55
- const date = value instanceof Date ? value : new Date(value);
56
- if (!Number.isFinite(date.getTime())) throw new Error("timestamp is invalid");
57
- return date.toISOString();
58
- }
59
-
60
- function digest(value) {
61
- return createHash("sha256").update(value).digest("hex");
62
- }
63
-
64
- function identityMaterial(binding) {
65
- return [binding.authenticator, binding.issuer, binding.tenantId, binding.host, binding.profileId,
66
- binding.subjectId, binding.kind].join("\0");
67
- }
68
-
69
- function stablePersonaId(binding) {
70
- return binding.kind + ":runtime:" + digest(identityMaterial(binding)).slice(0, 32);
71
- }
72
-
73
- function validBinding(binding) {
74
- return binding && ID_RE.test(binding.id || "") && KINDS.has(binding.kind)
75
- && AUTHENTICATORS.has(binding.authenticator) && ID_RE.test(binding.issuer || "")
76
- && ID_RE.test(binding.tenantId || "") && ID_RE.test(binding.host || "")
77
- && ID_RE.test(binding.profileId || "") && ID_RE.test(binding.subjectId || "")
78
- && ID_RE.test(binding.personaId || "") && binding.personaId === stablePersonaId(binding)
79
- && typeof binding.displayName === "string" && binding.displayName.length > 0 && !FORBIDDEN.test(binding.displayName)
80
- && (binding.sourceBinding === null || typeof binding.sourceBinding === "string")
81
- && (binding.groupId === null || ID_RE.test(binding.groupId || ""))
82
- && typeof binding.active === "boolean" && typeof binding.deactivated === "boolean"
83
- && !(binding.active && binding.deactivated) && binding.authority === "authenticated-identity-policy"
84
- && Number.isFinite(new Date(binding.createdAt).getTime())
85
- && Number.isFinite(new Date(binding.updatedAt).getTime());
86
- }
87
-
88
- function validPersona(persona) {
89
- return persona && ID_RE.test(persona.personaId || "") && ID_RE.test(persona.bindingId || "")
90
- && KINDS.has(persona.kind) && ACTIVE.has(persona.status)
91
- && typeof persona.displayName === "string" && persona.displayName.length > 0
92
- && (persona.groupId === null || ID_RE.test(persona.groupId || ""))
93
- && Number.isInteger(persona.sequence) && persona.sequence >= 1
94
- && persona.authority === "identity-state-only" && Number.isFinite(new Date(persona.updatedAt).getTime());
95
- }
96
-
97
- function validEvent(event) {
98
- if (!(event && event.schema === PERSONA_EVENT_SCHEMA && ID_RE.test(event.eventId || "")
99
- && ID_RE.test(event.personaId || "") && ID_RE.test(event.bindingId || "")
100
- && EVENTS.has(event.type) && Number.isInteger(event.sequence) && event.sequence >= 1
101
- && Number.isFinite(new Date(event.observedAt).getTime())
102
- && /^[a-f0-9]{64}$/.test(event.payloadDigest || "")
103
- && event.authority === "identity-state-only")) return false;
104
- const payload = { personaId: event.personaId, bindingId: event.bindingId, type: event.type, sequence: event.sequence,
105
- displayName: event.displayName, groupId: event.groupId, observedAt: event.observedAt };
106
- const payloadDigest = digest(JSON.stringify(payload));
107
- return event.payloadDigest === payloadDigest && event.eventId === "persona-event:" + payloadDigest.slice(0, 32);
108
- }
109
-
110
- function validReceipt(receipt) {
111
- if (!(receipt && ID_RE.test(receipt.id || "") && ID_RE.test(receipt.eventId || "")
112
- && /^[a-f0-9]{64}$/.test(receipt.payloadDigest || "") && /^[a-f0-9]{64}$/.test(receipt.digest || "")
113
- && Number.isFinite(new Date(receipt.at).getTime()) && receipt.authority === "identity-state-only")) return false;
114
- const material = { eventId: receipt.eventId, payloadDigest: receipt.payloadDigest, at: receipt.at,
115
- authority: "identity-state-only" };
116
- return receipt.digest === digest(JSON.stringify(material)) && receipt.id === "persona-receipt:" + receipt.digest.slice(0, 24);
117
- }
118
-
119
- function normalizePolicy(value, root) {
120
- if (!value || value.schema !== PERSONA_POLICY_SCHEMA || value.root !== root
121
- || !Number.isInteger(value.revision) || !Array.isArray(value.bindings) || !Array.isArray(value.history)
122
- || value.bindings.some((item) => !validBinding(item))
123
- || value.history.some((item) => !item || !validBinding(item.value) || item.authority !== "authenticated-identity-policy")) {
124
- throw new Error("persona policy is invalid; automatic persona synchronization is disabled");
125
- }
126
- return value;
127
- }
128
-
129
- function normalizeRuntime(value, root) {
130
- if (!value || value.schema !== PERSONA_RUNTIME_SCHEMA || value.root !== root
131
- || !Number.isInteger(value.revision) || !Array.isArray(value.personas)
132
- || !Array.isArray(value.events) || !Array.isArray(value.receipts)
133
- || value.personas.some((item) => !validPersona(item)) || value.events.some((item) => !validEvent(item))
134
- || value.receipts.some((item) => !validReceipt(item))) {
135
- throw new Error("persona runtime is invalid; persona context is disabled");
136
- }
137
- return value;
138
- }
139
-
140
- async function pathsFor(root, providedCatalog = null) {
141
- const catalog = providedCatalog || await buildCatalog(root);
142
- const directory = await projectStateDir(catalog.root);
143
- return { catalog, directory, personaPolicyPath: join(directory, "persona-policy.json"), personaRuntimePath: join(directory, "persona-runtime.json") };
144
- }
145
-
146
- async function readJson(path, root, normalize, empty) {
147
- try {
148
- const metadata = await stat(path);
149
- if (metadata.size > MAX_BYTES) throw new Error("persona state exceeds 5 MiB");
150
- return normalize(JSON.parse(await readFile(path, "utf8")), root);
151
- } catch (error) {
152
- if (error.code !== "ENOENT") throw error;
153
- return empty(root);
154
- }
155
- }
156
-
157
- async function writeJson(path, value) {
158
- const content = JSON.stringify(value, null, 2) + "\n";
159
- if (Buffer.byteLength(content) > MAX_BYTES) throw new Error("persona state exceeds 5 MiB");
160
- const temporary = path + "." + process.pid + "." + randomUUID() + ".tmp";
161
- try {
162
- await writeFile(temporary, content, { mode: 0o600 });
163
- await replaceFileWithRetry(temporary, path);
164
- } finally {
165
- await unlink(temporary).catch((error) => { if (error.code !== "ENOENT") throw error; });
166
- }
167
- }
168
-
169
- async function withLock(paths, task) {
170
- const lockPath = join(paths.directory, "persona-runtime.lock");
171
- let handle;
172
- for (let attempt = 0; attempt < 120; attempt += 1) {
173
- try { handle = await open(lockPath, "wx", 0o600); break; } catch (error) {
174
- if (!isFileLockContention(error)) throw error;
175
- try {
176
- const metadata = await stat(lockPath);
177
- if (Date.now() - metadata.mtimeMs > 90000) await unlink(lockPath);
178
- } catch (lockError) { if (!isTransientLockMetadataError(lockError)) throw lockError; }
179
- await new Promise((resolve) => setTimeout(resolve, 25));
180
- }
181
- }
182
- if (!handle) throw new Error("persona state is busy; retry later");
183
- try { return await task(); } finally {
184
- await handle.close();
185
- await unlink(lockPath).catch((error) => { if (error.code !== "ENOENT") throw error; });
186
- }
187
- }
188
-
189
- function normalizeBinding(input, timestamp) {
190
- const binding = {
191
- id: exactId(input.id || "persona-binding:" + randomUUID(), "bindingId"),
192
- authenticator: AUTHENTICATORS.has(input.authenticator) ? input.authenticator : null,
193
- issuer: exactId(input.issuer, "issuer"), tenantId: exactId(input.tenantId, "tenantId"),
194
- host: exactId(input.host, "host"), profileId: exactId(input.profileId, "profileId"),
195
- subjectId: exactId(input.subjectId, "subjectId"), kind: input.kind,
196
- displayName: exactText(input.displayName, "displayName"),
197
- sourceBinding: input.sourceBinding === null || input.sourceBinding === undefined ? null : sourceText(input.sourceBinding),
198
- groupId: exactId(input.groupId, "groupId", true), deactivated: input.deactivated === true,
199
- active: input.deactivated === true ? false : input.active !== false,
200
- createdAt: timestamp, updatedAt: timestamp, authority: "authenticated-identity-policy"
201
- };
202
- if (!binding.authenticator || !KINDS.has(binding.kind)) throw new Error("persona binding requires an approved authenticator and person, agent, or bot kind");
203
- binding.personaId = stablePersonaId(binding);
204
- return binding;
205
- }
206
-
207
- function eventPayload(binding, type, sequence, observedAt) {
208
- const payload = { personaId: binding.personaId, bindingId: binding.id, type, sequence, displayName: binding.displayName,
209
- groupId: binding.groupId, observedAt };
210
- return { schema: PERSONA_EVENT_SCHEMA, eventId: "persona-event:" + digest(JSON.stringify(payload)).slice(0, 32),
211
- ...payload, payloadDigest: digest(JSON.stringify(payload)), authority: "identity-state-only" };
212
- }
213
-
214
- function eventReceipt(event) {
215
- const material = { eventId: event.eventId, payloadDigest: event.payloadDigest, at: event.observedAt,
216
- authority: "identity-state-only" };
217
- const receiptDigest = digest(JSON.stringify(material));
218
- return { id: "persona-receipt:" + receiptDigest.slice(0, 24), ...material, digest: receiptDigest };
219
- }
220
-
221
- function nextEventTypes(previous, binding) {
222
- if (!previous) return ["join"];
223
- if (!binding.active && previous.status === "active") return [binding.deactivated ? "deactivate" : "leave"];
224
- if (!binding.active) return [];
225
- const types = previous.status !== "active" ? ["rejoin"] : [];
226
- if (previous.displayName !== binding.displayName) types.push("rename");
227
- if (previous.groupId !== binding.groupId) types.push("group-change");
228
- return types;
229
- }
230
-
231
- function runtimeEntityAttributes(persona, binding, existing) {
232
- return {
233
- ...(existing?.attributes || {}),
234
- runtimeKind: persona.kind,
235
- identityBindingId: persona.bindingId,
236
- identityStatus: persona.status,
237
- sourceBinding: binding?.sourceBinding || null
238
- };
239
- }
240
-
241
- function sameRuntimeEntity(entity, persona, binding) {
242
- if (!entity) return false;
243
- const expectedKind = persona.kind === "bot" ? "agent" : persona.kind;
244
- const expectedPrivacy = persona.groupId ? "group" : "shared";
245
- const attributes = runtimeEntityAttributes(persona, binding, entity);
246
- return entity.kind === expectedKind && entity.displayName === persona.displayName
247
- && entity.privacy === expectedPrivacy
248
- && JSON.stringify(entity.attributes) === JSON.stringify(attributes);
249
- }
250
-
251
- async function reconcilePersonaGraph(paths, policy, runtime) {
252
- let { graph } = await loadGraph(paths.catalog.root, paths.catalog);
253
- const changes = { groupsCreated: 0, entitiesUpdated: 0, membershipsAdded: 0, membershipsRemoved: 0 };
254
- const activeGroupIds = [...new Set(runtime.personas
255
- .filter((item) => item.status === "active" && item.groupId !== null)
256
- .map((item) => item.groupId))].sort();
257
-
258
- for (const groupId of activeGroupIds) {
259
- const existing = graph.entities.find((item) => item.id === groupId);
260
- if (existing && existing.kind !== "group") {
261
- throw new Error(`authenticated persona group conflicts with a non-group entity: ${groupId}`);
262
- }
263
- if (existing?.privacy === "private") {
264
- throw new Error(`authenticated persona group cannot use private relationship visibility: ${groupId}`);
265
- }
266
- if (!existing) {
267
- await upsertEntity({ root: paths.catalog.root, id: groupId, kind: "group", privacy: "group",
268
- attributes: { identitySource: "authenticated-persona-roster" }, confidence: 1, catalog: paths.catalog });
269
- changes.groupsCreated += 1;
270
- graph = (await loadGraph(paths.catalog.root, paths.catalog)).graph;
271
- }
272
- }
273
-
274
- for (const persona of runtime.personas) {
275
- const binding = policy.bindings.find((item) => item.id === persona.bindingId);
276
- let existing = graph.entities.find((item) => item.id === persona.personaId);
277
- if (existing && existing.kind !== (persona.kind === "bot" ? "agent" : persona.kind)) {
278
- throw new Error(`authenticated persona conflicts with an existing entity kind: ${persona.personaId}`);
279
- }
280
- if (!sameRuntimeEntity(existing, persona, binding)) {
281
- await upsertEntity({ root: paths.catalog.root, id: persona.personaId,
282
- kind: persona.kind === "bot" ? "agent" : persona.kind, displayName: persona.displayName,
283
- aliases: existing?.aliases || [], attributes: runtimeEntityAttributes(persona, binding, existing),
284
- sourceDocument: existing?.sourceDocument
285
- && paths.catalog.documents.some((item) => item.relativePath === existing.sourceDocument)
286
- ? existing.sourceDocument : null,
287
- privacy: persona.groupId ? "group" : "shared", confidence: 1, catalog: paths.catalog });
288
- changes.entitiesUpdated += 1;
289
- graph = (await loadGraph(paths.catalog.root, paths.catalog)).graph;
290
- existing = graph.entities.find((item) => item.id === persona.personaId);
291
- }
292
-
293
- const memberships = graph.entityEdges.filter((edge) => edge.from === persona.personaId && edge.relation === "member-of");
294
- for (const edge of memberships.filter((item) => persona.status !== "active" || item.to !== persona.groupId)) {
295
- await unlinkEntities({ root: paths.catalog.root, from: edge.from, to: edge.to, relation: edge.relation,
296
- catalog: paths.catalog });
297
- changes.membershipsRemoved += 1;
298
- graph = (await loadGraph(paths.catalog.root, paths.catalog)).graph;
299
- }
300
- if (persona.status === "active" && persona.groupId !== null
301
- && !graph.entityEdges.some((edge) => edge.from === persona.personaId && edge.to === persona.groupId
302
- && edge.relation === "member-of" && edge.privacy === "group")) {
303
- await linkEntities({ root: paths.catalog.root, from: persona.personaId, to: persona.groupId,
304
- relation: "member-of", reason: "Authenticated roster membership; context only.", confidence: 1, privacy: "group",
305
- catalog: paths.catalog });
306
- changes.membershipsAdded += 1;
307
- graph = (await loadGraph(paths.catalog.root, paths.catalog)).graph;
308
- }
309
- }
310
- return changes;
311
- }
312
-
313
- export async function applyPersonaRoster({
314
- root = process.cwd(), bindings, rosterScopes = [], confirmation, now = new Date(), catalog: providedCatalog = null
315
- }) {
316
- if (confirmation !== CONFIRMATION) throw new Error("persona roster changes require explicit local owner confirmation");
317
- if (!Array.isArray(bindings) || bindings.length > 256 || (!bindings.length && !rosterScopes.length)) {
318
- throw new Error("bindings must contain up to 256 persona bindings or one explicit roster scope");
319
- }
320
- const paths = await pathsFor(root, providedCatalog);
321
- return withLock(paths, async () => {
322
- const [policy, runtime] = await Promise.all([
323
- readJson(paths.personaPolicyPath, paths.catalog.root, normalizePolicy, emptyPolicy),
324
- readJson(paths.personaRuntimePath, paths.catalog.root, normalizeRuntime, emptyRuntime)
325
- ]);
326
- const observedAt = at(now);
327
- const normalized = bindings.map((item) => normalizeBinding(item, observedAt));
328
- let changed = false;
329
- const scopedRosterKeys = new Set([
330
- ...normalized.map((item) => [item.authenticator, item.issuer, item.tenantId, item.host, item.profileId].join("\0")),
331
- ...rosterScopes.map((item) => [item.authenticator, item.issuer, item.tenantId, item.host, item.profileId].join("\0"))
332
- ]);
333
- const suppliedIds = new Set(normalized.map((item) => item.id));
334
- for (const missing of policy.bindings.filter((item) => item.active && scopedRosterKeys.has([
335
- item.authenticator, item.issuer, item.tenantId, item.host, item.profileId
336
- ].join("\0")) && !suppliedIds.has(item.id))) {
337
- const retired = { ...missing, active: false, deactivated: false, updatedAt: observedAt };
338
- normalized.push(retired);
339
- }
340
- const identities = new Set();
341
- for (const binding of normalized) {
342
- const key = identityMaterial(binding);
343
- if (identities.has(key)) throw new Error("persona roster contains a duplicate authenticated identity");
344
- identities.add(key);
345
- const previousBinding = policy.bindings.find((item) => item.id === binding.id);
346
- if (previousBinding && previousBinding.personaId !== binding.personaId) throw new Error("a binding ID cannot be reassigned to another authenticated identity");
347
- const unchangedBinding = previousBinding && ["authenticator", "issuer", "tenantId", "host", "profileId", "subjectId", "kind",
348
- "displayName", "sourceBinding", "groupId", "active", "deactivated", "personaId"].every((key) => previousBinding[key] === binding[key]);
349
- if (unchangedBinding) continue;
350
- changed = true;
351
- if (previousBinding) {
352
- policy.history.push({ recordId: previousBinding.id, supersededAt: observedAt, value: structuredClone(previousBinding), authority: "authenticated-identity-policy" });
353
- binding.createdAt = previousBinding.createdAt;
354
- }
355
- policy.bindings = policy.bindings.filter((item) => item.id !== binding.id);
356
- policy.bindings.push(binding);
357
- const previous = runtime.personas.find((item) => item.personaId === binding.personaId);
358
- const types = nextEventTypes(previous, binding);
359
- let sequence = previous?.sequence || 0;
360
- for (const type of types) {
361
- sequence += 1;
362
- const event = eventPayload(binding, type, sequence, observedAt);
363
- if (!runtime.receipts.some((item) => item.eventId === event.eventId)) {
364
- runtime.events.push(event);
365
- runtime.receipts.push(eventReceipt(event));
366
- }
367
- }
368
- if (types.length) {
369
- runtime.personas = runtime.personas.filter((item) => item.personaId !== binding.personaId);
370
- runtime.personas.push({ personaId: binding.personaId, bindingId: binding.id, kind: binding.kind,
371
- displayName: binding.displayName, groupId: binding.groupId,
372
- status: binding.active ? "active" : binding.deactivated ? "deactivated" : "left",
373
- sequence, updatedAt: observedAt, authority: "identity-state-only" });
374
- }
375
- }
376
- if (changed) {
377
- policy.bindings.sort((a, b) => a.id.localeCompare(b.id));
378
- runtime.personas.sort((a, b) => a.personaId.localeCompare(b.personaId));
379
- runtime.events.sort((a, b) => a.observedAt.localeCompare(b.observedAt) || a.eventId.localeCompare(b.eventId));
380
- policy.revision += 1;
381
- runtime.revision += 1;
382
- await Promise.all([writeJson(paths.personaPolicyPath, policy), writeJson(paths.personaRuntimePath, runtime)]);
383
- }
384
- const graphChanges = await reconcilePersonaGraph(paths, policy, runtime);
385
- const graphReconciled = Object.values(graphChanges).some((value) => value > 0);
386
- return { policy, runtime, personaPolicyPath: paths.personaPolicyPath,
387
- personaRuntimePath: paths.personaRuntimePath, duplicate: !changed, graphReconciled, graphChanges };
388
- });
389
- }
390
-
391
- function normalizeNativeDiscovery(value) {
392
- if (!value || typeof value !== "object" || !NATIVE_HOSTS.has(value.host) || !NATIVE_SCOPES.has(value.scope)) {
393
- throw new Error("native persona discovery requires a supported host and user or project scope");
394
- }
395
- return {
396
- id: exactId(value.id, "nativeDiscovery.id"), host: value.host, scope: value.scope,
397
- authenticator: "host-manifest", issuer: exactId(value.issuer, "nativeDiscovery.issuer"),
398
- tenantId: exactId(value.tenantId, "nativeDiscovery.tenantId"),
399
- profileId: exactId(value.profileId, "nativeDiscovery.profileId"),
400
- kind: value.kind === "bot" ? "bot" : "agent", groupId: exactId(value.groupId, "nativeDiscovery.groupId", true)
401
- };
402
- }
403
-
404
- function nativeAgentDirectory(scope, catalog, env) {
405
- if (scope.scope === "project") return join(catalog.root, scope.host === "claude" ? ".claude" : ".codex", "agents");
406
- const home = scope.host === "claude" ? env.CLAUDE_CONFIG_DIR
407
- : env.CODEX_HOME || env.BLUN_HOME;
408
- if (home) {
409
- if (!isAbsolute(home)) throw new Error(scope.host + " home override must be absolute");
410
- return join(home, "agents");
411
- }
412
- const userHome = env.HOME || env.USERPROFILE;
413
- if (!userHome || !isAbsolute(userHome)) throw new Error("native persona discovery requires an absolute host home");
414
- return join(userHome, scope.host === "claude" ? ".claude" : ".codex", "agents");
415
- }
416
-
417
- function manifestName(host, content) {
418
- if (host === "claude") {
419
- const frontmatter = content.startsWith("---") ? content.slice(3, content.indexOf("\n---", 3) + 1) : "";
420
- const match = frontmatter.match(/^\s*name\s*:\s*['\"]?([^'\"\r\n]+)['\"]?\s*$/mi);
421
- return match ? exactText(match[1], "manifest name") : null;
422
- }
423
- const match = content.match(/^\s*name\s*=\s*['\"]([^'\"\r\n]+)['\"]\s*$/mi);
424
- return match ? exactText(match[1], "manifest name") : null;
425
- }
426
-
427
- async function nativeManifestBindings(scope, catalog, env) {
428
- const directory = nativeAgentDirectory(scope, catalog, env);
429
- let metadata;
430
- try { metadata = await lstat(directory); } catch (error) { if (error.code === "ENOENT") return []; throw error; }
431
- if (metadata.isSymbolicLink() || !metadata.isDirectory()) throw new Error("native persona directory must be a regular non-symlink directory");
432
- const canonicalDirectory = await realpath(directory);
433
- const stream = await opendir(canonicalDirectory); const entries = [];
434
- try { for await (const entry of stream) entries.push(entry); } finally { await stream.close().catch(() => {}); }
435
- const extension = scope.host === "claude" ? ".md" : ".toml";
436
- const candidates = entries.filter((entry) => entry.isFile() && !entry.isSymbolicLink() && entry.name.endsWith(extension))
437
- .sort((left, right) => left.name.localeCompare(right.name));
438
- if (candidates.length > 128) throw new Error("native persona directory exceeds 128 direct manifests");
439
- const bindings = [];
440
- for (const entry of candidates) {
441
- const path = join(canonicalDirectory, entry.name);
442
- const pathBefore = await lstat(path);
443
- if (pathBefore.isSymbolicLink() || !pathBefore.isFile()) throw new Error("native persona manifest must be a regular non-symlink file");
444
- const handle = await open(path, fsConstants.O_RDONLY | (fsConstants.O_NOFOLLOW || 0));
445
- try {
446
- const before = await handle.stat();
447
- if (!before.isFile() || before.size > 256 * 1024) throw new Error("native persona manifest exceeds 256 KiB");
448
- const content = await handle.readFile("utf8");
449
- const after = await handle.stat();
450
- const pathAfter = await lstat(path);
451
- if (before.dev !== after.dev || before.ino !== after.ino || before.size !== after.size || before.mtimeMs !== after.mtimeMs) {
452
- throw new Error("native persona manifest changed during read");
453
- }
454
- if (pathAfter.isSymbolicLink() || !pathAfter.isFile() || pathAfter.dev !== before.dev || pathAfter.ino !== before.ino) {
455
- throw new Error("native persona manifest was exchanged during read");
456
- }
457
- const displayName = manifestName(scope.host, content);
458
- if (!displayName) continue;
459
- const sourceBinding = `${scope.host}:${scope.scope}-agents/${entry.name}`;
460
- const subjectId = "manifest:" + digest([scope.host, scope.profileId, sourceBinding].join("\0")).slice(0, 32);
461
- bindings.push({ id: "persona-binding:native:" + digest(scope.id + "\0" + sourceBinding).slice(0, 24),
462
- authenticator: "host-manifest", issuer: scope.issuer, tenantId: scope.tenantId, host: scope.host,
463
- profileId: scope.profileId, subjectId, kind: scope.kind, displayName, sourceBinding, groupId: scope.groupId });
464
- } finally { await handle.close(); }
465
- }
466
- return bindings;
467
- }
468
-
469
- export async function loadPersonaRuntime(root = process.cwd(), providedCatalog = null) {
470
- const paths = await pathsFor(root, providedCatalog);
471
- const [policy, runtime] = await Promise.all([
472
- readJson(paths.personaPolicyPath, paths.catalog.root, normalizePolicy, emptyPolicy),
473
- readJson(paths.personaRuntimePath, paths.catalog.root, normalizeRuntime, emptyRuntime)
474
- ]);
475
- return { policy, runtime, ...paths };
476
- }
477
-
478
- export async function syncPersonaRosterFromEnvironment({
479
- root = process.cwd(), env = process.env, now = new Date(), catalog: providedCatalog = null
480
- } = {}) {
481
- const configured = env.AGENTSPINE_PERSONA_ROSTER_FILE;
482
- if (!configured) return { configured: false, changed: false };
483
- if (!isAbsolute(configured)) throw new Error("AGENTSPINE_PERSONA_ROSTER_FILE must be an absolute path");
484
- const catalog = providedCatalog || await buildCatalog(root);
485
- const supplied = await lstat(configured);
486
- if (supplied.isSymbolicLink() || !supplied.isFile()) throw new Error("persona roster must be a regular non-symlink file");
487
- const canonical = await realpath(configured);
488
- if (isInside(catalog.root, canonical)) throw new Error("persona roster must remain outside the agent project");
489
- const handle = await open(canonical, "r");
490
- let value;
491
- try {
492
- const metadata = await handle.stat();
493
- if (!metadata.isFile() || metadata.size > 1024 * 1024) throw new Error("persona roster exceeds its 1 MiB limit");
494
- value = JSON.parse(await handle.readFile("utf8"));
495
- } finally { await handle.close(); }
496
- if (!value || value.schema !== PERSONA_ROSTER_SCHEMA || !Number.isInteger(value.revision)
497
- || value.revision < 1 || !Array.isArray(value.bindings || []) || !Array.isArray(value.nativeDiscovery || [])) {
498
- throw new Error("persona roster envelope is invalid");
499
- }
500
- const nativeScopes = (value.nativeDiscovery || []).map(normalizeNativeDiscovery);
501
- const nativeBindings = (await Promise.all(nativeScopes.map((scope) => nativeManifestBindings(scope, catalog, env)))).flat();
502
- const bindings = [...(value.bindings || []), ...nativeBindings];
503
- const rosterScopes = nativeScopes.map((scope) => ({ authenticator: "host-manifest", issuer: scope.issuer,
504
- tenantId: scope.tenantId, host: scope.host, profileId: scope.profileId }));
505
- const result = await applyPersonaRoster({ root: catalog.root, bindings, rosterScopes,
506
- confirmation: CONFIRMATION, now: value.observedAt || now, catalog });
507
- return { configured: true, changed: !result.duplicate || result.graphReconciled,
508
- rosterChanged: !result.duplicate, graphReconciled: result.graphReconciled, graphChanges: result.graphChanges,
509
- revision: value.revision,
510
- personas: result.runtime.personas.length, nativeManifests: nativeBindings.length,
511
- rosterDigest: digest(JSON.stringify(value)) };
512
- }
513
-
514
- export async function inspectPersonaRuntime(root = process.cwd(), providedCatalog = null) {
515
- const paths = await pathsFor(root, providedCatalog);
516
- const errors = [];
517
- let policy = emptyPolicy(paths.catalog.root);
518
- let runtime = emptyRuntime(paths.catalog.root);
519
- try { policy = await readJson(paths.personaPolicyPath, paths.catalog.root, normalizePolicy, emptyPolicy); } catch (error) { errors.push("policy:" + error.message); }
520
- try { runtime = await readJson(paths.personaRuntimePath, paths.catalog.root, normalizeRuntime, emptyRuntime); } catch (error) { errors.push("runtime:" + error.message); }
521
- return { policy, runtime, errors, ...paths };
522
- }
523
-
524
- export function personaRuntimeFindings(policy, runtime, graph = null) {
525
- const findings = [];
526
- const bindingIds = new Set();
527
- const personaIds = new Set();
528
- for (const binding of policy.bindings) {
529
- if (!validBinding(binding)) findings.push("invalid-persona-binding:" + (binding?.id || "unknown"));
530
- if (bindingIds.has(binding.id)) findings.push("duplicate-persona-binding:" + binding.id);
531
- bindingIds.add(binding.id);
532
- }
533
- for (const persona of runtime.personas) {
534
- if (!validPersona(persona)) findings.push("invalid-persona:" + (persona?.personaId || "unknown"));
535
- if (personaIds.has(persona.personaId)) findings.push("duplicate-persona:" + persona.personaId);
536
- if (!bindingIds.has(persona.bindingId)) findings.push("orphan-persona:" + persona.personaId);
537
- if (graph) {
538
- const entity = graph.entities.find((item) => item.id === persona.personaId);
539
- const expectedKind = persona.kind === "bot" ? "agent" : persona.kind;
540
- if (!entity || entity.kind !== expectedKind) findings.push("persona-graph-mismatch:" + persona.personaId);
541
- if (entity?.attributes?.identityStatus !== persona.status) findings.push("persona-graph-status-mismatch:" + persona.personaId);
542
- const memberships = graph.entityEdges.filter((edge) => edge.from === persona.personaId && edge.relation === "member-of");
543
- const group = persona.groupId === null ? null : graph.entities.find((item) => item.id === persona.groupId);
544
- if (persona.status === "active" && persona.groupId !== null
545
- && (!group || group.kind !== "group" || group.privacy === "private")) {
546
- findings.push("persona-group-entity-mismatch:" + persona.personaId);
547
- }
548
- if (persona.status === "active" && persona.groupId !== null
549
- && !memberships.some((edge) => edge.to === persona.groupId && edge.privacy === "group")) {
550
- findings.push("persona-group-membership-mismatch:" + persona.personaId);
551
- }
552
- if (memberships.some((edge) => edge.to !== persona.groupId || persona.status !== "active")) {
553
- findings.push("persona-stale-group-membership:" + persona.personaId);
554
- }
555
- }
556
- personaIds.add(persona.personaId);
557
- }
558
- const eventIds = new Set();
559
- for (const event of runtime.events) {
560
- if (!validEvent(event) || !personaIds.has(event.personaId)) findings.push("invalid-persona-event:" + (event?.eventId || "unknown"));
561
- if (eventIds.has(event.eventId)) findings.push("duplicate-persona-event:" + event.eventId);
562
- eventIds.add(event.eventId);
563
- }
564
- const receiptIds = new Set();
565
- for (const receipt of runtime.receipts) {
566
- if (!validReceipt(receipt) || !eventIds.has(receipt.eventId)) findings.push("invalid-persona-receipt:" + (receipt?.id || "unknown"));
567
- if (receiptIds.has(receipt.id)) findings.push("duplicate-persona-receipt:" + receipt.id);
568
- receiptIds.add(receipt.id);
569
- }
570
- return findings;
571
- }
572
-
573
- export async function personaContext({ root = process.cwd(), personaId = null, groupId = undefined, includeInactive = false } = {}) {
574
- const { policy, runtime } = await loadPersonaRuntime(root);
575
- const findings = personaRuntimeFindings(policy, runtime);
576
- if (findings.length) throw new Error("persona runtime failed closed: " + findings.join(", "));
577
- const items = runtime.personas.filter((item) => (includeInactive || item.status === "active")
578
- && (personaId === null || item.personaId === exactId(personaId, "personaId"))
579
- && (groupId === undefined || item.groupId === exactId(groupId, "groupId", true)));
580
- return { schema: "agentspine.persona-context/v1", items: structuredClone(items), authority: "identity-state-only" };
581
- }