kairo-mcp 1.3.0

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 (384) hide show
  1. package/CHANGELOG.md +1122 -0
  2. package/LICENSE +21 -0
  3. package/README.md +662 -0
  4. package/dist/cli/cli.d.ts +3 -0
  5. package/dist/cli/cli.d.ts.map +1 -0
  6. package/dist/cli/cli.js +226 -0
  7. package/dist/cli/cli.js.map +1 -0
  8. package/dist/cli/commands.d.ts +10 -0
  9. package/dist/cli/commands.d.ts.map +1 -0
  10. package/dist/cli/commands.js +938 -0
  11. package/dist/cli/commands.js.map +1 -0
  12. package/dist/cli/flags.d.ts +30 -0
  13. package/dist/cli/flags.d.ts.map +1 -0
  14. package/dist/cli/flags.js +90 -0
  15. package/dist/cli/flags.js.map +1 -0
  16. package/dist/cli/output.d.ts +69 -0
  17. package/dist/cli/output.d.ts.map +1 -0
  18. package/dist/cli/output.js +166 -0
  19. package/dist/cli/output.js.map +1 -0
  20. package/dist/cli/types.d.ts +34 -0
  21. package/dist/cli/types.d.ts.map +1 -0
  22. package/dist/cli/types.js +2 -0
  23. package/dist/cli/types.js.map +1 -0
  24. package/dist/contracts/migrations.d.ts +31 -0
  25. package/dist/contracts/migrations.d.ts.map +1 -0
  26. package/dist/contracts/migrations.js +71 -0
  27. package/dist/contracts/migrations.js.map +1 -0
  28. package/dist/contracts/schemas.d.ts +53 -0
  29. package/dist/contracts/schemas.d.ts.map +1 -0
  30. package/dist/contracts/schemas.js +27 -0
  31. package/dist/contracts/schemas.js.map +1 -0
  32. package/dist/contracts/stability.d.ts +32 -0
  33. package/dist/contracts/stability.d.ts.map +1 -0
  34. package/dist/contracts/stability.js +140 -0
  35. package/dist/contracts/stability.js.map +1 -0
  36. package/dist/contracts/zodSchemas.d.ts +811 -0
  37. package/dist/contracts/zodSchemas.d.ts.map +1 -0
  38. package/dist/contracts/zodSchemas.js +139 -0
  39. package/dist/contracts/zodSchemas.js.map +1 -0
  40. package/dist/core/brief/budget.d.ts +21 -0
  41. package/dist/core/brief/budget.d.ts.map +1 -0
  42. package/dist/core/brief/budget.js +42 -0
  43. package/dist/core/brief/budget.js.map +1 -0
  44. package/dist/core/checkpoint/checkpointManager.d.ts +29 -0
  45. package/dist/core/checkpoint/checkpointManager.d.ts.map +1 -0
  46. package/dist/core/checkpoint/checkpointManager.js +49 -0
  47. package/dist/core/checkpoint/checkpointManager.js.map +1 -0
  48. package/dist/core/compaction/compactor.d.ts +40 -0
  49. package/dist/core/compaction/compactor.d.ts.map +1 -0
  50. package/dist/core/compaction/compactor.js +168 -0
  51. package/dist/core/compaction/compactor.js.map +1 -0
  52. package/dist/core/continuation/continuationBuilder.d.ts +19 -0
  53. package/dist/core/continuation/continuationBuilder.d.ts.map +1 -0
  54. package/dist/core/continuation/continuationBuilder.js +184 -0
  55. package/dist/core/continuation/continuationBuilder.js.map +1 -0
  56. package/dist/core/coordination/coordinationManager.d.ts +34 -0
  57. package/dist/core/coordination/coordinationManager.d.ts.map +1 -0
  58. package/dist/core/coordination/coordinationManager.js +253 -0
  59. package/dist/core/coordination/coordinationManager.js.map +1 -0
  60. package/dist/core/coordination/types.d.ts +52 -0
  61. package/dist/core/coordination/types.d.ts.map +1 -0
  62. package/dist/core/coordination/types.js +6 -0
  63. package/dist/core/coordination/types.js.map +1 -0
  64. package/dist/core/github/changelog.d.ts +9 -0
  65. package/dist/core/github/changelog.d.ts.map +1 -0
  66. package/dist/core/github/changelog.js +41 -0
  67. package/dist/core/github/changelog.js.map +1 -0
  68. package/dist/core/github/commitMessage.d.ts +4 -0
  69. package/dist/core/github/commitMessage.d.ts.map +1 -0
  70. package/dist/core/github/commitMessage.js +125 -0
  71. package/dist/core/github/commitMessage.js.map +1 -0
  72. package/dist/core/github/gitContext.d.ts +3 -0
  73. package/dist/core/github/gitContext.d.ts.map +1 -0
  74. package/dist/core/github/gitContext.js +67 -0
  75. package/dist/core/github/gitContext.js.map +1 -0
  76. package/dist/core/github/releasePlan.d.ts +8 -0
  77. package/dist/core/github/releasePlan.d.ts.map +1 -0
  78. package/dist/core/github/releasePlan.js +56 -0
  79. package/dist/core/github/releasePlan.js.map +1 -0
  80. package/dist/core/github/semver.d.ts +11 -0
  81. package/dist/core/github/semver.d.ts.map +1 -0
  82. package/dist/core/github/semver.js +23 -0
  83. package/dist/core/github/semver.js.map +1 -0
  84. package/dist/core/github/types.d.ts +36 -0
  85. package/dist/core/github/types.d.ts.map +1 -0
  86. package/dist/core/github/types.js +2 -0
  87. package/dist/core/github/types.js.map +1 -0
  88. package/dist/core/graph/derived.d.ts +6 -0
  89. package/dist/core/graph/derived.d.ts.map +1 -0
  90. package/dist/core/graph/derived.js +133 -0
  91. package/dist/core/graph/derived.js.map +1 -0
  92. package/dist/core/graph/graphEngine.d.ts +11 -0
  93. package/dist/core/graph/graphEngine.d.ts.map +1 -0
  94. package/dist/core/graph/graphEngine.js +28 -0
  95. package/dist/core/graph/graphEngine.js.map +1 -0
  96. package/dist/core/graph/imports.d.ts +19 -0
  97. package/dist/core/graph/imports.d.ts.map +1 -0
  98. package/dist/core/graph/imports.js +0 -0
  99. package/dist/core/graph/imports.js.map +1 -0
  100. package/dist/core/graph/mermaid.d.ts +6 -0
  101. package/dist/core/graph/mermaid.d.ts.map +1 -0
  102. package/dist/core/graph/mermaid.js +40 -0
  103. package/dist/core/graph/mermaid.js.map +1 -0
  104. package/dist/core/graph/moduleGraph.d.ts +27 -0
  105. package/dist/core/graph/moduleGraph.d.ts.map +1 -0
  106. package/dist/core/graph/moduleGraph.js +186 -0
  107. package/dist/core/graph/moduleGraph.js.map +1 -0
  108. package/dist/core/graph/types.d.ts +32 -0
  109. package/dist/core/graph/types.d.ts.map +1 -0
  110. package/dist/core/graph/types.js +2 -0
  111. package/dist/core/graph/types.js.map +1 -0
  112. package/dist/core/query/queryEngine.d.ts +26 -0
  113. package/dist/core/query/queryEngine.d.ts.map +1 -0
  114. package/dist/core/query/queryEngine.js +258 -0
  115. package/dist/core/query/queryEngine.js.map +1 -0
  116. package/dist/core/query/types.d.ts +70 -0
  117. package/dist/core/query/types.d.ts.map +1 -0
  118. package/dist/core/query/types.js +6 -0
  119. package/dist/core/query/types.js.map +1 -0
  120. package/dist/core/repo/fingerprint.d.ts +0 -0
  121. package/dist/core/repo/fingerprint.d.ts.map +1 -0
  122. package/dist/core/repo/fingerprint.js +17 -0
  123. package/dist/core/repo/fingerprint.js.map +1 -0
  124. package/dist/core/repo/frameworkDetectors.d.ts +14 -0
  125. package/dist/core/repo/frameworkDetectors.d.ts.map +1 -0
  126. package/dist/core/repo/frameworkDetectors.js +151 -0
  127. package/dist/core/repo/frameworkDetectors.js.map +1 -0
  128. package/dist/core/repo/repoScanner.d.ts +20 -0
  129. package/dist/core/repo/repoScanner.d.ts.map +1 -0
  130. package/dist/core/repo/repoScanner.js +290 -0
  131. package/dist/core/repo/repoScanner.js.map +1 -0
  132. package/dist/core/repo/summary.d.ts +7 -0
  133. package/dist/core/repo/summary.d.ts.map +1 -0
  134. package/dist/core/repo/summary.js +34 -0
  135. package/dist/core/repo/summary.js.map +1 -0
  136. package/dist/core/repo/types.d.ts +62 -0
  137. package/dist/core/repo/types.d.ts.map +1 -0
  138. package/dist/core/repo/types.js +10 -0
  139. package/dist/core/repo/types.js.map +1 -0
  140. package/dist/core/risk/guardrail.d.ts +3 -0
  141. package/dist/core/risk/guardrail.d.ts.map +1 -0
  142. package/dist/core/risk/guardrail.js +47 -0
  143. package/dist/core/risk/guardrail.js.map +1 -0
  144. package/dist/core/risk/riskEngine.d.ts +8 -0
  145. package/dist/core/risk/riskEngine.d.ts.map +1 -0
  146. package/dist/core/risk/riskEngine.js +112 -0
  147. package/dist/core/risk/riskEngine.js.map +1 -0
  148. package/dist/core/risk/riskHeuristics.d.ts +4 -0
  149. package/dist/core/risk/riskHeuristics.d.ts.map +1 -0
  150. package/dist/core/risk/riskHeuristics.js +36 -0
  151. package/dist/core/risk/riskHeuristics.js.map +1 -0
  152. package/dist/core/salience/config.d.ts +14 -0
  153. package/dist/core/salience/config.d.ts.map +1 -0
  154. package/dist/core/salience/config.js +87 -0
  155. package/dist/core/salience/config.js.map +1 -0
  156. package/dist/core/salience/salienceEngine.d.ts +16 -0
  157. package/dist/core/salience/salienceEngine.d.ts.map +1 -0
  158. package/dist/core/salience/salienceEngine.js +64 -0
  159. package/dist/core/salience/salienceEngine.js.map +1 -0
  160. package/dist/core/salience/signals.d.ts +4 -0
  161. package/dist/core/salience/signals.d.ts.map +1 -0
  162. package/dist/core/salience/signals.js +143 -0
  163. package/dist/core/salience/signals.js.map +1 -0
  164. package/dist/core/salience/types.d.ts +69 -0
  165. package/dist/core/salience/types.d.ts.map +1 -0
  166. package/dist/core/salience/types.js +7 -0
  167. package/dist/core/salience/types.js.map +1 -0
  168. package/dist/core/session/eventPayloads.d.ts +92 -0
  169. package/dist/core/session/eventPayloads.d.ts.map +1 -0
  170. package/dist/core/session/eventPayloads.js +2 -0
  171. package/dist/core/session/eventPayloads.js.map +1 -0
  172. package/dist/core/session/reducer.d.ts +14 -0
  173. package/dist/core/session/reducer.d.ts.map +1 -0
  174. package/dist/core/session/reducer.js +181 -0
  175. package/dist/core/session/reducer.js.map +1 -0
  176. package/dist/core/session/sessionManager.d.ts +252 -0
  177. package/dist/core/session/sessionManager.d.ts.map +1 -0
  178. package/dist/core/session/sessionManager.js +655 -0
  179. package/dist/core/session/sessionManager.js.map +1 -0
  180. package/dist/core/telemetry/analytics.d.ts +24 -0
  181. package/dist/core/telemetry/analytics.d.ts.map +1 -0
  182. package/dist/core/telemetry/analytics.js +167 -0
  183. package/dist/core/telemetry/analytics.js.map +1 -0
  184. package/dist/core/telemetry/exporter.d.ts +17 -0
  185. package/dist/core/telemetry/exporter.d.ts.map +1 -0
  186. package/dist/core/telemetry/exporter.js +31 -0
  187. package/dist/core/telemetry/exporter.js.map +1 -0
  188. package/dist/core/telemetry/recorder.d.ts +19 -0
  189. package/dist/core/telemetry/recorder.d.ts.map +1 -0
  190. package/dist/core/telemetry/recorder.js +43 -0
  191. package/dist/core/telemetry/recorder.js.map +1 -0
  192. package/dist/core/telemetry/reports.d.ts +6 -0
  193. package/dist/core/telemetry/reports.d.ts.map +1 -0
  194. package/dist/core/telemetry/reports.js +84 -0
  195. package/dist/core/telemetry/reports.js.map +1 -0
  196. package/dist/core/telemetry/types.d.ts +82 -0
  197. package/dist/core/telemetry/types.d.ts.map +1 -0
  198. package/dist/core/telemetry/types.js +9 -0
  199. package/dist/core/telemetry/types.js.map +1 -0
  200. package/dist/core/vector/chunking/memoryChunker.d.ts +10 -0
  201. package/dist/core/vector/chunking/memoryChunker.d.ts.map +1 -0
  202. package/dist/core/vector/chunking/memoryChunker.js +202 -0
  203. package/dist/core/vector/chunking/memoryChunker.js.map +1 -0
  204. package/dist/core/vector/compression/architectureDigest.d.ts +12 -0
  205. package/dist/core/vector/compression/architectureDigest.d.ts.map +1 -0
  206. package/dist/core/vector/compression/architectureDigest.js +37 -0
  207. package/dist/core/vector/compression/architectureDigest.js.map +1 -0
  208. package/dist/core/vector/embedding/deterministicEmbedder.d.ts +10 -0
  209. package/dist/core/vector/embedding/deterministicEmbedder.d.ts.map +1 -0
  210. package/dist/core/vector/embedding/deterministicEmbedder.js +84 -0
  211. package/dist/core/vector/embedding/deterministicEmbedder.js.map +1 -0
  212. package/dist/core/vector/memory/memoryEngine.d.ts +56 -0
  213. package/dist/core/vector/memory/memoryEngine.d.ts.map +1 -0
  214. package/dist/core/vector/memory/memoryEngine.js +204 -0
  215. package/dist/core/vector/memory/memoryEngine.js.map +1 -0
  216. package/dist/core/vector/memory/memoryFingerprint.d.ts +12 -0
  217. package/dist/core/vector/memory/memoryFingerprint.d.ts.map +1 -0
  218. package/dist/core/vector/memory/memoryFingerprint.js +33 -0
  219. package/dist/core/vector/memory/memoryFingerprint.js.map +1 -0
  220. package/dist/core/vector/providers/deterministicProvider.d.ts +14 -0
  221. package/dist/core/vector/providers/deterministicProvider.d.ts.map +1 -0
  222. package/dist/core/vector/providers/deterministicProvider.js +22 -0
  223. package/dist/core/vector/providers/deterministicProvider.js.map +1 -0
  224. package/dist/core/vector/providers/httpEmbeddingProvider.d.ts +32 -0
  225. package/dist/core/vector/providers/httpEmbeddingProvider.d.ts.map +1 -0
  226. package/dist/core/vector/providers/httpEmbeddingProvider.js +93 -0
  227. package/dist/core/vector/providers/httpEmbeddingProvider.js.map +1 -0
  228. package/dist/core/vector/providers/registry.d.ts +9 -0
  229. package/dist/core/vector/providers/registry.d.ts.map +1 -0
  230. package/dist/core/vector/providers/registry.js +79 -0
  231. package/dist/core/vector/providers/registry.js.map +1 -0
  232. package/dist/core/vector/providers/types.d.ts +23 -0
  233. package/dist/core/vector/providers/types.d.ts.map +1 -0
  234. package/dist/core/vector/providers/types.js +2 -0
  235. package/dist/core/vector/providers/types.js.map +1 -0
  236. package/dist/core/vector/retrieval/hybridRetriever.d.ts +37 -0
  237. package/dist/core/vector/retrieval/hybridRetriever.d.ts.map +1 -0
  238. package/dist/core/vector/retrieval/hybridRetriever.js +131 -0
  239. package/dist/core/vector/retrieval/hybridRetriever.js.map +1 -0
  240. package/dist/core/vector/types.d.ts +87 -0
  241. package/dist/core/vector/types.d.ts.map +1 -0
  242. package/dist/core/vector/types.js +6 -0
  243. package/dist/core/vector/types.js.map +1 -0
  244. package/dist/index.d.ts +3 -0
  245. package/dist/index.d.ts.map +1 -0
  246. package/dist/index.js +30 -0
  247. package/dist/index.js.map +1 -0
  248. package/dist/inspect/cli.d.ts +3 -0
  249. package/dist/inspect/cli.d.ts.map +1 -0
  250. package/dist/inspect/cli.js +40 -0
  251. package/dist/inspect/cli.js.map +1 -0
  252. package/dist/inspect/projections.d.ts +141 -0
  253. package/dist/inspect/projections.d.ts.map +1 -0
  254. package/dist/inspect/projections.js +311 -0
  255. package/dist/inspect/projections.js.map +1 -0
  256. package/dist/inspect/render.d.ts +27 -0
  257. package/dist/inspect/render.d.ts.map +1 -0
  258. package/dist/inspect/render.js +325 -0
  259. package/dist/inspect/render.js.map +1 -0
  260. package/dist/inspect/server.d.ts +18 -0
  261. package/dist/inspect/server.d.ts.map +1 -0
  262. package/dist/inspect/server.js +112 -0
  263. package/dist/inspect/server.js.map +1 -0
  264. package/dist/perf/index.d.ts +24 -0
  265. package/dist/perf/index.d.ts.map +1 -0
  266. package/dist/perf/index.js +38 -0
  267. package/dist/perf/index.js.map +1 -0
  268. package/dist/perf/report.d.ts +8 -0
  269. package/dist/perf/report.d.ts.map +1 -0
  270. package/dist/perf/report.js +52 -0
  271. package/dist/perf/report.js.map +1 -0
  272. package/dist/perf/runner.d.ts +29 -0
  273. package/dist/perf/runner.d.ts.map +1 -0
  274. package/dist/perf/runner.js +74 -0
  275. package/dist/perf/runner.js.map +1 -0
  276. package/dist/perf/scenarios.d.ts +8 -0
  277. package/dist/perf/scenarios.d.ts.map +1 -0
  278. package/dist/perf/scenarios.js +119 -0
  279. package/dist/perf/scenarios.js.map +1 -0
  280. package/dist/perf/types.d.ts +32 -0
  281. package/dist/perf/types.d.ts.map +1 -0
  282. package/dist/perf/types.js +6 -0
  283. package/dist/perf/types.js.map +1 -0
  284. package/dist/plugins/loader.d.ts +78 -0
  285. package/dist/plugins/loader.d.ts.map +1 -0
  286. package/dist/plugins/loader.js +193 -0
  287. package/dist/plugins/loader.js.map +1 -0
  288. package/dist/plugins/types.d.ts +38 -0
  289. package/dist/plugins/types.d.ts.map +1 -0
  290. package/dist/plugins/types.js +10 -0
  291. package/dist/plugins/types.js.map +1 -0
  292. package/dist/pressure/pressureModel.d.ts +6 -0
  293. package/dist/pressure/pressureModel.d.ts.map +1 -0
  294. package/dist/pressure/pressureModel.js +102 -0
  295. package/dist/pressure/pressureModel.js.map +1 -0
  296. package/dist/prompts/continuityPrompt.d.ts +7 -0
  297. package/dist/prompts/continuityPrompt.d.ts.map +1 -0
  298. package/dist/prompts/continuityPrompt.js +43 -0
  299. package/dist/prompts/continuityPrompt.js.map +1 -0
  300. package/dist/sdk/index.d.ts +53 -0
  301. package/dist/sdk/index.d.ts.map +1 -0
  302. package/dist/sdk/index.js +130 -0
  303. package/dist/sdk/index.js.map +1 -0
  304. package/dist/security/patterns.d.ts +16 -0
  305. package/dist/security/patterns.d.ts.map +1 -0
  306. package/dist/security/patterns.js +61 -0
  307. package/dist/security/patterns.js.map +1 -0
  308. package/dist/security/redactor.d.ts +20 -0
  309. package/dist/security/redactor.d.ts.map +1 -0
  310. package/dist/security/redactor.js +58 -0
  311. package/dist/security/redactor.js.map +1 -0
  312. package/dist/server/createServer.d.ts +10 -0
  313. package/dist/server/createServer.d.ts.map +1 -0
  314. package/dist/server/createServer.js +60 -0
  315. package/dist/server/createServer.js.map +1 -0
  316. package/dist/server/registerTools.d.ts +4 -0
  317. package/dist/server/registerTools.d.ts.map +1 -0
  318. package/dist/server/registerTools.js +1086 -0
  319. package/dist/server/registerTools.js.map +1 -0
  320. package/dist/server/responses.d.ts +17 -0
  321. package/dist/server/responses.d.ts.map +1 -0
  322. package/dist/server/responses.js +21 -0
  323. package/dist/server/responses.js.map +1 -0
  324. package/dist/snapshot/export.d.ts +26 -0
  325. package/dist/snapshot/export.d.ts.map +1 -0
  326. package/dist/snapshot/export.js +164 -0
  327. package/dist/snapshot/export.js.map +1 -0
  328. package/dist/snapshot/import.d.ts +34 -0
  329. package/dist/snapshot/import.d.ts.map +1 -0
  330. package/dist/snapshot/import.js +114 -0
  331. package/dist/snapshot/import.js.map +1 -0
  332. package/dist/snapshot/types.d.ts +63 -0
  333. package/dist/snapshot/types.d.ts.map +1 -0
  334. package/dist/snapshot/types.js +2 -0
  335. package/dist/snapshot/types.js.map +1 -0
  336. package/dist/storage/faultAdapter.d.ts +64 -0
  337. package/dist/storage/faultAdapter.d.ts.map +1 -0
  338. package/dist/storage/faultAdapter.js +134 -0
  339. package/dist/storage/faultAdapter.js.map +1 -0
  340. package/dist/storage/fileStorageAdapter.d.ts +55 -0
  341. package/dist/storage/fileStorageAdapter.d.ts.map +1 -0
  342. package/dist/storage/fileStorageAdapter.js +219 -0
  343. package/dist/storage/fileStorageAdapter.js.map +1 -0
  344. package/dist/storage/paths.d.ts +30 -0
  345. package/dist/storage/paths.d.ts.map +1 -0
  346. package/dist/storage/paths.js +32 -0
  347. package/dist/storage/paths.js.map +1 -0
  348. package/dist/storage/quarantine.d.ts +36 -0
  349. package/dist/storage/quarantine.d.ts.map +1 -0
  350. package/dist/storage/quarantine.js +26 -0
  351. package/dist/storage/quarantine.js.map +1 -0
  352. package/dist/storage/redactingAdapter.d.ts +13 -0
  353. package/dist/storage/redactingAdapter.d.ts.map +1 -0
  354. package/dist/storage/redactingAdapter.js +91 -0
  355. package/dist/storage/redactingAdapter.js.map +1 -0
  356. package/dist/storage/storageAdapter.d.ts +46 -0
  357. package/dist/storage/storageAdapter.d.ts.map +1 -0
  358. package/dist/storage/storageAdapter.js +2 -0
  359. package/dist/storage/storageAdapter.js.map +1 -0
  360. package/dist/types/domain.d.ts +139 -0
  361. package/dist/types/domain.d.ts.map +1 -0
  362. package/dist/types/domain.js +9 -0
  363. package/dist/types/domain.js.map +1 -0
  364. package/dist/types/events.d.ts +28 -0
  365. package/dist/types/events.d.ts.map +1 -0
  366. package/dist/types/events.js +7 -0
  367. package/dist/types/events.js.map +1 -0
  368. package/dist/utils/errors.d.ts +6 -0
  369. package/dist/utils/errors.d.ts.map +1 -0
  370. package/dist/utils/errors.js +10 -0
  371. package/dist/utils/errors.js.map +1 -0
  372. package/dist/utils/ids.d.ts +7 -0
  373. package/dist/utils/ids.d.ts.map +1 -0
  374. package/dist/utils/ids.js +22 -0
  375. package/dist/utils/ids.js.map +1 -0
  376. package/dist/utils/logger.d.ts +7 -0
  377. package/dist/utils/logger.d.ts.map +1 -0
  378. package/dist/utils/logger.js +26 -0
  379. package/dist/utils/logger.js.map +1 -0
  380. package/dist/utils/time.d.ts +8 -0
  381. package/dist/utils/time.d.ts.map +1 -0
  382. package/dist/utils/time.js +11 -0
  383. package/dist/utils/time.js.map +1 -0
  384. package/package.json +79 -0
