@iworkforces/tracelattice 2.1.1 → 2.2.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 (129) hide show
  1. package/README.md +20 -3
  2. package/dist/contracts/PersistenceBackend.d.ts +10 -1
  3. package/dist/contracts/PersistenceBackend.d.ts.map +1 -1
  4. package/dist/contracts/calibrator.d.ts +9 -6
  5. package/dist/contracts/calibrator.d.ts.map +1 -1
  6. package/dist/contracts/interfaces.d.ts +6 -0
  7. package/dist/contracts/interfaces.d.ts.map +1 -1
  8. package/dist/contracts/persistence-work.d.ts +13 -1
  9. package/dist/contracts/persistence-work.d.ts.map +1 -1
  10. package/dist/contracts/strategy.d.ts +14 -9
  11. package/dist/contracts/strategy.d.ts.map +1 -1
  12. package/dist/core/DurableThoughtIdentityIndex.d.ts +35 -0
  13. package/dist/core/DurableThoughtIdentityIndex.d.ts.map +1 -0
  14. package/dist/core/DurableThoughtIdentityIndex.js +94 -0
  15. package/dist/core/DurableThoughtIdentityIndex.js.map +1 -0
  16. package/dist/core/HistoryManager.d.ts +5 -0
  17. package/dist/core/HistoryManager.d.ts.map +1 -1
  18. package/dist/core/HistoryManager.js +37 -4
  19. package/dist/core/HistoryManager.js.map +1 -1
  20. package/dist/core/IHistoryManager.d.ts +2 -0
  21. package/dist/core/IHistoryManager.d.ts.map +1 -1
  22. package/dist/core/PersistenceBuffer.d.ts +7 -1
  23. package/dist/core/PersistenceBuffer.d.ts.map +1 -1
  24. package/dist/core/PersistenceBuffer.js +13 -1
  25. package/dist/core/PersistenceBuffer.js.map +1 -1
  26. package/dist/core/PersistenceRestore.d.ts.map +1 -1
  27. package/dist/core/PersistenceRestore.js +11 -3
  28. package/dist/core/PersistenceRestore.js.map +1 -1
  29. package/dist/core/PersistenceWorkQueue.d.ts +13 -1
  30. package/dist/core/PersistenceWorkQueue.d.ts.map +1 -1
  31. package/dist/core/PersistenceWorkQueue.js +86 -11
  32. package/dist/core/PersistenceWorkQueue.js.map +1 -1
  33. package/dist/core/PersistenceWriter.d.ts.map +1 -1
  34. package/dist/core/PersistenceWriter.js +3 -0
  35. package/dist/core/PersistenceWriter.js.map +1 -1
  36. package/dist/core/ThoughtEvaluator.d.ts +7 -4
  37. package/dist/core/ThoughtEvaluator.d.ts.map +1 -1
  38. package/dist/core/ThoughtEvaluator.js +15 -7
  39. package/dist/core/ThoughtEvaluator.js.map +1 -1
  40. package/dist/core/ThoughtProcessor.d.ts.map +1 -1
  41. package/dist/core/ThoughtProcessor.js +19 -7
  42. package/dist/core/ThoughtProcessor.js.map +1 -1
  43. package/dist/core/ThoughtReferenceIndex.d.ts +4 -0
  44. package/dist/core/ThoughtReferenceIndex.d.ts.map +1 -1
  45. package/dist/core/ThoughtReferenceIndex.js +28 -1
  46. package/dist/core/ThoughtReferenceIndex.js.map +1 -1
  47. package/dist/core/VerificationOutcomeAdmission.d.ts +8 -1
  48. package/dist/core/VerificationOutcomeAdmission.d.ts.map +1 -1
  49. package/dist/core/VerificationOutcomeAdmission.js.map +1 -1
  50. package/dist/core/VerificationTargetRestore.d.ts +5 -0
  51. package/dist/core/VerificationTargetRestore.d.ts.map +1 -0
  52. package/dist/core/VerificationTargetRestore.js +61 -0
  53. package/dist/core/VerificationTargetRestore.js.map +1 -0
  54. package/dist/core/evaluator/Aggregator.d.ts +2 -1
  55. package/dist/core/evaluator/Aggregator.d.ts.map +1 -1
  56. package/dist/core/evaluator/Aggregator.js +4 -12
  57. package/dist/core/evaluator/Aggregator.js.map +1 -1
  58. package/dist/core/evaluator/Calibrator.d.ts +13 -9
  59. package/dist/core/evaluator/Calibrator.d.ts.map +1 -1
  60. package/dist/core/evaluator/Calibrator.js +25 -11
  61. package/dist/core/evaluator/Calibrator.js.map +1 -1
  62. package/dist/core/evaluator/PatternDetector.d.ts +2 -1
  63. package/dist/core/evaluator/PatternDetector.d.ts.map +1 -1
  64. package/dist/core/evaluator/PatternDetector.js +13 -12
  65. package/dist/core/evaluator/PatternDetector.js.map +1 -1
  66. package/dist/core/evaluator/SignalComputer.d.ts +3 -2
  67. package/dist/core/evaluator/SignalComputer.d.ts.map +1 -1
  68. package/dist/core/evaluator/SignalComputer.js +4 -9
  69. package/dist/core/evaluator/SignalComputer.js.map +1 -1
  70. package/dist/core/evaluator/VerificationLinks.d.ts +19 -0
  71. package/dist/core/evaluator/VerificationLinks.d.ts.map +1 -0
  72. package/dist/core/evaluator/VerificationLinks.js +113 -0
  73. package/dist/core/evaluator/VerificationLinks.js.map +1 -0
  74. package/dist/core/evaluator/calibration-math.d.ts +12 -2
  75. package/dist/core/evaluator/calibration-math.d.ts.map +1 -1
  76. package/dist/core/evaluator/calibration-math.js +11 -2
  77. package/dist/core/evaluator/calibration-math.js.map +1 -1
  78. package/dist/core/graph/EdgeEmitter.d.ts.map +1 -1
  79. package/dist/core/graph/EdgeEmitter.js +2 -1
  80. package/dist/core/graph/EdgeEmitter.js.map +1 -1
  81. package/dist/core/graph/GraphView.d.ts +5 -5
  82. package/dist/core/graph/GraphView.d.ts.map +1 -1
  83. package/dist/core/graph/GraphView.js +11 -11
  84. package/dist/core/graph/GraphView.js.map +1 -1
  85. package/dist/core/reasoning/ActiveEvidenceProjection.d.ts +20 -0
  86. package/dist/core/reasoning/ActiveEvidenceProjection.d.ts.map +1 -0
  87. package/dist/core/reasoning/ActiveEvidenceProjection.js +100 -0
  88. package/dist/core/reasoning/ActiveEvidenceProjection.js.map +1 -0
  89. package/dist/core/reasoning/strategies/TreeOfThoughtStrategy.d.ts +5 -4
  90. package/dist/core/reasoning/strategies/TreeOfThoughtStrategy.d.ts.map +1 -1
  91. package/dist/core/reasoning/strategies/TreeOfThoughtStrategy.js +24 -14
  92. package/dist/core/reasoning/strategies/TreeOfThoughtStrategy.js.map +1 -1
  93. package/dist/lib.d.ts.map +1 -1
  94. package/dist/lib.js +3 -1
  95. package/dist/lib.js.map +1 -1
  96. package/dist/persistence/BacktrackPersistence.d.ts +13 -0
  97. package/dist/persistence/BacktrackPersistence.d.ts.map +1 -0
  98. package/dist/persistence/BacktrackPersistence.js +90 -0
  99. package/dist/persistence/BacktrackPersistence.js.map +1 -0
  100. package/dist/persistence/FilePersistence.d.ts +2 -1
  101. package/dist/persistence/FilePersistence.d.ts.map +1 -1
  102. package/dist/persistence/FilePersistence.js +28 -0
  103. package/dist/persistence/FilePersistence.js.map +1 -1
  104. package/dist/persistence/FileSnapshotV2.d.ts +2 -0
  105. package/dist/persistence/FileSnapshotV2.d.ts.map +1 -1
  106. package/dist/persistence/FileSnapshotV2.js +6 -2
  107. package/dist/persistence/FileSnapshotV2.js.map +1 -1
  108. package/dist/persistence/MemoryPersistence.d.ts +2 -1
  109. package/dist/persistence/MemoryPersistence.d.ts.map +1 -1
  110. package/dist/persistence/MemoryPersistence.js +21 -1
  111. package/dist/persistence/MemoryPersistence.js.map +1 -1
  112. package/dist/persistence/PersistenceCodec.d.ts.map +1 -1
  113. package/dist/persistence/PersistenceCodec.js +5 -0
  114. package/dist/persistence/PersistenceCodec.js.map +1 -1
  115. package/dist/persistence/PersistenceErrors.d.ts +1 -1
  116. package/dist/persistence/PersistenceErrors.d.ts.map +1 -1
  117. package/dist/persistence/PersistenceErrors.js.map +1 -1
  118. package/dist/persistence/PersistenceScope.d.ts +1 -1
  119. package/dist/persistence/PersistenceScope.d.ts.map +1 -1
  120. package/dist/persistence/PersistenceScope.js.map +1 -1
  121. package/dist/persistence/SqlitePersistence.d.ts +2 -1
  122. package/dist/persistence/SqlitePersistence.d.ts.map +1 -1
  123. package/dist/persistence/SqlitePersistence.js +18 -0
  124. package/dist/persistence/SqlitePersistence.js.map +1 -1
  125. package/dist/registry/BaseRegistry.d.ts +10 -2
  126. package/dist/registry/BaseRegistry.d.ts.map +1 -1
  127. package/dist/registry/BaseRegistry.js +128 -81
  128. package/dist/registry/BaseRegistry.js.map +1 -1
  129. package/package.json +4 -3
