@iworkforces/tracelattice 2.3.5 → 2.4.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 (85) hide show
  1. package/README.md +18 -5
  2. package/dist/ServerConfig.d.ts +16 -0
  3. package/dist/ServerConfig.d.ts.map +1 -1
  4. package/dist/ServerConfig.js +11 -0
  5. package/dist/ServerConfig.js.map +1 -1
  6. package/dist/cli.js +239 -22
  7. package/dist/cli.js.map +1 -1
  8. package/dist/config/ConfigLoader.d.ts +2 -0
  9. package/dist/config/ConfigLoader.d.ts.map +1 -1
  10. package/dist/config/ConfigLoader.js +2 -0
  11. package/dist/config/ConfigLoader.js.map +1 -1
  12. package/dist/contracts/PersistenceBackend.d.ts +26 -0
  13. package/dist/contracts/PersistenceBackend.d.ts.map +1 -1
  14. package/dist/contracts/persistence-backlog.d.ts +21 -0
  15. package/dist/contracts/persistence-backlog.d.ts.map +1 -0
  16. package/dist/contracts/persistence-backlog.js +1 -0
  17. package/dist/core/HistoryManager.d.ts +15 -1
  18. package/dist/core/HistoryManager.d.ts.map +1 -1
  19. package/dist/core/HistoryManager.js +12 -2
  20. package/dist/core/HistoryManager.js.map +1 -1
  21. package/dist/core/IHistoryManager.d.ts +2 -0
  22. package/dist/core/IHistoryManager.d.ts.map +1 -1
  23. package/dist/core/PersistenceBuffer.d.ts +25 -0
  24. package/dist/core/PersistenceBuffer.d.ts.map +1 -1
  25. package/dist/core/PersistenceBuffer.js +27 -5
  26. package/dist/core/PersistenceBuffer.js.map +1 -1
  27. package/dist/core/PersistenceBufferErrors.d.ts +10 -0
  28. package/dist/core/PersistenceBufferErrors.d.ts.map +1 -1
  29. package/dist/core/PersistenceBufferErrors.js +13 -1
  30. package/dist/core/PersistenceBufferErrors.js.map +1 -1
  31. package/dist/core/PersistenceRestore.d.ts.map +1 -1
  32. package/dist/core/PersistenceRestore.js +25 -30
  33. package/dist/core/PersistenceRestore.js.map +1 -1
  34. package/dist/core/PersistenceWorkQueue.d.ts +9 -0
  35. package/dist/core/PersistenceWorkQueue.d.ts.map +1 -1
  36. package/dist/core/PersistenceWorkQueue.js +18 -0
  37. package/dist/core/PersistenceWorkQueue.js.map +1 -1
  38. package/dist/core/ThoughtEvaluator.d.ts +6 -0
  39. package/dist/core/ThoughtEvaluator.d.ts.map +1 -1
  40. package/dist/core/ThoughtEvaluator.js +15 -1
  41. package/dist/core/ThoughtEvaluator.js.map +1 -1
  42. package/dist/core/ThoughtProcessor.d.ts.map +1 -1
  43. package/dist/core/ThoughtProcessor.js +3 -10
  44. package/dist/core/ThoughtProcessor.js.map +1 -1
  45. package/dist/core/evaluator/VerificationLinks.d.ts +5 -0
  46. package/dist/core/evaluator/VerificationLinks.d.ts.map +1 -1
  47. package/dist/core/evaluator/VerificationLinks.js +47 -53
  48. package/dist/core/evaluator/VerificationLinks.js.map +1 -1
  49. package/dist/core/reasoning/ActiveEvidenceProjection.d.ts.map +1 -1
  50. package/dist/core/reasoning/ActiveEvidenceProjection.js +4 -3
  51. package/dist/core/reasoning/ActiveEvidenceProjection.js.map +1 -1
  52. package/dist/errors.d.ts +1 -0
  53. package/dist/errors.d.ts.map +1 -1
  54. package/dist/errors.js +2 -1
  55. package/dist/errors.js.map +1 -1
  56. package/dist/health/HealthChecker.d.ts +42 -1
  57. package/dist/health/HealthChecker.d.ts.map +1 -1
  58. package/dist/health/HealthChecker.js +60 -8
  59. package/dist/health/HealthChecker.js.map +1 -1
  60. package/dist/lib.d.ts +2 -2
  61. package/dist/lib.d.ts.map +1 -1
  62. package/dist/lib.js +1 -0
  63. package/dist/lib.js.map +1 -1
  64. package/dist/metrics/metrics.impl.js.map +1 -1
  65. package/dist/persistence/FilePersistence.d.ts +2 -1
  66. package/dist/persistence/FilePersistence.d.ts.map +1 -1
  67. package/dist/persistence/FilePersistence.js +6 -1
  68. package/dist/persistence/FilePersistence.js.map +1 -1
  69. package/dist/persistence/FileSnapshotV2.d.ts +2 -0
  70. package/dist/persistence/FileSnapshotV2.d.ts.map +1 -1
  71. package/dist/persistence/FileSnapshotV2.js +39 -1
  72. package/dist/persistence/FileSnapshotV2.js.map +1 -1
  73. package/dist/persistence/MemoryPersistence.d.ts +4 -1
  74. package/dist/persistence/MemoryPersistence.d.ts.map +1 -1
  75. package/dist/persistence/MemoryPersistence.js +30 -0
  76. package/dist/persistence/MemoryPersistence.js.map +1 -1
  77. package/dist/persistence/SqlitePersistence.d.ts +6 -1
  78. package/dist/persistence/SqlitePersistence.d.ts.map +1 -1
  79. package/dist/persistence/SqlitePersistence.js +31 -4
  80. package/dist/persistence/SqlitePersistence.js.map +1 -1
  81. package/dist/transport/StreamableHttpTransport.d.ts +12 -0
  82. package/dist/transport/StreamableHttpTransport.d.ts.map +1 -1
  83. package/dist/transport/StreamableHttpTransport.js +19 -5
  84. package/dist/transport/StreamableHttpTransport.js.map +1 -1
  85. package/package.json +20 -20
