@iworkforces/tracelattice 2.0.3

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 (422) hide show
  1. package/LICENSE +24 -0
  2. package/README.md +260 -0
  3. package/dist/CliLifecycle.d.ts +31 -0
  4. package/dist/CliLifecycle.d.ts.map +1 -0
  5. package/dist/CliLifecycle.js +90 -0
  6. package/dist/CliLifecycle.js.map +1 -0
  7. package/dist/ServerConfig.d.ts +290 -0
  8. package/dist/ServerConfig.d.ts.map +1 -0
  9. package/dist/ServerConfig.js +175 -0
  10. package/dist/ServerConfig.js.map +1 -0
  11. package/dist/cache/DiscoveryCache.d.ts +269 -0
  12. package/dist/cache/DiscoveryCache.d.ts.map +1 -0
  13. package/dist/cache/DiscoveryCache.js +104 -0
  14. package/dist/cache/DiscoveryCache.js.map +1 -0
  15. package/dist/cli.d.ts +3 -0
  16. package/dist/cli.d.ts.map +1 -0
  17. package/dist/cli.js +5177 -0
  18. package/dist/cli.js.map +1 -0
  19. package/dist/config/ConfigLoader.d.ts +270 -0
  20. package/dist/config/ConfigLoader.d.ts.map +1 -0
  21. package/dist/config/ConfigLoader.js +186 -0
  22. package/dist/config/ConfigLoader.js.map +1 -0
  23. package/dist/context/RequestContext.d.ts +43 -0
  24. package/dist/context/RequestContext.d.ts.map +1 -0
  25. package/dist/context/RequestContext.js +14 -0
  26. package/dist/context/RequestContext.js.map +1 -0
  27. package/dist/contracts/PersistenceBackend.d.ts +134 -0
  28. package/dist/contracts/PersistenceBackend.d.ts.map +1 -0
  29. package/dist/contracts/PersistenceBackend.js +6 -0
  30. package/dist/contracts/PersistenceBackend.js.map +1 -0
  31. package/dist/contracts/calibrator.d.ts +97 -0
  32. package/dist/contracts/calibrator.d.ts.map +1 -0
  33. package/dist/contracts/calibrator.js +1 -0
  34. package/dist/contracts/features.d.ts +35 -0
  35. package/dist/contracts/features.d.ts.map +1 -0
  36. package/dist/contracts/features.js +12 -0
  37. package/dist/contracts/features.js.map +1 -0
  38. package/dist/contracts/ids.d.ts +68 -0
  39. package/dist/contracts/ids.d.ts.map +1 -0
  40. package/dist/contracts/ids.js +40 -0
  41. package/dist/contracts/ids.js.map +1 -0
  42. package/dist/contracts/interfaces.d.ts +254 -0
  43. package/dist/contracts/interfaces.d.ts.map +1 -0
  44. package/dist/contracts/interfaces.js +1 -0
  45. package/dist/contracts/persistence-work.d.ts +96 -0
  46. package/dist/contracts/persistence-work.d.ts.map +1 -0
  47. package/dist/contracts/persistence-work.js +1 -0
  48. package/dist/contracts/reasoning-types.d.ts +21 -0
  49. package/dist/contracts/reasoning-types.d.ts.map +1 -0
  50. package/dist/contracts/reasoning-types.js +1 -0
  51. package/dist/contracts/strategy.d.ts +107 -0
  52. package/dist/contracts/strategy.d.ts.map +1 -0
  53. package/dist/contracts/strategy.js +1 -0
  54. package/dist/contracts/summary.d.ts +110 -0
  55. package/dist/contracts/summary.d.ts.map +1 -0
  56. package/dist/contracts/summary.js +1 -0
  57. package/dist/contracts/suspension.d.ts +215 -0
  58. package/dist/contracts/suspension.d.ts.map +1 -0
  59. package/dist/contracts/suspension.js +1 -0
  60. package/dist/contracts/transport.d.ts +26 -0
  61. package/dist/contracts/transport.d.ts.map +1 -0
  62. package/dist/contracts/transport.js +1 -0
  63. package/dist/core/CrossReferenceValidator.d.ts +18 -0
  64. package/dist/core/CrossReferenceValidator.d.ts.map +1 -0
  65. package/dist/core/CrossReferenceValidator.js +125 -0
  66. package/dist/core/CrossReferenceValidator.js.map +1 -0
  67. package/dist/core/HistoryManager.d.ts +215 -0
  68. package/dist/core/HistoryManager.d.ts.map +1 -0
  69. package/dist/core/HistoryManager.js +594 -0
  70. package/dist/core/HistoryManager.js.map +1 -0
  71. package/dist/core/IHistoryManager.d.ts +163 -0
  72. package/dist/core/IHistoryManager.d.ts.map +1 -0
  73. package/dist/core/IHistoryManager.js +1 -0
  74. package/dist/core/IThoughtFormatter.d.ts +51 -0
  75. package/dist/core/IThoughtFormatter.d.ts.map +1 -0
  76. package/dist/core/IThoughtFormatter.js +1 -0
  77. package/dist/core/InputNormalizer.d.ts +140 -0
  78. package/dist/core/InputNormalizer.d.ts.map +1 -0
  79. package/dist/core/InputNormalizer.js +95 -0
  80. package/dist/core/InputNormalizer.js.map +1 -0
  81. package/dist/core/PersistenceBuffer.d.ts +204 -0
  82. package/dist/core/PersistenceBuffer.d.ts.map +1 -0
  83. package/dist/core/PersistenceBuffer.js +382 -0
  84. package/dist/core/PersistenceBuffer.js.map +1 -0
  85. package/dist/core/PersistenceBufferErrors.d.ts +22 -0
  86. package/dist/core/PersistenceBufferErrors.d.ts.map +1 -0
  87. package/dist/core/PersistenceBufferErrors.js +30 -0
  88. package/dist/core/PersistenceBufferErrors.js.map +1 -0
  89. package/dist/core/PersistenceRestore.d.ts +21 -0
  90. package/dist/core/PersistenceRestore.d.ts.map +1 -0
  91. package/dist/core/PersistenceRestore.js +87 -0
  92. package/dist/core/PersistenceRestore.js.map +1 -0
  93. package/dist/core/PersistenceWorkQueue.d.ts +155 -0
  94. package/dist/core/PersistenceWorkQueue.d.ts.map +1 -0
  95. package/dist/core/PersistenceWorkQueue.js +298 -0
  96. package/dist/core/PersistenceWorkQueue.js.map +1 -0
  97. package/dist/core/PersistenceWriter.d.ts +55 -0
  98. package/dist/core/PersistenceWriter.d.ts.map +1 -0
  99. package/dist/core/PersistenceWriter.js +112 -0
  100. package/dist/core/PersistenceWriter.js.map +1 -0
  101. package/dist/core/SessionErrors.d.ts +37 -0
  102. package/dist/core/SessionErrors.d.ts.map +1 -0
  103. package/dist/core/SessionErrors.js +50 -0
  104. package/dist/core/SessionErrors.js.map +1 -0
  105. package/dist/core/SessionLifecycleCoordinator.d.ts +74 -0
  106. package/dist/core/SessionLifecycleCoordinator.d.ts.map +1 -0
  107. package/dist/core/SessionLifecycleCoordinator.js +222 -0
  108. package/dist/core/SessionLifecycleCoordinator.js.map +1 -0
  109. package/dist/core/SessionLock.d.ts +59 -0
  110. package/dist/core/SessionLock.d.ts.map +1 -0
  111. package/dist/core/SessionLock.js +39 -0
  112. package/dist/core/SessionLock.js.map +1 -0
  113. package/dist/core/SessionManager.d.ts +62 -0
  114. package/dist/core/SessionManager.d.ts.map +1 -0
  115. package/dist/core/SessionManager.js +75 -0
  116. package/dist/core/SessionManager.js.map +1 -0
  117. package/dist/core/SessionResetCoordinator.d.ts +37 -0
  118. package/dist/core/SessionResetCoordinator.d.ts.map +1 -0
  119. package/dist/core/SessionResetCoordinator.js +80 -0
  120. package/dist/core/SessionResetCoordinator.js.map +1 -0
  121. package/dist/core/ThoughtEvaluator.d.ts +48 -0
  122. package/dist/core/ThoughtEvaluator.d.ts.map +1 -0
  123. package/dist/core/ThoughtEvaluator.js +85 -0
  124. package/dist/core/ThoughtEvaluator.js.map +1 -0
  125. package/dist/core/ThoughtFormatter.d.ts +134 -0
  126. package/dist/core/ThoughtFormatter.d.ts.map +1 -0
  127. package/dist/core/ThoughtFormatter.js +118 -0
  128. package/dist/core/ThoughtFormatter.js.map +1 -0
  129. package/dist/core/ThoughtProcessor.d.ts +259 -0
  130. package/dist/core/ThoughtProcessor.d.ts.map +1 -0
  131. package/dist/core/ThoughtProcessor.js +451 -0
  132. package/dist/core/ThoughtProcessor.js.map +1 -0
  133. package/dist/core/ThoughtReferenceIndex.d.ts +23 -0
  134. package/dist/core/ThoughtReferenceIndex.d.ts.map +1 -0
  135. package/dist/core/ThoughtReferenceIndex.js +66 -0
  136. package/dist/core/ThoughtReferenceIndex.js.map +1 -0
  137. package/dist/core/VerificationOutcomeAdmission.d.ts +15 -0
  138. package/dist/core/VerificationOutcomeAdmission.d.ts.map +1 -0
  139. package/dist/core/VerificationOutcomeAdmission.js +28 -0
  140. package/dist/core/VerificationOutcomeAdmission.js.map +1 -0
  141. package/dist/core/compression/CompressionService.d.ts +76 -0
  142. package/dist/core/compression/CompressionService.d.ts.map +1 -0
  143. package/dist/core/compression/CompressionService.js +160 -0
  144. package/dist/core/compression/CompressionService.js.map +1 -0
  145. package/dist/core/compression/DehydrationPolicy.d.ts +75 -0
  146. package/dist/core/compression/DehydrationPolicy.d.ts.map +1 -0
  147. package/dist/core/compression/DehydrationPolicy.js +45 -0
  148. package/dist/core/compression/DehydrationPolicy.js.map +1 -0
  149. package/dist/core/compression/InMemorySummaryStore.d.ts +132 -0
  150. package/dist/core/compression/InMemorySummaryStore.d.ts.map +1 -0
  151. package/dist/core/compression/InMemorySummaryStore.js +69 -0
  152. package/dist/core/compression/InMemorySummaryStore.js.map +1 -0
  153. package/dist/core/compression/Summary.d.ts +74 -0
  154. package/dist/core/compression/Summary.d.ts.map +1 -0
  155. package/dist/core/compression/Summary.js +16 -0
  156. package/dist/core/compression/Summary.js.map +1 -0
  157. package/dist/core/evaluator/Aggregator.d.ts +40 -0
  158. package/dist/core/evaluator/Aggregator.d.ts.map +1 -0
  159. package/dist/core/evaluator/Aggregator.js +36 -0
  160. package/dist/core/evaluator/Aggregator.js.map +1 -0
  161. package/dist/core/evaluator/Calibrator.d.ts +52 -0
  162. package/dist/core/evaluator/Calibrator.d.ts.map +1 -0
  163. package/dist/core/evaluator/Calibrator.js +135 -0
  164. package/dist/core/evaluator/Calibrator.js.map +1 -0
  165. package/dist/core/evaluator/PatternDetector.d.ts +69 -0
  166. package/dist/core/evaluator/PatternDetector.d.ts.map +1 -0
  167. package/dist/core/evaluator/PatternDetector.js +192 -0
  168. package/dist/core/evaluator/PatternDetector.js.map +1 -0
  169. package/dist/core/evaluator/SignalComputer.d.ts +116 -0
  170. package/dist/core/evaluator/SignalComputer.d.ts.map +1 -0
  171. package/dist/core/evaluator/SignalComputer.js +110 -0
  172. package/dist/core/evaluator/SignalComputer.js.map +1 -0
  173. package/dist/core/evaluator/calibration-math.d.ts +39 -0
  174. package/dist/core/evaluator/calibration-math.d.ts.map +1 -0
  175. package/dist/core/evaluator/calibration-math.js +42 -0
  176. package/dist/core/evaluator/calibration-math.js.map +1 -0
  177. package/dist/core/evaluator/internals.d.ts +36 -0
  178. package/dist/core/evaluator/internals.d.ts.map +1 -0
  179. package/dist/core/evaluator/internals.js +43 -0
  180. package/dist/core/evaluator/internals.js.map +1 -0
  181. package/dist/core/graph/Edge.d.ts +58 -0
  182. package/dist/core/graph/Edge.d.ts.map +1 -0
  183. package/dist/core/graph/Edge.js +1 -0
  184. package/dist/core/graph/EdgeEmitter.d.ts +68 -0
  185. package/dist/core/graph/EdgeEmitter.d.ts.map +1 -0
  186. package/dist/core/graph/EdgeEmitter.js +118 -0
  187. package/dist/core/graph/EdgeEmitter.js.map +1 -0
  188. package/dist/core/graph/EdgeStore.d.ts +116 -0
  189. package/dist/core/graph/EdgeStore.d.ts.map +1 -0
  190. package/dist/core/graph/EdgeStore.js +107 -0
  191. package/dist/core/graph/EdgeStore.js.map +1 -0
  192. package/dist/core/graph/GraphView.d.ts +157 -0
  193. package/dist/core/graph/GraphView.d.ts.map +1 -0
  194. package/dist/core/graph/GraphView.js +149 -0
  195. package/dist/core/graph/GraphView.js.map +1 -0
  196. package/dist/core/ids.d.ts +33 -0
  197. package/dist/core/ids.d.ts.map +1 -0
  198. package/dist/core/ids.js +11 -0
  199. package/dist/core/ids.js.map +1 -0
  200. package/dist/core/reasoning/OutcomeRecorder.d.ts +88 -0
  201. package/dist/core/reasoning/OutcomeRecorder.d.ts.map +1 -0
  202. package/dist/core/reasoning/OutcomeRecorder.js +51 -0
  203. package/dist/core/reasoning/OutcomeRecorder.js.map +1 -0
  204. package/dist/core/reasoning/strategies/SequentialStrategy.d.ts +54 -0
  205. package/dist/core/reasoning/strategies/SequentialStrategy.d.ts.map +1 -0
  206. package/dist/core/reasoning/strategies/SequentialStrategy.js +22 -0
  207. package/dist/core/reasoning/strategies/SequentialStrategy.js.map +1 -0
  208. package/dist/core/reasoning/strategies/StrategyFactory.d.ts +25 -0
  209. package/dist/core/reasoning/strategies/StrategyFactory.d.ts.map +1 -0
  210. package/dist/core/reasoning/strategies/StrategyFactory.js +16 -0
  211. package/dist/core/reasoning/strategies/StrategyFactory.js.map +1 -0
  212. package/dist/core/reasoning/strategies/TreeOfThoughtStrategy.d.ts +58 -0
  213. package/dist/core/reasoning/strategies/TreeOfThoughtStrategy.d.ts.map +1 -0
  214. package/dist/core/reasoning/strategies/TreeOfThoughtStrategy.js +103 -0
  215. package/dist/core/reasoning/strategies/TreeOfThoughtStrategy.js.map +1 -0
  216. package/dist/core/reasoning/strategies/plateau.d.ts +18 -0
  217. package/dist/core/reasoning/strategies/plateau.d.ts.map +1 -0
  218. package/dist/core/reasoning/strategies/plateau.js +12 -0
  219. package/dist/core/reasoning/strategies/plateau.js.map +1 -0
  220. package/dist/core/reasoning/strategies/totScoring.d.ts +91 -0
  221. package/dist/core/reasoning/strategies/totScoring.d.ts.map +1 -0
  222. package/dist/core/reasoning/strategies/totScoring.js +88 -0
  223. package/dist/core/reasoning/strategies/totScoring.js.map +1 -0
  224. package/dist/core/reasoning.d.ts +179 -0
  225. package/dist/core/reasoning.d.ts.map +1 -0
  226. package/dist/core/reasoning.js +1 -0
  227. package/dist/core/step.d.ts +50 -0
  228. package/dist/core/step.d.ts.map +1 -0
  229. package/dist/core/step.js +1 -0
  230. package/dist/core/thought.d.ts +113 -0
  231. package/dist/core/thought.d.ts.map +1 -0
  232. package/dist/core/thought.js +1 -0
  233. package/dist/core/tools/InMemorySuspensionStore.d.ts +66 -0
  234. package/dist/core/tools/InMemorySuspensionStore.d.ts.map +1 -0
  235. package/dist/core/tools/InMemorySuspensionStore.js +121 -0
  236. package/dist/core/tools/InMemorySuspensionStore.js.map +1 -0
  237. package/dist/di/Container.d.ts +253 -0
  238. package/dist/di/Container.d.ts.map +1 -0
  239. package/dist/di/Container.js +111 -0
  240. package/dist/di/Container.js.map +1 -0
  241. package/dist/di/ServiceRegistry.d.ts +50 -0
  242. package/dist/di/ServiceRegistry.d.ts.map +1 -0
  243. package/dist/di/ServiceRegistry.js +1 -0
  244. package/dist/errors.d.ts +663 -0
  245. package/dist/errors.d.ts.map +1 -0
  246. package/dist/errors.js +282 -0
  247. package/dist/errors.js.map +1 -0
  248. package/dist/health/HealthChecker.d.ts +73 -0
  249. package/dist/health/HealthChecker.d.ts.map +1 -0
  250. package/dist/health/HealthChecker.js +70 -0
  251. package/dist/health/HealthChecker.js.map +1 -0
  252. package/dist/lib.d.ts +273 -0
  253. package/dist/lib.d.ts.map +1 -0
  254. package/dist/lib.js +409 -0
  255. package/dist/lib.js.map +1 -0
  256. package/dist/logger/NullLogger.d.ts +154 -0
  257. package/dist/logger/NullLogger.d.ts.map +1 -0
  258. package/dist/logger/NullLogger.js +24 -0
  259. package/dist/logger/NullLogger.js.map +1 -0
  260. package/dist/logger/StructuredLogger.d.ts +327 -0
  261. package/dist/logger/StructuredLogger.d.ts.map +1 -0
  262. package/dist/logger/StructuredLogger.js +72 -0
  263. package/dist/logger/StructuredLogger.js.map +1 -0
  264. package/dist/metrics/metrics.impl.d.ts +252 -0
  265. package/dist/metrics/metrics.impl.d.ts.map +1 -0
  266. package/dist/metrics/metrics.impl.js +197 -0
  267. package/dist/metrics/metrics.impl.js.map +1 -0
  268. package/dist/persistence/FileLegacyImport.d.ts +2 -0
  269. package/dist/persistence/FileLegacyImport.d.ts.map +1 -0
  270. package/dist/persistence/FileLegacyImport.js +183 -0
  271. package/dist/persistence/FileLegacyImport.js.map +1 -0
  272. package/dist/persistence/FilePersistence.d.ts +53 -0
  273. package/dist/persistence/FilePersistence.d.ts.map +1 -0
  274. package/dist/persistence/FilePersistence.js +312 -0
  275. package/dist/persistence/FilePersistence.js.map +1 -0
  276. package/dist/persistence/FileSnapshotTypes.d.ts +29 -0
  277. package/dist/persistence/FileSnapshotTypes.d.ts.map +1 -0
  278. package/dist/persistence/FileSnapshotTypes.js +1 -0
  279. package/dist/persistence/FileSnapshotV2.d.ts +377 -0
  280. package/dist/persistence/FileSnapshotV2.d.ts.map +1 -0
  281. package/dist/persistence/FileSnapshotV2.js +124 -0
  282. package/dist/persistence/FileSnapshotV2.js.map +1 -0
  283. package/dist/persistence/FileSnapshotValidation.d.ts +15 -0
  284. package/dist/persistence/FileSnapshotValidation.d.ts.map +1 -0
  285. package/dist/persistence/FileSnapshotValidation.js +64 -0
  286. package/dist/persistence/FileSnapshotValidation.js.map +1 -0
  287. package/dist/persistence/FileWriter.d.ts +30 -0
  288. package/dist/persistence/FileWriter.d.ts.map +1 -0
  289. package/dist/persistence/FileWriter.js +155 -0
  290. package/dist/persistence/FileWriter.js.map +1 -0
  291. package/dist/persistence/MemoryPersistence.d.ts +45 -0
  292. package/dist/persistence/MemoryPersistence.d.ts.map +1 -0
  293. package/dist/persistence/MemoryPersistence.js +180 -0
  294. package/dist/persistence/MemoryPersistence.js.map +1 -0
  295. package/dist/persistence/PersistenceCodec.d.ts +7 -0
  296. package/dist/persistence/PersistenceCodec.d.ts.map +1 -0
  297. package/dist/persistence/PersistenceCodec.js +97 -0
  298. package/dist/persistence/PersistenceCodec.js.map +1 -0
  299. package/dist/persistence/PersistenceErrors.d.ts +23 -0
  300. package/dist/persistence/PersistenceErrors.d.ts.map +1 -0
  301. package/dist/persistence/PersistenceErrors.js +26 -0
  302. package/dist/persistence/PersistenceErrors.js.map +1 -0
  303. package/dist/persistence/PersistenceFactory.d.ts +21 -0
  304. package/dist/persistence/PersistenceFactory.d.ts.map +1 -0
  305. package/dist/persistence/PersistenceFactory.js +28 -0
  306. package/dist/persistence/PersistenceFactory.js.map +1 -0
  307. package/dist/persistence/PersistenceScope.d.ts +42 -0
  308. package/dist/persistence/PersistenceScope.d.ts.map +1 -0
  309. package/dist/persistence/PersistenceScope.js +93 -0
  310. package/dist/persistence/PersistenceScope.js.map +1 -0
  311. package/dist/persistence/SessionScopedPersistence.d.ts +4 -0
  312. package/dist/persistence/SessionScopedPersistence.d.ts.map +1 -0
  313. package/dist/persistence/SessionScopedPersistence.js +9 -0
  314. package/dist/persistence/SessionScopedPersistence.js.map +1 -0
  315. package/dist/persistence/SqliteDriver.d.ts +22 -0
  316. package/dist/persistence/SqliteDriver.d.ts.map +1 -0
  317. package/dist/persistence/SqliteDriver.js +29 -0
  318. package/dist/persistence/SqliteDriver.js.map +1 -0
  319. package/dist/persistence/SqliteLegacyImport.d.ts +14 -0
  320. package/dist/persistence/SqliteLegacyImport.d.ts.map +1 -0
  321. package/dist/persistence/SqliteLegacyImport.js +136 -0
  322. package/dist/persistence/SqliteLegacyImport.js.map +1 -0
  323. package/dist/persistence/SqliteLegacySchema.d.ts +15 -0
  324. package/dist/persistence/SqliteLegacySchema.d.ts.map +1 -0
  325. package/dist/persistence/SqliteLegacySchema.js +72 -0
  326. package/dist/persistence/SqliteLegacySchema.js.map +1 -0
  327. package/dist/persistence/SqlitePayload.d.ts +11 -0
  328. package/dist/persistence/SqlitePayload.d.ts.map +1 -0
  329. package/dist/persistence/SqlitePayload.js +86 -0
  330. package/dist/persistence/SqlitePayload.js.map +1 -0
  331. package/dist/persistence/SqlitePersistence.d.ts +49 -0
  332. package/dist/persistence/SqlitePersistence.d.ts.map +1 -0
  333. package/dist/persistence/SqlitePersistence.js +248 -0
  334. package/dist/persistence/SqlitePersistence.js.map +1 -0
  335. package/dist/persistence/SqliteSchemaV2.d.ts +14 -0
  336. package/dist/persistence/SqliteSchemaV2.d.ts.map +1 -0
  337. package/dist/persistence/SqliteSchemaV2.js +129 -0
  338. package/dist/persistence/SqliteSchemaV2.js.map +1 -0
  339. package/dist/persistence/SqliteSnapshotWriter.d.ts +17 -0
  340. package/dist/persistence/SqliteSnapshotWriter.d.ts.map +1 -0
  341. package/dist/persistence/SqliteSnapshotWriter.js +30 -0
  342. package/dist/persistence/SqliteSnapshotWriter.js.map +1 -0
  343. package/dist/pool/ConnectionPool.d.ts +203 -0
  344. package/dist/pool/ConnectionPool.d.ts.map +1 -0
  345. package/dist/pool/ConnectionPool.js +303 -0
  346. package/dist/pool/ConnectionPool.js.map +1 -0
  347. package/dist/pool/IConnectionPool.d.ts +143 -0
  348. package/dist/pool/IConnectionPool.d.ts.map +1 -0
  349. package/dist/pool/IConnectionPool.js +1 -0
  350. package/dist/pool/PoolErrors.d.ts +11 -0
  351. package/dist/pool/PoolErrors.d.ts.map +1 -0
  352. package/dist/pool/PoolErrors.js +16 -0
  353. package/dist/pool/PoolErrors.js.map +1 -0
  354. package/dist/registry/BaseRegistry.d.ts +219 -0
  355. package/dist/registry/BaseRegistry.d.ts.map +1 -0
  356. package/dist/registry/BaseRegistry.js +215 -0
  357. package/dist/registry/BaseRegistry.js.map +1 -0
  358. package/dist/registry/SkillRegistry.d.ts +67 -0
  359. package/dist/registry/SkillRegistry.d.ts.map +1 -0
  360. package/dist/registry/SkillRegistry.js +87 -0
  361. package/dist/registry/SkillRegistry.js.map +1 -0
  362. package/dist/registry/ToolRegistry.d.ts +70 -0
  363. package/dist/registry/ToolRegistry.d.ts.map +1 -0
  364. package/dist/registry/ToolRegistry.js +96 -0
  365. package/dist/registry/ToolRegistry.js.map +1 -0
  366. package/dist/sanitize.d.ts +164 -0
  367. package/dist/sanitize.d.ts.map +1 -0
  368. package/dist/sanitize.js +100 -0
  369. package/dist/sanitize.js.map +1 -0
  370. package/dist/schema.d.ts +562 -0
  371. package/dist/schema.d.ts.map +1 -0
  372. package/dist/schema.js +251 -0
  373. package/dist/schema.js.map +1 -0
  374. package/dist/transport/BaseTransport.d.ts +166 -0
  375. package/dist/transport/BaseTransport.d.ts.map +1 -0
  376. package/dist/transport/BaseTransport.js +199 -0
  377. package/dist/transport/BaseTransport.js.map +1 -0
  378. package/dist/transport/HttpHelpers.d.ts +53 -0
  379. package/dist/transport/HttpHelpers.d.ts.map +1 -0
  380. package/dist/transport/HttpHelpers.js +44 -0
  381. package/dist/transport/HttpHelpers.js.map +1 -0
  382. package/dist/transport/HttpRequestLifecycle.d.ts +37 -0
  383. package/dist/transport/HttpRequestLifecycle.d.ts.map +1 -0
  384. package/dist/transport/HttpRequestLifecycle.js +87 -0
  385. package/dist/transport/HttpRequestLifecycle.js.map +1 -0
  386. package/dist/transport/HttpTransport.d.ts +140 -0
  387. package/dist/transport/HttpTransport.d.ts.map +1 -0
  388. package/dist/transport/HttpTransport.js +245 -0
  389. package/dist/transport/HttpTransport.js.map +1 -0
  390. package/dist/transport/SseTransport.d.ts +149 -0
  391. package/dist/transport/SseTransport.d.ts.map +1 -0
  392. package/dist/transport/SseTransport.js +470 -0
  393. package/dist/transport/SseTransport.js.map +1 -0
  394. package/dist/transport/StreamableHttpTransport.d.ts +225 -0
  395. package/dist/transport/StreamableHttpTransport.d.ts.map +1 -0
  396. package/dist/transport/StreamableHttpTransport.js +449 -0
  397. package/dist/transport/StreamableHttpTransport.js.map +1 -0
  398. package/dist/types/disposable.d.ts +22 -0
  399. package/dist/types/disposable.d.ts.map +1 -0
  400. package/dist/types/disposable.js +1 -0
  401. package/dist/types/server-config.d.ts +32 -0
  402. package/dist/types/server-config.d.ts.map +1 -0
  403. package/dist/types/server-config.js +1 -0
  404. package/dist/types/skill.d.ts +74 -0
  405. package/dist/types/skill.d.ts.map +1 -0
  406. package/dist/types/skill.js +1 -0
  407. package/dist/types/tool.d.ts +78 -0
  408. package/dist/types/tool.d.ts.map +1 -0
  409. package/dist/types/tool.js +1 -0
  410. package/dist/utils.d.ts +27 -0
  411. package/dist/utils.d.ts.map +1 -0
  412. package/dist/utils.js +6 -0
  413. package/dist/utils.js.map +1 -0
  414. package/dist/watchers/SkillWatcher.d.ts +25 -0
  415. package/dist/watchers/SkillWatcher.d.ts.map +1 -0
  416. package/dist/watchers/SkillWatcher.js +96 -0
  417. package/dist/watchers/SkillWatcher.js.map +1 -0
  418. package/dist/watchers/ToolWatcher.d.ts +24 -0
  419. package/dist/watchers/ToolWatcher.d.ts.map +1 -0
  420. package/dist/watchers/ToolWatcher.js +92 -0
  421. package/dist/watchers/ToolWatcher.js.map +1 -0
  422. package/package.json +106 -0