@@ -12,6 +12,8 @@ import { getOwner } from "../context/RequestContext.js";
12
12
  import { ThoughtReferenceIndex } from "./ThoughtReferenceIndex.js";
13
13
  import { resolveThoughtReferencesForAdmission } from "./CrossReferenceValidator.js";
14
14
  import { SessionLifecycleCoordinator } from "./SessionLifecycleCoordinator.js";
15
+ import { resolvedVerificationTarget } from "./evaluator/VerificationLinks.js";
16
+ import { reconstructVerificationTargets } from "./VerificationTargetRestore.js";
15
17
  const ABSOLUTE_MAX_HISTORY_SIZE = 10000;
16
18
  class HistoryManager {
17
19
  static SESSION_TTL_MS = 1800000;
@@ -78,6 +80,8 @@ class HistoryManager {
78
80
  bufferSize: config.persistenceBufferSize ?? 100,
79
81
  flushInterval: config.persistenceFlushInterval ?? 1000,
80
82
  maxRetries: config.persistenceMaxRetries ?? 3,
83
+ durableHistorySize: config.persistenceHistorySize ?? ABSOLUTE_MAX_HISTORY_SIZE,
84
+ persistBranches: config.persistBranches ?? true,
81
85
  eventEmitter: this._eventEmitter,
82
86
  logger: this._logger
83
87
  });
