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,493 +0,0 @@
1
- import { buildCatalog, catalogForStateRoot } from "./catalog.js";
2
- import { resolveContext } from "./context.js";
3
- import { relationshipContext } from "./graph.js";
4
- import { learningContext } from "./learning.js";
5
- import { attentionContext } from "./attention.js";
6
- import { taskContext } from "./coordination.js";
7
- import { sharedContext } from "./sharing.js";
8
- import { loadPersonaRuntime, personaRuntimeFindings } from "./persona-runtime.js";
9
- import { gatewayRuntimeFindings, loadGatewayRuntime } from "./gateway-runtime.js";
10
- import { voiceCue } from "./voice-runtime.js";
11
- import { worldContext } from "./world-model.js";
12
- import { projectPortfolioContext } from "./project-portfolio.js";
13
-
14
- const MIN_BYTES = 4096;
15
- const MAX_BYTES = 262144;
16
-
17
- function integer(value, field, minimum, maximum) {
18
- const result = Number(value);
19
- if (!Number.isInteger(result) || result < minimum || result > maximum) {
20
- throw new Error(`${field} must be an integer between ${minimum} and ${maximum}`);
21
- }
22
- return result;
23
- }
24
-
25
- function compactBytes(value) {
26
- return Buffer.byteLength(JSON.stringify(value));
27
- }
28
-
29
- function normalizeKey(item) {
30
- return `${item.kind}\0${item.subjectId || ""}\0${item.claim.trim().toLowerCase()}`;
31
- }
32
-
33
- function sourceDescriptor(document, content = null) {
34
- return {
35
- path: document.relativePath,
36
- layer: document.effectiveLayer,
37
- sha256: document.sha256,
38
- bytes: document.bytes,
39
- loaded: content !== null,
40
- content,
41
- authority: document.authority
42
- };
43
- }
44
-
45
- function recalculateBudget(result) {
46
- for (let attempt = 0; attempt < 5; attempt += 1) {
47
- const usedBytes = compactBytes(result);
48
- const remainingBytes = Math.max(0, result.budget.maxBytes - usedBytes);
49
- if (result.budget.usedBytes === usedBytes && result.budget.remainingBytes === remainingBytes) break;
50
- result.budget.usedBytes = usedBytes;
51
- result.budget.remainingBytes = remainingBytes;
52
- }
53
- }
54
-
55
- function tryAdd(result, collection, item) {
56
- collection.push(item);
57
- recalculateBudget(result);
58
- if (result.budget.usedBytes <= result.budget.maxBytes - 128) return true;
59
- collection.pop();
60
- recalculateBudget(result);
61
- return false;
62
- }
63
-
64
- function trySet(result, object, key, item) {
65
- const previous = object[key];
66
- object[key] = item;
67
- recalculateBudget(result);
68
- if (result.budget.usedBytes <= result.budget.maxBytes - 128) return true;
69
- object[key] = previous;
70
- recalculateBudget(result);
71
- return false;
72
- }
73
-
74
- function countOmitted(result, section, count = 1) {
75
- result.budget.omitted[section] += count;
76
- recalculateBudget(result);
77
- }
78
-
79
- function matchesScope(item, entityId, projectId) {
80
- if (!entityId && !projectId) return item.subjectId === null;
81
- return item.subjectId === null || item.subjectId === entityId || item.subjectId === projectId;
82
- }
83
-
84
- function taskMatchesScope(task, entityId) {
85
- return !entityId || task.createdBy === entityId || task.assigneeId === entityId;
86
- }
87
-
88
- function voiceProfile(entity) {
89
- const value = entity?.attributes?.voice;
90
- if (!value || typeof value !== "object" || Array.isArray(value)) return {};
91
- const allowed = new Set(["warmth", "directness", "humor", "length", "rhythm", "formality"]);
92
- return Object.fromEntries(Object.entries(value)
93
- .filter(([key, item]) => allowed.has(key) && ["string", "number", "boolean"].includes(typeof item))
94
- .map(([key, item]) => [key, typeof item === "string" ? item.slice(0, 120) : item]));
95
- }
96
-
97
- function pick(value, keys) {
98
- return Object.fromEntries(keys.map((key) => [key, value[key]]));
99
- }
100
-
101
- function feedbackCandidates(values) {
102
- if (values.length < 3) return values.map((item) =>
103
- pick(item, ["id", "text", "provider", "digest", "session", "message", "at"]));
104
- const shared = ["provider", "digest", "session"].filter((key) =>
105
- values.every((item) => item[key] === values[0][key]));
106
- const fields = ["id", "text", "message", "at",
107
- ...["provider", "digest", "session"].filter((key) => !shared.includes(key))];
108
- const expected = { id: "assertion:user-feedback-", message: "timeline-event:" };
109
- const prefixes = fields.map((key) => {
110
- const prefix = expected[key] || (key === "at"
111
- && values.every((item) => /^\d{4}-\d{2}-\d{2}T\d{2}:/.test(item[key]))
112
- ? values[0][key].slice(0, 14) : "");
113
- return values.every((item) => item[key].startsWith(prefix)) ? prefix : "";
114
- });
115
- return { fields, common: Object.fromEntries(shared.map((key) => [key, values[0][key]])), prefixes,
116
- rows: values.map((item) => fields.map((key, index) => item[key].slice(prefixes[index].length))) };
117
- }
118
-
119
- function preAnswerRecall(world, currentTaskId) {
120
- if (!currentTaskId) return null;
121
- const task = [...(world.knowledge?.continuation?.tasks || []),
122
- ...(world.knowledge?.continuation?.terminal || [])]
123
- .find((item) => item.taskId === currentTaskId);
124
- if (!task) return null;
125
- const feedback = (world.knowledge?.taskContext?.items || []).filter((item) =>
126
- item?.source?.kind === "uninterpreted-user-message"
127
- && item.value?.targetAssertionId === task.assertionId)
128
- .sort((left, right) => right.observedAt.localeCompare(left.observedAt));
129
- const interpretations = (world.knowledge?.taskContext?.items || []).filter((item) =>
130
- item?.source?.kind === "model-suggestion"
131
- && ["agentspine.timeline-user-feedback-interpretation/v1",
132
- "agentspine.timeline-user-feedback-clarification/v2"].includes(item.value?.schema)
133
- && item.value?.targetAssertionId === task.assertionId);
134
- const taskValue = pick(task, ["taskId", "status", "objective"]);
135
- taskValue.lastVerifiedStep = task.lastVerifiedStep
136
- ? pick(task.lastVerifiedStep, ["summary", "result"]) : null;
137
- taskValue.nextStep = task.nextStep ? pick(task.nextStep, ["summary"]) : null;
138
- const values = feedback.slice(0, 3).map(({ id, value, source, observedAt }) => ({
139
- id,
140
- text: value.sourceText,
141
- status: value.interpretationStatus, completionVerified: value.completionVerified,
142
- provider: value.sourceProvider, digest: value.sourceDigest,
143
- session: source.sessionRef, message: source.messageRef, at: observedAt
144
- }));
145
- if (values.length && task.status === "completed" && task.source?.kind === "objective-measurement") {
146
- taskValue.completionEvidence = {
147
- status: "objective-verified", assertionId: task.assertionId, observedAt: task.observedAt,
148
- source: pick(task.source, ["kind", "id", "digest", "sessionRef", "messageRef"])
149
- };
150
- }
151
- if (!values.length) {
152
- Object.assign(taskValue, pick(task, ["assertionId", "observedAt"]));
153
- taskValue.source = pick(task.source, ["kind", "id", "digest", "sessionRef", "messageRef"]);
154
- taskValue.scope = pick(task.scope, ["projectId", "groupId", "privacy", "portalRef", "threadRef"]);
155
- taskValue.correctionStatus = task.source.kind === "explicit-user-feedback"
156
- ? "applied-source-verified" : "none-current";
157
- }
158
- if (values.length === 1) {
159
- const proposal = interpretations.find((item) =>
160
- item.value.sourceFeedbackAssertionId === feedback[0].id);
161
- if (proposal) {
162
- const value = proposal.value;
163
- const model = {
164
- status: value.interpretationStatus, kind: value.interpretationKind,
165
- nextStep: value.proposedNextStepSummary, question: value.clarificationQuestion,
166
- provider: value.modelProvider, replaces: value.replacedNextStepId,
167
- digest: proposal.source.digest, completionVerified: false
168
- };
169
- for (const key of ["nextStep", "question"]) {
170
- if (model[key] === null) delete model[key];
171
- }
172
- values[0].modelInterpretation = model;
173
- }
174
- }
175
- return {
176
- schema: "agentspine.pre-answer-recall/v1",
177
- order: "review-before-claims-and-actions",
178
- task: taskValue,
179
- ...(values.length === 1 ? { feedback: values[0], ...(task.status === "completed" ? {} : {
180
- interpretationInput: { feedbackAssertionId: feedback[0].id,
181
- targetAssertionId: feedback[0].value.targetAssertionId }
182
- }) } : {}),
183
- ...(values.length > 1 ? { feedbackCandidates: feedbackCandidates(values),
184
- feedbackReview: { status: "multiple-unresolved", completionVerified: false,
185
- targetAssertionId: feedback[0].value.targetAssertionId,
186
- ...(() => {
187
- const ids = feedback.slice(0, 3).map((item) => item.id).sort();
188
- const proposal = interpretations.find((item) => item.value?.schema
189
- === "agentspine.timeline-user-feedback-clarification/v2"
190
- && JSON.stringify(item.value.sourceBindings.map((source) => source.feedbackAssertionId))
191
- === JSON.stringify(ids));
192
- return proposal ? { modelClarification: { status: proposal.value.interpretationStatus,
193
- question: proposal.value.clarificationQuestion, provider: proposal.value.modelProvider,
194
- replaces: proposal.value.replacedNextStepId, digest: proposal.source.digest,
195
- completionVerified: false } } : {};
196
- })(),
197
- ...(feedback.length > 3 ? { omitted: feedback.length - 3 } : {}) } } : {}),
198
- authority: "context-only"
199
- };
200
- }
201
-
202
- async function settleReads(promises) {
203
- const settled = await Promise.allSettled(promises);
204
- const failed = settled.find((item) => item.status === "rejected");
205
- if (failed) throw failed.reason;
206
- return settled.map((item) => item.value);
207
- }
208
-
209
- export async function sessionBriefing({
210
- root = process.cwd(), cwd = root, host = "generic", entityId = null,
211
- userId = null, tenantId = null, groupId = null, projectId = null, currentTaskId = null,
212
- portalRef = null, threadRef = null,
213
- includePrivate = false, focusActive = true, includeSourceContent = true,
214
- maxBytes = 16384, now = new Date(), catalog: providedCatalog = null, userStateRoot = null,
215
- sourceDiagnostics = null, prompt = null, preAnswer = false
216
- } = {}) {
217
- const limit = integer(maxBytes, "maxBytes", MIN_BYTES, MAX_BYTES);
218
- if (!new Set(["codex", "claude", "generic"]).has(host)) throw new Error(`unsupported host: ${host}`);
219
- if (groupId !== null && includePrivate) throw new Error("private context cannot be assembled for a group audience");
220
-
221
- const catalog = providedCatalog || await buildCatalog(root);
222
- const sources = await resolveContext({
223
- root: catalog.root, cwd, host, maxBytes: limit,
224
- includeContent: includeSourceContent && groupId === null,
225
- catalog
226
- });
227
- const portableRelationship = Boolean(entityId && userStateRoot && userStateRoot !== catalog.root);
228
- const userCatalog = userStateRoot && userStateRoot !== catalog.root
229
- ? catalogForStateRoot(catalog, userStateRoot) : catalog;
230
- const learningScope = {
231
- personaId: entityId, userId, tenantId, projectId, groupId, taskId: currentTaskId
232
- };
233
- const relationship = entityId
234
- ? await relationshipContext(userStateRoot && userStateRoot !== catalog.root
235
- ? { root: userStateRoot, entityId, includePrivate, groupId, catalog: userCatalog }
236
- : { root: catalog.root, entityId, includePrivate, groupId, catalog })
237
- : null;
238
- const [learned, attention, tasks, shared, userLearned, personas, gateway, world, portfolio] = await settleReads([
239
- learningContext({ root: catalog.root, includePrivate, groupId, scope: learningScope, maxItems: 50,
240
- catalog, now, taskFocus: currentTaskId }),
241
- attentionContext({
242
- root: catalog.root, includePrivate, entityId, groupId, projectId, currentTaskId,
243
- focusActive, markPresented: false, maxItems: 20, now, catalog
244
- }),
245
- taskContext({ root: catalog.root, includePrivate, groupId, projectId, includeClosed: false, maxItems: 100, catalog }),
246
- sharedContext({ root: catalog.root, includePrivate, groupId, maxItems: 50, catalog }),
247
- userStateRoot && userStateRoot !== catalog.root
248
- ? learningContext({ root: userStateRoot, includePrivate, groupId, scope: learningScope, maxItems: 50, now,
249
- catalog: userCatalog, taskFocus: currentTaskId })
250
- : Promise.resolve({ items: [] }),
251
- loadPersonaRuntime(catalog.root, catalog),
252
- loadGatewayRuntime(catalog.root, catalog),
253
- worldContext({ root: catalog.root, projectId, groupId, includePrivate, portalRef, threadRef,
254
- continuationTaskId: currentTaskId, maxItems: 50, now }),
255
- tenantId ? projectPortfolioContext({ root: catalog.root, tenantId, groupId, markPresented: false, now })
256
- : Promise.resolve({ projects: [], observations: [], notice: null, rateLimited: false })
257
- ]);
258
- const personaFindings = personaRuntimeFindings(personas.policy, personas.runtime);
259
- if (personaFindings.length) throw new Error(`persona runtime failed closed: ${personaFindings.join(", ")}`);
260
- const registeredPersona = entityId ? personas.runtime.personas.find((item) => item.personaId === entityId) : null;
261
- if (registeredPersona && registeredPersona.status !== "active") throw new Error(`persona is not active in the authenticated roster: ${entityId}`);
262
- if (registeredPersona && groupId !== null && registeredPersona.groupId !== groupId) {
263
- throw new Error(`persona is not visible in the exact group scope: ${entityId}`);
264
- }
265
- const gatewayFindings = gatewayRuntimeFindings(gateway.policy, gateway.runtime);
266
- if (gatewayFindings.length) throw new Error(`gateway runtime failed closed: ${gatewayFindings.join(", ")}`);
267
- const compactFeedbackRecall = !preAnswer && currentTaskId
268
- && world.knowledge.taskContext.items.filter((item) => item.predicate === "task.user-feedback").length >= 3;
269
-
270
- const result = {
271
- schema: "agentspine.session-briefing/v1",
272
- ...(preAnswer ? {} : { root: catalog.root, cwd: sources.cwd }),
273
- host,
274
- scope: { entityId, userId, tenantId, groupId, projectId, includePrivate,
275
- ...(portalRef && threadRef ? { portalRef, threadRef } : {}) },
276
- focus: { active: Boolean(focusActive), currentTaskId },
277
- sources: { documents: [], diagnostics: sourceDiagnostics },
278
- tasks: [],
279
- relationship: relationship ? {
280
- status: relationship.status || "loaded",
281
- reason: relationship.reason || null,
282
- entity: null,
283
- relatedEntities: [],
284
- edges: []
285
- } : null,
286
- voiceBrief: {
287
- schema: "agentspine.voice-brief/v1",
288
- personaId: entityId,
289
- displayName: null,
290
- language: null,
291
- profile: {},
292
- personaSources: [],
293
- preferences: [],
294
- corrections: [],
295
- noGos: [],
296
- currentTask: null,
297
- currentGoal: null,
298
- activeSignals: [],
299
- cue: voiceCue(prompt),
300
- guidance: [
301
- "Use scoped facts first; be honest; never claim consciousness; heed corrections; own errors."
302
- ],
303
- authority: "context-only"
304
- },
305
- learning: [],
306
- shared: [],
307
- ...(preAnswer || compactFeedbackRecall
308
- ? { preAnswerRecall: preAnswerRecall(world, currentTaskId) } : {}),
309
- world: {
310
- schema: world.schema,
311
- facts: [], conflicts: [], proposals: [], stale: [],
312
- ...(world.knowledge.current.length ? { knowledge: {
313
- schema: world.knowledge.schema, current: [], counts: world.knowledge.counts,
314
- continuation: { ...world.knowledge.continuation, tasks: [], terminal: [] },
315
- taskContext: { ...world.knowledge.taskContext, items: [] },
316
- omitted: { ...world.knowledge.omitted }, authority: "context-only"
317
- } } : {}),
318
- uncertainty: world.uncertainty,
319
- authority: "context-only"
320
- },
321
- attention: { suppressed: attention.suppressed, items: [] },
322
- portfolio: { projects: [], observations: [], notice: portfolio.notice, rateLimited: portfolio.rateLimited, authority: "context-only" },
323
- budget: {
324
- maxBytes: limit,
325
- usedBytes: 0,
326
- remainingBytes: 0,
327
- measurement: "compact-json-utf8",
328
- omitted: { sources: 0, tasks: 0, relationships: 0, voice: 0, learning: 0, shared: 0, world: 0, attention: 0, portfolio: 0 }
329
- },
330
- authority: "context-only"
331
- };
332
- recalculateBudget(result);
333
- if (result.budget.usedBytes > limit) throw new Error(`maxBytes is too small for the briefing envelope; use at least ${MIN_BYTES}`);
334
-
335
- const portableKinds = new Set(["preference", "no-go", "correction", "reference"]);
336
- const portableItems = userLearned.items.filter((item) => portableKinds.has(item.kind) && matchesScope(item, entityId, null));
337
- const localItems = [...portableItems, ...learned.items.filter((item) => matchesScope(item, entityId, projectId))];
338
- const attemptedLearning = new Set();
339
-
340
- const continuationIds = new Set([
341
- ...world.knowledge.continuation.tasks.map((item) => item.assertionId),
342
- ...world.knowledge.continuation.terminal.map((item) => item.assertionId)
343
- ]);
344
- for (const [items, key] of [[world.knowledge.continuation.tasks, "tasks"],
345
- [world.knowledge.continuation.terminal, "terminal"]]) {
346
- for (const item of items) {
347
- if (preAnswer || !tryAdd(result, result.world.knowledge.continuation[key], item)) countOmitted(result, "world");
348
- }
349
- }
350
- const contextualIds = new Set([...continuationIds, ...world.knowledge.current
351
- .filter((item) => ["task.user-feedback", "task.user-feedback-interpretation"]
352
- .includes(item.predicate)).map((item) => item.id)]);
353
- for (const item of world.knowledge.taskContext.items) {
354
- contextualIds.add(item.id);
355
- if (preAnswer || (compactFeedbackRecall
356
- && ["task.user-feedback", "task.user-feedback-interpretation"].includes(item.predicate))) {
357
- result.world.knowledge.taskContext.omitted += 1;
358
- countOmitted(result, "world");
359
- } else if (!tryAdd(result, result.world.knowledge.taskContext.items, item)) {
360
- result.world.knowledge.taskContext.omitted += 1;
361
- countOmitted(result, "world");
362
- }
363
- }
364
- for (const item of localItems.filter((entry) => entry.relevance)) {
365
- attemptedLearning.add(item);
366
- if (!tryAdd(result, result.learning, item)) countOmitted(result, "learning");
367
- }
368
- for (const section of ["facts", "conflicts", "proposals", "stale"]) {
369
- const items = section === "facts"
370
- ? world[section].filter((item) => !item.assertionIds?.some((id) => contextualIds.has(id)))
371
- : world[section].filter((item) => !contextualIds.has(item.id));
372
- for (const item of items) {
373
- if (!tryAdd(result, result.world[section], item)) countOmitted(result, "world");
374
- }
375
- }
376
- for (const item of world.knowledge.current.filter((entry) => !contextualIds.has(entry.id))) {
377
- if (!tryAdd(result, result.world.knowledge.current, item)) {
378
- result.world.knowledge.omitted.current += 1;
379
- countOmitted(result, "world");
380
- }
381
- }
382
-
383
- const scopedTasks = tasks.items.filter((task) => taskMatchesScope(task, entityId));
384
- const continuedTask = [...world.knowledge.continuation.tasks, ...world.knowledge.continuation.terminal]
385
- .find((task) => task.taskId === currentTaskId) || null;
386
- if (currentTaskId && !scopedTasks.some((task) => task.id === currentTaskId) && !continuedTask) {
387
- throw new Error(`current task is not visible in this briefing scope: ${currentTaskId}`);
388
- }
389
- const orderedTasks = [...scopedTasks].sort((left, right) => {
390
- if (left.id === currentTaskId) return -1;
391
- if (right.id === currentTaskId) return 1;
392
- return right.priority - left.priority || left.id.localeCompare(right.id);
393
- });
394
- for (const task of orderedTasks) {
395
- if (!tryAdd(result, result.tasks, task)) countOmitted(result, "tasks");
396
- }
397
- const focusedTask = orderedTasks.find((task) => task.id === currentTaskId) || orderedTasks[0] || null;
398
- if (focusedTask && !trySet(result, result.voiceBrief, "currentTask", {
399
- id: focusedTask.id, title: focusedTask.title, status: focusedTask.status
400
- })) countOmitted(result, "voice");
401
- if (!focusedTask && continuedTask && !trySet(result, result.voiceBrief, "currentTask", {
402
- id: continuedTask.taskId, title: continuedTask.objective, status: continuedTask.status,
403
- nextStep: continuedTask.nextStep
404
- })) countOmitted(result, "voice");
405
- const focusedGoal = entityId ? gateway.policy.goals.find((goal) => goal.agentId === entityId && goal.status === "active"
406
- && (projectId === null || goal.projectId === projectId) && goal.groupId === groupId) : null;
407
- if (focusedGoal && !trySet(result, result.voiceBrief, "currentGoal", {
408
- goalId: focusedGoal.goalId, successCriterion: focusedGoal.successCriterion,
409
- nextSafeStep: focusedGoal.nextSafeStep, deadline: focusedGoal.deadline,
410
- heartbeatAt: focusedGoal.heartbeatAt, blocker: focusedGoal.blocker
411
- })) countOmitted(result, "voice");
412
-
413
- if (registeredPersona) {
414
- if (!trySet(result, result.voiceBrief, "displayName", registeredPersona.displayName)) countOmitted(result, "voice");
415
- const binding = personas.policy.bindings.find((item) => item.id === registeredPersona.bindingId && item.active);
416
- if (binding?.sourceBinding && !tryAdd(result, result.voiceBrief.personaSources, binding.sourceBinding)) countOmitted(result, "voice");
417
- }
418
-
419
- if (relationship && relationship.status !== "degraded") {
420
- if (!trySet(result, result.relationship, "entity", relationship.entity)) countOmitted(result, "relationships");
421
- if (!registeredPersona && !trySet(result, result.voiceBrief, "displayName", relationship.entity.displayName || null)) countOmitted(result, "voice");
422
- const language = typeof relationship.entity.attributes?.language === "string"
423
- ? relationship.entity.attributes.language.slice(0, 40) : null;
424
- if (!trySet(result, result.voiceBrief, "language", language)) countOmitted(result, "voice");
425
- if (!trySet(result, result.voiceBrief, "profile", voiceProfile(relationship.entity))) countOmitted(result, "voice");
426
- if (!portableRelationship) {
427
- for (const entity of relationship.relatedEntities.filter((item) => item.id !== entityId)) {
428
- if (!tryAdd(result, result.relationship.relatedEntities, entity)) countOmitted(result, "relationships");
429
- }
430
- for (const edge of relationship.edges) {
431
- if (!tryAdd(result, result.relationship.edges, edge)) countOmitted(result, "relationships");
432
- }
433
- }
434
- }
435
-
436
- const voiceCollections = {
437
- preference: result.voiceBrief.preferences,
438
- correction: result.voiceBrief.corrections,
439
- "no-go": result.voiceBrief.noGos
440
- };
441
- for (const item of localItems.filter((entry) => voiceCollections[entry.kind]).slice(0, 12)) {
442
- if (!tryAdd(result, voiceCollections[item.kind], item.claim)) countOmitted(result, "voice");
443
- }
444
- const localKeys = new Set(localItems.map(normalizeKey));
445
- for (const item of localItems.filter((entry) => !attemptedLearning.has(entry))) {
446
- if (!tryAdd(result, result.learning, item)) countOmitted(result, "learning");
447
- }
448
- for (const item of shared.items.filter((entry) => matchesScope(entry, entityId, projectId))) {
449
- if (localKeys.has(normalizeKey(item))) {
450
- countOmitted(result, "shared");
451
- continue;
452
- }
453
- if (!tryAdd(result, result.shared, item)) countOmitted(result, "shared");
454
- }
455
-
456
- const sourceByteCap = Math.min(8192, Math.floor(limit / 2));
457
- let sourceBytes = 0;
458
- const personaLayers = new Set(["soul", "identity", "voice", "conduct"]);
459
- for (const document of sources.documents.filter((item) => personaLayers.has(item.effectiveLayer))) {
460
- if (!tryAdd(result, result.voiceBrief.personaSources, document.relativePath)) countOmitted(result, "voice");
461
- }
462
- for (const document of sources.documents) {
463
- const mayLoad = document.loaded && document.content !== null && sourceBytes + document.bytes <= sourceByteCap;
464
- const loaded = mayLoad ? sourceDescriptor(document, document.content) : null;
465
- if (loaded && tryAdd(result, result.sources.documents, loaded)) {
466
- sourceBytes += document.bytes;
467
- continue;
468
- }
469
- if (tryAdd(result, result.sources.documents, sourceDescriptor(document))) {
470
- if (includeSourceContent) countOmitted(result, "sources");
471
- } else countOmitted(result, "sources");
472
- }
473
-
474
- const attentionItems = attention.items.filter((item) => !entityId || item.entityId === null || item.entityId === entityId);
475
- for (const item of attentionItems.filter((entry) => ["promise", "blocker"].includes(entry.kind)).slice(0, 6)) {
476
- if (!tryAdd(result, result.voiceBrief.activeSignals, {
477
- kind: item.kind, summary: item.summary, taskId: item.taskId || null, dueAt: item.dueAt || null
478
- })) countOmitted(result, "voice");
479
- }
480
- for (const item of attentionItems) {
481
- if (!tryAdd(result, result.attention.items, item)) countOmitted(result, "attention");
482
- }
483
- for (const item of portfolio.projects) {
484
- if (!tryAdd(result, result.portfolio.projects, item)) countOmitted(result, "portfolio");
485
- }
486
- for (const item of portfolio.observations) {
487
- if (!tryAdd(result, result.portfolio.observations, item)) countOmitted(result, "portfolio");
488
- }
489
-
490
- recalculateBudget(result);
491
- if (result.budget.usedBytes > limit) throw new Error("briefing budget invariant failed");
492
- return result;
493
- }
@@ -1,51 +0,0 @@
1
- import { createHash } from "node:crypto";
2
- import { constants } from "node:fs";
3
- import { lstat, open, realpath } from "node:fs/promises";
4
- import { relative, resolve } from "node:path";
5
- import { canonicalPath, isInside } from "./paths.js";
6
-
7
- function sameFile(a, b) {
8
- return a.dev === b.dev && a.ino === b.ino && a.size === b.size
9
- && a.mtimeMs === b.mtimeMs && a.ctimeMs === b.ctimeMs;
10
- }
11
-
12
- export async function readCatalogDocument({ root, catalog, path, offset = 0, length = 65536 }) {
13
- if (catalog.root !== await canonicalPath(root)) throw new Error("catalog belongs to a different project root");
14
- const absolute = resolve(catalog.root, path);
15
- const document = catalog.documents.find(item => item.relativePath === path
16
- || (isInside(catalog.root, absolute) && item.path === absolute));
17
- if (!document) throw new Error("path is not an indexed Markdown document in the bounded host sources");
18
- const before = await lstat(document.path);
19
- if (!before.isFile() || before.isSymbolicLink() || before.size !== document.bytes
20
- || before.size > 4 * 1024 * 1024 || await realpath(document.path) !== document.path) {
21
- throw new Error("indexed contract source changed before reading");
22
- }
23
- const handle = await open(document.path, constants.O_RDONLY | (constants.O_NOFOLLOW || 0));
24
- let buffer;
25
- try {
26
- if (!sameFile(before, await handle.stat())) throw new Error("indexed contract source was replaced");
27
- // A concurrent append must not turn this bounded read into an unbounded one.
28
- buffer = Buffer.alloc(before.size + 1);
29
- let bytesRead = 0;
30
- while (bytesRead < buffer.length) {
31
- const result = await handle.read(buffer, bytesRead, buffer.length - bytesRead, bytesRead);
32
- if (!result.bytesRead) break;
33
- bytesRead += result.bytesRead;
34
- }
35
- buffer = buffer.subarray(0, bytesRead);
36
- if (!sameFile(before, await handle.stat()) || !sameFile(before, await lstat(document.path))
37
- || await realpath(document.path) !== document.path
38
- || createHash("sha256").update(buffer).digest("hex") !== document.sha256) {
39
- throw new Error("indexed contract source changed during reading");
40
- }
41
- } finally {
42
- await handle.close();
43
- }
44
- const start = Math.min(buffer.length, Math.max(0, Number(offset) || 0));
45
- const end = Math.min(buffer.length, start + Math.max(0, Number(length) || 0));
46
- return { path: isInside(catalog.root, document.path)
47
- ? relative(catalog.root, document.path).replaceAll("\\", "/") : document.relativePath,
48
- sha256: document.sha256, offset: start, bytes: end - start, totalBytes: buffer.length,
49
- eof: end >= buffer.length, encoding: "utf8", content: buffer.subarray(start, end).toString("utf8"),
50
- contentBase64: buffer.subarray(start, end).toString("base64") };
51
- }