@@ -0,0 +1,655 @@
1
+ import { EVENT_SCHEMA_VERSION } from '../../types/events.js';
2
+ import { applyEvent, reduceAll, repeatedRereads, unresolvedErrors } from './reducer.js';
3
+ import { computePressure } from '../../pressure/pressureModel.js';
4
+ import { CheckpointManager } from '../checkpoint/checkpointManager.js';
5
+ import { inferRisk } from '../risk/riskHeuristics.js';
6
+ import { assessChange, assessSession } from '../risk/riskEngine.js';
7
+ import { evaluateGuardrail } from '../risk/guardrail.js';
8
+ import { readGitContext } from '../github/gitContext.js';
9
+ import { proposeCommit } from '../github/commitMessage.js';
10
+ import { proposeChangelog } from '../github/changelog.js';
11
+ import { proposeReleasePlan } from '../github/releasePlan.js';
12
+ import { RepoScanner } from '../repo/repoScanner.js';
13
+ import { INTELLIGENCE_SCHEMA } from '../repo/types.js';
14
+ import { buildGraph, buildAllGraphs, GRAPH_KINDS } from '../graph/graphEngine.js';
15
+ import { renderGraphMarkdown } from '../graph/mermaid.js';
16
+ import { MemoryEngine } from '../vector/memory/memoryEngine.js';
17
+ import { CoordinationManager } from '../coordination/coordinationManager.js';
18
+ import { TelemetryRecorder } from '../telemetry/recorder.js';
19
+ import { analyticsSummary, teamActivity, riskReport, moduleActivity, } from '../telemetry/analytics.js';
20
+ import { renderAnalyticsSummary, renderTeamActivity, renderRiskReport, } from '../telemetry/reports.js';
21
+ import { resolveExporter } from '../telemetry/exporter.js';
22
+ import { buildSessionToWorker, queryEvents, timeline, checkpointLineage, conflictHistory, retrievalTrace, whyEvent, } from '../query/queryEngine.js';
23
+ import { buildContinuationMarkdown } from '../continuation/continuationBuilder.js';
24
+ import { resolveBudget, clip } from '../brief/budget.js';
25
+ import { readFile } from 'node:fs/promises';
26
+ import { join } from 'node:path';
27
+ import { newId } from '../../utils/ids.js';
28
+ import { KairoError } from '../../utils/errors.js';
29
+ import { logger } from '../../utils/logger.js';
30
+ /**
31
+ * Orchestrates the continuity loop for a single agent connection. Holds the active
32
+ * session projection in memory (rebuilt from the log on start) and drives every write
33
+ * through the adapter, which enforces redaction.
34
+ */
35
+ export class SessionManager {
36
+ adapter;
37
+ clock;
38
+ current;
39
+ projectRoot = '';
40
+ workerId = 'default';
41
+ namespace = 'workspace';
42
+ checkpoints;
43
+ scanner;
44
+ memory;
45
+ coordination;
46
+ telemetry;
47
+ constructor(adapter, clock) {
48
+ this.adapter = adapter;
49
+ this.clock = clock;
50
+ this.checkpoints = new CheckpointManager(adapter, clock);
51
+ this.scanner = new RepoScanner(clock);
52
+ this.memory = new MemoryEngine(adapter);
53
+ this.coordination = new CoordinationManager(adapter, clock);
54
+ this.telemetry = new TelemetryRecorder(adapter, clock);
55
+ }
56
+ async init() {
57
+ await this.adapter.init();
58
+ }
59
+ /** Begins a new session, surfacing the prior continuation brief to avoid rescanning. */
60
+ async startSession(args) {
61
+ const priorBrief = await this.adapter.loadLatestContinuation();
62
+ const sessionId = newId(this.clock.now());
63
+ this.workerId = args.worker?.trim() || args.agent;
64
+ // Default: per-worker isolation. Pass namespace:"workspace" to share session memory.
65
+ this.namespace = args.namespace?.trim() || this.workerId;
66
+ this.current = undefined;
67
+ await this.append(sessionId, 'session.started', {
68
+ agent: args.agent,
69
+ task: args.task,
70
+ projectRoot: args.projectRoot,
71
+ startedAt: this.clock.iso(),
72
+ });
73
+ await this.coordination.registerWorker(sessionId, this.workerId, this.namespace, args.agent);
74
+ const resumed = priorBrief !== undefined;
75
+ if (resumed) {
76
+ await this.append(sessionId, 'session.resumed', { fromContinuation: 'latest' });
77
+ }
78
+ // Anti-rescan core: reuse cached repo intelligence if present; only scan when
79
+ // none exists yet (or the cache predates the current schema). Keeps resume cheap.
80
+ this.projectRoot = args.projectRoot;
81
+ let intelligence = await this.loadValidIntelligence();
82
+ let intelligenceFromCache = true;
83
+ if (!intelligence) {
84
+ intelligence = await this.scanner.scan(args.projectRoot);
85
+ await this.adapter.saveIntelligence(intelligence);
86
+ await this.persistGraphs(intelligence);
87
+ intelligenceFromCache = false;
88
+ }
89
+ this.telemetry.setContext(sessionId, this.workerId, this.namespace);
90
+ await this.telemetry.emit('session.started', {
91
+ repo: args.projectRoot,
92
+ resumed,
93
+ intelligenceFromCache,
94
+ });
95
+ // Build/reuse semantic memory (fingerprint-keyed: no re-embed on a cache hit).
96
+ await this.indexMemory(intelligence).catch((e) => logger.warn(`Memory index skipped: ${e instanceof Error ? e.message : String(e)}`));
97
+ return {
98
+ sessionId,
99
+ resumed,
100
+ intelligenceFromCache,
101
+ ...(priorBrief !== undefined ? { priorBrief } : {}),
102
+ ...(intelligence !== undefined ? { intelligence } : {}),
103
+ pressure: this.pressure(),
104
+ };
105
+ }
106
+ async record(input) {
107
+ const sid = this.requireSession().id;
108
+ switch (input.kind) {
109
+ case 'file':
110
+ await this.append(sid, 'file.changed', {
111
+ path: input.path,
112
+ changeKind: input.changeKind ?? 'modified',
113
+ risk: input.risk ?? inferRisk(input.path),
114
+ ...(input.bytes !== undefined ? { bytes: input.bytes } : {}),
115
+ ...(input.note !== undefined ? { note: input.note } : {}),
116
+ });
117
+ break;
118
+ case 'decision':
119
+ await this.append(sid, 'decision.recorded', {
120
+ summary: input.summary,
121
+ ...(input.rationale !== undefined ? { rationale: input.rationale } : {}),
122
+ });
123
+ break;
124
+ case 'command':
125
+ await this.append(sid, 'command.run', {
126
+ command: input.command,
127
+ ...(input.exitCode !== undefined ? { exitCode: input.exitCode } : {}),
128
+ ...(input.note !== undefined ? { note: input.note } : {}),
129
+ });
130
+ break;
131
+ case 'error':
132
+ await this.append(sid, 'error.recorded', {
133
+ message: input.message,
134
+ ...(input.context !== undefined ? { context: input.context } : {}),
135
+ });
136
+ break;
137
+ case 'error-resolved':
138
+ await this.append(sid, 'error.resolved', { message: input.message });
139
+ break;
140
+ case 'retry':
141
+ await this.append(sid, 'retry.recorded', input.what !== undefined ? { what: input.what } : {});
142
+ break;
143
+ case 'note':
144
+ await this.append(sid, 'note.recorded', { note: input.note });
145
+ break;
146
+ case 'compaction':
147
+ await this.append(sid, 'compaction.observed', input.note !== undefined ? { note: input.note } : {});
148
+ break;
149
+ case 'clarification':
150
+ await this.append(sid, 'clarification.recorded', input.note !== undefined ? { note: input.note } : {});
151
+ break;
152
+ case 'completed':
153
+ await this.append(sid, 'work.completed', { item: input.item });
154
+ break;
155
+ case 'pending':
156
+ await this.append(sid, 'work.pending', { item: input.item });
157
+ break;
158
+ case 'blocker':
159
+ await this.append(sid, 'blocker.recorded', { item: input.item });
160
+ break;
161
+ }
162
+ return this.pressure();
163
+ }
164
+ async heartbeat(args = {}) {
165
+ const sid = this.requireSession().id;
166
+ await this.append(sid, 'heartbeat', {
167
+ ...(args.reread !== undefined ? { reread: args.reread } : {}),
168
+ ...(args.note !== undefined ? { note: args.note } : {}),
169
+ ...(args.turns !== undefined ? { turns: args.turns } : {}),
170
+ });
171
+ return this.pressure();
172
+ }
173
+ async checkpoint(input) {
174
+ const state = this.requireSession();
175
+ const pressure = this.pressure();
176
+ const out = await this.checkpoints.create(state, pressure, await this.withCoordination(input));
177
+ await this.append(state.id, 'checkpoint.created', {
178
+ checkpointId: out.checkpoint.id,
179
+ reason: input.reason,
180
+ });
181
+ await this.telemetry.emit('checkpoint.created', {
182
+ reason: input.reason,
183
+ files: Object.keys(state.changedFiles).length,
184
+ risk: out.checkpoint.risk.level,
185
+ });
186
+ // Refresh shared memory so this checkpoint is visible to other workers and to
187
+ // this brief's own recall (auto-invalidated by the memory fingerprint, v0.7.1).
188
+ await this.refreshMemory();
189
+ const brief = out.continuationMarkdown + (await this.recallSection(state.task));
190
+ if (brief !== out.continuationMarkdown) {
191
+ await this.adapter.saveContinuation(out.checkpoint.continuationRef, brief);
192
+ }
193
+ return {
194
+ checkpoint: out.checkpoint,
195
+ brief,
196
+ pressure: this.pressure(),
197
+ };
198
+ }
199
+ async endSession() {
200
+ const state = this.requireSession();
201
+ const out = await this.checkpoints.create(state, this.pressure(), await this.withCoordination({ reason: 'session-end' }));
202
+ await this.append(state.id, 'checkpoint.created', {
203
+ checkpointId: out.checkpoint.id,
204
+ reason: 'session-end',
205
+ });
206
+ await this.telemetry.emit('checkpoint.created', {
207
+ reason: 'session-end',
208
+ files: Object.keys(state.changedFiles).length,
209
+ risk: out.checkpoint.risk.level,
210
+ });
211
+ await this.append(state.id, 'session.ended', {});
212
+ await this.refreshMemory();
213
+ const brief = out.continuationMarkdown + (await this.recallSection(state.task));
214
+ if (brief !== out.continuationMarkdown) {
215
+ await this.adapter.saveContinuation(out.checkpoint.continuationRef, brief);
216
+ }
217
+ return { checkpoint: out.checkpoint, brief };
218
+ }
219
+ status() {
220
+ return { state: this.requireSession(), pressure: this.pressure() };
221
+ }
222
+ /** Aggregate engineering risk of everything changed so far this session. */
223
+ sessionRisk() {
224
+ return assessSession(this.requireSession());
225
+ }
226
+ /**
227
+ * Evaluate a proposed change against engineering risk AND current context-loss
228
+ * pressure. Conservatism scales with pressure (see guardrail.ts): the same change
229
+ * gets a stricter decision as the session degrades. With no files supplied, falls
230
+ * back to the accumulated session risk.
231
+ */
232
+ assess(args) {
233
+ this.requireSession();
234
+ const risk = args.files && args.files.length > 0
235
+ ? assessChange(args.files.map((f) => ({
236
+ path: f.path,
237
+ changeKind: f.changeKind ?? 'modified',
238
+ ...(f.risk !== undefined ? { declaredRisk: f.risk } : {}),
239
+ })), args.intent)
240
+ : assessSession(this.requireSession());
241
+ return evaluateGuardrail(risk, this.pressure());
242
+ }
243
+ // ── GitHub engine (v0.4.0, advisory only — see ADR-0003) ─────────────────
244
+ /** Read-only git introspection of the active session's project root. */
245
+ gitContext() {
246
+ return readGitContext(this.requireSession().projectRoot);
247
+ }
248
+ /** Conventional-commit message proposed from the session ledger. No commit. */
249
+ proposeCommitMessage(extraSummary) {
250
+ return proposeCommit(this.requireSession(), extraSummary);
251
+ }
252
+ /** Keep-a-Changelog fragment proposed from the session. No file edit. */
253
+ proposeChangelog() {
254
+ return proposeChangelog(this.requireSession());
255
+ }
256
+ /** Release plan (semver bump, tag, notes). No version bump / tag / push. */
257
+ async proposeReleasePlan() {
258
+ const state = this.requireSession();
259
+ let version = '0.0.0';
260
+ try {
261
+ const raw = await readFile(join(state.projectRoot, 'package.json'), 'utf8');
262
+ const v = JSON.parse(raw).version;
263
+ if (typeof v === 'string')
264
+ version = v;
265
+ }
266
+ catch {
267
+ /* no package.json / unparseable: fall back to 0.0.0 */
268
+ }
269
+ const plan = proposeReleasePlan(state, version);
270
+ await this.telemetry.emit('release.prepared', {
271
+ bump: plan.bump,
272
+ nextVersion: plan.nextVersion,
273
+ });
274
+ return plan;
275
+ }
276
+ /** Latest persisted checkpoint across all sessions (for the MCP resource). */
277
+ latestCheckpoint() {
278
+ return this.adapter.loadLatestCheckpoint();
279
+ }
280
+ /** Latest persisted continuation brief, if any. */
281
+ latestContinuation() {
282
+ return this.adapter.loadLatestContinuation();
283
+ }
284
+ /** Cached repo intelligence (schema-valid only), if any (no scan). */
285
+ getIntelligence() {
286
+ return this.loadValidIntelligence();
287
+ }
288
+ /** Render a requested graph from cached intelligence (no scan). */
289
+ async graph(kind) {
290
+ const intel = await this.loadValidIntelligence();
291
+ if (!intel)
292
+ return undefined;
293
+ const graph = buildGraph(intel, kind);
294
+ await this.telemetry.emit('graph.generated', {
295
+ kind,
296
+ nodes: graph.nodes.length,
297
+ edges: graph.edges.length,
298
+ truncated: graph.truncated,
299
+ });
300
+ return { graph, markdown: renderGraphMarkdown(graph) };
301
+ }
302
+ /**
303
+ * Scan (or reuse) repo intelligence. With `force`, always rescans and persists.
304
+ * Without it, returns the cached artifact when present — that is the whole point:
305
+ * agents stop re-deriving repo understanding every session. A cache from an older
306
+ * artifact schema is treated as absent so new fields (e.g. the graph) are filled.
307
+ */
308
+ async scanRepo(projectRoot, force = false) {
309
+ const cached = await this.loadValidIntelligence();
310
+ if (cached && !force) {
311
+ return { intelligence: cached, fromCache: true, changed: false };
312
+ }
313
+ const intelligence = await this.scanner.scan(projectRoot);
314
+ const changed = !cached || cached.fingerprint !== intelligence.fingerprint;
315
+ await this.adapter.saveIntelligence(intelligence);
316
+ await this.persistGraphs(intelligence);
317
+ return { intelligence, fromCache: false, changed };
318
+ }
319
+ /** Load cached intelligence, ignoring caches written by an older artifact schema. */
320
+ async loadValidIntelligence() {
321
+ const intel = await this.adapter.loadLatestIntelligence();
322
+ if (!intel || intel.schema !== INTELLIGENCE_SCHEMA)
323
+ return undefined;
324
+ return intel;
325
+ }
326
+ /** Write the rendered Mermaid mirrors under `.kairo/graphs/` (best-effort). */
327
+ async persistGraphs(intel) {
328
+ const all = buildAllGraphs(intel);
329
+ for (const kind of GRAPH_KINDS) {
330
+ await this.adapter.saveGraph(kind, renderGraphMarkdown(all[kind]));
331
+ }
332
+ }
333
+ async priorSessions() {
334
+ const all = reduceAll(await this.adapter.readEvents());
335
+ return [...all.values()];
336
+ }
337
+ // ── Semantic memory (v0.6.0) ─────────────────────────────────────────────
338
+ /** Build/reuse the fingerprint-keyed semantic index. No re-embed on cache hit. */
339
+ async indexMemory(intel, force = false) {
340
+ const intelligence = intel ?? (await this.loadValidIntelligence());
341
+ if (!intelligence)
342
+ return undefined;
343
+ const sessions = await this.priorSessions();
344
+ const checkpoint = await this.adapter.loadLatestCheckpoint();
345
+ const nsMap = await this.coordination.sessionNamespaceMap();
346
+ const r = await this.memory.index({
347
+ intel: intelligence,
348
+ sessions,
349
+ checkpoint,
350
+ projectRoot: this.projectRoot || intelligence.projectRoot,
351
+ namespaceOf: (sid) => nsMap.get(sid) ?? 'workspace',
352
+ }, force);
353
+ await this.telemetry.emit('memory.refreshed', {
354
+ rebuilt: !r.reused,
355
+ chunks: r.chunks,
356
+ });
357
+ return { chunks: r.chunks, reused: r.reused };
358
+ }
359
+ /** Hybrid, explainable semantic recall — isolated to this worker's namespace. */
360
+ async searchMemory(query) {
361
+ const checkpoint = await this.adapter.loadLatestCheckpoint();
362
+ const results = await this.memory.search(query, {
363
+ checkpoint,
364
+ namespace: this.namespace,
365
+ });
366
+ await this.telemetry.emit('retrieval.performed', {
367
+ results: results.length,
368
+ topKind: results[0]?.chunk.kind ?? 'none',
369
+ });
370
+ return results;
371
+ }
372
+ /**
373
+ * Ensure shared memory reflects the latest session/decision/checkpoint state
374
+ * (v0.7.1). Auto-invalidated by the memory fingerprint: rebuilds only when the
375
+ * chunk set actually changed, so repeated calls are idempotent and offline-safe.
376
+ */
377
+ async refreshMemory() {
378
+ const r = await this.indexMemory();
379
+ return r ? { rebuilt: !r.reused, chunks: r.chunks } : undefined;
380
+ }
381
+ /** Deterministic compressed architectural memory (reduces rescanning). */
382
+ compressMemory() {
383
+ return this.memory.compress();
384
+ }
385
+ memoryStats() {
386
+ return this.memory.stats();
387
+ }
388
+ /**
389
+ * Markdown "semantic recall" appendix injected into continuation briefs.
390
+ * Budget-aware (ADR-0010): tiny mode → empty; normal mode → top-k small chunks.
391
+ */
392
+ async recallSection(task, budget) {
393
+ const b = budget ?? resolveBudget('normal');
394
+ if (b.maxRecallItems <= 0)
395
+ return '';
396
+ try {
397
+ const results = await this.memory.search({ text: task, limit: b.maxRecallItems }, { checkpoint: await this.adapter.loadLatestCheckpoint(), namespace: this.namespace });
398
+ if (results.length === 0)
399
+ return '';
400
+ const lines = results.map((r) => {
401
+ const why = clip(r.why, b.maxChunkChars);
402
+ return `- **${r.chunk.locator}** (${r.chunk.kind}, score ${r.score.toFixed(3)}) — ${why}`;
403
+ });
404
+ return [
405
+ '',
406
+ '## Semantic architecture recall',
407
+ '_Auto-retrieved so you can resume without rescanning. Lexical+structural hybrid (ADR-0005)._',
408
+ ...lines,
409
+ ].join('\n');
410
+ }
411
+ catch {
412
+ return '';
413
+ }
414
+ }
415
+ // ── Coordinated cognition (v0.7.0) ───────────────────────────────────────
416
+ /** Acquire a cooperative lease over a task/path/module scope. */
417
+ async acquireLease(args) {
418
+ const sid = this.requireSession().id;
419
+ const d = await this.coordination.acquire({
420
+ sessionId: sid,
421
+ workerId: this.workerId,
422
+ scopeKind: args.scopeKind,
423
+ scope: args.scope,
424
+ ttlMs: Math.max(1, args.ttlSeconds ?? 1800) * 1000,
425
+ });
426
+ await this.telemetry.emit(d.granted ? 'lease.granted' : 'lease.denied', {
427
+ scopeKind: args.scopeKind,
428
+ scope: args.scope,
429
+ ...(d.conflict ? { holder: d.conflict.workerId } : {}),
430
+ });
431
+ return d;
432
+ }
433
+ async renewLease(leaseId, ttlSeconds = 1800) {
434
+ const sid = this.requireSession().id;
435
+ return this.coordination.renew(sid, this.workerId, leaseId, Math.max(1, ttlSeconds) * 1000);
436
+ }
437
+ async releaseLease(leaseId) {
438
+ const sid = this.requireSession().id;
439
+ return this.coordination.release(sid, this.workerId, leaseId);
440
+ }
441
+ coordinationStatus() {
442
+ return this.coordination.state();
443
+ }
444
+ /** Distributed checkpoint graph (engineering timeline) as Mermaid markdown. */
445
+ async timeline() {
446
+ const graph = await this.coordination.timelineGraph();
447
+ return { markdown: renderGraphMarkdown(graph), checkpoints: graph.nodes.length };
448
+ }
449
+ // ── Telemetry & analytics (v0.8.0) ───────────────────────────────────────
450
+ /** Emit guardrail telemetry (called by the kairo_assess tool path). */
451
+ async recordAssessment(decision, riskLevel, directive) {
452
+ await this.telemetry.emit('risk.assessed', {
453
+ decision,
454
+ riskLevel,
455
+ pressureDirective: directive,
456
+ });
457
+ if (decision === 'HOLD')
458
+ await this.telemetry.emit('guard.hold', { riskLevel });
459
+ }
460
+ async analyticsInputs() {
461
+ const [telemetry, events, audit, sessions, coordination] = await Promise.all([
462
+ this.adapter.readTelemetry(),
463
+ this.adapter.readEvents(),
464
+ this.adapter.readAudit(),
465
+ this.priorSessions(),
466
+ this.coordination.state(),
467
+ ]);
468
+ return { telemetry, events, audit, sessions, coordination, generatedAt: this.clock.iso() };
469
+ }
470
+ async analyticsSummary() {
471
+ return analyticsSummary(await this.analyticsInputs());
472
+ }
473
+ async teamActivity() {
474
+ return teamActivity(await this.analyticsInputs());
475
+ }
476
+ async riskReport() {
477
+ return riskReport(await this.analyticsInputs());
478
+ }
479
+ async moduleActivity() {
480
+ return moduleActivity(await this.priorSessions());
481
+ }
482
+ /** Render the three reports to `.kairo/reports/` and opt-in export (no network). */
483
+ async writeReports() {
484
+ const inputs = await this.analyticsInputs();
485
+ const a = analyticsSummary(inputs);
486
+ await this.adapter.saveReport('ANALYTICS_SUMMARY.md', renderAnalyticsSummary(a));
487
+ await this.adapter.saveReport('TEAM_ACTIVITY.md', renderTeamActivity(teamActivity(inputs)));
488
+ await this.adapter.saveReport('RISK_REPORT.md', renderRiskReport(riskReport(inputs)));
489
+ const exporter = resolveExporter();
490
+ if (exporter)
491
+ await exporter.export(inputs.telemetry);
492
+ return {
493
+ analytics: a,
494
+ reports: ['ANALYTICS_SUMMARY.md', 'TEAM_ACTIVITY.md', 'RISK_REPORT.md'],
495
+ };
496
+ }
497
+ async telemetryStatus() {
498
+ const tel = await this.adapter.readTelemetry();
499
+ const byKind = {};
500
+ for (const e of tel)
501
+ byKind[e.kind] = (byKind[e.kind] ?? 0) + 1;
502
+ return {
503
+ events: tel.length,
504
+ byKind,
505
+ exportEnabled: resolveExporter() !== undefined,
506
+ network: false,
507
+ };
508
+ }
509
+ // ── Historical introspection (v0.8.1, ADR-0009) ─────────────────────────
510
+ async queryInputs() {
511
+ const [events, telemetry, audit] = await Promise.all([
512
+ this.adapter.readEvents(),
513
+ this.adapter.readTelemetry(),
514
+ this.adapter.readAudit(),
515
+ ]);
516
+ return { events, telemetry, audit, sessionToWorker: buildSessionToWorker(events) };
517
+ }
518
+ async queryEvents(filter = {}) {
519
+ return queryEvents({ ...filter, callerNamespace: this.namespace }, await this.queryInputs());
520
+ }
521
+ async timelineQuery(kind) {
522
+ return timeline(kind, await this.queryInputs(), this.namespace);
523
+ }
524
+ async checkpointLineage(id) {
525
+ return checkpointLineage(id, (cid) => this.adapter.loadCheckpoint(cid));
526
+ }
527
+ async conflictHistory() {
528
+ return conflictHistory(await this.queryInputs(), this.namespace);
529
+ }
530
+ async retrievalTrace(eventId) {
531
+ return retrievalTrace(eventId, await this.queryInputs(), this.namespace);
532
+ }
533
+ async whyEvent(eventId) {
534
+ return whyEvent(eventId, await this.queryInputs(), this.namespace);
535
+ }
536
+ // ── Token-efficient brief generation (v0.8.2, ADR-0010) ─────────────────
537
+ /**
538
+ * Build a continuation brief in `tiny` / `normal` / `deep` mode within a
539
+ * character budget. Sources the latest checkpoint (or a specific session's
540
+ * latest, if `sessionId` is provided). Appends namespace-safe semantic recall
541
+ * unless the budget zeroes it out (tiny).
542
+ */
543
+ async buildBrief(opts = {}) {
544
+ const budget = resolveBudget(opts.mode ?? 'normal', opts.maxChars !== undefined ? { maxBriefChars: opts.maxChars } : {});
545
+ let cp = await this.adapter.loadLatestCheckpoint();
546
+ if (opts.sessionId) {
547
+ const events = await this.adapter.readEvents();
548
+ const lastCpId = [...events]
549
+ .reverse()
550
+ .find((e) => e.type === 'checkpoint.created' && e.sessionId === opts.sessionId);
551
+ if (lastCpId) {
552
+ const id = lastCpId.payload.checkpointId;
553
+ if (id)
554
+ cp = (await this.adapter.loadCheckpoint(id)) ?? cp;
555
+ }
556
+ }
557
+ if (!cp)
558
+ return undefined;
559
+ let md = buildContinuationMarkdown(cp, { budget });
560
+ const recall = await this.recallSection(cp.task, budget);
561
+ if (recall)
562
+ md = clip(md + recall, budget.maxBriefChars);
563
+ return { markdown: md, chars: md.length, mode: budget.mode };
564
+ }
565
+ /** Augment a checkpoint with owning worker + parent checkpoint (the DAG link). */
566
+ async withCoordination(input) {
567
+ const parent = await this.adapter.loadLatestCheckpoint();
568
+ return {
569
+ ...input,
570
+ ownerWorkerId: this.workerId,
571
+ ...(parent ? { parentCheckpointId: parent.id } : {}),
572
+ };
573
+ }
574
+ // ── internals ────────────────────────────────────────────────────────────
575
+ requireSession() {
576
+ if (!this.current) {
577
+ throw new KairoError('No active Kairo session.', 'Call kairo_session_start before any other Kairo tool.');
578
+ }
579
+ return this.current;
580
+ }
581
+ async append(sessionId, type, payload) {
582
+ const event = {
583
+ schema: EVENT_SCHEMA_VERSION,
584
+ id: newId(this.clock.now()),
585
+ ts: this.clock.iso(),
586
+ sessionId,
587
+ type,
588
+ payload,
589
+ };
590
+ // Append to the durable log first, then update the in-memory projection and
591
+ // persist the derived snapshot. Order matters for crash consistency.
592
+ await this.adapter.appendEvent(event);
593
+ if (!this.current || this.current.id !== sessionId) {
594
+ this.current = applyEvent(this.blankState(sessionId), event);
595
+ }
596
+ else {
597
+ this.current = applyEvent(this.current, event);
598
+ }
599
+ await this.adapter.saveSessionSnapshot(this.current);
600
+ }
601
+ blankState(id) {
602
+ return {
603
+ id,
604
+ agent: 'unknown',
605
+ task: '',
606
+ projectRoot: '',
607
+ startedAt: this.clock.iso(),
608
+ lastActivityAt: this.clock.iso(),
609
+ status: 'active',
610
+ changedFiles: {},
611
+ decisions: [],
612
+ commands: [],
613
+ errors: [],
614
+ completedWork: [],
615
+ pendingWork: [],
616
+ blockers: [],
617
+ retries: 0,
618
+ heartbeats: 0,
619
+ toolCalls: 0,
620
+ compactions: 0,
621
+ clarificationLoops: 0,
622
+ cumulativeDiffBytes: 0,
623
+ rereadCounts: {},
624
+ };
625
+ }
626
+ pressure() {
627
+ const s = this.current;
628
+ if (!s) {
629
+ return computePressure({
630
+ toolCalls: 0,
631
+ changedFiles: 0,
632
+ cumulativeDiffBytes: 0,
633
+ retries: 0,
634
+ unresolvedErrors: 0,
635
+ repeatedRereads: 0,
636
+ compactions: 0,
637
+ clarificationLoops: 0,
638
+ elapsedMs: 0,
639
+ });
640
+ }
641
+ const startedMs = Date.parse(s.startedAt) || this.clock.now();
642
+ return computePressure({
643
+ toolCalls: s.toolCalls,
644
+ changedFiles: Object.keys(s.changedFiles).length,
645
+ cumulativeDiffBytes: s.cumulativeDiffBytes,
646
+ retries: s.retries,
647
+ unresolvedErrors: unresolvedErrors(s),
648
+ repeatedRereads: repeatedRereads(s),
649
+ compactions: s.compactions,
650
+ clarificationLoops: s.clarificationLoops,
651
+ elapsedMs: Math.max(0, this.clock.now() - startedMs),
652
+ });
653
+ }
654
+ }
655
+ //# sourceMappingURL=sessionManager.js.map