@@ -211,6 +215,7 @@ class HistoryManager {
211
215
  return {
212
216
  thought_history: [],
213
217
  branches: {},
218
+ verificationTargets: new Map(),
214
219
  availableMcpTools: void 0,
215
220
  availableSkills: void 0,
216
221
  lastAccessedAt: Date.now(),
@@ -237,14 +242,22 @@ class HistoryManager {
237
242
  const sessionId = asSessionId(thought.session_id);
238
243
  this._lifecycle.runMutation(sessionId, ()=>this._addThoughtWithinOperation(sessionId, thought, context));
239
244
  }
245
+ assertThoughtIdentityAvailable(thought) {
246
+ if (void 0 === thought.id) return;
247
+ const sessionId = asSessionId(thought.session_id);
248
+ this._authorizeExistingSession(sessionId, this._getCurrentOwner());
249
+ if (this._referenceIndex.has(sessionId, thought.id) || this._persistenceBuffer?.hasThoughtIdentity(sessionId, thought.id) === true) throw new ValidationError('id', `Thought id already exists in session: ${thought.id}`);
250
+ }
240
251
  _addThoughtWithinOperation(sessionId, thought, context) {
241
252
  this._persistenceBuffer?.assertSessionAdmissionOpen(sessionId);
242
253
  const owner = this._getCurrentOwner();
243
254
  this._authorizeExistingSession(sessionId, owner);
255
+ this.assertThoughtIdentityAvailable(thought);
244
256
  const resolvedReferences = this._resolveAdmissionReferences(sessionId, thought, context);
245
257
  const session = this._getSessionWithinOperation(sessionId, owner);
246
258
  this._metrics?.counter('thought_requests_total', 1, {}, 'Total thought requests added to history');
247
259
  session.thought_history.push(thought);
260
+ this._recordVerificationTarget(session, thought, resolvedReferences);
248
261
  if (void 0 !== resolvedReferences.backtrackTargetThoughtId) this._applyRetraction(session, resolvedReferences.backtrackTargetThoughtId);
249
262
  if (thought.available_mcp_tools) session.availableMcpTools = thought.available_mcp_tools;
250
263
  if (thought.available_skills) session.availableSkills = thought.available_skills;
@@ -255,9 +268,10 @@ class HistoryManager {
255
268
  resolvedReferences
256
269
  });
257
270
  const evictedBranchIds = this._enforceRetention(session, thought.branch_id);
271
+ this._pruneVerificationTargets(session);
258
272
  this._rebuildReferenceIndex(sessionId, session);
259
273
  const prunedEdges = this._pruneUnretainedEdges(sessionId, session);
260
- this._bufferRetainedState(sessionId, session, thought, evictedBranchIds, edgeAdded, prunedEdges);
274
+ this._bufferRetainedState(sessionId, session, thought, evictedBranchIds, edgeAdded, prunedEdges, resolvedReferences.backtrackTargetThoughtId);
261
275
  }
262
276
  _resolveAdmissionReferences(sessionId, thought, context) {
263
277
  const resolved = context?.resolvedReferences ?? resolveThoughtReferencesForAdmission(thought, (thoughtNumber)=>this._referenceIndex.resolve(sessionId, thoughtNumber));
@@ -274,6 +288,19 @@ class HistoryManager {
274
288
  if (void 0 !== branchId) this._trimSessionBranchSize(session, branchId);
275
289
  return this._cleanupSessionBranches(session);
276
290
  }
291
+ _recordVerificationTarget(session, thought, references) {
292
+ const targetId = resolvedVerificationTarget(thought, references);
293
+ if (void 0 !== thought.id && void 0 !== targetId) session.verificationTargets.set(thought.id, targetId);
294
+ }
295
+ _pruneVerificationTargets(session) {
296
+ const retainedIds = new Set([
297
+ session.thought_history,
298
+ ...Object.values(session.branches)
299
+ ].flat().flatMap((thought)=>void 0 === thought.id ? [] : [
300
+ thought.id
301
+ ]));
302
+ for (const [verifierId, targetId] of session.verificationTargets)if (!retainedIds.has(verifierId) || !retainedIds.has(targetId)) session.verificationTargets.delete(verifierId);
303
+ }
277
304
  _pruneUnretainedEdges(sessionId, session) {
278
305
  if (void 0 === this._edgeStore) return 0;
279
306
  const retainedIds = new Set();
@@ -285,11 +312,12 @@ class HistoryManager {
285
312
  for (const thought of Object.values(session.branches).flat())if (void 0 !== thought.id) retainedBranchThoughtIds.add(thought.id);
286
313
  return this._edgeStore.pruneSession(sessionId, retainedIds, retainedBranchThoughtIds);
287
314
  }
288
- _bufferRetainedState(sessionId, session, thought, evictedBranchIds, edgeAdded, prunedEdges) {
315
+ _bufferRetainedState(sessionId, session, thought, evictedBranchIds, edgeAdded, prunedEdges, backtrackTargetThoughtId) {
289
316
  const buffer = this._persistenceBuffer;
290
317
  if (null === buffer) return;
291
- buffer.bufferThought(sessionId, thought);
292
- if (void 0 !== thought.branch_id || evictedBranchIds.length > 0 || session.pendingRestoreBranchDeletes.size > 0) this._stageBranchPersistence(sessionId, session, evictedBranchIds);
318
+ if (void 0 === backtrackTargetThoughtId) buffer.bufferThought(sessionId, thought);
319
+ else buffer.bufferBacktrack(sessionId, thought, backtrackTargetThoughtId);
320
+ if (void 0 !== thought.branch_id || void 0 !== backtrackTargetThoughtId || evictedBranchIds.length > 0 || session.pendingRestoreBranchDeletes.size > 0) this._stageBranchPersistence(sessionId, session, evictedBranchIds);
293
321
  if (void 0 !== this._edgeStore && (edgeAdded || prunedEdges > 0)) buffer.bufferEdges(sessionId, this._edgeStore.edgesForSession(sessionId));
294
322
  }
295
323
  _stageAllRestoreBranchReconciliation() {
@@ -384,6 +412,7 @@ class HistoryManager {
384
412
  if (void 0 === session) return {
385
413
  history: [],
386
414
  branches: {},
415
+ verificationTargets: new Map(),
387
416
  branchIds: [],
388
417
  availableMcpTools: void 0,
389
418
  availableSkills: void 0
@@ -398,6 +427,7 @@ class HistoryManager {
398
427
  ...thoughts
399
428
  ]
400
429
  ])),
430
+ verificationTargets: new Map(session.verificationTargets),
401
431
  branchIds: Array.from(session.branchIdentities),
402
432
  availableMcpTools: void 0 === session.availableMcpTools ? void 0 : [
403
433
  ...session.availableMcpTools
@@ -470,6 +500,7 @@ class HistoryManager {
470
500
  }
471
501
  _restoredState(restored) {
472
502
  const session = this._createSessionState(void 0, 'restored');
503
+ session.verificationTargets = reconstructVerificationTargets(restored.sessionId, restored.history, restored.branches);
473
504
  for(let index = restored.history.length - 1; index >= 0; index--){
474
505
  const thought = restored.history[index];
475
506
  if (void 0 !== thought) {
@@ -490,6 +521,7 @@ class HistoryManager {
490
521
  session.branchIdentities.add(branch.branchId);
491
522
  session.branches[branch.branchId] = branch.thoughts.slice(-this._maxBranchSize);
492
523
  }
524
+ this._pruneVerificationTargets(session);
493
525
  return session;
494
526
  }
495
527
  async loadFromPersistence() {
@@ -515,6 +547,7 @@ class HistoryManager {
515
547
  thought.id
516
548
  ]))));
517
549
  }
550
+ this._persistenceBuffer?.replaceDurableThoughtIdentities(restored.sessions);
518
551
  this._edgeStore?.clearAll();
519
552
  this._summaryStore?.clearAll();
520
553
  this._sessions.clear();
@@ -1 +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 { asSessionId, type BranchId, type SessionId, type ThoughtId } from '../contracts/ids.js';\nimport type { ISummaryStore } from '../contracts/summary.js';\nimport {\n\tERROR_CODES,\n\tInvalidBacktrackError,\n\tMaxSessionsReachedError,\n\tSequentialThinkingError,\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 { 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\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 serialize session resets. */\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 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 | 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\tlogger: this._logger,\n\t\t});\n\n\t\tthis._sessionManager = new SessionManager<SessionState>({\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({\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\teventEmitter: this._eventEmitter,\n\t\t\t\tlogger: this._logger,\n\t\t\t});\n\t\t\tthis._startFlushTimer();\n\t\t}\n\t\tconst resetDurability =\n\t\t\tthis._persistence === null || this._persistenceBuffer === null\n\t\t\t\t? { persistence: null, barrier: null }\n\t\t\t\t: { persistence: this._persistence, barrier: this._persistenceBuffer };\n\t\tthis._resetCoordinator = new SessionResetCoordinator({\n\t\t\t...resetDurability,\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 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 = 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\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;\n\t\tif (firstSessionId !== undefined) {\n\t\t\tthrow new SessionAccessDeniedError(firstSessionId, 'trusted ownerless context', owner);\n\t\t}\n\t\tthrow new SequentialThinkingError(\n\t\t\t`Access denied to all sessions: trusted ownerless context required, accessed by '${owner}'`,\n\t\t\tERROR_CODES.SESSION_ACCESS_DENIED\n\t\t);\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);\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 policy = new DehydrationPolicy(this._summaryStore);\n\t\treturn policy.apply(history, asSessionId(sessionId), 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, 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);\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 });\n\t\t});\n\t}\n\n\tpublic branchExists(sessionId: string, 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/** 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 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","Map","ThoughtReferenceIndex","config","NullLogger","requestedMaxSize","Math","SessionLifecycleCoordinator","EdgeEmitter","SessionManager","PersistenceBuffer","resetDurability","SessionResetCoordinator","owner","sessionId","sessionIds","Promise","session","undefined","summaries","message","meta","getOwner","key","asSessionId","existing","Date","SessionAccessDeniedError","victims","MaxSessionsReachedError","evicted","persistenceState","results","failures","result","AggregateError","provenance","Set","sessionOwner","firstSessionId","SequentialThinkingError","ERROR_CODES","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","policy","DehydrationPolicy","canonicalSessionId","thoughts","ValidationError","clearAuxiliaryState","reset","preservedOwner","restored","index","retainedStart","retainedBranches","stagePersistenceRestore","sessions","referenceIndex","retainedThoughtIds","retainedBranchIds","edge","summary","emitter","TypeError"],"mappings":";;;;;;;;;;;;;;AAmDO,MAAMA,4BAA4B;AAyDlC,MAAMC;IACZ,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,mBAA6C;IACpC,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,kBAAkBN;QAClD,IAAIM,mBAAmBN,2BACtB,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,mDAAmD;YACpE,WAAWM;YACX,SAASN;QACV;QAED,IAAI,CAAC,YAAY,GAAGI,OAAO,WAAW,IAAI;QAC1C,IAAI,CAAC,cAAc,GAAGA,OAAO,aAAa,IAAI;QAC9C,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CAAC,cAAc,GAAG9E;IACvB;IAGO,WAA0B;QAChC,IAAI,AAAwB,SAAxB,IAAI,CAAC,cAAc,EAAW,OAAO,IAAI,CAAC,cAAc;QAC5D,OAAO,IAAI,CAAC,UAAU,CAAC,QAAQ,CAAC;YAC/B,MAAM,IAAI,CAAC,uBAAuB;YAClC,IAAI,CAAC,2BAA2B;QACjC;IACD;IAGA,MAAa,0BAAyC;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"}
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 { asSessionId, type BranchId, type SessionId, type ThoughtId } from '../contracts/ids.js';\nimport type { ISummaryStore } from '../contracts/summary.js';\nimport {\n\tERROR_CODES,\n\tInvalidBacktrackError,\n\tMaxSessionsReachedError,\n\tSequentialThinkingError,\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 { 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';\nimport { resolvedVerificationTarget } from './evaluator/VerificationLinks.js';\nimport { reconstructVerificationTargets } from './VerificationTargetRestore.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\tverificationTargets: Map<ThoughtId, ThoughtId>;\n\tavailableMcpTools: string[] | undefined;\n\tavailableSkills: string[] | undefined;\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\tpersistenceHistorySize?: number;\n\tpersistBranches?: boolean;\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 serialize session resets. */\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 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 | 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\tlogger: this._logger,\n\t\t});\n\n\t\tthis._sessionManager = new SessionManager<SessionState>({\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({\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\tdurableHistorySize: config.persistenceHistorySize ?? ABSOLUTE_MAX_HISTORY_SIZE,\n\t\t\t\tpersistBranches: config.persistBranches ?? true,\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\tconst resetDurability =\n\t\t\tthis._persistence === null || this._persistenceBuffer === null\n\t\t\t\t? { persistence: null, barrier: null }\n\t\t\t\t: { persistence: this._persistence, barrier: this._persistenceBuffer };\n\t\tthis._resetCoordinator = new SessionResetCoordinator({\n\t\t\t...resetDurability,\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 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 = 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\tverificationTargets: new Map<ThoughtId, ThoughtId>(),\n\t\t\tavailableMcpTools: undefined,\n\t\t\tavailableSkills: undefined,\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;\n\t\tif (firstSessionId !== undefined) {\n\t\t\tthrow new SessionAccessDeniedError(firstSessionId, 'trusted ownerless context', owner);\n\t\t}\n\t\tthrow new SequentialThinkingError(\n\t\t\t`Access denied to all sessions: trusted ownerless context required, accessed by '${owner}'`,\n\t\t\tERROR_CODES.SESSION_ACCESS_DENIED\n\t\t);\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);\n\t\tthis._lifecycle.runMutation(sessionId, () =>\n\t\t\tthis._addThoughtWithinOperation(sessionId, thought, context)\n\t\t);\n\t}\n\n\tpublic assertThoughtIdentityAvailable(thought: ThoughtData): void {\n\t\tif (thought.id === undefined) return;\n\t\tconst sessionId = asSessionId(thought.session_id);\n\t\tthis._authorizeExistingSession(sessionId, this._getCurrentOwner());\n\t\tif (\n\t\t\tthis._referenceIndex.has(sessionId, thought.id) ||\n\t\t\tthis._persistenceBuffer?.hasThoughtIdentity(sessionId, thought.id) === true\n\t\t) {\n\t\t\tthrow new ValidationError('id', `Thought id already exists in session: ${thought.id}`);\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\tthis.assertThoughtIdentityAvailable(thought);\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\t\tthis._recordVerificationTarget(session, thought, resolvedReferences);\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._pruneVerificationTargets(session);\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\tresolvedReferences.backtrackTargetThoughtId\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 _recordVerificationTarget(\n\t\tsession: SessionState,\n\t\tthought: ThoughtData,\n\t\treferences: NonNullable<ThoughtAdmissionContext['resolvedReferences']>\n\t): void {\n\t\tconst targetId = resolvedVerificationTarget(thought, references);\n\t\tif (thought.id !== undefined && targetId !== undefined) {\n\t\t\tsession.verificationTargets.set(thought.id, targetId);\n\t\t}\n\t}\n\n\tprivate _pruneVerificationTargets(session: SessionState): void {\n\t\tconst retainedIds = new Set(\n\t\t\t[session.thought_history, ...Object.values(session.branches)]\n\t\t\t\t.flat()\n\t\t\t\t.flatMap((thought) => (thought.id === undefined ? [] : [thought.id]))\n\t\t);\n\t\tfor (const [verifierId, targetId] of session.verificationTargets) {\n\t\t\tif (!retainedIds.has(verifierId) || !retainedIds.has(targetId)) {\n\t\t\t\tsession.verificationTargets.delete(verifierId);\n\t\t\t}\n\t\t}\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\tbacktrackTargetThoughtId?: ThoughtId\n\t): void {\n\t\tconst buffer = this._persistenceBuffer;\n\t\tif (buffer === null) return;\n\t\tif (backtrackTargetThoughtId === undefined) buffer.bufferThought(sessionId, thought);\n\t\telse buffer.bufferBacktrack(sessionId, thought, backtrackTargetThoughtId);\n\t\tif (\n\t\t\tthought.branch_id !== undefined ||\n\t\t\tbacktrackTargetThoughtId !== 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 policy = new DehydrationPolicy(this._summaryStore);\n\t\treturn policy.apply(history, asSessionId(sessionId), 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\tverificationTargets: new Map(),\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\tverificationTargets: new Map(session.verificationTargets),\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, 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);\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 });\n\t\t});\n\t}\n\n\tpublic branchExists(sessionId: string, 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/** 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 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\tsession.verificationTargets = reconstructVerificationTargets(\n\t\t\trestored.sessionId,\n\t\t\trestored.history,\n\t\t\trestored.branches\n\t\t);\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\tthis._pruneVerificationTargets(session);\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\t\tthis._persistenceBuffer?.replaceDurableThoughtIdentities(restored.sessions);\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","Map","ThoughtReferenceIndex","config","NullLogger","requestedMaxSize","Math","SessionLifecycleCoordinator","EdgeEmitter","SessionManager","PersistenceBuffer","resetDurability","SessionResetCoordinator","owner","sessionId","sessionIds","Promise","session","undefined","summaries","message","meta","getOwner","key","asSessionId","existing","Date","SessionAccessDeniedError","victims","MaxSessionsReachedError","evicted","persistenceState","results","failures","result","AggregateError","provenance","Set","sessionOwner","firstSessionId","SequentialThinkingError","ERROR_CODES","thought","context","ValidationError","resolvedReferences","edgeAdded","evictedBranchIds","prunedEdges","resolved","resolveThoughtReferencesForAdmission","thoughtNumber","InvalidBacktrackError","branchId","references","targetId","resolvedVerificationTarget","retainedIds","Object","verifierId","retainedBranchThoughtIds","backtrackTargetThoughtId","buffer","ordinaryDeletes","branch","branchIdsToDelete","t","branchThoughts","retained","branchCount","identitiesToRemove","Array","branchesToDelete","removed","opts","history","policy","DehydrationPolicy","canonicalSessionId","thoughts","clearAuxiliaryState","reset","preservedOwner","restored","reconstructVerificationTargets","index","retainedStart","retainedBranches","stagePersistenceRestore","sessions","referenceIndex","retainedThoughtIds","retainedBranchIds","edge","summary","emitter","TypeError"],"mappings":";;;;;;;;;;;;;;;;AAqDO,MAAMA,4BAA4B;AA4DlC,MAAMC;IACZ,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,mBAA6C;IACpC,gBAA8C;IAC9C,kBAAyD;IACzD,aAA4B;IAC5B,W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e;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"}
@@ -14,6 +14,7 @@ import type { ThoughtData } from './thought.js';
14
14
  export interface HistorySessionSnapshot {
15
15
  readonly history: readonly ThoughtData[];
16
16
  readonly branches: Readonly<Record<BranchId, readonly ThoughtData[]>>;
17
+ readonly verificationTargets: ReadonlyMap<ThoughtId, ThoughtId>;
17
18
  readonly branchIds: readonly BranchId[];
18
19
  readonly availableMcpTools: readonly string[] | undefined;
19
20
  readonly availableSkills: readonly string[] | undefined;
@@ -69,6 +70,7 @@ export interface IHistoryManager {
69
70
  * @param thought - The thought data to add
70
71
  */
71
72
  addThought(thought: ThoughtData, context?: ThoughtAdmissionContext): void;
73
+ assertThoughtIdentityAvailable(thought: ThoughtData): void;
72
74
  /** Resolves a retained same-session numeric reference to stable thought identity. */
73
75
  resolveThoughtReference(sessionId: SessionId, thoughtNumber: number): ThoughtReferenceResolution;
74
76
  /**
@@ -1 +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,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AAC,CAAC;IAEjB,iFAAiF;IACjF,QAAQ,CAAC,mBAAmB,CAAC,EAAE,MAAM,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAE1D,yFAAyF;IACzF,uBAAuB,CAAC,mBAAmB,CAAC,EAAE,MAAM,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAEzE,iFAAiF;IACjF,cAAc,CAAC,SAAS,EAAE,MAAM,GAAG,sBAAsB,CAAC;IAE1D,wFAAwF;IACxF,aAAa,IAAI,MAAM,EAAE,CAAC;IAE1B;;;;;OAKG;IACH,oBAAoB,CAAC,SAAS,EAAE,MAAM,GAAG,MAAM,EAAE,GAAG,SAAS,CAAC;IAE9D;;;;;OAKG;IACH,kBAAkB,CAAC,SAAS,EAAE,MAAM,GAAG,MAAM,EAAE,GAAG,SAAS,CAAC;IAE5D;;;;;;;OAOG;IACH,cAAc,CAAC,SAAS,EAAE,MAAM,EAAE,QAAQ,EAAE,QAAQ,GAAG,IAAI,CAAC;IAE5D;;;;;;OAMG;IACH,YAAY,CAAC,SAAS,EAAE,MAAM,EAAE,QAAQ,EAAE,QAAQ,GAAG,OAAO,CAAC;IAE7D;;;;;;;OAOG;IACH,YAAY,IAAI,UAAU,GAAG,SAAS,CAAC;CACvC"}
@@ -4,9 +4,10 @@
4
4
  * @module PersistenceBuffer
5
5
  */
6
6
  import type { PersistenceBackend } from '../contracts/PersistenceBackend.js';
7
- import type { BranchId, SessionId } from '../contracts/ids.js';
7
+ import type { BranchId, SessionId, ThoughtId } from '../contracts/ids.js';
8
8
  import type { Logger } from '../logger/StructuredLogger.js';
9
9
  import type { Summary } from './compression/Summary.js';
10
+ import type { DurableIdentitySession } from './DurableThoughtIdentityIndex.js';
10
11
  import type { Edge } from './graph/Edge.js';
11
12
  import { type PersistenceDelay } from './PersistenceWriter.js';
12
13
  import type { ThoughtData } from './thought.js';
@@ -30,6 +31,8 @@ export interface PersistenceBufferConfig {
30
31
  readonly logger?: Logger;
31
32
  /** Optional retry scheduler for deterministic coordination and testing. */
32
33
  readonly delay?: PersistenceDelay;
34
+ readonly durableHistorySize?: number;
35
+ readonly persistBranches?: boolean;
33
36
  }
34
37
  /**
35
38
  * Coordinates one globally joinable persistence generation at a time.
@@ -66,6 +69,8 @@ export declare class PersistenceBuffer {
66
69
  get isFlushing(): boolean;
67
70
  /** @returns Number of accepted thought writes not yet acknowledged successful. */
68
71
  get pendingThoughtCount(): number;
72
+ hasThoughtIdentity(sessionId: SessionId, thoughtId: ThoughtId): boolean;
73
+ replaceDurableThoughtIdentities(sessions: readonly DurableIdentitySession[]): void;
69
74
  /**
70
75
  * Sets or clears the persistence error event emitter.
71
76
  *
@@ -79,6 +84,7 @@ export declare class PersistenceBuffer {
79
84
  * @param thought - Thought to persist.
80
85
  */
81
86
  bufferThought(sessionId: SessionId, thought: ThoughtData): void;
87
+ bufferBacktrack(sessionId: SessionId, thought: ThoughtData, targetThoughtId: ThoughtId): void;
82
88
  /**
83
89
  * Accepts the latest snapshot for one session-owned branch.
84
90
  *
@@ -1 +1 @@
1
- {"version":3,"file":"PersistenceBuffer.d.ts","sourceRoot":"","sources":["../../src/core/PersistenceBuffer.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAIH,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,oCAAoC,CAAC;AAC7E,OAAO,KAAK,EAAE,QAAQ,EAAE,SAAS,EAAE,MAAM,qBAAqB,CAAC;AAQ/D,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,+BAA+B,CAAC;AAE5D,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,0BAA0B,CAAC;AACxD,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,iBAAiB,CAAC;AAE5C,OAAO,EAAqB,KAAK,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AAClF,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAEhD,2DAA2D;AAC3D,MAAM,WAAW,uBAAuB;IACvC,IA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AAS,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC;IA+B3F;;;;OAIG;IACI,uBAAuB,CAAC,CAAC,EAAE,SAAS,EAAE,SAAS,EAAE,SAAS,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC;IA4ChG,qEAAqE;IAC9D,sBAAsB,CAAC,CAAC,EAAE,SAAS,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC;IA+BzE,OAAO,CAAC,YAAY;IA8BpB,OAAO,CAAC,uBAAuB;YAOjB,SAAS;IAiBvB,OAAO,CAAC,gBAAgB;YAsCV,uBAAuB;IAmBrC,OAAO,CAAC,kBAAkB;IAkB1B,OAAO,CAAC,uBAAuB;IAQ/B,OAAO,CAAC,sBAAsB;IAO9B,OAAO,CAAC,2BAA2B;IAYnC,OAAO,CAAC,eAAe;CAOvB"}
@@ -7,7 +7,7 @@ import { PersistenceWriter } from "./PersistenceWriter.js";
7
7
  class PersistenceBuffer {
8
8
  _bufferSize;
9
9
  _flushInterval;
10
- _queue = new PersistenceWorkQueue();
10
+ _queue;
11
11
  _writer;
12
12
  _eventEmitter;
13
13
  _logger;
@@ -22,6 +22,7 @@ class PersistenceBuffer {
22
22
  _globalResetOwners = 0;
23
23
  _globalQuarantined = false;
24
24
  constructor(config){
25
+ this._queue = new PersistenceWorkQueue(config.durableHistorySize, config.persistBranches);
25
26
  this._bufferSize = config.bufferSize;
26
27
  this._flushInterval = config.flushInterval;
27
28
  this._eventEmitter = config.eventEmitter ?? null;
@@ -41,6 +42,12 @@ class PersistenceBuffer {
41
42
  get pendingThoughtCount() {
42
43
  return this._queue.pendingThoughtCount;
43
44
  }
45
+ hasThoughtIdentity(sessionId, thoughtId) {
46
+ return this._queue.hasThoughtIdentity(sessionId, thoughtId);
47
+ }
48
+ replaceDurableThoughtIdentities(sessions) {
49
+ this._queue.replaceDurableThoughtIdentities(sessions);
50
+ }
44
51
  setEventEmitter(emitter) {
45
52
  this._eventEmitter = emitter;
46
53
  }
@@ -53,6 +60,11 @@ class PersistenceBuffer {
53
60
  this._queue.enqueueThought(sessionId, thought);
54
61
  if (this._queue.pendingThoughtCount >= this._bufferSize) this._triggerBackgroundDrain();
55
62
  }
63
+ bufferBacktrack(sessionId, thought, targetThoughtId) {
64
+ this._assertSessionAdmissionOpen(sessionId);
65
+ this._queue.enqueueBacktrack(sessionId, thought, targetThoughtId);
66
+ if (this._queue.pendingThoughtCount >= this._bufferSize) this._triggerBackgroundDrain();
67
+ }
56
68
  bufferBranch(sessionId, branchId, thoughts) {
57
69
  this._assertSessionAdmissionOpen(sessionId);
58
70
  this._queue.replaceBranch(sessionId, branchId, thoughts);