@@ -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, SessionExpiredError } 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 readonly _expiredSessions = new Map<SessionId, { readonly owner: string | undefined }>();\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\tassertReplacementCapacity: (sessionId, owner) => {\n\t\t\t\tif (!this._sessions.has(sessionId)) this._planCapacityForSession(owner);\n\t\t\t},\n\t\t\tadmitReplacement: (sessionId, owner) => {\n\t\t\t\tif (!this._sessions.has(sessionId)) this._makeCapacityForSession(owner);\n\t\t\t},\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._authorizeExistingSession(sessionId, this._getCurrentOwner());\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): bypasses ownership checks without setting\n\t * owner; expired sessions still reject access.\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\tthis._authorizeExistingSession(key, owner);\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\tthis._authorizeExistingSession(key, owner);\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 _planCapacityForSession(owner: string | undefined): readonly SessionId[] {\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\treturn victims;\n\t}\n\n\tprivate _makeCapacityForSession(owner: string | undefined): void {\n\t\tconst victims = this._planCapacityForSession(owner);\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\tconst session = this._sessions.get(sessionId);\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\tif (session !== undefined) this._expiredSessions.set(sessionId, { owner: session.owner });\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 preservedOwner = this._authorizeSessionReset(sessionId, owner);\n\t\tif (this._expiredSessions.has(sessionId)) throw new SessionExpiredError(sessionId);\n\t\treturn preservedOwner;\n\t}\n\n\tprivate _authorizeSessionReset(\n\t\tsessionId: SessionId,\n\t\towner: string | undefined\n\t): string | undefined {\n\t\tconst marker = this._expiredSessions.get(sessionId);\n\t\tconst sessionOwner = marker === undefined ? this._sessions.get(sessionId)?.owner : marker.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\tpublic assertSessionResetAuthorized(sessionId: string): void {\n\t\tthis._authorizeSessionReset(asSessionId(sessionId), this._getCurrentOwner());\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._authorizeExistingSession(sessionId, this._getCurrentOwner());\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\tconst sessionId = asSessionId(thought.session_id);\n\t\tthis._authorizeExistingSession(sessionId, this._getCurrentOwner());\n\t\tif (thought.id === undefined) return;\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\tthis._authorizeExistingSession(asSessionId(sessionId), this._getCurrentOwner());\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.assertSessionResetAuthorized(canonicalSessionId);\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._authorizeSessionReset(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\tthis._expiredSessions.delete(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\tthis._expiredSessions.clear();\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\tthis._expiredSessions.clear();\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","preservedOwner","SessionExpiredError","marker","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","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;IAC3C,mBAAmB,IAAIA,MAAyD;IACzF,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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AAC,eAAe,CAAC,QAAQ;QAC7B,IAAI,CAAC,UAAU,EAAE;QACjB,IAAI,CAAC,aAAa,EAAE;QACpB,IAAI,CAAC,uBAAuB;QAC5B,IAAI,CAAC,gBAAgB,CAAC,KAAK;IAC5B;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 type { PersistenceBacklogView } from '../contracts/persistence-backlog.js';\nimport {\n\tDehydrationPolicy,\n\ttype DehydrationOptions,\n\ttype HydratedEntry,\n} from './compression/DehydrationPolicy.js';\nimport type { Summary } from './compression/Summary.js';\nimport { SessionAccessDeniedError, SessionExpiredError } 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\t/** Per-session limit on unacknowledged thought writes, terminal failures included. @default 10000 */\n\tpersistenceMaxPendingThoughtsPerSession?: 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 readonly _expiredSessions = new Map<SessionId, { readonly owner: string | undefined }>();\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\tmaxPendingThoughtsPerSession: config.persistenceMaxPendingThoughtsPerSession ?? 10_000,\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\tassertReplacementCapacity: (sessionId, owner) => {\n\t\t\t\tif (!this._sessions.has(sessionId)) this._planCapacityForSession(owner);\n\t\t\t},\n\t\t\tadmitReplacement: (sessionId, owner) => {\n\t\t\t\tif (!this._sessions.has(sessionId)) this._makeCapacityForSession(owner);\n\t\t\t},\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._authorizeExistingSession(sessionId, this._getCurrentOwner());\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): bypasses ownership checks without setting\n\t * owner; expired sessions still reject access.\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\tthis._authorizeExistingSession(key, owner);\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\tthis._authorizeExistingSession(key, owner);\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 _planCapacityForSession(owner: string | undefined): readonly SessionId[] {\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\treturn victims;\n\t}\n\n\tprivate _makeCapacityForSession(owner: string | undefined): void {\n\t\tconst victims = this._planCapacityForSession(owner);\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\tconst session = this._sessions.get(sessionId);\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\tif (session !== undefined) this._expiredSessions.set(sessionId, { owner: session.owner });\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 preservedOwner = this._authorizeSessionReset(sessionId, owner);\n\t\tif (this._expiredSessions.has(sessionId)) throw new SessionExpiredError(sessionId);\n\t\treturn preservedOwner;\n\t}\n\n\tprivate _authorizeSessionReset(\n\t\tsessionId: SessionId,\n\t\towner: string | undefined\n\t): string | undefined {\n\t\tconst marker = this._expiredSessions.get(sessionId);\n\t\tconst sessionOwner = marker === undefined ? this._sessions.get(sessionId)?.owner : marker.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\tpublic assertSessionResetAuthorized(sessionId: string): void {\n\t\tthis._authorizeSessionReset(asSessionId(sessionId), this._getCurrentOwner());\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._authorizeExistingSession(sessionId, this._getCurrentOwner());\n\t\tthis._lifecycle.runMutation(sessionId, () =>\n\t\t\tthis._addThoughtWithinOperation(sessionId, thought, context)\n\t\t);\n\t}\n\n\t/**\n\t * Pre-mutation admission guard: authorizes, rejects a duplicate thought id, then rejects when\n\t * the session already holds its limit of unacknowledged persistence writes.\n\t *\n\t * @throws {ValidationError} If the thought id already exists in the session.\n\t * @throws {PersistenceBacklogFullError} If the session persistence backlog is at its limit.\n\t */\n\tpublic assertThoughtIdentityAvailable(thought: ThoughtData): void {\n\t\tconst sessionId = asSessionId(thought.session_id);\n\t\tthis._authorizeExistingSession(sessionId, this._getCurrentOwner());\n\t\tif (\n\t\t\tthought.id !== undefined &&\n\t\t\t(this._referenceIndex.has(sessionId, thought.id) ||\n\t\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\tthis._persistenceBuffer?.assertThoughtBacklogAvailable(sessionId);\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\tpublic assertSessionAccessible(sessionId: string): void {\n\t\tthis._authorizeExistingSession(asSessionId(sessionId), this._getCurrentOwner());\n\t}\n\n\tpublic getVerificationTargets(sessionId: string): ReadonlyMap<ThoughtId, ThoughtId> {\n\t\treturn this._getSession(sessionId, this._getCurrentOwner()).verificationTargets;\n\t}\n\n\t/** @throws {ValidationError} If branchId is empty or already exists. */\n\tpublic registerBranch(sessionId: string, branchId: BranchId): void {\n\t\tthis._authorizeExistingSession(asSessionId(sessionId), this._getCurrentOwner());\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.assertSessionResetAuthorized(canonicalSessionId);\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._authorizeSessionReset(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\tthis._expiredSessions.delete(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\tthis._expiredSessions.clear();\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\tthis._expiredSessions.clear();\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\t/** Persistence backlog counts for readiness probes; `null` when persistence is disabled. */\n\tpublic getPersistenceBacklogView(): PersistenceBacklogView | null {\n\t\treturn this._persistenceBuffer?.getBacklogView() ?? null;\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","preservedOwner","SessionExpiredError","marker","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","restored","reconstructVerificationTargets","index","retainedStart","retainedBranches","stagePersistenceRestore","sessions","referenceIndex","retainedThoughtIds","retainedBranchIds","edge","summary","emitter","TypeError"],"mappings":";;;;;;;;;;;;;;;;AAsDO,MAAMA,4BAA4B;AA8DlC,MAAMC;IACZ,OAAwB,iBAAiB,QAAe;IACxD,OAAwB,eAAe,IAAI;IACnC,YAA0C,IAAIC,MAAM;IAC3C,mBAAmB,IAAIA,MAAyD;IACzF,gBAAwB;IACxB,aAAqB;IACrB,eAAuB;IACvB,QAAgB;IAChB,aAAwC;IACxC,oBAA6B;IAC7B,SAAoB;IAEpB,WAAwB;IACxB,cAA8B;IAC9B,UAAmB;IAEnB,cAA8C;IAErC,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A;QACrB,IAAI,CAAC,kBAAkB,EAAE,gBAAgBA;IAC1C;IASO,kBAAkBpF,KAA0B,EAAQ;QAC1D,IAAI,AAAwB,SAAxB,IAAI,CAAC,cAAc,EACtB,MAAM,IAAIqF,UAAU;QAErB,IAAI,CAAC,cAAc,GAAGrF;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;QAC5B,IAAI,CAAC,gBAAgB,CAAC,KAAK;IAC5B;IAGO,uBAA+B;QACrC,OAAO,IAAI,CAAC,kBAAkB,EAAE,uBAAuB;IACxD;IAGO,4BAA2D;QACjE,OAAO,IAAI,CAAC,kBAAkB,EAAE,oBAAoB;IACrD;AACD"}
@@ -111,6 +111,8 @@ export interface IHistoryManager {
111
111
  resetAllWithinExclusive(clearAuxiliaryState?: () => void): Promise<void>;
112
112
  /** Returns a non-mutating session snapshot without creating or binding state. */
113
113
  inspectSession(sessionId: string): HistorySessionSnapshot;
114
+ assertSessionAccessible(sessionId: string): void;
115
+ getVerificationTargets(sessionId: string): ReadonlyMap<ThoughtId, ThoughtId>;
114
116
  /** Checks reset authorization without creating or claiming state; permits expired scopes. */
115
117
  assertSessionResetAuthorized(sessionId: string): void;
116
118
  /** Returns the currently materialized session identifiers without binding ownership. */
@@ -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,OAAO,KAAK,EAAE,0BAA0B,EAAE,MAAM,4BAA4B,CAAC;AAC7E,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAEhD,+EAA+E;AAC/E,MAAM,WAAW,sBAAsB;IACtC,QAAQ,CAAC,OAAO,EAAE,SAAS,WAAW,EAAE,CAAC;IACzC,QAAQ,CAAC,QAAQ,EAAE,QAAQ,CAAC,MAAM,CAAC,QAAQ,EAAE,SAAS,WAAW,EAAE,CAAC,CAAC,CAAC;IACtE,QAAQ,CAAC,mBAAmB,EAAE,WAAW,CAAC,SAAS,EAAE,SAAS,CAAC,CAAC;IAChE,QAAQ,CAAC,SAAS,EAAE,SAAS,QAAQ,EAAE,CAAC;IACxC,QAAQ,CAAC,iBAAiB,EAAE,SAAS,MAAM,EAAE,GAAG,SAAS,CAAC;IAC1D,QAAQ,CAAC,eAAe,EAAE,SAAS,MAAM,EAAE,GAAG,SAAS,CAAC;CACxD;AAED,MAAM,WAAW,yBAAyB;IACzC,QAAQ,CAAC,2BAA2B,CAAC,EAAE,SAAS,CAAC;IACjD,QAAQ,CAAC,gBAAgB,CAAC,EAAE,SAAS,CAAC;IACtC,QAAQ,CAAC,mBAAmB,CAAC,EAAE,SAAS,CAAC;IACzC,QAAQ,CAAC,yBAAyB,CAAC,EAAE,SAAS,SAAS,EAAE,CAAC;IAC1D,QAAQ,CAAC,mBAAmB,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D;;;;;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"}
@@ -5,6 +5,7 @@
5
5
  */
6
6
  import type { PersistenceBackend } from '../contracts/PersistenceBackend.js';
7
7
  import type { BranchId, SessionId, ThoughtId } from '../contracts/ids.js';
8
+ import type { PersistenceBacklogView } from '../contracts/persistence-backlog.js';
8
9
  import type { Logger } from '../logger/StructuredLogger.js';
9
10
  import type { Summary } from './compression/Summary.js';
10
11
  import type { DurableIdentitySession } from './DurableThoughtIdentityIndex.js';
@@ -33,6 +34,12 @@ export interface PersistenceBufferConfig {
33
34
  readonly delay?: PersistenceDelay;
34
35
  readonly durableHistorySize?: number;
35
36
  readonly persistBranches?: boolean;
37
+ /**
38
+ * Per-session limit on unacknowledged thought and backtrack writes, terminal failures
39
+ * included. Enforced by {@link PersistenceBuffer.assertThoughtBacklogAvailable}.
40
+ * @default 10000
41
+ */
42
+ readonly maxPendingThoughtsPerSession?: number;
36
43
  }
37
44
  /**
38
45
  * Coordinates one globally joinable persistence generation at a time.
@@ -43,6 +50,7 @@ export interface PersistenceBufferConfig {
43
50
  export declare class PersistenceBuffer {
44
51
  private readonly _bufferSize;
45
52
  private readonly _flushInterval;
53
+ private readonly _maxPendingThoughtsPerSession;
46
54
  private readonly _queue;
47
55
  private readonly _writer;
48
56
  private _eventEmitter;
@@ -80,6 +88,9 @@ export declare class PersistenceBuffer {
80
88
  /**
81
89
  * Accepts a thought with authoritative session attribution.
82
90
  *
91
+ * Never rejects on backlog: callers enforce the per-session limit before they mutate state
92
+ * with {@link assertThoughtBacklogAvailable}.
93
+ *
83
94
  * @param sessionId - Session that owns the accepted thought.
84
95
  * @param thought - Thought to persist.
85
96
  */
@@ -114,6 +125,18 @@ export declare class PersistenceBuffer {
114
125
  bufferSummaries(sessionId: SessionId, summaries: readonly Summary[]): void;
115
126
  /** Rejects synchronously when lifecycle coordination has closed persistence admission. */
116
127
  assertSessionAdmissionOpen(sessionId: SessionId): void;
128
+ /**
129
+ * Rejects synchronously when the session already holds its limit of unacknowledged thought
130
+ * and backtrack writes, terminal failures included.
131
+ *
132
+ * At the limit this starts or joins an explicit drain without awaiting it, so retained
133
+ * failures are retried and a later call succeeds once the backend recovers. Call it before
134
+ * any session state changes: {@link bufferThought} and {@link bufferBacktrack} never reject.
135
+ *
136
+ * @param sessionId - Session whose thought backlog is checked.
137
+ * @throws {@link PersistenceBacklogFullError} when the session is at its limit.
138
+ */
139
+ assertThoughtBacklogAvailable(sessionId: SessionId): void;
117
140
  /** Starts the periodic background-drain timer without keeping the process alive. */
118
141
  startFlushTimer(): void;
119
142
  /** Stops the periodic background-drain timer. */
@@ -179,6 +202,8 @@ export declare class PersistenceBuffer {
179
202
  withSessionResetBarrier<T>(sessionId: SessionId, operation: () => Promise<T>): Promise<T>;
180
203
  /** Runs a trusted global reset behind a global admission barrier. */
181
204
  withGlobalResetBarrier<T>(operation: () => Promise<T>): Promise<T>;
205
+ /** @returns A frozen point-in-time view of quarantine and unflushed work for readiness probes. */
206
+ getBacklogView(): PersistenceBacklogView;
182
207
  private _joinOrStart;
183
208
  private _triggerBackgroundDrain;
184
209
  private _runDrain;
@@ -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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AAC,CAAC;IA4ChG,qEAAqE;IAC9D,sBAAsB,CAAC,CAAC,EAAE,SAAS,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC;IA+BzE,kGAAkG;IAC3F,cAAc,IAAI,sBAAsB;IAa/C,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"}
@@ -1,12 +1,14 @@
1
1
  import { AsyncLocalStorage } from "node:async_hooks";
2
- import { PersistenceDrainError, PersistenceSessionAdmissionClosedError, PersistenceSessionBarrierReentrancyError } from "./PersistenceBufferErrors.js";
2
+ import { PersistenceBacklogFullError, PersistenceDrainError, PersistenceSessionAdmissionClosedError, PersistenceSessionBarrierReentrancyError } from "./PersistenceBufferErrors.js";
3
3
  import { NullLogger } from "../logger/NullLogger.js";
4
4
  import { assertNever } from "../utils.js";
5
5
  import { PersistenceWorkQueue } from "./PersistenceWorkQueue.js";
6
6
  import { PersistenceWriter } from "./PersistenceWriter.js";
7
+ const DEFAULT_MAX_PENDING_THOUGHTS_PER_SESSION = 10000;
7
8
  class PersistenceBuffer {
8
9
  _bufferSize;
9
10
  _flushInterval;
11
+ _maxPendingThoughtsPerSession;
10
12
  _queue;
11
13
  _writer;
12
14
  _eventEmitter;
@@ -25,6 +27,7 @@ class PersistenceBuffer {
25
27
  this._queue = new PersistenceWorkQueue(config.durableHistorySize, config.persistBranches);
26
28
  this._bufferSize = config.bufferSize;
27
29
  this._flushInterval = config.flushInterval;
30
+ this._maxPendingThoughtsPerSession = config.maxPendingThoughtsPerSession ?? DEFAULT_MAX_PENDING_THOUGHTS_PER_SESSION;
28
31
  this._eventEmitter = config.eventEmitter ?? null;
29
32
  this._logger = config.logger ?? new NullLogger();
30
33
  this._writer = new PersistenceWriter({
@@ -53,10 +56,6 @@ class PersistenceBuffer {
53
56
  }
54
57
  bufferThought(sessionId, thought) {
55
58
  this._assertSessionAdmissionOpen(sessionId);
56
- if (this._queue.pendingThoughtCount >= this._bufferSize && this.isFlushing) this._logger.info('Write buffer full and flush in progress, applying backpressure', {
57
- bufferSize: this._queue.pendingThoughtCount,
58
- maxSize: this._bufferSize
59
- });
60
59
  this._queue.enqueueThought(sessionId, thought);
61
60
  if (this._queue.pendingThoughtCount >= this._bufferSize) this._triggerBackgroundDrain();
62
61
  }
@@ -84,6 +83,17 @@ class PersistenceBuffer {
84
83
  assertSessionAdmissionOpen(sessionId) {
85
84
  this._assertSessionAdmissionOpen(sessionId);
86
85
  }
86
+ assertThoughtBacklogAvailable(sessionId) {
87
+ const pending = this._queue.pendingThoughtCountForSession(sessionId);
88
+ if (pending < this._maxPendingThoughtsPerSession) return;
89
+ this._joinOrStart('explicit').promise.catch(()=>void 0);
90
+ this._logger.warn('Persistence backlog full, rejecting thought', {
91
+ sessionId,
92
+ pending,
93
+ limit: this._maxPendingThoughtsPerSession
94
+ });
95
+ throw new PersistenceBacklogFullError(sessionId, pending, this._maxPendingThoughtsPerSession);
96
+ }
87
97
  startFlushTimer() {
88
98
  if (null !== this._flushTimer) return;
89
99
  this._flushTimer = setInterval(()=>this._triggerBackgroundDrain(), this._flushInterval);
@@ -231,6 +241,18 @@ class PersistenceBuffer {
231
241
  this._globalResetTail = result.then(()=>void 0, ()=>void 0);
232
242
  return result;
233
243
  }
244
+ getBacklogView() {
245
+ const quarantinedSessions = new Set([
246
+ ...this._quarantinedSessions,
247
+ ...this._evictionQuarantinedSessions
248
+ ]);
249
+ return Object.freeze({
250
+ globalQuarantined: this._globalQuarantined,
251
+ quarantinedSessionCount: quarantinedSessions.size,
252
+ retainedFailureCount: this._queue.currentFailures().length,
253
+ pendingThoughtCount: this._queue.pendingThoughtCount
254
+ });
255
+ }
234
256
  _joinOrStart(mode) {
235
257
  const active = this._activeDrain;
236
258
  if (null !== active) {