@@ -0,0 +1 @@
1
+ {"version":3,"file":"core/HistoryManager.js","sources":["../../src/core/HistoryManager.ts"],"sourcesContent":["/**\n * History and branch management for sequential thinking.\n *\n * This module provides the `HistoryManager` class which manages thought history,\n * branching, and optional persistence with per-session state isolation.\n *\n * Internally delegates to three focused collaborators:\n * - `EdgeEmitter` — DAG edge emission\n * - `PersistenceBuffer` — buffered persistence + retry/backoff\n * - `SessionManager` — session lifecycle (TTL/LRU eviction)\n *\n * @module HistoryManager\n */\n\nimport type { IEdgeStore, IMetrics, ISessionLock } from '../contracts/interfaces.js';\nimport {\n\tasSessionId,\n\tGLOBAL_SESSION_ID,\n\ttype BranchId,\n\ttype SessionId,\n\ttype ThoughtId,\n} from '../contracts/ids.js';\nimport type { ISummaryStore } from '../contracts/summary.js';\nimport {\n\tInvalidBacktrackError,\n\tMaxSessionsReachedError,\n\tValidationError,\n} from '../errors.js';\nimport { NullLogger } from '../logger/NullLogger.js';\nimport type { Logger } from '../logger/StructuredLogger.js';\nimport type { PersistenceBackend } from '../contracts/PersistenceBackend.js';\nimport {\n\tDehydrationPolicy,\n\ttype DehydrationOptions,\n\ttype HydratedEntry,\n} from './compression/DehydrationPolicy.js';\nimport type { Summary } from './compression/Summary.js';\nimport { AsyncResetRequiredError, SessionAccessDeniedError } from './SessionErrors.js';\nimport { EdgeEmitter } from './graph/EdgeEmitter.js';\nimport type {\n\tHistorySessionSnapshot,\n\tIHistoryManager,\n\tThoughtAdmissionContext,\n} from './IHistoryManager.js';\nimport { PersistenceBuffer, type PersistenceEventEmitter } from './PersistenceBuffer.js';\nimport { SessionManager } from './SessionManager.js';\nimport { SessionResetCoordinator } from './SessionResetCoordinator.js';\nimport { stagePersistenceRestore, type RestoredSession } from './PersistenceRestore.js';\nimport type { ThoughtData } from './thought.js';\nimport { getOwner } from '../context/RequestContext.js';\nimport { ThoughtReferenceIndex, type ThoughtReferenceResolution } from './ThoughtReferenceIndex.js';\nimport { resolveThoughtReferencesForAdmission } from './CrossReferenceValidator.js';\nimport { SessionLifecycleCoordinator } from './SessionLifecycleCoordinator.js';\n\n/** Absolute maximum history size (~20MB at 2KB/thought). Cannot be overridden. */\nexport const ABSOLUTE_MAX_HISTORY_SIZE = 10_000;\n\ninterface SessionState {\n\tthought_history: ThoughtData[];\n\tbranches: Record<string, ThoughtData[]>;\n\tavailableMcpTools: string[] | undefined;\n\tavailableSkills: string[] | undefined;\n\twriteBuffer: ThoughtData[];\n\tlastAccessedAt: number;\n\tbranchIdentities: Set<BranchId>;\n\tpendingRestoreBranchDeletes: Set<BranchId>;\n\t/** Owner identifier set on first owner-aware access. Immutable thereafter. */\n\towner?: string;\n\t/** Non-persisted startup provenance used to block unverified network ownership. */\n\tprovenance?: 'restored';\n}\n\nexport interface HistoryManagerConfig {\n\t/** Maximum number of thoughts to keep in main history. @default 1000 */\n\tmaxHistorySize?: number;\n\t/** Maximum number of branches to maintain. @default 50 */\n\tmaxBranches?: number;\n\t/** Maximum size of each branch. @default 100 */\n\tmaxBranchSize?: number;\n\tlogger?: Logger;\n\tpersistence?: PersistenceBackend | null;\n\tmetrics?: IMetrics;\n\t/** Maximum number of thoughts to buffer before flushing. @default 100 */\n\tpersistenceBufferSize?: number;\n\t/** Periodic flush interval in ms. @default 1000 */\n\tpersistenceFlushInterval?: number;\n\t/** Max retries for failed persistence flushes. @default 3 */\n\tpersistenceMaxRetries?: number;\n\teventEmitter?: PersistenceEventEmitter;\n\tedgeStore?: IEdgeStore;\n\tsummaryStore?: ISummaryStore;\n\t/** Whether to emit DAG edges (gated independently of edgeStore). @default false */\n\tdagEdges?: boolean;\n\t/** Maximum sessions per owner (per-owner LRU bucket). @default 50 */\n\tmaxSessionsPerOwner?: number;\n\t/** Shared processor lock used to reject unsafe legacy synchronous clears. */\n\tsessionLock?: ISessionLock;\n\t/** Shared admission and exclusive lifecycle coordinator. */\n\tlifecycleCoordinator?: SessionLifecycleCoordinator;\n\t/** Clears processor-owned state after a session is actually removed. */\n\tclearSessionAuxiliaryState?: (sessionId: SessionId) => void;\n\t/** Clears all processor-owned state after a successful global lifecycle operation. */\n\tclearAllAuxiliaryState?: () => void;\n}\n\n/**\n * Manages thought history and branching for sequential thinking.\n *\n * Owns the per-session `Map<string, SessionState>`. Delegates DAG edge emission,\n * buffered persistence, and session TTL/LRU eviction to focused collaborators while\n * preserving test-coupled private member names (`_flushTimer`, `_startFlushTimer`,\n * `_flushBuffer`, `_sessions`).\n */\nexport class HistoryManager implements IHistoryManager {\n\tprivate static readonly DEFAULT_SESSION = GLOBAL_SESSION_ID;\n\tprivate static readonly SESSION_TTL_MS = 30 * 60 * 1000;\n\tprivate static readonly MAX_SESSIONS = 100;\n\tprivate _sessions: Map<SessionId, SessionState> = new Map();\n\tprivate _maxHistorySize: number;\n\tprivate _maxBranches: number;\n\tprivate _maxBranchSize: number;\n\tprivate _logger: Logger;\n\tprivate _persistence: PersistenceBackend | null;\n\tprivate _persistenceEnabled: boolean;\n\tprivate _metrics?: IMetrics;\n\n\tprivate _edgeStore?: IEdgeStore;\n\tprivate _summaryStore?: ISummaryStore;\n\tprivate _dagEdges: boolean;\n\n\tprivate _eventEmitter: PersistenceEventEmitter | null;\n\n\tprivate readonly _edgeEmitter: EdgeEmitter;\n\tprivate _referenceIndex = new ThoughtReferenceIndex();\n\tprivate _persistenceBuffer: PersistenceBuffer<SessionState> | null;\n\tprivate readonly _sessionManager: SessionManager<SessionState>;\n\tprivate readonly _resetCoordinator: SessionResetCoordinator<SessionState>;\n\tprivate readonly _sessionLock?: ISessionLock;\n\tprivate readonly _lifecycle: SessionLifecycleCoordinator;\n\tprivate _shutdownOwner: (() => Promise<void>) | null = null;\n\tprivate readonly _clearSessionAuxiliaryState?: (sessionId: SessionId) => void;\n\tprivate readonly _clearAllAuxiliaryState?: () => void;\n\n\tconstructor(config: HistoryManagerConfig = {}) {\n\t\tthis._logger = config.logger ?? new NullLogger();\n\t\tconst requestedMaxSize = config.maxHistorySize ?? 10000;\n\t\tthis._maxHistorySize = Math.min(requestedMaxSize, ABSOLUTE_MAX_HISTORY_SIZE);\n\t\tif (requestedMaxSize > ABSOLUTE_MAX_HISTORY_SIZE) {\n\t\t\tthis._logger.warn('maxHistorySize exceeds absolute maximum, capped', {\n\t\t\t\trequested: requestedMaxSize,\n\t\t\t\tapplied: ABSOLUTE_MAX_HISTORY_SIZE,\n\t\t\t});\n\t\t}\n\t\tthis._maxBranches = config.maxBranches ?? 50;\n\t\tthis._maxBranchSize = config.maxBranchSize || 100;\n\t\tthis._persistence = config.persistence ?? null;\n\t\tthis._persistenceEnabled = this._persistence !== null;\n\t\tthis._metrics = config.metrics;\n\t\tthis._eventEmitter = config.eventEmitter ?? null;\n\t\tthis._edgeStore = config.edgeStore;\n\t\tthis._summaryStore = config.summaryStore;\n\t\tthis._dagEdges = config.dagEdges ?? true;\n\t\tthis._sessionLock = config.sessionLock;\n\t\tthis._lifecycle = config.lifecycleCoordinator ?? new SessionLifecycleCoordinator();\n\t\tthis._clearSessionAuxiliaryState = config.clearSessionAuxiliaryState;\n\t\tthis._clearAllAuxiliaryState = config.clearAllAuxiliaryState;\n\n\t\t// Wire delegates\n\t\tthis._edgeEmitter = new EdgeEmitter({\n\t\t\tedgeStore: this._edgeStore,\n\t\t\tdagEdges: this._dagEdges,\n\t\t\tdefaultSessionId: HistoryManager.DEFAULT_SESSION,\n\t\t\tlogger: this._logger,\n\t\t});\n\n\t\tthis._sessionManager = new SessionManager<SessionState>({\n\t\t\tdefaultSessionId: HistoryManager.DEFAULT_SESSION,\n\t\t\tsessionTtlMs: HistoryManager.SESSION_TTL_MS,\n\t\t\tcleanupIntervalMs: 5 * 60 * 1000,\n\t\t\tgetMaxSessions: () => HistoryManager.MAX_SESSIONS,\n\t\t\tmaxSessionsPerOwner: config.maxSessionsPerOwner ?? 50,\n\t\t\tlogger: this._logger,\n\t\t});\n\n\t\tthis._persistenceBuffer = null;\n\t\tif (this._persistenceEnabled && this._persistence) {\n\t\t\tthis._persistenceBuffer = new PersistenceBuffer<SessionState>({\n\t\t\t\tpersistence: this._persistence,\n\t\t\t\tbufferSize: config.persistenceBufferSize ?? 100,\n\t\t\t\tflushInterval: config.persistenceFlushInterval ?? 1000,\n\t\t\t\tmaxRetries: config.persistenceMaxRetries ?? 3,\n\t\t\t\tdefaultSessionId: asSessionId(HistoryManager.DEFAULT_SESSION),\n\t\t\t\tgetSessions: () => this._sessions,\n\t\t\t\tgetDefaultSession: () => this._getSession(),\n\t\t\t\tedgeStore: this._edgeStore,\n\t\t\t\teventEmitter: this._eventEmitter,\n\t\t\t\tlogger: this._logger,\n\t\t\t});\n\t\t\tthis._startFlushTimer();\n\t\t}\n\t\tthis._resetCoordinator = new SessionResetCoordinator({\n\t\t\tpersistence: this._persistence,\n\t\t\tbarrier: this._persistenceBuffer,\n\t\t\tedgeStore: this._edgeStore,\n\t\t\tsummaryStore: this._summaryStore,\n\t\t\tsessions: this._sessions,\n\t\t\tcreateSessionState: (owner) => this._createSessionState(owner),\n\t\t\tlogger: this._logger,\n\t\t});\n\n\t\tthis._sessionManager.startCleanupTimer(\n\t\t\tthis._sessions,\n\t\t\t(sessionId) => this._isTtlEvictionEligible(sessionId),\n\t\t\t(sessionIds) => this._evictSessions(sessionIds)\n\t\t);\n\t}\n\n\t// Test-coupled accessors: these private member names must remain reachable\n\t// via `manager as unknown as { _flushTimer; _startFlushTimer }`.\n\tprivate get _flushTimer(): ReturnType<typeof setInterval> | null {\n\t\treturn this._persistenceBuffer?.timer ?? null;\n\t}\n\n\tprivate _startFlushTimer(): void {\n\t\tthis._persistenceBuffer?.startFlushTimer();\n\t}\n\n\tprivate _stopFlushTimer(): void {\n\t\tif (this._flushTimer === null) return;\n\t\tthis._persistenceBuffer?.stopFlushTimer();\n\t}\n\n\t/** @internal Public for backward-compatible test coupling. */\n\tpublic _flushBuffer(): Promise<void> {\n\t\tthis._stageAllRestoreBranchReconciliation();\n\t\treturn this._persistenceBuffer?.flush() ?? Promise.resolve();\n\t}\n\n\t/**\n\t * Drains accepted persistence work and projects terminal failures to one session.\n\t *\n\t * @param sessionId - Authoritative session whose persistence barrier to await.\n\t * @returns A promise that settles when the session's accepted work settles.\n\t */\n\tpublic drainSession(sessionId: SessionId): Promise<void> {\n\t\tconst session = this._sessions.get(sessionId);\n\t\tif (session !== undefined) this._stageRestoreBranchReconciliation(sessionId, session);\n\t\treturn this._persistenceBuffer?.drainSession(sessionId) ?? Promise.resolve();\n\t}\n\n\t/**\n\t * Registers the latest summary snapshot for coordinator-owned persistence.\n\t *\n\t * @param sessionId - Authoritative session that owns the summaries.\n\t * @param summaries - Complete current summary snapshot for the session.\n\t */\n\tpublic bufferSummaries(sessionId: SessionId, summaries: readonly Summary[]): void {\n\t\tthis._lifecycle.runMutation(sessionId, () => {\n\t\t\tthis._persistenceBuffer?.bufferSummaries(sessionId, summaries);\n\t\t\tconst session = this._sessions.get(sessionId);\n\t\t\tif (session !== undefined) this._stageRestoreBranchReconciliation(sessionId, session);\n\t\t});\n\t}\n\n\t/** EdgeStore instance, if configured. Used by ThoughtProcessor for StrategyContext. */\n\tpublic getEdgeStore(): IEdgeStore | undefined {\n\t\treturn this._edgeStore;\n\t}\n\n\tprivate log(message: string, meta?: Record<string, unknown>): void {\n\t\tthis._logger.info(message, meta);\n\t}\n\n\t/** Reads owner from RequestContext (AsyncLocalStorage). Stdio path returns undefined. */\n\tprivate _getCurrentOwner(): string | undefined {\n\t\treturn getOwner();\n\t}\n\n\t/**\n\t * Gets or creates session state; updates lastAccessedAt.\n\t *\n\t * Ownership semantics:\n\t * - `owner === undefined` (stdio path): never rejects, never sets owner.\n\t * - `owner !== undefined`: if session has a different owner, throws\n\t * `SessionAccessDeniedError`. If session was created without an owner\n\t * (e.g. by stdio), the owner is set on first owner-aware access.\n\t */\n\tprivate _getSession(sessionId?: string, owner?: string): SessionState {\n\t\tconst key = sessionId === undefined ? HistoryManager.DEFAULT_SESSION : asSessionId(sessionId);\n\t\tconst existing = this._sessions.get(key);\n\t\tif (existing !== undefined) {\n\t\t\tthis._assertSessionOwner(key, existing, owner);\n\t\t\texisting.lastAccessedAt = Date.now();\n\t\t\treturn existing;\n\t\t}\n\t\treturn this._lifecycle.runMutation(key, () => this._getSessionWithinOperation(key, owner));\n\t}\n\n\tprivate _getSessionWithinOperation(key: SessionId, owner?: string): SessionState {\n\t\tlet session = this._sessions.get(key);\n\t\tif (!session) {\n\t\t\tthis._makeCapacityForSession(owner);\n\t\t\tsession = this._createSessionState(owner);\n\t\t\tthis._sessions.set(key, session);\n\t\t} else {\n\t\t\tthis._assertSessionOwner(key, session, owner);\n\t\t}\n\t\tsession.lastAccessedAt = Date.now();\n\t\treturn session;\n\t}\n\n\tprivate _assertSessionOwner(\n\t\tsessionId: SessionId,\n\t\tsession: SessionState,\n\t\towner: string | undefined\n\t): void {\n\t\tif (owner === undefined) return;\n\t\tif (session.provenance === 'restored') {\n\t\t\tthrow new SessionAccessDeniedError(sessionId, 'unavailable', owner);\n\t\t}\n\t\tif (session.owner !== undefined && session.owner !== owner) {\n\t\t\tthrow new SessionAccessDeniedError(sessionId, session.owner, owner);\n\t\t}\n\t\tif (session.owner === undefined) session.owner = owner;\n\t}\n\n\tprivate _makeCapacityForSession(owner: string | undefined): void {\n\t\tconst victims = this._sessionManager.planProspectiveAdmission(\n\t\t\tthis._sessions,\n\t\t\towner,\n\t\t\t(sessionId) => this._isCapacityEvictionEligible(sessionId)\n\t\t);\n\t\tif (victims === undefined) throw new MaxSessionsReachedError(HistoryManager.MAX_SESSIONS);\n\t\tif (victims.length === 0) return;\n\t\tconst evicted = this._lifecycle.tryEvictIdleSessions(victims, (sessionIds) => {\n\t\t\tif (sessionIds.some((sessionId) => !this._isPersistenceQuiescent(sessionId))) {\n\t\t\t\tthrow new MaxSessionsReachedError(HistoryManager.MAX_SESSIONS);\n\t\t\t}\n\t\t\tfor (const sessionId of sessionIds) this._removeLiveSession(sessionId);\n\t\t});\n\t\tif (!evicted) throw new MaxSessionsReachedError(HistoryManager.MAX_SESSIONS);\n\t}\n\n\tprivate _isCapacityEvictionEligible(sessionId: SessionId): boolean {\n\t\treturn this._lifecycle.isIdle(sessionId) && this._isPersistenceQuiescent(sessionId);\n\t}\n\n\tprivate _isTtlEvictionEligible(sessionId: SessionId): boolean {\n\t\tconst persistenceState =\n\t\t\tthis._persistenceBuffer?.sessionEvictionState(sessionId) ?? 'quiescent';\n\t\treturn (\n\t\t\tthis._lifecycle.isIdle(sessionId) &&\n\t\t\tpersistenceState !== 'failed' &&\n\t\t\tpersistenceState !== 'barrier'\n\t\t);\n\t}\n\n\tprivate _isPersistenceQuiescent(sessionId: SessionId): boolean {\n\t\treturn (\n\t\t\t(this._persistenceBuffer?.sessionEvictionState(sessionId) ?? 'quiescent') === 'quiescent'\n\t\t);\n\t}\n\n\tprivate async _evictSessions(sessionIds: readonly SessionId[]): Promise<void> {\n\t\tconst results = await Promise.allSettled(\n\t\t\tsessionIds.map((sessionId) => this._evictSession(sessionId))\n\t\t);\n\t\tconst failures = results.flatMap((result) =>\n\t\t\tresult.status === 'rejected' ? [result.reason] : []\n\t\t);\n\t\tif (failures.length > 0) throw new AggregateError(failures, 'Session eviction failed');\n\t}\n\n\tprivate _evictSession(sessionId: SessionId): Promise<void> {\n\t\treturn this._lifecycle.withSessionEviction(sessionId, async () => {\n\t\t\tif (this._persistenceBuffer === null) {\n\t\t\t\tthis._removeLiveSession(sessionId);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst session = this._sessions.get(sessionId);\n\t\t\tif (session !== undefined) this._stageRestoreBranchReconciliation(sessionId, session);\n\t\t\tawait this._persistenceBuffer.withSessionEvictionBarrier(sessionId, async () => {\n\t\t\t\tthis._removeLiveSession(sessionId);\n\t\t\t});\n\t\t});\n\t}\n\n\tprivate _removeLiveSession(sessionId: SessionId): void {\n\t\tthis._clearSessionAuxiliaryState?.(sessionId);\n\t\tthis._edgeStore?.clearSession(sessionId);\n\t\tthis._summaryStore?.clearSession(sessionId);\n\t\tthis._referenceIndex.clearSession(sessionId);\n\t\tthis._sessions.delete(sessionId);\n\t\tthis._persistenceBuffer?.forgetQuiescentSession(sessionId);\n\t}\n\n\tprivate _createSessionState(owner?: string, provenance?: 'restored'): SessionState {\n\t\treturn {\n\t\t\tthought_history: [],\n\t\t\tbranches: {},\n\t\t\tavailableMcpTools: undefined,\n\t\t\tavailableSkills: undefined,\n\t\t\twriteBuffer: [],\n\t\t\tlastAccessedAt: Date.now(),\n\t\t\tbranchIdentities: new Set<BranchId>(),\n\t\t\tpendingRestoreBranchDeletes: new Set<BranchId>(),\n\t\t\towner,\n\t\t\tprovenance,\n\t\t};\n\t}\n\n\tprivate _authorizeExistingSession(\n\t\tsessionId: SessionId,\n\t\towner: string | undefined\n\t): string | undefined {\n\t\tconst sessionOwner = this._sessions.get(sessionId)?.owner;\n\t\tif (owner !== undefined && this._sessions.get(sessionId)?.provenance === 'restored') {\n\t\t\tthrow new SessionAccessDeniedError(sessionId, 'unavailable', owner);\n\t\t}\n\t\tif (owner !== undefined && sessionOwner !== undefined && sessionOwner !== owner) {\n\t\t\tthrow new SessionAccessDeniedError(sessionId, sessionOwner, owner);\n\t\t}\n\t\treturn sessionOwner ?? owner;\n\t}\n\n\tprivate _assertOwnerlessResetAll(): void {\n\t\tconst owner = this._getCurrentOwner();\n\t\tif (owner === undefined) return;\n\t\tconst firstSessionId = this._sessions.keys().next().value ?? HistoryManager.DEFAULT_SESSION;\n\t\tthrow new SessionAccessDeniedError(firstSessionId, 'trusted ownerless context', owner);\n\t}\n\n\t/**\n\t * Adds a thought to the history. Routes per-session, applies retraction for backtrack,\n\t * caches tools/skills, trims, branches, emits DAG edges, and buffers for persistence.\n\t */\n\tpublic addThought(thought: ThoughtData, context?: ThoughtAdmissionContext): void {\n\t\tconst sessionId = asSessionId(thought.session_id ?? HistoryManager.DEFAULT_SESSION);\n\t\tthis._lifecycle.runMutation(sessionId, () =>\n\t\t\tthis._addThoughtWithinOperation(sessionId, thought, context)\n\t\t);\n\t}\n\n\tprivate _addThoughtWithinOperation(\n\t\tsessionId: SessionId,\n\t\tthought: ThoughtData,\n\t\tcontext?: ThoughtAdmissionContext\n\t): void {\n\t\tthis._persistenceBuffer?.assertSessionAdmissionOpen(sessionId);\n\t\tconst owner = this._getCurrentOwner();\n\t\tthis._authorizeExistingSession(sessionId, owner);\n\t\tconst resolvedReferences = this._resolveAdmissionReferences(sessionId, thought, context);\n\t\tconst session = this._getSessionWithinOperation(sessionId, owner);\n\t\tthis._metrics?.counter(\n\t\t\t'thought_requests_total',\n\t\t\t1,\n\t\t\t{},\n\t\t\t'Total thought requests added to history'\n\t\t);\n\n\t\tsession.thought_history.push(thought);\n\n\t\t// Logical retraction: when a backtrack thought is added, mark its target\n\t\t// as retracted (append-only — target remains in history).\n\t\tif (resolvedReferences.backtrackTargetThoughtId !== undefined) {\n\t\t\tthis._applyRetraction(session, resolvedReferences.backtrackTargetThoughtId);\n\t\t}\n\n\t\t// Cache available_mcp_tools/available_skills for cross-call persistence\n\t\tif (thought.available_mcp_tools) {\n\t\t\tsession.availableMcpTools = thought.available_mcp_tools;\n\t\t}\n\t\tif (thought.available_skills) {\n\t\t\tsession.availableSkills = thought.available_skills;\n\t\t}\n\n\t\tif (thought.branch_from_thought && thought.branch_id) {\n\t\t\tthis._addToSessionBranch(session, thought.branch_id, thought);\n\t\t}\n\n\t\tif (thought.merge_from_thoughts?.length || thought.merge_branch_ids?.length) {\n\t\t\tthis._metrics?.counter(\n\t\t\t\t'thought_merge_operations_total',\n\t\t\t\t1,\n\t\t\t\t{},\n\t\t\t\t'Total merge operations (graph topology)'\n\t\t\t);\n\t\t}\n\n\t\tconst edgeAdded = this._edgeEmitter.emitEdgesForThought(session, thought, {\n\t\t\t...context,\n\t\t\tresolvedReferences,\n\t\t});\n\t\tconst evictedBranchIds = this._enforceRetention(session, thought.branch_id);\n\t\tthis._rebuildReferenceIndex(sessionId, session);\n\t\tconst prunedEdges = this._pruneUnretainedEdges(sessionId, session);\n\t\tthis._bufferRetainedState(\n\t\t\tsessionId,\n\t\t\tsession,\n\t\t\tthought,\n\t\t\tevictedBranchIds,\n\t\t\tedgeAdded,\n\t\t\tprunedEdges\n\t\t);\n\t}\n\n\tprivate _resolveAdmissionReferences(\n\t\tsessionId: SessionId,\n\t\tthought: ThoughtData,\n\t\tcontext?: ThoughtAdmissionContext\n\t): NonNullable<ThoughtAdmissionContext['resolvedReferences']> {\n\t\tconst resolved =\n\t\t\tcontext?.resolvedReferences ??\n\t\t\tresolveThoughtReferencesForAdmission(thought, (thoughtNumber) =>\n\t\t\t\tthis._referenceIndex.resolve(sessionId, thoughtNumber)\n\t\t\t);\n\t\tif (\n\t\t\tthought.thought_type === 'backtrack' &&\n\t\t\tthought.backtrack_target !== undefined &&\n\t\t\tresolved.backtrackTargetThoughtId === undefined\n\t\t) {\n\t\t\tthrow new InvalidBacktrackError(\n\t\t\t\t`backtrack_target ${thought.backtrack_target} is missing in session history`\n\t\t\t);\n\t\t}\n\t\treturn resolved;\n\t}\n\n\tprivate _enforceRetention(\n\t\tsession: SessionState,\n\t\tbranchId: BranchId | undefined\n\t): readonly BranchId[] {\n\t\tif (session.thought_history.length > this._maxHistorySize) {\n\t\t\tsession.thought_history = session.thought_history.slice(-this._maxHistorySize);\n\t\t\tthis.log(`History trimmed to ${this._maxHistorySize} items`, {\n\t\t\t\tmaxSize: this._maxHistorySize,\n\t\t\t});\n\t\t}\n\t\tif (branchId !== undefined) this._trimSessionBranchSize(session, branchId);\n\t\treturn this._cleanupSessionBranches(session);\n\t}\n\n\tprivate _pruneUnretainedEdges(sessionId: SessionId, session: SessionState): number {\n\t\tif (this._edgeStore === undefined) return 0;\n\t\tconst retainedIds = new Set<ThoughtId>();\n\t\tconst retainedBranchThoughtIds = new Set<ThoughtId>();\n\t\tfor (const thought of [session.thought_history, ...Object.values(session.branches)].flat()) {\n\t\t\tif (thought.id !== undefined) retainedIds.add(thought.id);\n\t\t}\n\t\tfor (const thought of Object.values(session.branches).flat()) {\n\t\t\tif (thought.id !== undefined) retainedBranchThoughtIds.add(thought.id);\n\t\t}\n\t\treturn this._edgeStore.pruneSession(sessionId, retainedIds, retainedBranchThoughtIds);\n\t}\n\n\tprivate _bufferRetainedState(\n\t\tsessionId: SessionId,\n\t\tsession: SessionState,\n\t\tthought: ThoughtData,\n\t\tevictedBranchIds: readonly BranchId[],\n\t\tedgeAdded: boolean,\n\t\tprunedEdges: number\n\t): void {\n\t\tconst buffer = this._persistenceBuffer;\n\t\tif (buffer === null) return;\n\t\tbuffer.bufferThought(sessionId, thought);\n\t\tif (\n\t\t\tthought.branch_id !== undefined ||\n\t\t\tevictedBranchIds.length > 0 ||\n\t\t\tsession.pendingRestoreBranchDeletes.size > 0\n\t\t) {\n\t\t\tthis._stageBranchPersistence(sessionId, session, evictedBranchIds);\n\t\t}\n\t\tif (this._edgeStore !== undefined && (edgeAdded || prunedEdges > 0)) {\n\t\t\tbuffer.bufferEdges(sessionId, this._edgeStore.edgesForSession(sessionId));\n\t\t}\n\t}\n\n\tprivate _stageAllRestoreBranchReconciliation(): void {\n\t\tfor (const [sessionId, session] of this._sessions) {\n\t\t\tthis._stageRestoreBranchReconciliation(sessionId, session);\n\t\t}\n\t}\n\n\tprivate _stageRestoreBranchReconciliation(sessionId: SessionId, session: SessionState): void {\n\t\tif (session.pendingRestoreBranchDeletes.size === 0) return;\n\t\tthis._stageBranchPersistence(sessionId, session, []);\n\t}\n\n\tprivate _stageBranchPersistence(\n\t\tsessionId: SessionId,\n\t\tsession: SessionState,\n\t\tordinaryDeletes: readonly BranchId[]\n\t): void {\n\t\tconst buffer = this._persistenceBuffer;\n\t\tif (buffer === null) return;\n\t\tfor (const branchId of session.branchIdentities) {\n\t\t\tconst branch = session.branches[branchId];\n\t\t\tif (branch !== undefined) buffer.bufferBranch(sessionId, branchId, branch);\n\t\t}\n\t\tconst branchIdsToDelete = new Set([...session.pendingRestoreBranchDeletes, ...ordinaryDeletes]);\n\t\tfor (const branchId of branchIdsToDelete) {\n\t\t\tif (session.branches[branchId] === undefined) buffer.deleteBranch(sessionId, branchId);\n\t\t}\n\t\tsession.pendingRestoreBranchDeletes.clear();\n\t}\n\n\t/** Marks the thought as retracted within the session (append-only). */\n\tprivate _applyRetraction(session: SessionState, targetId: ThoughtId): void {\n\t\tfor (const t of session.thought_history) {\n\t\t\tif (t.id === targetId) t.retracted = true;\n\t\t}\n\t\tfor (const branchThoughts of Object.values(session.branches)) {\n\t\t\tfor (const t of branchThoughts) {\n\t\t\t\tif (t.id === targetId) t.retracted = true;\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate _rebuildReferenceIndex(sessionId: SessionId, session: SessionState): void {\n\t\tconst retained = [session.thought_history, ...Object.values(session.branches)].flat();\n\t\tthis._referenceIndex.replaceSession(sessionId, retained);\n\t}\n\n\tpublic resolveThoughtReference(\n\t\tsessionId: SessionId,\n\t\tthoughtNumber: number\n\t): ThoughtReferenceResolution {\n\t\tthis._authorizeExistingSession(sessionId, this._getCurrentOwner());\n\t\treturn this._referenceIndex.resolve(sessionId, thoughtNumber);\n\t}\n\n\tprivate _addToSessionBranch(\n\t\tsession: SessionState,\n\t\tbranchId: BranchId,\n\t\tthought: ThoughtData\n\t): void {\n\t\tif (!session.branches[branchId]) {\n\t\t\tsession.branches[branchId] = [];\n\t\t}\n\t\tsession.branchIdentities.add(branchId);\n\t\tsession.branches[branchId].push(thought);\n\t}\n\n\tprivate _cleanupSessionBranches(session: SessionState): readonly BranchId[] {\n\t\tconst branchCount = session.branchIdentities.size;\n\t\tif (branchCount <= this._maxBranches) return [];\n\t\tconst identitiesToRemove = Array.from(session.branchIdentities).slice(\n\t\t\t0,\n\t\t\tbranchCount - this._maxBranches\n\t\t);\n\t\tconst branchesToDelete: BranchId[] = [];\n\t\tfor (const branchId of identitiesToRemove) {\n\t\t\tsession.branchIdentities.delete(branchId);\n\t\t\tif (session.branches[branchId] !== undefined) branchesToDelete.push(branchId);\n\t\t\tdelete session.branches[branchId];\n\t\t\tthis.log(`Removed old branch: ${branchId}`, { branchId });\n\t\t}\n\t\treturn branchesToDelete;\n\t}\n\n\tprivate _trimSessionBranchSize(session: SessionState, branchId: BranchId): void {\n\t\tconst branch = session.branches[branchId];\n\t\tif (branch !== undefined && branch.length > this._maxBranchSize) {\n\t\t\tconst removed = branch.length - this._maxBranchSize;\n\t\t\tsession.branches[branchId] = branch.slice(-this._maxBranchSize);\n\t\t\tthis.log(`Trimmed branch '${branchId}': removed ${removed} old thoughts`, {\n\t\t\t\tbranchId,\n\t\t\t\tremoved,\n\t\t\t});\n\t\t}\n\t}\n\n\tpublic getHistory(sessionId?: string): ThoughtData[] {\n\t\treturn this._getSession(sessionId, this._getCurrentOwner()).thought_history;\n\t}\n\n\t/**\n\t * Returns history with optional sliding-window dehydration. Non-mutating: when\n\t * `dagEdges` is off OR no `ISummaryStore` is configured, returns same as getHistory.\n\t */\n\tpublic getHistoryHydrated(sessionId?: string, opts?: DehydrationOptions): HydratedEntry[] {\n\t\tconst history = this.getHistory(sessionId);\n\t\tif (!this._dagEdges || !this._summaryStore) {\n\t\t\treturn history.slice();\n\t\t}\n\t\tconst sid = sessionId ?? HistoryManager.DEFAULT_SESSION;\n\t\tconst policy = new DehydrationPolicy(this._summaryStore);\n\t\treturn policy.apply(history, asSessionId(sid), opts);\n\t}\n\n\tpublic getHistoryLength(sessionId?: string): number {\n\t\treturn this._getSession(sessionId, this._getCurrentOwner()).thought_history.length;\n\t}\n\n\tpublic getBranches(sessionId?: string): Record<BranchId, ThoughtData[]> {\n\t\treturn this._getSession(sessionId, this._getCurrentOwner()).branches;\n\t}\n\n\tpublic getBranchIds(sessionId?: string): BranchId[] {\n\t\treturn Array.from(this._getSession(sessionId, this._getCurrentOwner()).branchIdentities);\n\t}\n\n\t/** Returns validation state without creating a session, binding an owner, or updating LRU data. */\n\tpublic inspectSession(sessionId: string): HistorySessionSnapshot {\n\t\tconst canonicalSessionId = asSessionId(sessionId);\n\t\tthis._authorizeExistingSession(canonicalSessionId, this._getCurrentOwner());\n\t\tconst session = this._sessions.get(canonicalSessionId);\n\t\tif (session === undefined) {\n\t\t\treturn {\n\t\t\t\thistory: [],\n\t\t\t\tbranches: {},\n\t\t\t\tbranchIds: [],\n\t\t\t\tavailableMcpTools: undefined,\n\t\t\t\tavailableSkills: undefined,\n\t\t\t};\n\t\t}\n\t\treturn {\n\t\t\thistory: [...session.thought_history],\n\t\t\tbranches: Object.fromEntries(\n\t\t\t\tObject.entries(session.branches).map(([branchId, thoughts]) => [branchId, [...thoughts]])\n\t\t\t) as Record<BranchId, readonly ThoughtData[]>,\n\t\t\tbranchIds: Array.from(session.branchIdentities),\n\t\t\tavailableMcpTools:\n\t\t\t\tsession.availableMcpTools === undefined ? undefined : [...session.availableMcpTools],\n\t\t\tavailableSkills:\n\t\t\t\tsession.availableSkills === undefined ? undefined : [...session.availableSkills],\n\t\t};\n\t}\n\n\t/** @throws {ValidationError} If branchId is empty or already exists. */\n\tpublic registerBranch(sessionId: string | undefined, branchId: BranchId): void {\n\t\tif (typeof branchId !== 'string' || branchId.length === 0) {\n\t\t\tthrow new ValidationError('branch_id', 'branch_id must be a non-empty string');\n\t\t}\n\t\tconst canonicalSessionId = asSessionId(sessionId ?? HistoryManager.DEFAULT_SESSION);\n\t\tthis._lifecycle.runMutation(canonicalSessionId, () => {\n\t\t\tthis._persistenceBuffer?.assertSessionAdmissionOpen(canonicalSessionId);\n\t\t\tconst session = this._getSessionWithinOperation(canonicalSessionId, this._getCurrentOwner());\n\t\t\tif (session.branchIdentities.has(branchId)) {\n\t\t\t\tthrow new ValidationError('branch_id', `Branch already exists: ${branchId}`);\n\t\t\t}\n\t\t\tsession.branchIdentities.add(branchId);\n\t\t\tconst evictedBranchIds = this._cleanupSessionBranches(session);\n\t\t\tthis._rebuildReferenceIndex(canonicalSessionId, session);\n\t\t\tconst prunedEdges = this._pruneUnretainedEdges(canonicalSessionId, session);\n\t\t\tif (evictedBranchIds.length > 0 || session.pendingRestoreBranchDeletes.size > 0) {\n\t\t\t\tthis._stageBranchPersistence(canonicalSessionId, session, evictedBranchIds);\n\t\t\t}\n\t\t\tif (this._edgeStore !== undefined && prunedEdges > 0) {\n\t\t\t\tthis._persistenceBuffer?.bufferEdges(\n\t\t\t\t\tcanonicalSessionId,\n\t\t\t\t\tthis._edgeStore.edgesForSession(canonicalSessionId)\n\t\t\t\t);\n\t\t\t}\n\t\t\tthis.log('Registered branch', { branchId, sessionId: sessionId ?? null });\n\t\t});\n\t}\n\n\tpublic branchExists(sessionId: string | undefined, branchId: BranchId): boolean {\n\t\tconst session = this._getSession(sessionId, this._getCurrentOwner());\n\t\treturn session.branchIdentities.has(branchId);\n\t}\n\n\tpublic getAvailableMcpTools(sessionId?: string): string[] | undefined {\n\t\treturn this._getSession(sessionId, this._getCurrentOwner()).availableMcpTools;\n\t}\n\n\tpublic getAvailableSkills(sessionId?: string): string[] | undefined {\n\t\treturn this._getSession(sessionId, this._getCurrentOwner()).availableSkills;\n\t}\n\n\tpublic getBranch(branchId: BranchId, sessionId?: string): ThoughtData[] | undefined {\n\t\treturn this._getSession(sessionId, this._getCurrentOwner()).branches[branchId];\n\t}\n\n\t/** Clears only persistence-disabled state synchronously. */\n\tpublic clear(sessionId?: string): void {\n\t\tif (sessionId !== undefined) {\n\t\t\tconst canonicalSessionId = asSessionId(sessionId);\n\t\t\tthis._authorizeExistingSession(canonicalSessionId, this._getCurrentOwner());\n\t\t\tif (this._sessionLock?.isActive(canonicalSessionId) === true) {\n\t\t\t\tthrow new AsyncResetRequiredError('session', canonicalSessionId, 'active');\n\t\t\t}\n\t\t\tthis._resetCoordinator.clearSession(canonicalSessionId);\n\t\t\tthis._referenceIndex.clearSession(canonicalSessionId);\n\t\t\tthis._clearSessionAuxiliaryState?.(canonicalSessionId);\n\t\t\treturn;\n\t\t}\n\t\tthis._assertOwnerlessResetAll();\n\t\tif (this._sessionLock !== undefined && this._sessionLock.size > 0) {\n\t\t\tthrow new AsyncResetRequiredError('all', undefined, 'active');\n\t\t}\n\t\tthis._resetCoordinator.clearAll();\n\t\tthis._referenceIndex.clearAll();\n\t\tthis._clearAllAuxiliaryState?.();\n\t}\n\n\t/** Awaitably deletes one authorized durable namespace before replacing its live state. */\n\tpublic async resetSession(sessionId: string, clearAuxiliaryState?: () => void): Promise<void> {\n\t\tconst canonicalSessionId = asSessionId(sessionId);\n\t\tthis._authorizeExistingSession(canonicalSessionId, this._getCurrentOwner());\n\t\tawait this._lifecycle.withSessionReset(canonicalSessionId, async () => {\n\t\t\tconst reset = async (): Promise<void> =>\n\t\t\t\tawait this.resetSessionWithinExclusive(canonicalSessionId, clearAuxiliaryState);\n\t\t\tif (this._sessionLock === undefined) return await reset();\n\t\t\tawait this._sessionLock.withLock(canonicalSessionId, reset);\n\t\t});\n\t}\n\n\t/** Performs scoped reset work while its lifecycle exclusive is already owned. */\n\tpublic async resetSessionWithinExclusive(\n\t\tsessionId: SessionId,\n\t\tclearAuxiliaryState?: () => void\n\t): Promise<void> {\n\t\tconst preservedOwner = this._authorizeExistingSession(sessionId, this._getCurrentOwner());\n\t\tawait this._resetCoordinator.resetSession(\n\t\t\tsessionId,\n\t\t\tpreservedOwner,\n\t\t\tclearAuxiliaryState ??\n\t\t\t\t(this._clearSessionAuxiliaryState === undefined\n\t\t\t\t\t? undefined\n\t\t\t\t\t: () => this._clearSessionAuxiliaryState?.(sessionId))\n\t\t);\n\t\tthis._referenceIndex.clearSession(sessionId);\n\t}\n\n\t/** Awaitably deletes all durable namespaces from a trusted ownerless context. */\n\tpublic async resetAll(clearAuxiliaryState?: () => void): Promise<void> {\n\t\tthis._assertOwnerlessResetAll();\n\t\tawait this._lifecycle.withGlobalReset(\n\t\t\tasync () => await this.resetAllWithinExclusive(clearAuxiliaryState)\n\t\t);\n\t}\n\n\t/** Performs global reset work while its lifecycle exclusive is already owned. */\n\tpublic async resetAllWithinExclusive(clearAuxiliaryState?: () => void): Promise<void> {\n\t\tthis._assertOwnerlessResetAll();\n\t\tawait this._resetCoordinator.resetAll(clearAuxiliaryState ?? this._clearAllAuxiliaryState);\n\t\tthis._referenceIndex.clearAll();\n\t}\n\n\tpublic clearSession(sessionId: string): void {\n\t\tthis.clear(sessionId);\n\t}\n\n\tpublic getSessionIds(): string[] {\n\t\treturn Array.from(this._sessions.keys());\n\t}\n\n\tpublic getSessionCount(): number {\n\t\treturn this._sessions.size;\n\t}\n\n\tprivate _restoredState(restored: RestoredSession): SessionState {\n\t\tconst session = this._createSessionState(undefined, 'restored');\n\t\tfor (let index = restored.history.length - 1; index >= 0; index--) {\n\t\t\tconst thought = restored.history[index];\n\t\t\tif (thought === undefined) continue;\n\t\t\tif (session.availableMcpTools === undefined && thought.available_mcp_tools !== undefined) {\n\t\t\t\tsession.availableMcpTools = [...thought.available_mcp_tools];\n\t\t\t}\n\t\t\tif (session.availableSkills === undefined && thought.available_skills !== undefined) {\n\t\t\t\tsession.availableSkills = [...thought.available_skills];\n\t\t\t}\n\t\t\tif (session.availableMcpTools !== undefined && session.availableSkills !== undefined) break;\n\t\t}\n\t\tsession.thought_history = restored.history.slice(-this._maxHistorySize);\n\t\tconst retainedStart = Math.max(0, restored.branches.length - this._maxBranches);\n\t\tconst retainedBranches = restored.branches.slice(retainedStart);\n\t\tfor (const branch of restored.branches.slice(0, retainedStart)) {\n\t\t\tsession.pendingRestoreBranchDeletes.add(branch.branchId);\n\t\t}\n\t\tfor (const branch of retainedBranches) {\n\t\t\tsession.branchIdentities.add(branch.branchId);\n\t\t\tsession.branches[branch.branchId] = branch.thoughts.slice(-this._maxBranchSize);\n\t\t}\n\t\treturn session;\n\t}\n\n\t/** Loads and atomically commits every authoritative persistence namespace. Call at init. */\n\tpublic async loadFromPersistence(): Promise<void> {\n\t\tif (!this._persistenceEnabled || !this._persistence) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst restored = await stagePersistenceRestore(this._persistence);\n\t\tconst sessions = restored.sessions.map(\n\t\t\t(session) => [session.sessionId, this._restoredState(session)] as const\n\t\t);\n\t\tconst referenceIndex = new ThoughtReferenceIndex();\n\t\tconst retainedThoughtIds = new Map<SessionId, ReadonlySet<ThoughtId>>();\n\t\tconst retainedBranchThoughtIds = new Map<SessionId, ReadonlySet<ThoughtId>>();\n\t\tfor (const [sessionId, session] of sessions) {\n\t\t\tconst retained = [session.thought_history, ...Object.values(session.branches)].flat();\n\t\t\treferenceIndex.replaceSession(sessionId, retained);\n\t\t\tretainedThoughtIds.set(\n\t\t\t\tsessionId,\n\t\t\t\tnew Set(retained.flatMap((thought) => (thought.id === undefined ? [] : [thought.id])))\n\t\t\t);\n\t\t\tretainedBranchThoughtIds.set(\n\t\t\t\tsessionId,\n\t\t\t\tnew Set(\n\t\t\t\t\tObject.values(session.branches).flatMap((branch) =>\n\t\t\t\t\t\tbranch.flatMap((thought) => (thought.id === undefined ? [] : [thought.id]))\n\t\t\t\t\t)\n\t\t\t\t)\n\t\t\t);\n\t\t}\n\n\t\tthis._edgeStore?.clearAll();\n\t\tthis._summaryStore?.clearAll();\n\t\tthis._sessions.clear();\n\t\tfor (const [sessionId, session] of sessions) this._sessions.set(sessionId, session);\n\t\tthis._referenceIndex = referenceIndex;\n\t\tfor (const session of restored.sessions) {\n\t\t\tconst retainedIds = retainedThoughtIds.get(session.sessionId) ?? new Set<ThoughtId>();\n\t\t\tconst retainedBranchIds =\n\t\t\t\tretainedBranchThoughtIds.get(session.sessionId) ?? new Set<ThoughtId>();\n\t\t\tfor (const edge of session.edges) {\n\t\t\t\tif (!retainedIds.has(edge.from) || !retainedIds.has(edge.to)) continue;\n\t\t\t\tif (edge.kind === 'branch' && !retainedBranchIds.has(edge.to)) continue;\n\t\t\t\tthis._edgeStore?.addEdge(edge);\n\t\t\t}\n\t\t\tfor (const summary of session.summaries) this._summaryStore?.add(summary);\n\t\t}\n\t\tthis.log(`Restored ${restored.sessions.length} persistence namespaces`);\n\t}\n\n\tpublic isPersistenceEnabled(): boolean {\n\t\treturn this._persistenceEnabled;\n\t}\n\n\tpublic getPersistenceBackend(): PersistenceBackend | null {\n\t\treturn this._persistence;\n\t}\n\n\t/** Sets the event emitter for persistence error events (post-construction wiring). */\n\tpublic setEventEmitter(emitter: PersistenceEventEmitter): void {\n\t\tthis._eventEmitter = emitter;\n\t\tthis._persistenceBuffer?.setEventEmitter(emitter);\n\t}\n\n\t/**\n\t * Binds shutdown to the resource owner responsible for the complete cleanup sequence.\n\t *\n\t * @internal\n\t * @param owner - Callback returning the owner's memoized shutdown promise.\n\t * @throws {TypeError} When a shutdown owner has already been bound.\n\t */\n\tpublic bindShutdownOwner(owner: () => Promise<void>): void {\n\t\tif (this._shutdownOwner !== null) {\n\t\t\tthrow new TypeError('HistoryManager shutdown owner is already bound');\n\t\t}\n\t\tthis._shutdownOwner = owner;\n\t}\n\n\t/** Stops timers, drains writes, and clears live state under one memoized lifecycle settlement. */\n\tpublic shutdown(): Promise<void> {\n\t\tif (this._shutdownOwner !== null) return this._shutdownOwner();\n\t\treturn this._lifecycle.shutdown(async () => {\n\t\t\tawait this.shutdownWithinLifecycle();\n\t\t\tthis.clearLiveStateAfterShutdown();\n\t\t});\n\t}\n\n\t/** Stops timers and drains writes while the caller owns global shutdown. */\n\tpublic async shutdownWithinLifecycle(): Promise<void> {\n\t\tthis._stopFlushTimer();\n\t\tthis._sessionManager.stopCleanupTimer();\n\t\tawait this._flushBuffer();\n\t}\n\n\t/** Clears non-durable state after every shutdown resource has closed successfully. */\n\tpublic clearLiveStateAfterShutdown(): void {\n\t\tfor (const sessionId of this._sessions.keys()) {\n\t\t\tthis._persistenceBuffer?.forgetQuiescentSession(sessionId);\n\t\t}\n\t\tthis._sessions.clear();\n\t\tthis._referenceIndex.clearAll();\n\t\tthis._edgeStore?.clearAll();\n\t\tthis._summaryStore?.clearAll();\n\t\tthis._clearAllAuxiliaryState?.();\n\t}\n\n\t/** Number of coordinator-owned thought writes not yet acknowledged successful. */\n\tpublic getWriteBufferLength(): number {\n\t\treturn this._persistenceBuffer?.pendingThoughtCount ?? 0;\n\t}\n}\n"],"names":["ABSOLUTE_MAX_HISTORY_SIZE","HistoryManager","GLOBAL_SESSION_ID","Map","ThoughtReferenceIndex","config","NullLogger","requestedMaxSize","Math","SessionLifecycleCoordinator","EdgeEmitter","SessionManager","PersistenceBuffer","asSessionId","SessionResetCoordinator","owner","sessionId","sessionIds","Promise","session","undefined","summaries","message","meta","getOwner","key","existing","Date","SessionAccessDeniedError","victims","MaxSessionsReachedError","evicted","persistenceState","results","failures","result","AggregateError","provenance","Set","sessionOwner","firstSessionId","thought","context","resolvedReferences","edgeAdded","evictedBranchIds","prunedEdges","resolved","resolveThoughtReferencesForAdmission","thoughtNumber","InvalidBacktrackError","branchId","retainedIds","retainedBranchThoughtIds","Object","buffer","ordinaryDeletes","branch","branchIdsToDelete","targetId","t","branchThoughts","retained","branchCount","identitiesToRemove","Array","branchesToDelete","removed","opts","history","sid","policy","DehydrationPolicy","canonicalSessionId","thoughts","ValidationError","AsyncResetRequiredError","clearAuxiliaryState","reset","preservedOwner","restored","index","retainedStart","retainedBranches","stagePersistenceRestore","sessions","referenceIndex","retainedThoughtIds","retainedBranchIds","edge","summary","emitter","TypeError"],"mappings":";;;;;;;;;;;;;;AAuDO,MAAMA,4BAA4B;AA0DlC,MAAMC;IACZ,OAAwB,kBAAkBC,kBAAkB;IAC5D,OAAwB,iBAAiB,QAAe;IACxD,OAAwB,eAAe,IAAI;IACnC,YAA0C,IAAIC,MAAM;IACpD,gBAAwB;IACxB,aAAqB;IACrB,eAAuB;IACvB,QAAgB;IAChB,aAAwC;IACxC,oBAA6B;IAC7B,SAAoB;IAEpB,WAAwB;IACxB,cAA8B;IAC9B,UAAmB;IAEnB,cAA8C;IAErC,aAA0B;IACnC,kBAAkB,IAAIC,wBAAwB;IAC9C,mBAA2D;IAClD,gBAA8C;IAC9C,kBAAyD;IACzD,aAA4B;IAC5B,WAAwC;IACjD,iBAA+C,KAAK;IAC3C,4BAA6D;IAC7D,wBAAqC;IAEtD,YAAYC,SAA+B,CAAC,CAAC,CAAE;QAC9C,IAAI,CAAC,OAAO,GAAGA,OAAO,MAAM,IAAI,IAAIC;QACpC,MAAMC,mBAAmBF,OAAO,cAAc,IAAI;QAClD,IAAI,CAAC,eAAe,GAAGG,KAAK,GAAG,CAACD,kBAAkBP;QAClD,IAAIO,mBAAmBP,2BACtB,IAAI,CAA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AyC;QACrD,IAAI,CAAC,eAAe;QACpB,IAAI,CAAC,eAAe,CAAC,gBAAgB;QACrC,MAAM,IAAI,CAAC,YAAY;IACxB;IAGO,8BAAoC;QAC1C,KAAK,MAAMC,aAAa,IAAI,CAAC,SAAS,CAAC,IAAI,GAC1C,IAAI,CAAC,kBAAkB,EAAE,uBAAuBA;QAEjD,IAAI,CAAC,SAAS,CAAC,KAAK;QACpB,IAAI,CAAC,eAAe,CAAC,QAAQ;QAC7B,IAAI,CAAC,UAAU,EAAE;QACjB,IAAI,CAAC,aAAa,EAAE;QACpB,IAAI,CAAC,uBAAuB;IAC7B;IAGO,uBAA+B;QACrC,OAAO,IAAI,CAAC,kBAAkB,EAAE,uBAAuB;IACxD;AACD"}
@@ -0,0 +1,163 @@
1
+ /**
2
+ * Interface for history and branch management.
3
+ *
4
+ * This module provides the `IHistoryManager` interface which defines the contract
5
+ * for history manager implementations. This allows for decoupling and testability.
6
+ *
7
+ * @module IHistoryManager
8
+ */
9
+ import type { IEdgeStore } from '../contracts/interfaces.js';
10
+ import type { BranchId, SessionId, ThoughtId } from '../contracts/ids.js';
11
+ import type { ThoughtReferenceResolution } from './ThoughtReferenceIndex.js';
12
+ import type { ThoughtData } from './thought.js';
13
+ /** Non-mutating view used to validate one operation before state admission. */
14
+ export interface HistorySessionSnapshot {
15
+ readonly history: readonly ThoughtData[];
16
+ readonly branches: Readonly<Record<BranchId, readonly ThoughtData[]>>;
17
+ readonly branchIds: readonly BranchId[];
18
+ readonly availableMcpTools: readonly string[] | undefined;
19
+ readonly availableSkills: readonly string[] | undefined;
20
+ }
21
+ export interface ResolvedThoughtReferences {
22
+ readonly verificationTargetThoughtId?: ThoughtId;
23
+ readonly revisesThoughtId?: ThoughtId;
24
+ readonly branchFromThoughtId?: ThoughtId;
25
+ readonly synthesisSourceThoughtIds?: readonly ThoughtId[];
26
+ readonly mergeFromThoughtIds?: readonly ThoughtId[];
27
+ readonly backtrackTargetThoughtId?: ThoughtId;
28
+ }
29
+ export interface ThoughtAdmissionContext {
30
+ readonly resolvedReferences?: ResolvedThoughtReferences;
31
+ readonly toolInvocationSourceThoughtId?: ThoughtId;
32
+ }
33
+ /**
34
+ * Interface for history and branch management.
35
+ *
36
+ * This interface defines the contract for history manager implementations,
37
+ * allowing for decoupling between components like ThoughtProcessor and
38
+ * concrete implementations. It supports dependency injection and mocking
39
+ * for testing purposes.
40
+ *
41
+ * @example
42
+ * ```typescript
43
+ * // Using the interface for dependency injection
44
+ * class MyComponent {
45
+ * constructor(private history: IHistoryManager) {}
46
+ *
47
+ * addThought(thought: ThoughtData) {
48
+ * this.history.addThought(thought);
49
+ * }
50
+ * }
51
+ *
52
+ * // Mock implementation for testing
53
+ * class MockHistoryManager implements IHistoryManager {
54
+ * private _history: ThoughtData[] = [];
55
+ * addThought(thought: ThoughtData): void { this._history.push(thought); }
56
+ * getHistory(): ThoughtData[] { return this._history; }
57
+ * getHistoryLength(): number { return this._history.length; }
58
+ * getBranches(): Record<string, ThoughtData[]> { return {}; }
59
+ * getBranchIds(): string[] { return []; }
60
+ * clear(): void { this._history = []; }
61
+ * }
62
+ * ```
63
+ */
64
+ export interface IHistoryManager {
65
+ /**
66
+ * Adds a thought to the history.
67
+ * Session is determined by `thought.session_id` (defaults to global session).
68
+ *
69
+ * @param thought - The thought data to add
70
+ */
71
+ addThought(thought: ThoughtData, context?: ThoughtAdmissionContext): void;
72
+ /** Resolves a retained same-session numeric reference to stable thought identity. */
73
+ resolveThoughtReference(sessionId: SessionId, thoughtNumber: number): ThoughtReferenceResolution;
74
+ /**
75
+ * Gets the complete thought history.
76
+ *
77
+ * @param sessionId - Optional session ID for session-scoped results
78
+ * @returns An array of all thoughts in chronological order
79
+ */
80
+ getHistory(sessionId?: string): ThoughtData[];
81
+ /**
82
+ * Gets the current length of the thought history.
83
+ *
84
+ * @param sessionId - Optional session ID for session-scoped results
85
+ * @returns The number of thoughts in history
86
+ */
87
+ getHistoryLength(sessionId?: string): number;
88
+ /**
89
+ * Gets all branches.
90
+ *
91
+ * @param sessionId - Optional session ID for session-scoped results
92
+ * @returns A record mapping branch IDs to their thought arrays
93
+ */
94
+ getBranches(sessionId?: string): Record<BranchId, ThoughtData[]>;
95
+ /**
96
+ * Gets all branch IDs.
97
+ *
98
+ * @param sessionId - Optional session ID for session-scoped results
99
+ * @returns An array of branch identifiers
100
+ */
101
+ getBranchIds(sessionId?: string): BranchId[];
102
+ /**
103
+ * Clears history and branches.
104
+ * If sessionId is provided, clears only that session.
105
+ * If omitted, clears all sessions.
106
+ *
107
+ * @param sessionId - Optional session ID to clear
108
+ */
109
+ clear(sessionId?: string): void;
110
+ /** Awaitably clears one authorized live and durable session. */
111
+ resetSession(sessionId: string, clearAuxiliaryState?: () => void): Promise<void>;
112
+ /** Clears one session while the caller already owns its lifecycle exclusive. */
113
+ resetSessionWithinExclusive(sessionId: SessionId, clearAuxiliaryState?: () => void): Promise<void>;
114
+ /** Awaitably clears every live and durable session from an ownerless context. */
115
+ resetAll(clearAuxiliaryState?: () => void): Promise<void>;
116
+ /** Clears every session while the caller already owns the global lifecycle exclusive. */
117
+ resetAllWithinExclusive(clearAuxiliaryState?: () => void): Promise<void>;
118
+ /** Returns a non-mutating session snapshot without creating or binding state. */
119
+ inspectSession(sessionId: string): HistorySessionSnapshot;
120
+ /** Returns the currently materialized session identifiers without binding ownership. */
121
+ getSessionIds(): string[];
122
+ /**
123
+ * Gets the most recently available MCP tools from the session.
124
+ *
125
+ * @param sessionId - Optional session ID for session-scoped results
126
+ * @returns The last-seen array of MCP tool names, or undefined if never set
127
+ */
128
+ getAvailableMcpTools(sessionId?: string): string[] | undefined;
129
+ /**
130
+ * Gets the most recently available skills from the session.
131
+ *
132
+ * @param sessionId - Optional session ID for session-scoped results
133
+ * @returns The last-seen array of skill names, or undefined if never set
134
+ */
135
+ getAvailableSkills(sessionId?: string): string[] | undefined;
136
+ /**
137
+ * Pre-declares a branch ID without adding any thoughts.
138
+ * Allows merge_branch_ids to reference branches that have not yet received thoughts.
139
+ *
140
+ * @param sessionId - Optional session ID (defaults to global session)
141
+ * @param branchId - The branch identifier to register
142
+ * @throws ValidationError if branchId is empty or already exists
143
+ */
144
+ registerBranch(sessionId: string | undefined, branchId: BranchId): void;
145
+ /**
146
+ * Checks whether a branch exists (has thoughts OR was pre-declared).
147
+ *
148
+ * @param sessionId - Optional session ID (defaults to global session)
149
+ * @param branchId - The branch identifier to check
150
+ * @returns true if the branch exists or has been registered
151
+ */
152
+ branchExists(sessionId: string | undefined, branchId: BranchId): boolean;
153
+ /**
154
+ * Access the EdgeStore, if configured.
155
+ *
156
+ * Returns undefined when DAG edges are not enabled.
157
+ * Used by ThoughtProcessor to build StrategyContext.
158
+ *
159
+ * @returns The edge store, or undefined if not configured
160
+ */
161
+ getEdgeStore(): IEdgeStore | undefined;
162
+ }
163
+ //# sourceMappingURL=IHistoryManager.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"IHistoryManager.d.ts","sourceRoot":"","sources":["../../src/core/IHistoryManager.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,4BAA4B,CAAC;AAC7D,OAAO,KAAK,EAAE,QAAQ,EAAE,SAAS,EAAE,SAAS,EAAE,MAAM,qBAAqB,CAAC;AAC1E,OAAO,KAAK,EAAE,0BAA0B,EAAE,MAAM,4BAA4B,CAAC;AAC7E,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAEhD,+EAA+E;AAC/E,MAAM,WAAW,sBAAsB;IACtC,QAAQ,CAAC,OAAO,EAAE,SAAS,WAAW,EAAE,CAAC;IACzC,QAAQ,CAAC,QAAQ,EAAE,QAAQ,CAAC,MAAM,CAAC,QAAQ,EAAE,SAAS,WAAW,EAAE,CAAC,CAAC,CAAC;IACtE,QAAQ,CAAC,SAAS,EAAE,SAAS,QAAQ,EAAE,CAAC;IACxC,QAAQ,CAAC,iBAAiB,EAAE,SAAS,MAAM,EAA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ting.
3
+ *
4
+ * This module provides the `IThoughtFormatter` interface which defines the
5
+ * contract for formatter implementations. This allows for decoupling and
6
+ * testability of presentation logic.
7
+ *
8
+ * @module IThoughtFormatter
9
+ */
10
+ import type { StepRecommendation } from './step.js';
11
+ import type { ThoughtData } from './thought.js';
12
+ /**
13
+ * Interface for formatting thought data and step recommendations.
14
+ *
15
+ * This interface defines the contract for formatter implementations,
16
+ * allowing for decoupling between components like ThoughtProcessor and
17
+ * concrete implementations. It supports dependency injection and mocking
18
+ * for testing purposes.
19
+ *
20
+ * @example
21
+ * ```typescript
22
+ * class MockFormatter implements IThoughtFormatter {
23
+ * formatRecommendation(_step: StepRecommendation): string { return ''; }
24
+ * formatThought(_thought: ThoughtData): string { return ''; }
25
+ * }
26
+ * ```
27
+ */
28
+ export interface IThoughtFormatter {
29
+ /**
30
+ * Formats a step recommendation into a readable string.
31
+ *
32
+ * Creates a structured display of the step description, recommended tools,
33
+ * recommended skills, expected outcome, and conditions for the next step.
34
+ *
35
+ * @param step - The step recommendation to format
36
+ * @returns A formatted string representation of the recommendation
37
+ */
38
+ formatRecommendation(step: StepRecommendation): string;
39
+ /**
40
+ * Formats a thought into a clean, simple display.
41
+ *
42
+ * Creates a clean output containing the thought content with an appropriate
43
+ * header indicating the thought type. Priority order for icon selection:
44
+ * `is_revision` > `branch_from_thought` > `thought_type`.
45
+ *
46
+ * @param thoughtData - The thought data to format
47
+ * @returns A formatted string with thought and recommendations
48
+ */
49
+ formatThought(thoughtData: ThoughtData): string;
50
+ }
51
+ //# sourceMappingURL=IThoughtFormatter.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"IThoughtFormatter.d.ts","sourceRoot":"","sources":["../../src/core/IThoughtFormatter.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,WAAW,CAAC;AACpD,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAEhD;;;;;;;;;;;;;;;GAeG;AACH,MAAM,WAAW,iBAAiB;IACjC;;;;;;;;OAQG;IACH,oBAAoB,CAAC,IAAI,EAAE,kBAAkB,GAAG,MAAM,CAAC;IAEvD;;;;;;;;;OASG;IACH,aAAa,CAAC,WAAW,EAAE,WAAW,GAAG,MAAM,CAAC;CAChD"}
@@ -0,0 +1 @@
1
+ export { };
@@ -0,0 +1,140 @@
1
+ /**
2
+ * Input normalization for common LLM field name mistakes.
3
+ *
4
+ * This module provides normalization logic to handle common mistakes
5
+ * that LLMs make when generating field names, such as using singular
6
+ * instead of plural forms (e.g., `recommended_tool` vs `recommended_tools`).
7
+ *
8
+ * It also fills in sensible defaults for missing fields in `previous_steps`,
9
+ * which LLMs naturally provide as partial/skeletal data (historical context).
10
+ *
11
+ * @module processor
12
+ */
13
+ import type { ThoughtData } from './thought.js';
14
+ import { type BranchId } from '../contracts/ids.js';
15
+ /**
16
+ * Recursively sanitizes all string values within an unknown structure.
17
+ * Walks into plain objects and arrays to reach deeply nested strings.
18
+ * Non-plain objects (Date, RegExp, etc.) are returned as-is.
19
+ *
20
+ * @param value - The value to sanitize recursively
21
+ * @returns The sanitized value with all nested strings cleaned
22
+ *
23
+ * @example
24
+ * ```typescript
25
+ * sanitizeRecursive('<script>x</script>'); // 'x'
26
+ * sanitizeRecursive({ a: { b: '<iframe>y' } }); // { a: { b: 'y' } }
27
+ * sanitizeRecursive(['a\x00b', 42]); // ['ab', 42]
28
+ * ```
29
+ */
30
+ export declare function sanitizeRecursive(value: unknown): unknown;
31
+ /**
32
+ * Sanitizes and validates a branch ID to prevent path traversal attacks.
33
+ *
34
+ * @param branchId - The branch ID to sanitize
35
+ * @returns The sanitized branch ID
36
+ * @throws ValidationError if the branch ID contains invalid characters
37
+ *
38
+ * @example
39
+ * ```typescript
40
+ * sanitizeBranchId('my-branch_01'); // 'my-branch_01'
41
+ * sanitizeBranchId('../etc/passwd'); // throws ValidationError
42
+ * ```
43
+ */
44
+ export declare function sanitizeBranchId(branchId: string): BranchId;
45
+ /**
46
+ * Sanitizes and validates a session ID.
47
+ *
48
+ * @param sessionId - The session ID to sanitize
49
+ * @returns The sanitized session ID, or undefined if invalid after sanitization
50
+ *
51
+ * @example
52
+ * ```typescript
53
+ * sanitizeSessionId('analysis-task-42'); // 'analysis-task-42'
54
+ * sanitizeSessionId('bad session!'); // undefined (stripped)
55
+ * ```
56
+ */
57
+ export declare function sanitizeSessionId(sessionId: string): string | undefined;
58
+ /**
59
+ * Normalizes reasoning-specific fields on a thought input object.
60
+ * Always applies reasoning normalization — reasoning is the default pipeline.
61
+ * Applies the following normalization rules:
62
+ * - Defaults `thought_type` to `'regular'` if not provided
63
+ * - Clamps `quality_score` to [0, 1] range
64
+ * - Clamps `confidence` to [0, 1] range
65
+ * - Sanitizes `hypothesis_id` using `sanitizeBranchId` pattern
66
+ * - Filters `synthesis_sources` to positive integers only
67
+ * - Filters `merge_from_thoughts` to positive integers only
68
+ * - Sanitizes each entry in `merge_branch_ids`
69
+ * - Defaults `reasoning_depth` to `'moderate'` for hypothesis/verification types
70
+ *
71
+ * @param input - The mutable normalized input object to apply reasoning defaults to
72
+ *
73
+ * @example
74
+ * ```typescript
75
+ * const input: Record<string, unknown> = { thought_type: 'hypothesis', quality_score: 1.5 };
76
+ * normalizeReasoningFields(input);
77
+ * // input.quality_score === 1, input.reasoning_depth === 'moderate'
78
+ * ```
79
+ */
80
+ export declare function normalizeReasoningFields(input: Record<string, unknown>): void;
81
+ /**
82
+ * Normalizes thought input data by fixing common LLM field name mistakes.
83
+ *
84
+ * This function handles cases where LLMs incorrectly use singular forms
85
+ * of field names that should be plural. It applies normalization to both
86
+ * `current_step` and `previous_steps` fields.
87
+ *
88
+ * The normalization is applied BEFORE schema validation, allowing the
89
+ * strict Valibot schema to remain correct while still being tolerant
90
+ * of common LLM mistakes.
91
+ *
92
+ * @param input - The raw thought input data to normalize
93
+ * @returns Normalized thought data with correct field names
94
+ *
95
+ * @remarks
96
+ * **Normalization Rules:**
97
+ * - `recommended_tool` (singular) → `recommended_tools` (plural)
98
+ * - `recommended_skill` (singular) → `recommended_skills` (plural)
99
+ * - Applied to `current_step` if present (strict mode)
100
+ * - Applied to all items in `previous_steps` if present (lenient mode with defaults)
101
+ *
102
+ * **Design Rationale:**
103
+ * LLMs sometimes use singular field names even when the schema explicitly
104
+ * defines plural forms. Rather than forcing the LLM to be perfect (which
105
+ * leads to cryptic validation errors), we normalize the input to handle
106
+ * these common mistakes gracefully.
107
+ *
108
+ * Additionally, LLMs naturally provide complete data for `current_step`
109
+ * but only partial/skeletal data for `previous_steps` (historical context).
110
+ * The lenient mode for `previous_steps` fills in sensible defaults:
111
+ * - `confidence`: 0.5 for missing tool recommendation confidence
112
+ * - `priority`: 999 for missing tool recommendation priority
113
+ * - `rationale`: empty string for missing tool recommendation rationale
114
+ * - `expected_outcome`: empty string for missing step expected outcome
115
+ *
116
+ * @example
117
+ * ```typescript
118
+ * const input = {
119
+ * thought: 'I need to analyze the data',
120
+ * thought_number: 1,
121
+ * total_thoughts: 3,
122
+ * next_thought_needed: true,
123
+ * current_step: {
124
+ * step_description: 'Read the data file',
125
+ * recommended_tool: [{ tool_name: 'Read', confidence: 0.9, rationale: 'test', priority: 1 }],
126
+ * expected_outcome: 'Data loaded'
127
+ * },
128
+ * previous_steps: [{
129
+ * step_description: 'Previous step',
130
+ * recommended_tools: [{ tool_name: 'Grep', rationale: 'Search code' }]
131
+ * }]
132
+ * };
133
+ *
134
+ * const normalized = normalizeInput(input);
135
+ * // current_step: recommended_tools exists (plural form)
136
+ * // previous_steps[0]: confidence=0.5, priority=999, expected_outcome='' filled in
137
+ * ```
138
+ */
139
+ export declare function normalizeInput(input: unknown): ThoughtData;
140
+ //# sourceMappingURL=InputNormalizer.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"InputNormalizer.d.ts","sourceRoot":"","sources":["../../src/core/InputNormalizer.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AASH,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAEhD,OAAO,EAA8C,KAAK,QAAQ,EAAE,MAAM,qBAAqB,CAAC;AAYhG;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,iBAAiB,CAAC,KAAK,EAAE,OAAO,GAAG,OAAO,CAuBzD;AAQD;;;;;;;;;;;;GAYG;AACH,wBAAgB,gBAAgB,CAAC,QAAQ,EAAE,MAAM,GAAG,QAAQ,CAS3D;AAED;;;;;;;;;;;GAWG;AACH,wBAAgB,iBAAiB,CAAC,SAAS,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAQvE;AA6ID;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,wBAAgB,wBAAwB,CAAC,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,IAAI,CAsD7E;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAyDG;AACH,wBAAgB,cAAc,CAAC,KAAK,EAAE,OAAO,GAAG,WAAW,CAwD1D"}
@@ -0,0 +1,95 @@
1
+ import { ValidationError } from "../errors.js";
2
+ import { sanitizeRationale, sanitizeStepField, sanitizeString, sanitizeSuggestedInputs } from "../sanitize.js";
3
+ import { MAX_SESSION_ID_LENGTH, SESSION_ID_PATTERN } from "./ids.js";
4
+ import { asBranchId, asSessionId, generateThoughtId } from "../contracts/ids.js";
5
+ const DEFAULT_RECOMMENDATION_CONFIDENCE = 0.5;
6
+ const DEFAULT_RECOMMENDATION_PRIORITY = 999;
7
+ const DEFAULT_RECOMMENDATION_RATIONALE = '';
8
+ const DEFAULT_STEP_OUTCOME = '';
9
+ function sanitizeRecursive(value) {
10
+ if (null == value) return value;
11
+ if ('string' == typeof value) return sanitizeString(value);
12
+ if (Array.isArray(value)) return value.map((item)=>sanitizeRecursive(item));
13
+ if ('object' == typeof value) {
14
+ const proto = Object.getPrototypeOf(value);
15
+ if (proto !== Object.prototype && null !== proto) return value;
16
+ const result = {};
17
+ for (const [key, val] of Object.entries(value))result[key] = sanitizeRecursive(val);
18
+ return result;
19
+ }
20
+ return value;
21
+ }
22
+ const BRANCH_ID_PATTERN = /^[a-zA-Z0-9_-]{1,64}$/;
23
+ function sanitizeBranchId(branchId) {
24
+ if (!BRANCH_ID_PATTERN.test(branchId)) throw new ValidationError('branch_id', 'Invalid format - must be 1-64 alphanumeric characters, hyphens, or underscores only');
25
+ return asBranchId(branchId);
26
+ }
27
+ function sanitizeSessionId(sessionId) {
28
+ const cleaned = sanitizeString(sessionId);
29
+ if (cleaned.length > MAX_SESSION_ID_LENGTH || !SESSION_ID_PATTERN.test(cleaned)) return;
30
+ return cleaned;
31
+ }
32
+ function normalizeRecommendation(rec) {
33
+ const normalized = {
34
+ ...rec
35
+ };
36
+ if (!('confidence' in normalized) || void 0 === normalized.confidence) normalized.confidence = DEFAULT_RECOMMENDATION_CONFIDENCE;
37
+ if (!('priority' in normalized) || void 0 === normalized.priority) normalized.priority = DEFAULT_RECOMMENDATION_PRIORITY;
38
+ if ('rationale' in normalized && void 0 !== normalized.rationale) {
39
+ if ('string' == typeof normalized.rationale) normalized.rationale = sanitizeRationale(normalized.rationale);
40
+ } else normalized.rationale = DEFAULT_RECOMMENDATION_RATIONALE;
41
+ if (normalized.suggested_inputs && 'object' == typeof normalized.suggested_inputs && !Array.isArray(normalized.suggested_inputs)) normalized.suggested_inputs = sanitizeSuggestedInputs(normalized.suggested_inputs);
42
+ return normalized;
43
+ }
44
+ function normalizeStepRecommendation(step, lenient) {
45
+ const normalized = {
46
+ ...step
47
+ };
48
+ if ('recommended_tool' in normalized && !('recommended_tools' in normalized)) {
49
+ normalized.recommended_tools = normalized.recommended_tool;
50
+ delete normalized.recommended_tool;
51
+ }
52
+ if ('recommended_skill' in normalized && !('recommended_skills' in normalized)) {
53
+ normalized.recommended_skills = normalized.recommended_skill;
54
+ delete normalized.recommended_skill;
55
+ }
56
+ if (Array.isArray(normalized.recommended_tools)) normalized.recommended_tools = normalized.recommended_tools.map((tool)=>'object' == typeof tool && null !== tool ? normalizeRecommendation(tool) : tool);
57
+ if (Array.isArray(normalized.recommended_skills)) normalized.recommended_skills = normalized.recommended_skills.map((skill)=>'object' == typeof skill && null !== skill ? normalizeRecommendation(skill) : skill);
58
+ if ('string' == typeof normalized.step_description) normalized.step_description = sanitizeStepField(normalized.step_description);
59
+ if ('string' == typeof normalized.expected_outcome) normalized.expected_outcome = sanitizeStepField(normalized.expected_outcome);
60
+ if (Array.isArray(normalized.next_step_conditions)) normalized.next_step_conditions = normalized.next_step_conditions.map((cond)=>'string' == typeof cond ? sanitizeStepField(cond) : cond);
61
+ if (lenient && !('expected_outcome' in normalized)) normalized.expected_outcome = DEFAULT_STEP_OUTCOME;
62
+ return normalized;
63
+ }
64
+ function normalizeReasoningFields(input) {
65
+ if (!('thought_type' in input) || void 0 === input.thought_type) input.thought_type = 'regular';
66
+ if ('number' == typeof input.quality_score) input.quality_score = Math.max(0, Math.min(1, input.quality_score));
67
+ if ('number' == typeof input.confidence) input.confidence = Math.max(0, Math.min(1, input.confidence));
68
+ if ('string' == typeof input.hypothesis_id) input.hypothesis_id = sanitizeBranchId(input.hypothesis_id);
69
+ if (Array.isArray(input.synthesis_sources)) input.synthesis_sources = input.synthesis_sources.filter((v)=>'number' == typeof v && Number.isInteger(v) && v > 0);
70
+ if (Array.isArray(input.merge_from_thoughts)) input.merge_from_thoughts = input.merge_from_thoughts.filter((v)=>'number' == typeof v && Number.isInteger(v) && v > 0);
71
+ if (Array.isArray(input.merge_branch_ids)) input.merge_branch_ids = input.merge_branch_ids.map((id)=>{
72
+ if ('string' == typeof id) return sanitizeBranchId(id);
73
+ return id;
74
+ });
75
+ if (('hypothesis' === input.thought_type || 'verification' === input.thought_type) && !('reasoning_depth' in input)) input.reasoning_depth = 'moderate';
76
+ }
77
+ function normalizeInput(input) {
78
+ if ('object' != typeof input || null === input) return input;
79
+ const normalized = {
80
+ ...input
81
+ };
82
+ if (normalized.current_step && 'object' == typeof normalized.current_step) normalized.current_step = normalizeStepRecommendation(normalized.current_step, false);
83
+ if (Array.isArray(normalized.previous_steps) && normalized.previous_steps.length > 0) normalized.previous_steps = normalized.previous_steps.map((step)=>'object' == typeof step && null !== step ? normalizeStepRecommendation(step, true) : step);
84
+ if ('string' == typeof normalized.branch_id) normalized.branch_id = sanitizeBranchId(normalized.branch_id);
85
+ if ('string' == typeof normalized.session_id) normalized.session_id = asSessionId(normalized.session_id);
86
+ if ('string' == typeof normalized.register_branch_id) normalized.register_branch_id = sanitizeBranchId(normalized.register_branch_id);
87
+ if (!normalized.id || 'string' != typeof normalized.id) normalized.id = generateThoughtId();
88
+ normalizeReasoningFields(normalized);
89
+ if ('string' == typeof normalized.meta_observation) normalized.meta_observation = sanitizeStepField(normalized.meta_observation);
90
+ const sanitized = sanitizeRecursive(normalized);
91
+ return sanitized;
92
+ }
93
+ export { normalizeInput, normalizeReasoningFields, sanitizeBranchId, sanitizeRecursive, sanitizeSessionId };
94
+
95
+ //# sourceMappingURL=InputNormalizer.js.map