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,478 +0,0 @@
1
- import { validateCodexTimelineHeader } from "./session-timeline-codex.js";
2
- import { validateKingTimelineHeader } from "./session-timeline-king.js";
3
- import { timelineProtocolFromRuntime, validTimelineHost } from "./session-timeline-provider.js";
4
- import { createHash } from "node:crypto";
5
- import { isAbsolute } from "node:path";
6
- import { canonicalPath } from "./paths.js";
7
- import { withOwnedFileLock } from "./owned-file-lock.js";
8
- import {
9
- privateEnrollmentPaths, readPrivateEnrollmentState, savePrivateEnrollmentState
10
- } from "./session-timeline-enrollment-storage.js";
11
- import {
12
- normalizePrivateTimelineSource, PRIVATE_TIMELINE_PREFIX_BYTES, privateTimelinePrefixDigest
13
- } from "./session-timeline-enrollment-source.js";
14
- import {
15
- hostReceiptId, hostReceiptResult, hostReceiptUnavailable, makeHostTranscriptReceipt, MAX_PENDING_RECEIPTS,
16
- PRIVATE_TIMELINE_HOST_RECEIPT_ORIGIN, PRIVATE_TIMELINE_HOST_RECEIPT_SCHEMA, purgeExpiredHostReceipts,
17
- sameHostReceiptSource, sameIssuedHostTranscriptEvent, validHostTranscriptReceipt
18
- } from "./session-timeline-host-receipt.js";
19
- import {
20
- completeTimelineBinding, hasTimelineGroupScope, sameTimelineBinding, sessionTimelineBinding,
21
- safeTimelineId, TIMELINE_ID_RE, validTimelineBinding
22
- } from "./session-timeline-contract.js";
23
- import { sameTimelineTransportDigest, timelineTransportDigest, validTimelineTransportDigest } from "./session-timeline-transport.js";
24
- import {
25
- sameSessionTimelineSourceLocation, sourcePath, validSessionTimelineSourceMetadata
26
- } from "./session-timeline-source.js";
27
- import { validVerifiedTimelineHostOrigin } from "./session-timeline-host-origin.js";
28
- import { sessionTimelineRootDigest } from "./session-timeline-root.js";
29
-
30
- export const PRIVATE_TIMELINE_ENROLLMENT_SCHEMA = "agentspine.session-timeline-private-enrollment/v1";
31
- export { PRIVATE_TIMELINE_HOST_RECEIPT_ORIGIN, PRIVATE_TIMELINE_HOST_RECEIPT_SCHEMA } from "./session-timeline-host-receipt.js";
32
- export const LOCAL_TIMELINE_ENROLLMENT_CONFIRMATION = "local-owner-confirmed";
33
- export const LOCAL_TIMELINE_ENROLLMENT_RECOVERY_CONFIRMATION = "local-owner-confirmed-timeline-enrollment-recovery";
34
- export const DEFAULT_TIMELINE_ENROLLMENT_TTL_MS = 8 * 60 * 60 * 1000;
35
- export const MAX_TIMELINE_ENROLLMENT_TTL_MS = 12 * 60 * 60 * 1000;
36
-
37
- const AUTHORITY = "context-only";
38
- const TIMELINE_VISIBILITY = "private-verified";
39
- const HEAD_SCHEMA = "agentspine.session-timeline-private-enrollment-head/v1";
40
- const HEAD_AUTHORITY = "state-integrity-only";
41
- const MAX_STATE_BYTES = 256 * 1024;
42
- const MAX_ENROLLMENTS = 16;
43
- function canonical(value) {
44
- if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`;
45
- if (value && typeof value === "object") {
46
- return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${canonical(value[key])}`).join(",")}}`;
47
- }
48
- return JSON.stringify(value);
49
- }
50
-
51
- function digest(value) { return createHash("sha256").update(value).digest("hex"); }
52
- function validSignature(value) { return /^[a-f0-9]{64}$/.test(value || ""); }
53
- function validGeneration(value) { return Number.isSafeInteger(value) && value > 0; }
54
- function validDate(value) { return Number.isFinite(new Date(value).getTime()); }
55
- function date(value) {
56
- const parsed = value instanceof Date ? value : new Date(value);
57
- return Number.isFinite(parsed.getTime()) ? parsed : null;
58
- }
59
-
60
- function runtimeDate(clock) {
61
- try { return date(typeof clock === "function" ? clock() : new Date()); }
62
- catch { return null; }
63
- }
64
-
65
- function enrollmentTtl(value) {
66
- return Number.isInteger(value) && value >= 60 * 1000 && value <= MAX_TIMELINE_ENROLLMENT_TTL_MS ? value : null;
67
- }
68
-
69
- function unavailable(reason) {
70
- return {
71
- schema: PRIVATE_TIMELINE_ENROLLMENT_SCHEMA, status: "unavailable", reason,
72
- binding: null, source: null, sourceDigest: null, expiresAt: null,
73
- enrollmentDigest: null, timelineVisibility: null, authority: AUTHORITY
74
- };
75
- }
76
-
77
- function empty(root) {
78
- return {
79
- schema: PRIVATE_TIMELINE_ENROLLMENT_SCHEMA, rootDigest: sessionTimelineRootDigest(root),
80
- enrollments: [], pendingReceipts: [], generation: 0, previousSignature: null, authority: AUTHORITY
81
- };
82
- }
83
-
84
- function sourceMetadata(source) {
85
- return {
86
- path: source?.path, profileRoot: source?.profileRoot, projectsRoot: source?.projectsRoot,
87
- pathDigest: source?.pathDigest, identity: source?.identity,
88
- size: source?.size, mtimeNs: source?.mtimeNs, ctimeNs: source?.ctimeNs
89
- };
90
- }
91
-
92
- function validSource(source) {
93
- return validSessionTimelineSourceMetadata(sourceMetadata(source))
94
- && Number.isSafeInteger(source.prefixBytes) && source.prefixBytes >= 0 && source.prefixBytes <= PRIVATE_TIMELINE_PREFIX_BYTES
95
- && /^[a-f0-9]{64}$/.test(source.prefixDigest || "")
96
- && source.commitment === null;
97
- }
98
-
99
- function sourceDigest(source) {
100
- return digest(`${source.pathDigest}\0${source.identity}\0${source.profileRoot}\0${source.projectsRoot}\0${source.size}\0${source.mtimeNs}\0${source.ctimeNs}\0${source.prefixDigest}\0lazy-snapshot/v1`);
101
- }
102
-
103
- function sameSource(left, right) { return sameSessionTimelineSourceLocation(sourceMetadata(left), sourceMetadata(right)); }
104
-
105
- function sameSourceSnapshot(left, right) {
106
- const first = sourceMetadata(left);
107
- const second = sourceMetadata(right);
108
- return validSessionTimelineSourceMetadata(first) && validSessionTimelineSourceMetadata(second)
109
- && ["path", "profileRoot", "projectsRoot", "pathDigest", "identity", "size", "mtimeNs", "ctimeNs"]
110
- .every((key) => first[key] === second[key]);
111
- }
112
-
113
- function enrollmentId(root, binding, source) {
114
- return `timeline-enrollment:${digest(canonical({ rootDigest: sessionTimelineRootDigest(root), binding, sourceDigest: sourceDigest(source) })).slice(0, 32)}`;
115
- }
116
-
117
- function enrollmentDigest(root, binding, source, expiresAt, transportDigest) {
118
- return digest(canonical({ rootDigest: sessionTimelineRootDigest(root), binding, sourceDigest: sourceDigest(source), expiresAt,
119
- transportDigest, confirmation: LOCAL_TIMELINE_ENROLLMENT_CONFIRMATION, timelineVisibility: TIMELINE_VISIBILITY }));
120
- }
121
-
122
- function validEnrollment(value, root) {
123
- return value && TIMELINE_ID_RE.test(value.id || "") && validTimelineBinding(value.binding)
124
- && completeTimelineBinding(value.binding) && value.binding.groupId === null && validSource(value.source)
125
- && validDate(value.confirmedAt) && validDate(value.expiresAt) && value.timelineVisibility === TIMELINE_VISIBILITY
126
- && value.confirmation === LOCAL_TIMELINE_ENROLLMENT_CONFIRMATION && value.authority === AUTHORITY
127
- && validTimelineTransportDigest(value.transportDigest)
128
- && value.id === enrollmentId(root, value.binding, value.source)
129
- && value.enrollmentDigest === enrollmentDigest(root, value.binding, value.source, value.expiresAt, value.transportDigest)
130
- && value.append === undefined;
131
- }
132
-
133
- function unambiguousEnrollments(enrollments) {
134
- const keys = new Set();
135
- for (const record of enrollments) {
136
- const key = [record.binding.host, record.binding.sessionId, sourceDigest(record.source)].join("\0");
137
- if (keys.has(key)) return false;
138
- keys.add(key);
139
- }
140
- return true;
141
- }
142
-
143
- function validate(state, root) {
144
- const receipts = state?.pendingReceipts === undefined ? [] : state.pendingReceipts;
145
- if (!state || state.schema !== PRIVATE_TIMELINE_ENROLLMENT_SCHEMA || state.rootDigest !== sessionTimelineRootDigest(root)
146
- || state.authority !== AUTHORITY || !Array.isArray(state.enrollments)
147
- || !validGeneration(state.generation) || !validSignature(state.signature)
148
- || (state.generation === 1 ? state.previousSignature !== null : !validSignature(state.previousSignature))
149
- || state.enrollments.length > MAX_ENROLLMENTS || !state.enrollments.every((item) => validEnrollment(item, root))
150
- || !unambiguousEnrollments(state.enrollments) || !Array.isArray(receipts) || receipts.length > MAX_PENDING_RECEIPTS
151
- || !receipts.every((item) => validHostTranscriptReceipt(item, root))
152
- || new Set(receipts.map((item) => item.id)).size !== receipts.length) {
153
- throw new Error("private timeline enrollment state is invalid");
154
- }
155
- return state;
156
- }
157
-
158
- function stateRoot(root) { return { value: root, digest: sessionTimelineRootDigest(root) }; }
159
-
160
- async function enrollmentPaths(root, options = {}) {
161
- return privateEnrollmentPaths(root, options);
162
- }
163
-
164
- async function readState(path, headPath, root, assertStable, assertOwned = null) {
165
- const state = await readPrivateEnrollmentState({
166
- path, headPath, root: stateRoot(root), assertStable, assertOwned, empty, validate,
167
- headSchema: HEAD_SCHEMA, headAuthority: HEAD_AUTHORITY, maximumBytes: MAX_STATE_BYTES
168
- });
169
- if (!Array.isArray(state.pendingReceipts)) state.pendingReceipts = [];
170
- return state;
171
- }
172
-
173
- async function saveState(state, path, headPath, root, assertOwned, assertStable) {
174
- await savePrivateEnrollmentState({
175
- state, path, headPath, root: stateRoot(root), assertOwned, assertStable,
176
- headSchema: HEAD_SCHEMA, headAuthority: HEAD_AUTHORITY, maximumBytes: MAX_STATE_BYTES
177
- });
178
- }
179
-
180
- async function loadStateWithRecovery(rootPath, { create = false } = {}) {
181
- const names = await enrollmentPaths(rootPath, { create });
182
- try {
183
- return { names, state: await readState(names.path, names.headPath, rootPath, names.assertStable) };
184
- } catch {
185
- const state = await withOwnedFileLock(names.lock, async ({ assertOwned }) => readState(
186
- names.path, names.headPath, rootPath, names.assertStable, assertOwned
187
- ), { assertPath: names.assertStable });
188
- return { names, state };
189
- }
190
- }
191
-
192
- function validHostReceiptInput({ host, sessionId, scope }) {
193
- const binding = sessionTimelineBinding({ host, sessionId, scope });
194
- if (!validTimelineHost(host)) return { reason: "unknown-timeline-host" };
195
- if (scope?.groupId !== null || hasTimelineGroupScope(scope)) return { reason: "group-suppressed" };
196
- if (!completeTimelineBinding(binding) || binding.groupId !== null) return { reason: "missing-or-unknown-session-scope" };
197
- return { binding };
198
- }
199
-
200
- function validResolverInput({ host, sessionId }) {
201
- if (!validTimelineHost(host)) return null;
202
- return safeTimelineId(sessionId);
203
- }
204
-
205
- async function canonicalRoot(root) {
206
- if (typeof root !== "string" || !root) return null;
207
- try { return await canonicalPath(root); }
208
- catch { return null; }
209
- }
210
-
211
- export async function issueHostTranscriptReceipt({
212
- root, host, sessionId, scope, transcriptPath, hostHome, event, eventId = null,
213
- hostOrigin = null, clock = null, environment = process.env
214
- }) {
215
- const current = runtimeDate(clock);
216
- if (!current) return hostReceiptUnavailable("invalid-host-receipt-time");
217
- if (event !== "UserPromptSubmit") return hostReceiptUnavailable("host-receipt-event-not-supported");
218
- const rootPath = await canonicalRoot(root);
219
- if (!rootPath) return hostReceiptUnavailable("unknown-project-root");
220
- const input = validHostReceiptInput({ host, sessionId, scope });
221
- if (!input.binding) return hostReceiptUnavailable(input.reason);
222
- const hookInput = { transcript_path: transcriptPath, event_id: eventId,
223
- protocol_version: timelineProtocolFromRuntime(host, environment) };
224
- if (!validVerifiedTimelineHostOrigin({ origin: hostOrigin, root: rootPath, input: hookInput,
225
- binding: input.binding, hostHome, event })) return hostReceiptUnavailable("host-lifecycle-receipt-required");
226
- const transportDigest = timelineTransportDigest({ root: rootPath, binding: input.binding, environment });
227
- if (!transportDigest) return hostReceiptUnavailable("local-transport-capability-required");
228
- const source = await sourcePath(transcriptPath, hostHome, host);
229
- if (source.status !== "registered") return hostReceiptUnavailable(source.reason || "transcript-unavailable");
230
- if (host === "codex" && !await validateCodexTimelineHeader({ source, root: rootPath, sessionId })) {
231
- return hostReceiptUnavailable("codex-history-format-or-binding-mismatch");
232
- }
233
- if (host === "king" && !await validateKingTimelineHeader({ source, sessionId,
234
- protocolVersion: timelineProtocolFromRuntime(host, environment) })) {
235
- return hostReceiptUnavailable("king-history-format-version-or-binding-mismatch");
236
- }
237
- const snapshot = await normalizePrivateTimelineSource(source);
238
- if (!snapshot) return hostReceiptUnavailable("transcript-snapshot-unavailable");
239
- try {
240
- const names = await enrollmentPaths(rootPath);
241
- return await withOwnedFileLock(names.lock, async ({ assertOwned }) => {
242
- const state = await readState(names.path, names.headPath, rootPath, names.assertStable, assertOwned);
243
- const changed = purgeExpiredHostReceipts(state, current);
244
- const receipt = makeHostTranscriptReceipt({ root: rootPath, binding: input.binding, source: snapshot,
245
- transportDigest, current, eventId });
246
- const existing = state.pendingReceipts.find((item) => sameIssuedHostTranscriptEvent(item, receipt));
247
- if (existing) {
248
- if (changed) await saveState(state, names.path, names.headPath, rootPath, assertOwned, names.assertStable);
249
- return hostReceiptResult(existing);
250
- }
251
- if (state.pendingReceipts.length >= MAX_PENDING_RECEIPTS) {
252
- if (changed) await saveState(state, names.path, names.headPath, rootPath, assertOwned, names.assertStable);
253
- return hostReceiptUnavailable("host-receipt-capacity-exhausted");
254
- }
255
- state.pendingReceipts.unshift(receipt);
256
- await saveState(state, names.path, names.headPath, rootPath, assertOwned, names.assertStable);
257
- return hostReceiptResult(receipt);
258
- }, { assertPath: names.assertStable });
259
- } catch {
260
- return hostReceiptUnavailable("host-receipt-state-unavailable");
261
- }
262
- }
263
-
264
- export async function currentHostTranscriptReceipt({ root, clock = null, environment = process.env }) {
265
- const current = runtimeDate(clock);
266
- if (!current) return hostReceiptUnavailable("invalid-host-receipt-time");
267
- const rootPath = await canonicalRoot(root);
268
- if (!rootPath) return hostReceiptUnavailable("unknown-project-root");
269
- try {
270
- const { state } = await loadStateWithRecovery(rootPath);
271
- const matches = state.pendingReceipts.filter((item) => {
272
- if (new Date(item.expiresAt).getTime() <= current.getTime()) return false;
273
- const transportDigest = timelineTransportDigest({ root: rootPath, binding: item.binding, environment });
274
- return transportDigest && sameTimelineTransportDigest(item.transportDigest, transportDigest);
275
- });
276
- return matches.length === 1 ? hostReceiptResult(matches[0])
277
- : hostReceiptUnavailable(matches.length ? "host-receipt-ambiguous" : "host-receipt-unavailable");
278
- } catch {
279
- return hostReceiptUnavailable("host-receipt-state-unavailable");
280
- }
281
- }
282
-
283
- export async function loadPrivateSessionTimelineEnrollment({
284
- root, host = null, sessionId = null, scope = null, enrollmentDigest: wantedDigest = null,
285
- expectedTransportDigest = null, clock = null
286
- }) {
287
- const current = runtimeDate(clock);
288
- if (!current) return inspectUnavailable("invalid-enrollment-time");
289
- const rootPath = await canonicalRoot(root);
290
- if (!rootPath || (wantedDigest !== null && !/^[a-f0-9]{64}$/.test(wantedDigest))) {
291
- return inspectUnavailable("private-enrollment-unavailable");
292
- }
293
- const requested = scope === null ? null : validHostReceiptInput({ host, sessionId, scope });
294
- if ((scope !== null || host !== null || sessionId !== null) && !requested?.binding) {
295
- return inspectUnavailable("private-enrollment-unavailable");
296
- }
297
- try {
298
- const { state } = await loadStateWithRecovery(rootPath);
299
- const matches = state.enrollments.filter((record) => (!requested || sameTimelineBinding(record.binding, requested.binding))
300
- && (wantedDigest === null || record.enrollmentDigest === wantedDigest));
301
- if (matches.length !== 1 || new Date(matches[0].expiresAt).getTime() <= current.getTime()) {
302
- return inspectUnavailable("private-enrollment-unavailable");
303
- }
304
- const [record] = matches;
305
- if (expectedTransportDigest !== null && (!validTimelineTransportDigest(expectedTransportDigest)
306
- || !sameTimelineTransportDigest(record.transportDigest, expectedTransportDigest))) {
307
- return inspectUnavailable("private-enrollment-transport-mismatch");
308
- }
309
- return { status: "loaded", rootPath, record, now: current };
310
- } catch {
311
- return inspectUnavailable("private-enrollment-state-unavailable");
312
- }
313
- }
314
-
315
- function activeResult(record, activeSource) {
316
- return {
317
- schema: PRIVATE_TIMELINE_ENROLLMENT_SCHEMA, status: "enrolled", id: record.id,
318
- binding: { ...record.binding }, source: {
319
- path: activeSource.path, profileRoot: activeSource.profileRoot, projectsRoot: activeSource.projectsRoot,
320
- pathDigest: activeSource.pathDigest, identity: activeSource.identity, size: activeSource.size,
321
- mtimeNs: activeSource.mtimeNs, ctimeNs: activeSource.ctimeNs,
322
- commitmentDigest: null, committedBytes: 0
323
- }, sourceDigest: sourceDigest(record.source), enrollmentDigest: record.enrollmentDigest,
324
- expiresAt: record.expiresAt, timelineVisibility: record.timelineVisibility, authority: AUTHORITY
325
- };
326
- }
327
-
328
- function inspectUnavailable(reason) { return { status: "unavailable", reason }; }
329
-
330
- export async function inspectPrivateSessionTimelineEnrollment({
331
- root, host, sessionId, transcriptPath, hostHome, clock = null, expectedTransportDigest = null
332
- }) {
333
- const current = runtimeDate(clock);
334
- if (!current) return inspectUnavailable("invalid-enrollment-time");
335
- const rootPath = await canonicalRoot(root);
336
- if (!rootPath) return inspectUnavailable("unknown-project-root");
337
- const activeSessionId = validResolverInput({ host, sessionId });
338
- if (!activeSessionId) return inspectUnavailable("unknown-timeline-host-or-session");
339
- try {
340
- const { state } = await loadStateWithRecovery(rootPath);
341
- const candidates = state.enrollments.filter((item) => item.binding.host === host && item.binding.sessionId === activeSessionId);
342
- const requestedPath = typeof transcriptPath === "string" && transcriptPath
343
- ? transcriptPath : candidates.length === 1 ? candidates[0].source.path : null;
344
- const trustedHome = hostHome === null || hostHome === undefined
345
- ? candidates.length === 1 ? candidates[0].source.profileRoot : null
346
- : isAbsolute(hostHome) ? hostHome : null;
347
- if (!requestedPath || !trustedHome) return inspectUnavailable("private-enrollment-unavailable");
348
- const active = await sourcePath(requestedPath, trustedHome, host);
349
- if (active.status !== "registered") return inspectUnavailable(active.reason || "transcript-unavailable");
350
- const matches = candidates.filter((item) => sameSource(item.source, active));
351
- if (matches.length !== 1) return inspectUnavailable("private-enrollment-unavailable");
352
- const [record] = matches;
353
- if (new Date(record.expiresAt).getTime() <= current.getTime()) return inspectUnavailable("private-enrollment-expired");
354
- if (expectedTransportDigest !== null && (!validTimelineTransportDigest(expectedTransportDigest)
355
- || !sameTimelineTransportDigest(record.transportDigest, expectedTransportDigest))) {
356
- return inspectUnavailable("private-enrollment-transport-mismatch");
357
- }
358
- return { status: "loaded", rootPath, record, active, now: current };
359
- } catch {
360
- return inspectUnavailable("private-enrollment-state-unavailable");
361
- }
362
- }
363
-
364
- export async function mutatePrivateSessionTimelineEnrollment({ root, task }) {
365
- const rootPath = await canonicalRoot(root);
366
- if (!rootPath || typeof task !== "function") return null;
367
- try {
368
- const names = await enrollmentPaths(rootPath);
369
- return await withOwnedFileLock(names.lock, async ({ assertOwned }) => {
370
- const state = await readState(names.path, names.headPath, rootPath, names.assertStable, assertOwned);
371
- let committed = false;
372
- const commit = async () => {
373
- if (committed) return;
374
- await saveState(state, names.path, names.headPath, rootPath, assertOwned, names.assertStable);
375
- committed = true;
376
- };
377
- return task({ rootPath, state, commit });
378
- }, { assertPath: names.assertStable });
379
- } catch {
380
- return null;
381
- }
382
- }
383
-
384
- export async function resetPrivateSessionTimelineEnrollment({ root, confirmation }) {
385
- if (confirmation !== LOCAL_TIMELINE_ENROLLMENT_RECOVERY_CONFIRMATION) return false;
386
- const rootPath = await canonicalRoot(root);
387
- if (!rootPath) return false;
388
- try {
389
- const names = await enrollmentPaths(rootPath);
390
- return await withOwnedFileLock(names.lock, async ({ assertOwned }) => {
391
- try {
392
- await readState(names.path, names.headPath, rootPath, names.assertStable, assertOwned);
393
- return false;
394
- } catch {
395
- const state = empty(rootPath);
396
- await saveState(state, names.path, names.headPath, rootPath, assertOwned, names.assertStable);
397
- return true;
398
- }
399
- }, { assertPath: names.assertStable });
400
- } catch {
401
- return false;
402
- }
403
- }
404
-
405
- export async function enrollPrivateSessionTimeline(options = {}) {
406
- const { root, hostReceipt, confirmation, ttlMs = DEFAULT_TIMELINE_ENROLLMENT_TTL_MS,
407
- clock = null, environment = process.env } = options || {};
408
- if (!options || typeof options !== "object" || Array.isArray(options)
409
- || ["host", "sessionId", "scope", "transcriptPath", "hostHome"].some((key) => options[key] !== undefined)) {
410
- return unavailable("host-transcript-receipt-required");
411
- }
412
- if (confirmation !== LOCAL_TIMELINE_ENROLLMENT_CONFIRMATION) return unavailable("local-owner-confirmation-required");
413
- if (!hostReceiptId(hostReceipt)) return unavailable("host-transcript-receipt-required");
414
- const current = runtimeDate(clock);
415
- if (!current) return unavailable("invalid-enrollment-time");
416
- const ttl = enrollmentTtl(ttlMs);
417
- if (!ttl) return unavailable("invalid-enrollment-expiry");
418
- const rootPath = await canonicalRoot(root);
419
- if (!rootPath) return unavailable("unknown-project-root");
420
- try {
421
- const names = await enrollmentPaths(rootPath);
422
- let result = unavailable("host-transcript-receipt-unavailable");
423
- await withOwnedFileLock(names.lock, async ({ assertOwned }) => {
424
- const state = await readState(names.path, names.headPath, rootPath, names.assertStable, assertOwned);
425
- const pruned = purgeExpiredHostReceipts(state, current);
426
- const receiptIndex = state.pendingReceipts.findIndex((item) => item.id === hostReceipt);
427
- const receipt = receiptIndex < 0 ? null : state.pendingReceipts[receiptIndex];
428
- if (!receipt) {
429
- if (pruned) await saveState(state, names.path, names.headPath, rootPath, assertOwned, names.assertStable);
430
- return;
431
- }
432
- const transportDigest = timelineTransportDigest({ root: rootPath, binding: receipt.binding, environment });
433
- if (!transportDigest || !sameTimelineTransportDigest(receipt.transportDigest, transportDigest)) {
434
- result = unavailable("local-transport-capability-required"); return;
435
- }
436
- const source = await sourcePath(receipt.source.path, receipt.source.profileRoot, receipt.binding.host);
437
- const normalized = source.status === "registered" ? await normalizePrivateTimelineSource(source) : null;
438
- state.pendingReceipts.splice(receiptIndex, 1);
439
- if (!normalized || !sameHostReceiptSource(receipt, normalized)) {
440
- await saveState(state, names.path, names.headPath, rootPath, assertOwned, names.assertStable);
441
- result = unavailable("transcript-snapshot-changed"); return;
442
- }
443
- const record = { binding: receipt.binding, source: normalized, confirmedAt: current.toISOString(),
444
- expiresAt: new Date(current.getTime() + ttl).toISOString(), timelineVisibility: TIMELINE_VISIBILITY,
445
- confirmation: LOCAL_TIMELINE_ENROLLMENT_CONFIRMATION, transportDigest: receipt.transportDigest, authority: AUTHORITY };
446
- record.id = enrollmentId(rootPath, record.binding, record.source);
447
- record.enrollmentDigest = enrollmentDigest(rootPath, record.binding, record.source, record.expiresAt, record.transportDigest);
448
- state.enrollments = state.enrollments.filter((item) => new Date(item.expiresAt).getTime() > current.getTime()
449
- && !(sameTimelineBinding(item.binding, record.binding)
450
- || (item.binding.host === record.binding.host && item.binding.sessionId === record.binding.sessionId
451
- && sameSource(item.source, record.source))));
452
- state.enrollments.unshift(record);
453
- state.enrollments = state.enrollments.slice(0, MAX_ENROLLMENTS);
454
- await saveState(state, names.path, names.headPath, rootPath, assertOwned, names.assertStable);
455
- result = activeResult(record, source);
456
- }, { assertPath: names.assertStable });
457
- return result;
458
- } catch {
459
- return unavailable("private-enrollment-state-unavailable");
460
- }
461
- }
462
-
463
- export async function resolvePrivateSessionTimelineEnrollment({
464
- root, host, sessionId, transcriptPath, hostHome, clock = null, expectedTransportDigest = null
465
- }) {
466
- const inspected = await inspectPrivateSessionTimelineEnrollment({
467
- root, host, sessionId, transcriptPath, hostHome, clock, expectedTransportDigest
468
- });
469
- if (inspected.status !== "loaded") return unavailable(inspected.reason);
470
- const { record, active } = inspected;
471
- if (!sameSourceSnapshot(record.source, active)) {
472
- return unavailable("transcript-snapshot-renewal-required");
473
- }
474
- if (await privateTimelinePrefixDigest(active, record.source.prefixBytes) !== record.source.prefixDigest) {
475
- return unavailable("transcript-replaced");
476
- }
477
- return activeResult(record, active);
478
- }
@@ -1,186 +0,0 @@
1
- import { codexTimelineToolResult, codexTimelineUserMessage } from "./session-timeline-codex.js";
2
- import { kingTimelineToolResult, kingTimelineUserMessage } from "./session-timeline-king.js";
3
- import { createHash } from "node:crypto";
4
- import { timelineTerms } from "./session-timeline-query.js";
5
-
6
- const MAX_LINE_BYTES = 1024 * 1024;
7
- const TEXT_KEY_RE = /^(?:content|text|result|output|error|message)$/i;
8
- const SENSITIVE_KEY_RE = /^(?:api[_-]?key|apikey|access[_-]?token|refresh[_-]?token|token|secret|client[_-]?secret|password|passwort|credential|authorization|proxy[_-]?authorization|cookie|set[_-]?cookie|private[_-]?key|aws[_-]?secret[_-]?access[_-]?key)$/i;
9
- const SECRET_RE = /-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?(?:-----END [A-Z ]*PRIVATE KEY-----|$)|\b(?:aspt|astp|astc)_[A-Za-z0-9_.-]{40,}\b|\b(?:sk[-_](?:proj[-_])?|gh[opusu]_)[A-Za-z0-9_-]{20,}\b|\b(?:xox[bapcrs]-|github_pat_|glpat-|npm_)[A-Za-z0-9_-]{12,}\b|\bAKIA[0-9A-Z]{16}\b|\b[a-z][a-z0-9+.-]{0,31}:\/\/[^\s\/@:]+:[^\s\/@]+@|https?:\/\/hooks\.slack\.com\/services\/[A-Za-z0-9_/-]+|\beyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\b/i;
10
- const CREDENTIAL_VALUE_RE = /["'](?:api[_-]?key|apikey|access[_-]?token|refresh[_-]?token|token|secret|client[_-]?secret|password|passwort|credential|authorization|proxy[_-]?authorization|cookie|set[_-]?cookie|private[_-]?key|aws[_-]?secret[_-]?access[_-]?key)["']\s*:\s*(?:["'][^"'\r\n]*["']|[^,}\]\s]+)|\b(?:api[_-]?key|apikey|access[_-]?token|refresh[_-]?token|token|secret|client[_-]?secret|password|passwort|credential|aws[_-]?secret[_-]?access[_-]?key)\s*[:=]\s*(?:["'][^"'\r\n]*["']|\S+)/i;
11
- const AUTHORIZATION_RE = /\b(?:authorization|proxy-authorization)\s*:\s*(?:bearer|basic|digest|token|apikey|api-key|aws4-hmac-sha256)\b|\b(?:bearer|basic|digest|token|apikey|api-key|aws4-hmac-sha256)\s+[A-Za-z0-9._~+\/=:-]+/i;
12
- const INSTRUCTION_RE = /(?:\b(?:ignore|disregard|override|bypass|forget)\b[\s\S]{0,180}\b(?:previous|prior|system|developer|instruction|instructions|prompt|prompts|rule|rules|safeguard|safeguards)\b|\b(?:ignoriere|missachte|übergehe|umgehe|vergesse)\b[\s\S]{0,180}\b(?:vorherige|frühere|system|entwickler|anweisung|anweisungen|prompt|prompts|regel|regeln|schutzmaßnahme|schutzmaßnahmen)\b|<\s*\/?\s*(?:system|developer|assistant|instructions?|prompt)\b[^>]*>)/i;
13
- const OBJECTIVE_RE = /\b(?:measur(?:e|ed|ement)|gemessen|benchmark|test(?:ed|ing)?|suite|assert(?:ion)?|ci\b|prüfung|durchlauf|ergebnis)\b/i;
14
- const OUTCOME_PATTERNS = [
15
- ["pass", /\b(?:pass(?:ed|ing)?|green|success(?:ful)?|ok|bestanden|erfolgreich)\b/gi],
16
- ["fail", /\b(?:fail(?:ed|ure)?|red|fehlgeschlagen)\b/gi],
17
- ["blocked", /\b(?:blocked|blockiert)\b/gi],
18
- ["timeout", /\b(?:timeout|zeitüberschreitung)\b/gi],
19
- ["error", /\b(?:error|fehler)\b/gi],
20
- ["skipped", /\b(?:skipped|übersprungen)\b/gi]
21
- ];
22
- const NEXT_STEP_CORRECTION_RE = /^(?:Correction:\s*next step:|Korrektur:\s*nächster Schritt:)\s*(.+)$/iu;
23
-
24
- function digest(value) { return createHash("sha256").update(value).digest("hex"); }
25
-
26
- export function extractTimelineTimestamp(value) {
27
- for (const key of ["timestamp", "created_at", "createdAt"]) {
28
- const current = value?.[key];
29
- if (typeof current !== "string" || !/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d{1,9})?Z$/.test(current)) continue;
30
- const parsed = new Date(current);
31
- if (Number.isFinite(parsed.getTime()) && parsed.toISOString().slice(0, 19) === current.slice(0, 19)) return parsed.toISOString();
32
- }
33
- return null;
34
- }
35
-
36
- function isToolResult(value) {
37
- const type = String(value?.type || value?.kind || "").toLowerCase().replaceAll("_", "-");
38
- return value?.role === "tool" || ["tool-result", "toolresult", "command-result", "runner-result"].includes(type);
39
- }
40
-
41
- function unsafeText(value) {
42
- return SECRET_RE.test(value) || CREDENTIAL_VALUE_RE.test(value) || AUTHORIZATION_RE.test(value) || INSTRUCTION_RE.test(value);
43
- }
44
-
45
- function unsafeObject(value) {
46
- const pending = [{ value, depth: 0 }];
47
- let visited = 0;
48
- while (pending.length && visited < 128) {
49
- const current = pending.pop();
50
- visited += 1;
51
- if (typeof current.value === "string") {
52
- if (unsafeText(current.value)) return true;
53
- continue;
54
- }
55
- if (!current.value || typeof current.value !== "object" || current.depth > 5) continue;
56
- for (const [key, item] of Object.entries(current.value).slice(0, 64)) {
57
- if (SENSITIVE_KEY_RE.test(key)) return true;
58
- pending.push({ value: item, depth: current.depth + 1 });
59
- }
60
- }
61
- return visited >= 128;
62
- }
63
-
64
- function objectiveText(value) {
65
- const values = [];
66
- const visit = (item, key = "", depth = 0) => {
67
- if (depth > 5 || values.length >= 12) return;
68
- if (typeof item === "string") {
69
- if (TEXT_KEY_RE.test(key)) values.push(item.slice(0, 4096));
70
- return;
71
- }
72
- if (!item || typeof item !== "object") return;
73
- for (const [name, current] of Object.entries(item).slice(0, 48)) visit(current, name, depth + 1);
74
- };
75
- visit(value);
76
- return values.join("\n");
77
- }
78
-
79
- function normalizedOutcome(value) {
80
- const found = OUTCOME_PATTERNS.filter(([, pattern]) => {
81
- pattern.lastIndex = 0;
82
- return pattern.test(value);
83
- }).map(([outcome]) => outcome);
84
- return found.length === 1 ? found[0] : null;
85
- }
86
-
87
- function normalizedCount(value) {
88
- const matches = [...value.matchAll(/\b(\d{1,6})\s*\/\s*(\d{1,6})\b/g)].map((match) => ({
89
- value: Number(match[1]), total: Number(match[2])
90
- })).filter((item) => item.value <= item.total && item.total > 0);
91
- if (!matches.length) return null;
92
- const first = matches[0];
93
- return matches.every((item) => item.value === first.value && item.total === first.total) ? first : null;
94
- }
95
-
96
- function normalizedTestLabel(value) {
97
- const suite = value.match(/\b(?:suite|test(?:\s+suite)?|testlauf|prüfung)\s*(?:#|nr\.?|nummer)?\s*(\d{1,4})\b/i);
98
- if (suite) return `suite-${Number(suite[1])}`;
99
- if (/\bacceptance\b/i.test(value)) return "acceptance";
100
- if (/\baudit\b/i.test(value)) return "audit";
101
- if (/\bnpm\s+run\s+check\b/i.test(value)) return "npm-check";
102
- if (/\bci\b/i.test(value)) return "ci";
103
- if (/\b(?:test|prüfung|durchlauf)\b/i.test(value)) return "test";
104
- return null;
105
- }
106
-
107
- function structuredTerms({ outcome, count, testLabel }) {
108
- return timelineTerms(["objective", "measurement", "messung", "result", "ergebnis", outcome, testLabel || "",
109
- count ? String(count.value) : "", count ? String(count.total) : ""].join(" "));
110
- }
111
-
112
- function objectiveExcerpt(body) {
113
- const segments = body.split(/(?:\r?\n)+|(?<=[.!?])\s+/u).map((item) => item.trim()).filter(Boolean);
114
- const selected = segments.find((item) => OBJECTIVE_RE.test(item) && normalizedOutcome(item));
115
- return (selected || "").replace(/\s+/g, " ").slice(0, 320);
116
- }
117
-
118
- function candidateFromToolResult(value) {
119
- if (!isToolResult(value) || unsafeObject(value)) return null;
120
- const body = objectiveText(value);
121
- if (!body || !OBJECTIVE_RE.test(body)) return null;
122
- const outcome = normalizedOutcome(body);
123
- if (!outcome) return null;
124
- const count = normalizedCount(body);
125
- const testLabel = normalizedTestLabel(body);
126
- return { kind: "objective-result", outcome, count, testLabel, terms: structuredTerms({ outcome, count, testLabel }) };
127
- }
128
-
129
- function candidateFromUserMessage(value) {
130
- if (value?.role !== "user" || typeof value.content !== "string" || /[\r\n]/u.test(value.content)) return null;
131
- const match = value.content.trim().match(NEXT_STEP_CORRECTION_RE);
132
- if (!match) {
133
- if (!value.content.trim() || Buffer.byteLength(value.content) > 2048 || unsafeText(value.content)) return null;
134
- return { kind: "user-message-candidate", sourceText: value.content,
135
- terms: ["user", "message"] };
136
- }
137
- const nextStepSummary = match[1].trim().replace(/\s+/gu, " ");
138
- if (!nextStepSummary || nextStepSummary.length > 500 || unsafeText(nextStepSummary)) return null;
139
- return { kind: "explicit-next-step-correction", nextStepSummary,
140
- terms: timelineTerms("correction Korrektur next step nächster Schritt") };
141
- }
142
-
143
- function claudeTimelineUserMessage(parsed) {
144
- const message = parsed?.message;
145
- if (!message || message.role !== "user") return null;
146
- if (typeof message.content === "string") return { role: "user", content: message.content };
147
- if (!Array.isArray(message.content) || message.content.length > 12
148
- || message.content.some((part) => !part || !["text", "input_text"].includes(part.type)
149
- || typeof part.text !== "string")) return null;
150
- return { role: "user", content: message.content.map((part) => part.text).join("\n") };
151
- }
152
-
153
- function timelineEventFromLine(line, offset, authority, includeExcerpt, host) {
154
- const source = Buffer.from(line);
155
- if (source.byteLength > MAX_LINE_BYTES) return null;
156
- let parsed;
157
- try { parsed = JSON.parse(line.trim()); } catch {
158
- if (["codex", "king"].includes(host)) throw new Error(`${host}-history-format-mismatch`);
159
- return null;
160
- }
161
- const tool = host === "codex" ? codexTimelineToolResult(parsed)
162
- : host === "king" ? kingTimelineToolResult(parsed) : null;
163
- const user = host === "codex" ? codexTimelineUserMessage(parsed)
164
- : host === "king" ? kingTimelineUserMessage(parsed) : claudeTimelineUserMessage(parsed);
165
- const at = tool?.at || user?.at || extractTimelineTimestamp(parsed);
166
- if (!at || unsafeObject(parsed)) return null;
167
- const candidate = ["codex", "king"].includes(host)
168
- ? candidateFromToolResult(tool) || candidateFromUserMessage(user)
169
- : candidateFromToolResult(parsed) || candidateFromToolResult(parsed.message) || candidateFromUserMessage(user);
170
- if (!candidate) return null;
171
- const stable = JSON.stringify({ at, ...candidate });
172
- const event = { id: `timeline-event:${digest(`${offset}\0${stable}`).slice(0, 32)}`, at, offset, bytes: source.byteLength,
173
- sha256: digest(source), ...candidate, authority };
174
- const nativeMessageId = tool?.nativeMessageId || user?.nativeMessageId;
175
- if (nativeMessageId) event.nativeMessageId = nativeMessageId;
176
- if (includeExcerpt && candidate.kind === "objective-result") event.excerpt = objectiveExcerpt(objectiveText(tool || parsed));
177
- return event;
178
- }
179
-
180
- export function eventFromTimelineLine(line, offset, authority = "context-only", host = "claude") {
181
- return timelineEventFromLine(line, offset, authority, false, host);
182
- }
183
-
184
- export function verifiedTimelineEventFromLine(line, offset, authority = "context-only", host = "claude") {
185
- return timelineEventFromLine(line, offset, authority, true, host);
186
- }