@iworkforces/tracelattice 2.2.0 → 2.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/README.md +31 -8
  2. package/dist/ServerConfig.d.ts +9 -5
  3. package/dist/ServerConfig.d.ts.map +1 -1
  4. package/dist/ServerConfig.js.map +1 -1
  5. package/dist/cli.js +6 -5
  6. package/dist/config/ConfigLoader.d.ts +20 -7
  7. package/dist/config/ConfigLoader.d.ts.map +1 -1
  8. package/dist/config/ConfigLoader.js.map +1 -1
  9. package/dist/core/HistoryManager.d.ts +6 -1
  10. package/dist/core/HistoryManager.d.ts.map +1 -1
  11. package/dist/core/HistoryManager.js +38 -6
  12. package/dist/core/HistoryManager.js.map +1 -1
  13. package/dist/core/IHistoryManager.d.ts +2 -0
  14. package/dist/core/IHistoryManager.d.ts.map +1 -1
  15. package/dist/core/SessionErrors.d.ts +4 -0
  16. package/dist/core/SessionErrors.d.ts.map +1 -1
  17. package/dist/core/SessionErrors.js +9 -1
  18. package/dist/core/SessionErrors.js.map +1 -1
  19. package/dist/core/SessionResetCoordinator.d.ts +4 -0
  20. package/dist/core/SessionResetCoordinator.d.ts.map +1 -1
  21. package/dist/core/SessionResetCoordinator.js +6 -0
  22. package/dist/core/SessionResetCoordinator.js.map +1 -1
  23. package/dist/core/ThoughtProcessor.d.ts.map +1 -1
  24. package/dist/core/ThoughtProcessor.js +5 -4
  25. package/dist/core/ThoughtProcessor.js.map +1 -1
  26. package/dist/errors.d.ts +1 -0
  27. package/dist/errors.d.ts.map +1 -1
  28. package/dist/errors.js +1 -0
  29. package/dist/errors.js.map +1 -1
  30. package/dist/metrics/metrics.impl.d.ts.map +1 -1
  31. package/dist/metrics/metrics.impl.js +19 -7
  32. package/dist/metrics/metrics.impl.js.map +1 -1
  33. package/dist/persistence/FileSnapshotV2.d.ts +6 -6
  34. package/dist/schema.d.ts +3 -3
  35. package/dist/schema.d.ts.map +1 -1
  36. package/dist/schema.js +5 -5
  37. package/dist/schema.js.map +1 -1
  38. package/package.json +13 -13
@@ -71,6 +71,7 @@ export declare class HistoryManager implements IHistoryManager {
71
71
  private static readonly SESSION_TTL_MS;
72
72
  private static readonly MAX_SESSIONS;
73
73
  private _sessions;
74
+ private readonly _expiredSessions;
74
75
  private _maxHistorySize;
75
76
  private _maxBranches;
76
77
  private _maxBranchSize;
@@ -121,7 +122,8 @@ export declare class HistoryManager implements IHistoryManager {
121
122
  * Gets or creates session state; updates lastAccessedAt.
122
123
  *
123
124
  * Ownership semantics:
124
- * - `owner === undefined` (stdio path): never rejects, never sets owner.
125
+ * - `owner === undefined` (stdio path): bypasses ownership checks without setting
126
+ * owner; expired sessions still reject access.
125
127
  * - `owner !== undefined`: if session has a different owner, throws
126
128
  * `SessionAccessDeniedError`. If session was created without an owner
127
129
  * (e.g. by stdio), the owner is set on first owner-aware access.
@@ -129,6 +131,7 @@ export declare class HistoryManager implements IHistoryManager {
129
131
  private _getSession;
130
132
  private _getSessionWithinOperation;
131
133
  private _assertSessionOwner;
134
+ private _planCapacityForSession;
132
135
  private _makeCapacityForSession;
133
136
  private _isCapacityEvictionEligible;
134
137
  private _isTtlEvictionEligible;
@@ -138,6 +141,8 @@ export declare class HistoryManager implements IHistoryManager {
138
141
  private _removeLiveSession;
139
142
  private _createSessionState;
140
143
  private _authorizeExistingSession;
144
+ private _authorizeSessionReset;
145
+ assertSessionResetAuthorized(sessionId: string): void;
141
146
  private _assertOwnerlessResetAll;
142
147
  /**
143
148
  * Adds a thought to the history. Routes per-session, applies retraction for backtrack,
@@ -1 +1 @@
1
- {"version":3,"file":"HistoryManager.d.ts","sourceRoot":"","sources":["../../src/core/HistoryManager.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,OAAO,KAAK,EAAE,UAAU,EAAE,QAAQ,EAAE,YAAY,EAAE,MAAM,4BAA4B,CAAC;AACrF,OAAO,EAAe,KAAK,QAAQ,EAAE,KAAK,SAA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,QAAQ,IAAI,OAAO,CAAC,IAAI,CAAC;IAQhC,4EAA4E;IAC/D,uBAAuB,IAAI,OAAO,CAAC,IAAI,CAAC;IAMrD,sFAAsF;IAC/E,2BAA2B,IAAI,IAAI;IAY1C,kFAAkF;IAC3E,oBAAoB,IAAI,MAAM;CAGrC"}
@@ -2,7 +2,7 @@ import { asSessionId } from "../contracts/ids.js";
2
2
  import { ERROR_CODES, InvalidBacktrackError, MaxSessionsReachedError, SequentialThinkingError, ValidationError } from "../errors.js";
3
3
  import { NullLogger } from "../logger/NullLogger.js";
4
4
  import { DehydrationPolicy } from "./compression/DehydrationPolicy.js";
5
- import { SessionAccessDeniedError } from "./SessionErrors.js";
5
+ import { SessionAccessDeniedError, SessionExpiredError } from "./SessionErrors.js";
6
6
  import { EdgeEmitter } from "./graph/EdgeEmitter.js";
7
7
  import { PersistenceBuffer } from "./PersistenceBuffer.js";
8
8
  import { SessionManager } from "./SessionManager.js";
@@ -19,6 +19,7 @@ class HistoryManager {
19
19
  static SESSION_TTL_MS = 1800000;
20
20
  static MAX_SESSIONS = 100;
21
21
  _sessions = new Map();
22
+ _expiredSessions = new Map();
22
23
  _maxHistorySize;
23
24
  _maxBranches;
24
25
  _maxBranchSize;
@@ -100,6 +101,12 @@ class HistoryManager {
100
101
  summaryStore: this._summaryStore,
101
102
  sessions: this._sessions,
102
103
  createSessionState: (owner)=>this._createSessionState(owner),
104
+ assertReplacementCapacity: (sessionId, owner)=>{
105
+ if (!this._sessions.has(sessionId)) this._planCapacityForSession(owner);
106
+ },
107
+ admitReplacement: (sessionId, owner)=>{
108
+ if (!this._sessions.has(sessionId)) this._makeCapacityForSession(owner);
109
+ },
103
110
  logger: this._logger
104
111
  });
105
112
  this._sessionManager.startCleanupTimer(this._sessions, (sessionId)=>this._isTtlEvictionEligible(sessionId), (sessionIds)=>this._evictSessions(sessionIds));
@@ -124,6 +131,7 @@ class HistoryManager {
124
131
  return this._persistenceBuffer?.drainSession(sessionId) ?? Promise.resolve();
125
132
  }
126
133
  bufferSummaries(sessionId, summaries) {
134
+ this._authorizeExistingSession(sessionId, this._getCurrentOwner());
127
135
  this._lifecycle.runMutation(sessionId, ()=>{
128
136
  this._persistenceBuffer?.bufferSummaries(sessionId, summaries);
129
137
  const session = this._sessions.get(sessionId);
@@ -141,6 +149,7 @@ class HistoryManager {
141
149
  }
142
150
  _getSession(sessionId, owner) {
143
151
  const key = asSessionId(sessionId);
152
+ this._authorizeExistingSession(key, owner);
144
153
  const existing = this._sessions.get(key);
145
154
  if (void 0 !== existing) {
146
155
  this._assertSessionOwner(key, existing, owner);
@@ -150,6 +159,7 @@ class HistoryManager {
150
159
  return this._lifecycle.runMutation(key, ()=>this._getSessionWithinOperation(key, owner));
151
160
  }
152
161
  _getSessionWithinOperation(key, owner) {
162
+ this._authorizeExistingSession(key, owner);
153
163
  let session = this._sessions.get(key);
154
164
  if (session) this._assertSessionOwner(key, session, owner);
155
165
  else {
@@ -166,9 +176,13 @@ class HistoryManager {
166
176
  if (void 0 !== session.owner && session.owner !== owner) throw new SessionAccessDeniedError(sessionId, session.owner, owner);
167
177
  if (void 0 === session.owner) session.owner = owner;
168
178
  }
169
- _makeCapacityForSession(owner) {
179
+ _planCapacityForSession(owner) {
170
180
  const victims = this._sessionManager.planProspectiveAdmission(this._sessions, owner, (sessionId)=>this._isCapacityEvictionEligible(sessionId));
171
181
  if (void 0 === victims) throw new MaxSessionsReachedError(HistoryManager.MAX_SESSIONS);
182
+ return victims;
183
+ }
184
+ _makeCapacityForSession(owner) {
185
+ const victims = this._planCapacityForSession(owner);
172
186
  if (0 === victims.length) return;
173
187
  const evicted = this._lifecycle.tryEvictIdleSessions(victims, (sessionIds)=>{
174
188
  if (sessionIds.some((sessionId)=>!this._isPersistenceQuiescent(sessionId))) throw new MaxSessionsReachedError(HistoryManager.MAX_SESSIONS);
@@ -204,12 +218,16 @@ class HistoryManager {
204
218
  });
205
219
  }
206
220
  _removeLiveSession(sessionId) {
221
+ const session = this._sessions.get(sessionId);
207
222
  this._clearSessionAuxiliaryState?.(sessionId);
208
223
  this._edgeStore?.clearSession(sessionId);
209
224
  this._summaryStore?.clearSession(sessionId);
210
225
  this._referenceIndex.clearSession(sessionId);
211
226
  this._sessions.delete(sessionId);
212
227
  this._persistenceBuffer?.forgetQuiescentSession(sessionId);
228
+ if (void 0 !== session) this._expiredSessions.set(sessionId, {
229
+ owner: session.owner
230
+ });
213
231
  }
214
232
  _createSessionState(owner, provenance) {
215
233
  return {
@@ -226,11 +244,20 @@ class HistoryManager {
226
244
  };
227
245
  }
228
246
  _authorizeExistingSession(sessionId, owner) {
229
- const sessionOwner = this._sessions.get(sessionId)?.owner;
247
+ const preservedOwner = this._authorizeSessionReset(sessionId, owner);
248
+ if (this._expiredSessions.has(sessionId)) throw new SessionExpiredError(sessionId);
249
+ return preservedOwner;
250
+ }
251
+ _authorizeSessionReset(sessionId, owner) {
252
+ const marker = this._expiredSessions.get(sessionId);
253
+ const sessionOwner = void 0 === marker ? this._sessions.get(sessionId)?.owner : marker.owner;
230
254
  if (void 0 !== owner && this._sessions.get(sessionId)?.provenance === 'restored') throw new SessionAccessDeniedError(sessionId, 'unavailable', owner);
231
255
  if (void 0 !== owner && void 0 !== sessionOwner && sessionOwner !== owner) throw new SessionAccessDeniedError(sessionId, sessionOwner, owner);
232
256
  return sessionOwner ?? owner;
233
257
  }
258
+ assertSessionResetAuthorized(sessionId) {
259
+ this._authorizeSessionReset(asSessionId(sessionId), this._getCurrentOwner());
260
+ }
234
261
  _assertOwnerlessResetAll() {
235
262
  const owner = this._getCurrentOwner();
236
263
  if (void 0 === owner) return;
@@ -240,12 +267,13 @@ class HistoryManager {
240
267
  }
241
268
  addThought(thought, context) {
242
269
  const sessionId = asSessionId(thought.session_id);
270
+ this._authorizeExistingSession(sessionId, this._getCurrentOwner());
243
271
  this._lifecycle.runMutation(sessionId, ()=>this._addThoughtWithinOperation(sessionId, thought, context));
244
272
  }
245
273
  assertThoughtIdentityAvailable(thought) {
246
- if (void 0 === thought.id) return;
247
274
  const sessionId = asSessionId(thought.session_id);
248
275
  this._authorizeExistingSession(sessionId, this._getCurrentOwner());
276
+ if (void 0 === thought.id) return;
249
277
  if (this._referenceIndex.has(sessionId, thought.id) || this._persistenceBuffer?.hasThoughtIdentity(sessionId, thought.id) === true) throw new ValidationError('id', `Thought id already exists in session: ${thought.id}`);
250
278
  }
251
279
  _addThoughtWithinOperation(sessionId, thought, context) {
@@ -438,6 +466,7 @@ class HistoryManager {
438
466
  };
439
467
  }
440
468
  registerBranch(sessionId, branchId) {
469
+ this._authorizeExistingSession(asSessionId(sessionId), this._getCurrentOwner());
441
470
  if ('string' != typeof branchId || 0 === branchId.length) throw new ValidationError('branch_id', 'branch_id must be a non-empty string');
442
471
  const canonicalSessionId = asSessionId(sessionId);
443
472
  this._lifecycle.runMutation(canonicalSessionId, ()=>{
@@ -471,7 +500,7 @@ class HistoryManager {
471
500
  }
472
501
  async resetSession(sessionId, clearAuxiliaryState) {
473
502
  const canonicalSessionId = asSessionId(sessionId);
474
- this._authorizeExistingSession(canonicalSessionId, this._getCurrentOwner());
503
+ this.assertSessionResetAuthorized(canonicalSessionId);
475
504
  await this._lifecycle.withSessionReset(canonicalSessionId, async ()=>{
476
505
  const reset = async ()=>await this.resetSessionWithinExclusive(canonicalSessionId, clearAuxiliaryState);
477
506
  if (void 0 === this._sessionLock) return await reset();
@@ -479,9 +508,10 @@ class HistoryManager {
479
508
  });
480
509
  }
481
510
  async resetSessionWithinExclusive(sessionId, clearAuxiliaryState) {
482
- const preservedOwner = this._authorizeExistingSession(sessionId, this._getCurrentOwner());
511
+ const preservedOwner = this._authorizeSessionReset(sessionId, this._getCurrentOwner());
483
512
  await this._resetCoordinator.resetSession(sessionId, preservedOwner, clearAuxiliaryState ?? (void 0 === this._clearSessionAuxiliaryState ? void 0 : ()=>this._clearSessionAuxiliaryState?.(sessionId)));
484
513
  this._referenceIndex.clearSession(sessionId);
514
+ this._expiredSessions.delete(sessionId);
485
515
  }
486
516
  async resetAll(clearAuxiliaryState) {
487
517
  this._assertOwnerlessResetAll();
@@ -491,6 +521,7 @@ class HistoryManager {
491
521
  this._assertOwnerlessResetAll();
492
522
  await this._resetCoordinator.resetAll(clearAuxiliaryState ?? this._clearAllAuxiliaryState);
493
523
  this._referenceIndex.clearAll();
524
+ this._expiredSessions.clear();
494
525
  }
495
526
  getSessionIds() {
496
527
  return Array.from(this._sessions.keys());
@@ -596,6 +627,7 @@ class HistoryManager {
596
627
  this._edgeStore?.clearAll();
597
628
  this._summaryStore?.clearAll();
598
629
  this._clearAllAuxiliaryState?.();
630
+ this._expiredSessions.clear();
599
631
  }
600
632
  getWriteBufferLength() {
601
633
  return this._persistenceBuffer?.pendingThoughtCount ?? 0;
@@ -1 +1 @@
1
- {"version":3,"file":"core/HistoryManager.js","sources":["../../src/core/HistoryManager.ts"],"sourcesContent":["/**\n * History and branch management for sequential thinking.\n *\n * This module provides the `HistoryManager` class which manages thought history,\n * branching, and optional persistence with per-session state isolation.\n *\n * Internally delegates to three focused collaborators:\n * - `EdgeEmitter` — DAG edge emission\n * - `PersistenceBuffer` — buffered persistence + retry/backoff\n * - `SessionManager` — session lifecycle (TTL/LRU eviction)\n *\n * @module HistoryManager\n */\n\nimport type { IEdgeStore, IMetrics, ISessionLock } from '../contracts/interfaces.js';\nimport { asSessionId, type BranchId, type SessionId, type ThoughtId } from '../contracts/ids.js';\nimport type { ISummaryStore } from '../contracts/summary.js';\nimport {\n\tERROR_CODES,\n\tInvalidBacktrackError,\n\tMaxSessionsReachedError,\n\tSequentialThinkingError,\n\tValidationError,\n} from '../errors.js';\nimport { NullLogger } from '../logger/NullLogger.js';\nimport type { Logger } from '../logger/StructuredLogger.js';\nimport type { PersistenceBackend } from '../contracts/PersistenceBackend.js';\nimport {\n\tDehydrationPolicy,\n\ttype DehydrationOptions,\n\ttype HydratedEntry,\n} from './compression/DehydrationPolicy.js';\nimport type { Summary } from './compression/Summary.js';\nimport { SessionAccessDeniedError } from './SessionErrors.js';\nimport { EdgeEmitter } from './graph/EdgeEmitter.js';\nimport type {\n\tHistorySessionSnapshot,\n\tIHistoryManager,\n\tThoughtAdmissionContext,\n} from './IHistoryManager.js';\nimport { PersistenceBuffer, type PersistenceEventEmitter } from './PersistenceBuffer.js';\nimport { SessionManager } from './SessionManager.js';\nimport { SessionResetCoordinator } from './SessionResetCoordinator.js';\nimport { stagePersistenceRestore, type RestoredSession } from './PersistenceRestore.js';\nimport type { ThoughtData } from './thought.js';\nimport { getOwner } from '../context/RequestContext.js';\nimport { ThoughtReferenceIndex, type ThoughtReferenceResolution } from './ThoughtReferenceIndex.js';\nimport { resolveThoughtReferencesForAdmission } from './CrossReferenceValidator.js';\nimport { SessionLifecycleCoordinator } from './SessionLifecycleCoordinator.js';\nimport { resolvedVerificationTarget } from './evaluator/VerificationLinks.js';\nimport { reconstructVerificationTargets } from './VerificationTargetRestore.js';\n\n/** Absolute maximum history size (~20MB at 2KB/thought). Cannot be overridden. */\nexport const ABSOLUTE_MAX_HISTORY_SIZE = 10_000;\n\ninterface SessionState {\n\tthought_history: ThoughtData[];\n\tbranches: Record<string, ThoughtData[]>;\n\tverificationTargets: Map<ThoughtId, ThoughtId>;\n\tavailableMcpTools: string[] | undefined;\n\tavailableSkills: string[] | undefined;\n\tlastAccessedAt: number;\n\tbranchIdentities: Set<BranchId>;\n\tpendingRestoreBranchDeletes: Set<BranchId>;\n\t/** Owner identifier set on first owner-aware access. Immutable thereafter. */\n\towner?: string;\n\t/** Non-persisted startup provenance used to block unverified network ownership. */\n\tprovenance?: 'restored';\n}\n\nexport interface HistoryManagerConfig {\n\t/** Maximum number of thoughts to keep in main history. @default 1000 */\n\tmaxHistorySize?: number;\n\t/** Maximum number of branches to maintain. @default 50 */\n\tmaxBranches?: number;\n\t/** Maximum size of each branch. @default 100 */\n\tmaxBranchSize?: number;\n\tlogger?: Logger;\n\tpersistence?: PersistenceBackend | null;\n\tmetrics?: IMetrics;\n\t/** Maximum number of thoughts to buffer before flushing. @default 100 */\n\tpersistenceBufferSize?: number;\n\t/** Periodic flush interval in ms. @default 1000 */\n\tpersistenceFlushInterval?: number;\n\t/** Max retries for failed persistence flushes. @default 3 */\n\tpersistenceMaxRetries?: number;\n\tpersistenceHistorySize?: number;\n\tpersistBranches?: boolean;\n\teventEmitter?: PersistenceEventEmitter;\n\tedgeStore?: IEdgeStore;\n\tsummaryStore?: ISummaryStore;\n\t/** Whether to emit DAG edges (gated independently of edgeStore). @default false */\n\tdagEdges?: boolean;\n\t/** Maximum sessions per owner (per-owner LRU bucket). @default 50 */\n\tmaxSessionsPerOwner?: number;\n\t/** Shared processor lock used to serialize session resets. */\n\tsessionLock?: ISessionLock;\n\t/** Shared admission and exclusive lifecycle coordinator. */\n\tlifecycleCoordinator?: SessionLifecycleCoordinator;\n\t/** Clears processor-owned state after a session is actually removed. */\n\tclearSessionAuxiliaryState?: (sessionId: SessionId) => void;\n\t/** Clears all processor-owned state after a successful global lifecycle operation. */\n\tclearAllAuxiliaryState?: () => void;\n}\n\n/**\n * Manages thought history and branching for sequential thinking.\n *\n * Owns the per-session `Map<string, SessionState>`. Delegates DAG edge emission,\n * buffered persistence, and session TTL/LRU eviction to focused collaborators while\n * preserving test-coupled private member names (`_flushTimer`, `_startFlushTimer`,\n * `_flushBuffer`, `_sessions`).\n */\nexport class HistoryManager implements IHistoryManager {\n\tprivate static readonly SESSION_TTL_MS = 30 * 60 * 1000;\n\tprivate static readonly MAX_SESSIONS = 100;\n\tprivate _sessions: Map<SessionId, SessionState> = new Map();\n\tprivate _maxHistorySize: number;\n\tprivate _maxBranches: number;\n\tprivate _maxBranchSize: number;\n\tprivate _logger: Logger;\n\tprivate _persistence: PersistenceBackend | null;\n\tprivate _persistenceEnabled: boolean;\n\tprivate _metrics?: IMetrics;\n\n\tprivate _edgeStore?: IEdgeStore;\n\tprivate _summaryStore?: ISummaryStore;\n\tprivate _dagEdges: boolean;\n\n\tprivate _eventEmitter: PersistenceEventEmitter | null;\n\n\tprivate readonly _edgeEmitter: EdgeEmitter;\n\tprivate _referenceIndex = new ThoughtReferenceIndex();\n\tprivate _persistenceBuffer: PersistenceBuffer | null;\n\tprivate readonly _sessionManager: SessionManager<SessionState>;\n\tprivate readonly _resetCoordinator: SessionResetCoordinator<SessionState>;\n\tprivate readonly _sessionLock?: ISessionLock;\n\tprivate readonly _lifecycle: SessionLifecycleCoordinator;\n\tprivate _shutdownOwner: (() => Promise<void>) | null = null;\n\tprivate readonly _clearSessionAuxiliaryState?: (sessionId: SessionId) => void;\n\tprivate readonly _clearAllAuxiliaryState?: () => void;\n\n\tconstructor(config: HistoryManagerConfig = {}) {\n\t\tthis._logger = config.logger ?? new NullLogger();\n\t\tconst requestedMaxSize = config.maxHistorySize ?? 10000;\n\t\tthis._maxHistorySize = Math.min(requestedMaxSize, ABSOLUTE_MAX_HISTORY_SIZE);\n\t\tif (requestedMaxSize > ABSOLUTE_MAX_HISTORY_SIZE) {\n\t\t\tthis._logger.warn('maxHistorySize exceeds absolute maximum, capped', {\n\t\t\t\trequested: requestedMaxSize,\n\t\t\t\tapplied: ABSOLUTE_MAX_HISTORY_SIZE,\n\t\t\t});\n\t\t}\n\t\tthis._maxBranches = config.maxBranches ?? 50;\n\t\tthis._maxBranchSize = config.maxBranchSize || 100;\n\t\tthis._persistence = config.persistence ?? null;\n\t\tthis._persistenceEnabled = this._persistence !== null;\n\t\tthis._metrics = config.metrics;\n\t\tthis._eventEmitter = config.eventEmitter ?? null;\n\t\tthis._edgeStore = config.edgeStore;\n\t\tthis._summaryStore = config.summaryStore;\n\t\tthis._dagEdges = config.dagEdges ?? true;\n\t\tthis._sessionLock = config.sessionLock;\n\t\tthis._lifecycle = config.lifecycleCoordinator ?? new SessionLifecycleCoordinator();\n\t\tthis._clearSessionAuxiliaryState = config.clearSessionAuxiliaryState;\n\t\tthis._clearAllAuxiliaryState = config.clearAllAuxiliaryState;\n\n\t\t// Wire delegates\n\t\tthis._edgeEmitter = new EdgeEmitter({\n\t\t\tedgeStore: this._edgeStore,\n\t\t\tdagEdges: this._dagEdges,\n\t\t\tlogger: this._logger,\n\t\t});\n\n\t\tthis._sessionManager = new SessionManager<SessionState>({\n\t\t\tsessionTtlMs: HistoryManager.SESSION_TTL_MS,\n\t\t\tcleanupIntervalMs: 5 * 60 * 1000,\n\t\t\tgetMaxSessions: () => HistoryManager.MAX_SESSIONS,\n\t\t\tmaxSessionsPerOwner: config.maxSessionsPerOwner ?? 50,\n\t\t\tlogger: this._logger,\n\t\t});\n\n\t\tthis._persistenceBuffer = null;\n\t\tif (this._persistenceEnabled && this._persistence) {\n\t\t\tthis._persistenceBuffer = new PersistenceBuffer({\n\t\t\t\tpersistence: this._persistence,\n\t\t\t\tbufferSize: config.persistenceBufferSize ?? 100,\n\t\t\t\tflushInterval: config.persistenceFlushInterval ?? 1000,\n\t\t\t\tmaxRetries: config.persistenceMaxRetries ?? 3,\n\t\t\t\tdurableHistorySize: config.persistenceHistorySize ?? ABSOLUTE_MAX_HISTORY_SIZE,\n\t\t\t\tpersistBranches: config.persistBranches ?? true,\n\t\t\t\teventEmitter: this._eventEmitter,\n\t\t\t\tlogger: this._logger,\n\t\t\t});\n\t\t\tthis._startFlushTimer();\n\t\t}\n\t\tconst resetDurability =\n\t\t\tthis._persistence === null || this._persistenceBuffer === null\n\t\t\t\t? { persistence: null, barrier: null }\n\t\t\t\t: { persistence: this._persistence, barrier: this._persistenceBuffer };\n\t\tthis._resetCoordinator = new SessionResetCoordinator({\n\t\t\t...resetDurability,\n\t\t\tedgeStore: this._edgeStore,\n\t\t\tsummaryStore: this._summaryStore,\n\t\t\tsessions: this._sessions,\n\t\t\tcreateSessionState: (owner) => this._createSessionState(owner),\n\t\t\tlogger: this._logger,\n\t\t});\n\n\t\tthis._sessionManager.startCleanupTimer(\n\t\t\tthis._sessions,\n\t\t\t(sessionId) => this._isTtlEvictionEligible(sessionId),\n\t\t\t(sessionIds) => this._evictSessions(sessionIds)\n\t\t);\n\t}\n\n\t// Test-coupled accessors: these private member names must remain reachable\n\t// via `manager as unknown as { _flushTimer; _startFlushTimer }`.\n\tprivate get _flushTimer(): ReturnType<typeof setInterval> | null {\n\t\treturn this._persistenceBuffer?.timer ?? null;\n\t}\n\n\tprivate _startFlushTimer(): void {\n\t\tthis._persistenceBuffer?.startFlushTimer();\n\t}\n\n\tprivate _stopFlushTimer(): void {\n\t\tif (this._flushTimer === null) return;\n\t\tthis._persistenceBuffer?.stopFlushTimer();\n\t}\n\n\t/** @internal Public for test coupling. */\n\tpublic _flushBuffer(): Promise<void> {\n\t\tthis._stageAllRestoreBranchReconciliation();\n\t\treturn this._persistenceBuffer?.flush() ?? Promise.resolve();\n\t}\n\n\t/**\n\t * Drains accepted persistence work and projects terminal failures to one session.\n\t *\n\t * @param sessionId - Authoritative session whose persistence barrier to await.\n\t * @returns A promise that settles when the session's accepted work settles.\n\t */\n\tpublic drainSession(sessionId: SessionId): Promise<void> {\n\t\tconst session = this._sessions.get(sessionId);\n\t\tif (session !== undefined) this._stageRestoreBranchReconciliation(sessionId, session);\n\t\treturn this._persistenceBuffer?.drainSession(sessionId) ?? Promise.resolve();\n\t}\n\n\t/**\n\t * Registers the latest summary snapshot for coordinator-owned persistence.\n\t *\n\t * @param sessionId - Authoritative session that owns the summaries.\n\t * @param summaries - Complete current summary snapshot for the session.\n\t */\n\tpublic bufferSummaries(sessionId: SessionId, summaries: readonly Summary[]): void {\n\t\tthis._lifecycle.runMutation(sessionId, () => {\n\t\t\tthis._persistenceBuffer?.bufferSummaries(sessionId, summaries);\n\t\t\tconst session = this._sessions.get(sessionId);\n\t\t\tif (session !== undefined) this._stageRestoreBranchReconciliation(sessionId, session);\n\t\t});\n\t}\n\n\t/** EdgeStore instance, if configured. Used by ThoughtProcessor for StrategyContext. */\n\tpublic getEdgeStore(): IEdgeStore | undefined {\n\t\treturn this._edgeStore;\n\t}\n\n\tprivate log(message: string, meta?: Record<string, unknown>): void {\n\t\tthis._logger.info(message, meta);\n\t}\n\n\t/** Reads owner from RequestContext (AsyncLocalStorage). Stdio path returns undefined. */\n\tprivate _getCurrentOwner(): string | undefined {\n\t\treturn getOwner();\n\t}\n\n\t/**\n\t * Gets or creates session state; updates lastAccessedAt.\n\t *\n\t * Ownership semantics:\n\t * - `owner === undefined` (stdio path): never rejects, never sets owner.\n\t * - `owner !== undefined`: if session has a different owner, throws\n\t * `SessionAccessDeniedError`. If session was created without an owner\n\t * (e.g. by stdio), the owner is set on first owner-aware access.\n\t */\n\tprivate _getSession(sessionId: string, owner?: string): SessionState {\n\t\tconst key = asSessionId(sessionId);\n\t\tconst existing = this._sessions.get(key);\n\t\tif (existing !== undefined) {\n\t\t\tthis._assertSessionOwner(key, existing, owner);\n\t\t\texisting.lastAccessedAt = Date.now();\n\t\t\treturn existing;\n\t\t}\n\t\treturn this._lifecycle.runMutation(key, () => this._getSessionWithinOperation(key, owner));\n\t}\n\n\tprivate _getSessionWithinOperation(key: SessionId, owner?: string): SessionState {\n\t\tlet session = this._sessions.get(key);\n\t\tif (!session) {\n\t\t\tthis._makeCapacityForSession(owner);\n\t\t\tsession = this._createSessionState(owner);\n\t\t\tthis._sessions.set(key, session);\n\t\t} else {\n\t\t\tthis._assertSessionOwner(key, session, owner);\n\t\t}\n\t\tsession.lastAccessedAt = Date.now();\n\t\treturn session;\n\t}\n\n\tprivate _assertSessionOwner(\n\t\tsessionId: SessionId,\n\t\tsession: SessionState,\n\t\towner: string | undefined\n\t): void {\n\t\tif (owner === undefined) return;\n\t\tif (session.provenance === 'restored') {\n\t\t\tthrow new SessionAccessDeniedError(sessionId, 'unavailable', owner);\n\t\t}\n\t\tif (session.owner !== undefined && session.owner !== owner) {\n\t\t\tthrow new SessionAccessDeniedError(sessionId, session.owner, owner);\n\t\t}\n\t\tif (session.owner === undefined) session.owner = owner;\n\t}\n\n\tprivate _makeCapacityForSession(owner: string | undefined): void {\n\t\tconst victims = this._sessionManager.planProspectiveAdmission(\n\t\t\tthis._sessions,\n\t\t\towner,\n\t\t\t(sessionId) => this._isCapacityEvictionEligible(sessionId)\n\t\t);\n\t\tif (victims === undefined) throw new MaxSessionsReachedError(HistoryManager.MAX_SESSIONS);\n\t\tif (victims.length === 0) return;\n\t\tconst evicted = this._lifecycle.tryEvictIdleSessions(victims, (sessionIds) => {\n\t\t\tif (sessionIds.some((sessionId) => !this._isPersistenceQuiescent(sessionId))) {\n\t\t\t\tthrow new MaxSessionsReachedError(HistoryManager.MAX_SESSIONS);\n\t\t\t}\n\t\t\tfor (const sessionId of sessionIds) this._removeLiveSession(sessionId);\n\t\t});\n\t\tif (!evicted) throw new MaxSessionsReachedError(HistoryManager.MAX_SESSIONS);\n\t}\n\n\tprivate _isCapacityEvictionEligible(sessionId: SessionId): boolean {\n\t\treturn this._lifecycle.isIdle(sessionId) && this._isPersistenceQuiescent(sessionId);\n\t}\n\n\tprivate _isTtlEvictionEligible(sessionId: SessionId): boolean {\n\t\tconst persistenceState =\n\t\t\tthis._persistenceBuffer?.sessionEvictionState(sessionId) ?? 'quiescent';\n\t\treturn (\n\t\t\tthis._lifecycle.isIdle(sessionId) &&\n\t\t\tpersistenceState !== 'failed' &&\n\t\t\tpersistenceState !== 'barrier'\n\t\t);\n\t}\n\n\tprivate _isPersistenceQuiescent(sessionId: SessionId): boolean {\n\t\treturn (\n\t\t\t(this._persistenceBuffer?.sessionEvictionState(sessionId) ?? 'quiescent') === 'quiescent'\n\t\t);\n\t}\n\n\tprivate async _evictSessions(sessionIds: readonly SessionId[]): Promise<void> {\n\t\tconst results = await Promise.allSettled(\n\t\t\tsessionIds.map((sessionId) => this._evictSession(sessionId))\n\t\t);\n\t\tconst failures = results.flatMap((result) =>\n\t\t\tresult.status === 'rejected' ? [result.reason] : []\n\t\t);\n\t\tif (failures.length > 0) throw new AggregateError(failures, 'Session eviction failed');\n\t}\n\n\tprivate _evictSession(sessionId: SessionId): Promise<void> {\n\t\treturn this._lifecycle.withSessionEviction(sessionId, async () => {\n\t\t\tif (this._persistenceBuffer === null) {\n\t\t\t\tthis._removeLiveSession(sessionId);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst session = this._sessions.get(sessionId);\n\t\t\tif (session !== undefined) this._stageRestoreBranchReconciliation(sessionId, session);\n\t\t\tawait this._persistenceBuffer.withSessionEvictionBarrier(sessionId, async () => {\n\t\t\t\tthis._removeLiveSession(sessionId);\n\t\t\t});\n\t\t});\n\t}\n\n\tprivate _removeLiveSession(sessionId: SessionId): void {\n\t\tthis._clearSessionAuxiliaryState?.(sessionId);\n\t\tthis._edgeStore?.clearSession(sessionId);\n\t\tthis._summaryStore?.clearSession(sessionId);\n\t\tthis._referenceIndex.clearSession(sessionId);\n\t\tthis._sessions.delete(sessionId);\n\t\tthis._persistenceBuffer?.forgetQuiescentSession(sessionId);\n\t}\n\n\tprivate _createSessionState(owner?: string, provenance?: 'restored'): SessionState {\n\t\treturn {\n\t\t\tthought_history: [],\n\t\t\tbranches: {},\n\t\t\tverificationTargets: new Map<ThoughtId, ThoughtId>(),\n\t\t\tavailableMcpTools: undefined,\n\t\t\tavailableSkills: undefined,\n\t\t\tlastAccessedAt: Date.now(),\n\t\t\tbranchIdentities: new Set<BranchId>(),\n\t\t\tpendingRestoreBranchDeletes: new Set<BranchId>(),\n\t\t\towner,\n\t\t\tprovenance,\n\t\t};\n\t}\n\n\tprivate _authorizeExistingSession(\n\t\tsessionId: SessionId,\n\t\towner: string | undefined\n\t): string | undefined {\n\t\tconst sessionOwner = this._sessions.get(sessionId)?.owner;\n\t\tif (owner !== undefined && this._sessions.get(sessionId)?.provenance === 'restored') {\n\t\t\tthrow new SessionAccessDeniedError(sessionId, 'unavailable', owner);\n\t\t}\n\t\tif (owner !== undefined && sessionOwner !== undefined && sessionOwner !== owner) {\n\t\t\tthrow new SessionAccessDeniedError(sessionId, sessionOwner, owner);\n\t\t}\n\t\treturn sessionOwner ?? owner;\n\t}\n\n\tprivate _assertOwnerlessResetAll(): void {\n\t\tconst owner = this._getCurrentOwner();\n\t\tif (owner === undefined) return;\n\t\tconst firstSessionId = this._sessions.keys().next().value;\n\t\tif (firstSessionId !== undefined) {\n\t\t\tthrow new SessionAccessDeniedError(firstSessionId, 'trusted ownerless context', owner);\n\t\t}\n\t\tthrow new SequentialThinkingError(\n\t\t\t`Access denied to all sessions: trusted ownerless context required, accessed by '${owner}'`,\n\t\t\tERROR_CODES.SESSION_ACCESS_DENIED\n\t\t);\n\t}\n\n\t/**\n\t * Adds a thought to the history. Routes per-session, applies retraction for backtrack,\n\t * caches tools/skills, trims, branches, emits DAG edges, and buffers for persistence.\n\t */\n\tpublic addThought(thought: ThoughtData, context?: ThoughtAdmissionContext): void {\n\t\tconst sessionId = asSessionId(thought.session_id);\n\t\tthis._lifecycle.runMutation(sessionId, () =>\n\t\t\tthis._addThoughtWithinOperation(sessionId, thought, context)\n\t\t);\n\t}\n\n\tpublic assertThoughtIdentityAvailable(thought: ThoughtData): void {\n\t\tif (thought.id === undefined) return;\n\t\tconst sessionId = asSessionId(thought.session_id);\n\t\tthis._authorizeExistingSession(sessionId, this._getCurrentOwner());\n\t\tif (\n\t\t\tthis._referenceIndex.has(sessionId, thought.id) ||\n\t\t\tthis._persistenceBuffer?.hasThoughtIdentity(sessionId, thought.id) === true\n\t\t) {\n\t\t\tthrow new ValidationError('id', `Thought id already exists in session: ${thought.id}`);\n\t\t}\n\t}\n\n\tprivate _addThoughtWithinOperation(\n\t\tsessionId: SessionId,\n\t\tthought: ThoughtData,\n\t\tcontext?: ThoughtAdmissionContext\n\t): void {\n\t\tthis._persistenceBuffer?.assertSessionAdmissionOpen(sessionId);\n\t\tconst owner = this._getCurrentOwner();\n\t\tthis._authorizeExistingSession(sessionId, owner);\n\t\tthis.assertThoughtIdentityAvailable(thought);\n\t\tconst resolvedReferences = this._resolveAdmissionReferences(sessionId, thought, context);\n\t\tconst session = this._getSessionWithinOperation(sessionId, owner);\n\t\tthis._metrics?.counter(\n\t\t\t'thought_requests_total',\n\t\t\t1,\n\t\t\t{},\n\t\t\t'Total thought requests added to history'\n\t\t);\n\n\t\tsession.thought_history.push(thought);\n\t\tthis._recordVerificationTarget(session, thought, resolvedReferences);\n\n\t\t// Logical retraction: when a backtrack thought is added, mark its target\n\t\t// as retracted (append-only — target remains in history).\n\t\tif (resolvedReferences.backtrackTargetThoughtId !== undefined) {\n\t\t\tthis._applyRetraction(session, resolvedReferences.backtrackTargetThoughtId);\n\t\t}\n\n\t\t// Cache available_mcp_tools/available_skills for cross-call persistence\n\t\tif (thought.available_mcp_tools) {\n\t\t\tsession.availableMcpTools = thought.available_mcp_tools;\n\t\t}\n\t\tif (thought.available_skills) {\n\t\t\tsession.availableSkills = thought.available_skills;\n\t\t}\n\n\t\tif (thought.branch_from_thought && thought.branch_id) {\n\t\t\tthis._addToSessionBranch(session, thought.branch_id, thought);\n\t\t}\n\n\t\tif (thought.merge_from_thoughts?.length || thought.merge_branch_ids?.length) {\n\t\t\tthis._metrics?.counter(\n\t\t\t\t'thought_merge_operations_total',\n\t\t\t\t1,\n\t\t\t\t{},\n\t\t\t\t'Total merge operations (graph topology)'\n\t\t\t);\n\t\t}\n\n\t\tconst edgeAdded = this._edgeEmitter.emitEdgesForThought(session, thought, {\n\t\t\t...context,\n\t\t\tresolvedReferences,\n\t\t});\n\t\tconst evictedBranchIds = this._enforceRetention(session, thought.branch_id);\n\t\tthis._pruneVerificationTargets(session);\n\t\tthis._rebuildReferenceIndex(sessionId, session);\n\t\tconst prunedEdges = this._pruneUnretainedEdges(sessionId, session);\n\t\tthis._bufferRetainedState(\n\t\t\tsessionId,\n\t\t\tsession,\n\t\t\tthought,\n\t\t\tevictedBranchIds,\n\t\t\tedgeAdded,\n\t\t\tprunedEdges,\n\t\t\tresolvedReferences.backtrackTargetThoughtId\n\t\t);\n\t}\n\n\tprivate _resolveAdmissionReferences(\n\t\tsessionId: SessionId,\n\t\tthought: ThoughtData,\n\t\tcontext?: ThoughtAdmissionContext\n\t): NonNullable<ThoughtAdmissionContext['resolvedReferences']> {\n\t\tconst resolved =\n\t\t\tcontext?.resolvedReferences ??\n\t\t\tresolveThoughtReferencesForAdmission(thought, (thoughtNumber) =>\n\t\t\t\tthis._referenceIndex.resolve(sessionId, thoughtNumber)\n\t\t\t);\n\t\tif (\n\t\t\tthought.thought_type === 'backtrack' &&\n\t\t\tthought.backtrack_target !== undefined &&\n\t\t\tresolved.backtrackTargetThoughtId === undefined\n\t\t) {\n\t\t\tthrow new InvalidBacktrackError(\n\t\t\t\t`backtrack_target ${thought.backtrack_target} is missing in session history`\n\t\t\t);\n\t\t}\n\t\treturn resolved;\n\t}\n\n\tprivate _enforceRetention(\n\t\tsession: SessionState,\n\t\tbranchId: BranchId | undefined\n\t): readonly BranchId[] {\n\t\tif (session.thought_history.length > this._maxHistorySize) {\n\t\t\tsession.thought_history = session.thought_history.slice(-this._maxHistorySize);\n\t\t\tthis.log(`History trimmed to ${this._maxHistorySize} items`, {\n\t\t\t\tmaxSize: this._maxHistorySize,\n\t\t\t});\n\t\t}\n\t\tif (branchId !== undefined) this._trimSessionBranchSize(session, branchId);\n\t\treturn this._cleanupSessionBranches(session);\n\t}\n\n\tprivate _recordVerificationTarget(\n\t\tsession: SessionState,\n\t\tthought: ThoughtData,\n\t\treferences: NonNullable<ThoughtAdmissionContext['resolvedReferences']>\n\t): void {\n\t\tconst targetId = resolvedVerificationTarget(thought, references);\n\t\tif (thought.id !== undefined && targetId !== undefined) {\n\t\t\tsession.verificationTargets.set(thought.id, targetId);\n\t\t}\n\t}\n\n\tprivate _pruneVerificationTargets(session: SessionState): void {\n\t\tconst retainedIds = new Set(\n\t\t\t[session.thought_history, ...Object.values(session.branches)]\n\t\t\t\t.flat()\n\t\t\t\t.flatMap((thought) => (thought.id === undefined ? [] : [thought.id]))\n\t\t);\n\t\tfor (const [verifierId, targetId] of session.verificationTargets) {\n\t\t\tif (!retainedIds.has(verifierId) || !retainedIds.has(targetId)) {\n\t\t\t\tsession.verificationTargets.delete(verifierId);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate _pruneUnretainedEdges(sessionId: SessionId, session: SessionState): number {\n\t\tif (this._edgeStore === undefined) return 0;\n\t\tconst retainedIds = new Set<ThoughtId>();\n\t\tconst retainedBranchThoughtIds = new Set<ThoughtId>();\n\t\tfor (const thought of [session.thought_history, ...Object.values(session.branches)].flat()) {\n\t\t\tif (thought.id !== undefined) retainedIds.add(thought.id);\n\t\t}\n\t\tfor (const thought of Object.values(session.branches).flat()) {\n\t\t\tif (thought.id !== undefined) retainedBranchThoughtIds.add(thought.id);\n\t\t}\n\t\treturn this._edgeStore.pruneSession(sessionId, retainedIds, retainedBranchThoughtIds);\n\t}\n\n\tprivate _bufferRetainedState(\n\t\tsessionId: SessionId,\n\t\tsession: SessionState,\n\t\tthought: ThoughtData,\n\t\tevictedBranchIds: readonly BranchId[],\n\t\tedgeAdded: boolean,\n\t\tprunedEdges: number,\n\t\tbacktrackTargetThoughtId?: ThoughtId\n\t): void {\n\t\tconst buffer = this._persistenceBuffer;\n\t\tif (buffer === null) return;\n\t\tif (backtrackTargetThoughtId === undefined) buffer.bufferThought(sessionId, thought);\n\t\telse buffer.bufferBacktrack(sessionId, thought, backtrackTargetThoughtId);\n\t\tif (\n\t\t\tthought.branch_id !== undefined ||\n\t\t\tbacktrackTargetThoughtId !== undefined ||\n\t\t\tevictedBranchIds.length > 0 ||\n\t\t\tsession.pendingRestoreBranchDeletes.size > 0\n\t\t) {\n\t\t\tthis._stageBranchPersistence(sessionId, session, evictedBranchIds);\n\t\t}\n\t\tif (this._edgeStore !== undefined && (edgeAdded || prunedEdges > 0)) {\n\t\t\tbuffer.bufferEdges(sessionId, this._edgeStore.edgesForSession(sessionId));\n\t\t}\n\t}\n\n\tprivate _stageAllRestoreBranchReconciliation(): void {\n\t\tfor (const [sessionId, session] of this._sessions) {\n\t\t\tthis._stageRestoreBranchReconciliation(sessionId, session);\n\t\t}\n\t}\n\n\tprivate _stageRestoreBranchReconciliation(sessionId: SessionId, session: SessionState): void {\n\t\tif (session.pendingRestoreBranchDeletes.size === 0) return;\n\t\tthis._stageBranchPersistence(sessionId, session, []);\n\t}\n\n\tprivate _stageBranchPersistence(\n\t\tsessionId: SessionId,\n\t\tsession: SessionState,\n\t\tordinaryDeletes: readonly BranchId[]\n\t): void {\n\t\tconst buffer = this._persistenceBuffer;\n\t\tif (buffer === null) return;\n\t\tfor (const branchId of session.branchIdentities) {\n\t\t\tconst branch = session.branches[branchId];\n\t\t\tif (branch !== undefined) buffer.bufferBranch(sessionId, branchId, branch);\n\t\t}\n\t\tconst branchIdsToDelete = new Set([...session.pendingRestoreBranchDeletes, ...ordinaryDeletes]);\n\t\tfor (const branchId of branchIdsToDelete) {\n\t\t\tif (session.branches[branchId] === undefined) buffer.deleteBranch(sessionId, branchId);\n\t\t}\n\t\tsession.pendingRestoreBranchDeletes.clear();\n\t}\n\n\t/** Marks the thought as retracted within the session (append-only). */\n\tprivate _applyRetraction(session: SessionState, targetId: ThoughtId): void {\n\t\tfor (const t of session.thought_history) {\n\t\t\tif (t.id === targetId) t.retracted = true;\n\t\t}\n\t\tfor (const branchThoughts of Object.values(session.branches)) {\n\t\t\tfor (const t of branchThoughts) {\n\t\t\t\tif (t.id === targetId) t.retracted = true;\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate _rebuildReferenceIndex(sessionId: SessionId, session: SessionState): void {\n\t\tconst retained = [session.thought_history, ...Object.values(session.branches)].flat();\n\t\tthis._referenceIndex.replaceSession(sessionId, retained);\n\t}\n\n\tpublic resolveThoughtReference(\n\t\tsessionId: SessionId,\n\t\tthoughtNumber: number\n\t): ThoughtReferenceResolution {\n\t\tthis._authorizeExistingSession(sessionId, this._getCurrentOwner());\n\t\treturn this._referenceIndex.resolve(sessionId, thoughtNumber);\n\t}\n\n\tprivate _addToSessionBranch(\n\t\tsession: SessionState,\n\t\tbranchId: BranchId,\n\t\tthought: ThoughtData\n\t): void {\n\t\tif (!session.branches[branchId]) {\n\t\t\tsession.branches[branchId] = [];\n\t\t}\n\t\tsession.branchIdentities.add(branchId);\n\t\tsession.branches[branchId].push(thought);\n\t}\n\n\tprivate _cleanupSessionBranches(session: SessionState): readonly BranchId[] {\n\t\tconst branchCount = session.branchIdentities.size;\n\t\tif (branchCount <= this._maxBranches) return [];\n\t\tconst identitiesToRemove = Array.from(session.branchIdentities).slice(\n\t\t\t0,\n\t\t\tbranchCount - this._maxBranches\n\t\t);\n\t\tconst branchesToDelete: BranchId[] = [];\n\t\tfor (const branchId of identitiesToRemove) {\n\t\t\tsession.branchIdentities.delete(branchId);\n\t\t\tif (session.branches[branchId] !== undefined) branchesToDelete.push(branchId);\n\t\t\tdelete session.branches[branchId];\n\t\t\tthis.log(`Removed old branch: ${branchId}`, { branchId });\n\t\t}\n\t\treturn branchesToDelete;\n\t}\n\n\tprivate _trimSessionBranchSize(session: SessionState, branchId: BranchId): void {\n\t\tconst branch = session.branches[branchId];\n\t\tif (branch !== undefined && branch.length > this._maxBranchSize) {\n\t\t\tconst removed = branch.length - this._maxBranchSize;\n\t\t\tsession.branches[branchId] = branch.slice(-this._maxBranchSize);\n\t\t\tthis.log(`Trimmed branch '${branchId}': removed ${removed} old thoughts`, {\n\t\t\t\tbranchId,\n\t\t\t\tremoved,\n\t\t\t});\n\t\t}\n\t}\n\n\tpublic getHistory(sessionId: string): ThoughtData[] {\n\t\treturn this._getSession(sessionId, this._getCurrentOwner()).thought_history;\n\t}\n\n\t/**\n\t * Returns history with optional sliding-window dehydration. Non-mutating: when\n\t * `dagEdges` is off OR no `ISummaryStore` is configured, returns same as getHistory.\n\t */\n\tpublic getHistoryHydrated(sessionId: string, opts?: DehydrationOptions): HydratedEntry[] {\n\t\tconst history = this.getHistory(sessionId);\n\t\tif (!this._dagEdges || !this._summaryStore) {\n\t\t\treturn history.slice();\n\t\t}\n\t\tconst policy = new DehydrationPolicy(this._summaryStore);\n\t\treturn policy.apply(history, asSessionId(sessionId), opts);\n\t}\n\n\tpublic getHistoryLength(sessionId: string): number {\n\t\treturn this._getSession(sessionId, this._getCurrentOwner()).thought_history.length;\n\t}\n\n\tpublic getBranches(sessionId: string): Record<BranchId, ThoughtData[]> {\n\t\treturn this._getSession(sessionId, this._getCurrentOwner()).branches;\n\t}\n\n\tpublic getBranchIds(sessionId: string): BranchId[] {\n\t\treturn Array.from(this._getSession(sessionId, this._getCurrentOwner()).branchIdentities);\n\t}\n\n\t/** Returns validation state without creating a session, binding an owner, or updating LRU data. */\n\tpublic inspectSession(sessionId: string): HistorySessionSnapshot {\n\t\tconst canonicalSessionId = asSessionId(sessionId);\n\t\tthis._authorizeExistingSession(canonicalSessionId, this._getCurrentOwner());\n\t\tconst session = this._sessions.get(canonicalSessionId);\n\t\tif (session === undefined) {\n\t\t\treturn {\n\t\t\t\thistory: [],\n\t\t\t\tbranches: {},\n\t\t\t\tverificationTargets: new Map(),\n\t\t\t\tbranchIds: [],\n\t\t\t\tavailableMcpTools: undefined,\n\t\t\t\tavailableSkills: undefined,\n\t\t\t};\n\t\t}\n\t\treturn {\n\t\t\thistory: [...session.thought_history],\n\t\t\tbranches: Object.fromEntries(\n\t\t\t\tObject.entries(session.branches).map(([branchId, thoughts]) => [branchId, [...thoughts]])\n\t\t\t) as Record<BranchId, readonly ThoughtData[]>,\n\t\t\tverificationTargets: new Map(session.verificationTargets),\n\t\t\tbranchIds: Array.from(session.branchIdentities),\n\t\t\tavailableMcpTools:\n\t\t\t\tsession.availableMcpTools === undefined ? undefined : [...session.availableMcpTools],\n\t\t\tavailableSkills:\n\t\t\t\tsession.availableSkills === undefined ? undefined : [...session.availableSkills],\n\t\t};\n\t}\n\n\t/** @throws {ValidationError} If branchId is empty or already exists. */\n\tpublic registerBranch(sessionId: string, branchId: BranchId): void {\n\t\tif (typeof branchId !== 'string' || branchId.length === 0) {\n\t\t\tthrow new ValidationError('branch_id', 'branch_id must be a non-empty string');\n\t\t}\n\t\tconst canonicalSessionId = asSessionId(sessionId);\n\t\tthis._lifecycle.runMutation(canonicalSessionId, () => {\n\t\t\tthis._persistenceBuffer?.assertSessionAdmissionOpen(canonicalSessionId);\n\t\t\tconst session = this._getSessionWithinOperation(canonicalSessionId, this._getCurrentOwner());\n\t\t\tif (session.branchIdentities.has(branchId)) {\n\t\t\t\tthrow new ValidationError('branch_id', `Branch already exists: ${branchId}`);\n\t\t\t}\n\t\t\tsession.branchIdentities.add(branchId);\n\t\t\tconst evictedBranchIds = this._cleanupSessionBranches(session);\n\t\t\tthis._rebuildReferenceIndex(canonicalSessionId, session);\n\t\t\tconst prunedEdges = this._pruneUnretainedEdges(canonicalSessionId, session);\n\t\t\tif (evictedBranchIds.length > 0 || session.pendingRestoreBranchDeletes.size > 0) {\n\t\t\t\tthis._stageBranchPersistence(canonicalSessionId, session, evictedBranchIds);\n\t\t\t}\n\t\t\tif (this._edgeStore !== undefined && prunedEdges > 0) {\n\t\t\t\tthis._persistenceBuffer?.bufferEdges(\n\t\t\t\t\tcanonicalSessionId,\n\t\t\t\t\tthis._edgeStore.edgesForSession(canonicalSessionId)\n\t\t\t\t);\n\t\t\t}\n\t\t\tthis.log('Registered branch', { branchId, sessionId });\n\t\t});\n\t}\n\n\tpublic branchExists(sessionId: string, branchId: BranchId): boolean {\n\t\tconst session = this._getSession(sessionId, this._getCurrentOwner());\n\t\treturn session.branchIdentities.has(branchId);\n\t}\n\n\tpublic getAvailableMcpTools(sessionId: string): string[] | undefined {\n\t\treturn this._getSession(sessionId, this._getCurrentOwner()).availableMcpTools;\n\t}\n\n\tpublic getAvailableSkills(sessionId: string): string[] | undefined {\n\t\treturn this._getSession(sessionId, this._getCurrentOwner()).availableSkills;\n\t}\n\n\tpublic getBranch(branchId: BranchId, sessionId: string): ThoughtData[] | undefined {\n\t\treturn this._getSession(sessionId, this._getCurrentOwner()).branches[branchId];\n\t}\n\n\t/** Awaitably deletes one authorized durable namespace before replacing its live state. */\n\tpublic async resetSession(sessionId: string, clearAuxiliaryState?: () => void): Promise<void> {\n\t\tconst canonicalSessionId = asSessionId(sessionId);\n\t\tthis._authorizeExistingSession(canonicalSessionId, this._getCurrentOwner());\n\t\tawait this._lifecycle.withSessionReset(canonicalSessionId, async () => {\n\t\t\tconst reset = async (): Promise<void> =>\n\t\t\t\tawait this.resetSessionWithinExclusive(canonicalSessionId, clearAuxiliaryState);\n\t\t\tif (this._sessionLock === undefined) return await reset();\n\t\t\tawait this._sessionLock.withLock(canonicalSessionId, reset);\n\t\t});\n\t}\n\n\t/** Performs scoped reset work while its lifecycle exclusive is already owned. */\n\tpublic async resetSessionWithinExclusive(\n\t\tsessionId: SessionId,\n\t\tclearAuxiliaryState?: () => void\n\t): Promise<void> {\n\t\tconst preservedOwner = this._authorizeExistingSession(sessionId, this._getCurrentOwner());\n\t\tawait this._resetCoordinator.resetSession(\n\t\t\tsessionId,\n\t\t\tpreservedOwner,\n\t\t\tclearAuxiliaryState ??\n\t\t\t\t(this._clearSessionAuxiliaryState === undefined\n\t\t\t\t\t? undefined\n\t\t\t\t\t: () => this._clearSessionAuxiliaryState?.(sessionId))\n\t\t);\n\t\tthis._referenceIndex.clearSession(sessionId);\n\t}\n\n\t/** Awaitably deletes all durable namespaces from a trusted ownerless context. */\n\tpublic async resetAll(clearAuxiliaryState?: () => void): Promise<void> {\n\t\tthis._assertOwnerlessResetAll();\n\t\tawait this._lifecycle.withGlobalReset(\n\t\t\tasync () => await this.resetAllWithinExclusive(clearAuxiliaryState)\n\t\t);\n\t}\n\n\t/** Performs global reset work while its lifecycle exclusive is already owned. */\n\tpublic async resetAllWithinExclusive(clearAuxiliaryState?: () => void): Promise<void> {\n\t\tthis._assertOwnerlessResetAll();\n\t\tawait this._resetCoordinator.resetAll(clearAuxiliaryState ?? this._clearAllAuxiliaryState);\n\t\tthis._referenceIndex.clearAll();\n\t}\n\n\tpublic getSessionIds(): string[] {\n\t\treturn Array.from(this._sessions.keys());\n\t}\n\n\tpublic getSessionCount(): number {\n\t\treturn this._sessions.size;\n\t}\n\n\tprivate _restoredState(restored: RestoredSession): SessionState {\n\t\tconst session = this._createSessionState(undefined, 'restored');\n\t\tsession.verificationTargets = reconstructVerificationTargets(\n\t\t\trestored.sessionId,\n\t\t\trestored.history,\n\t\t\trestored.branches\n\t\t);\n\t\tfor (let index = restored.history.length - 1; index >= 0; index--) {\n\t\t\tconst thought = restored.history[index];\n\t\t\tif (thought === undefined) continue;\n\t\t\tif (session.availableMcpTools === undefined && thought.available_mcp_tools !== undefined) {\n\t\t\t\tsession.availableMcpTools = [...thought.available_mcp_tools];\n\t\t\t}\n\t\t\tif (session.availableSkills === undefined && thought.available_skills !== undefined) {\n\t\t\t\tsession.availableSkills = [...thought.available_skills];\n\t\t\t}\n\t\t\tif (session.availableMcpTools !== undefined && session.availableSkills !== undefined) break;\n\t\t}\n\t\tsession.thought_history = restored.history.slice(-this._maxHistorySize);\n\t\tconst retainedStart = Math.max(0, restored.branches.length - this._maxBranches);\n\t\tconst retainedBranches = restored.branches.slice(retainedStart);\n\t\tfor (const branch of restored.branches.slice(0, retainedStart)) {\n\t\t\tsession.pendingRestoreBranchDeletes.add(branch.branchId);\n\t\t}\n\t\tfor (const branch of retainedBranches) {\n\t\t\tsession.branchIdentities.add(branch.branchId);\n\t\t\tsession.branches[branch.branchId] = branch.thoughts.slice(-this._maxBranchSize);\n\t\t}\n\t\tthis._pruneVerificationTargets(session);\n\t\treturn session;\n\t}\n\n\t/** Loads and atomically commits every authoritative persistence namespace. Call at init. */\n\tpublic async loadFromPersistence(): Promise<void> {\n\t\tif (!this._persistenceEnabled || !this._persistence) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst restored = await stagePersistenceRestore(this._persistence);\n\t\tconst sessions = restored.sessions.map(\n\t\t\t(session) => [session.sessionId, this._restoredState(session)] as const\n\t\t);\n\t\tconst referenceIndex = new ThoughtReferenceIndex();\n\t\tconst retainedThoughtIds = new Map<SessionId, ReadonlySet<ThoughtId>>();\n\t\tconst retainedBranchThoughtIds = new Map<SessionId, ReadonlySet<ThoughtId>>();\n\t\tfor (const [sessionId, session] of sessions) {\n\t\t\tconst retained = [session.thought_history, ...Object.values(session.branches)].flat();\n\t\t\treferenceIndex.replaceSession(sessionId, retained);\n\t\t\tretainedThoughtIds.set(\n\t\t\t\tsessionId,\n\t\t\t\tnew Set(retained.flatMap((thought) => (thought.id === undefined ? [] : [thought.id])))\n\t\t\t);\n\t\t\tretainedBranchThoughtIds.set(\n\t\t\t\tsessionId,\n\t\t\t\tnew Set(\n\t\t\t\t\tObject.values(session.branches).flatMap((branch) =>\n\t\t\t\t\t\tbranch.flatMap((thought) => (thought.id === undefined ? [] : [thought.id]))\n\t\t\t\t\t)\n\t\t\t\t)\n\t\t\t);\n\t\t}\n\t\tthis._persistenceBuffer?.replaceDurableThoughtIdentities(restored.sessions);\n\n\t\tthis._edgeStore?.clearAll();\n\t\tthis._summaryStore?.clearAll();\n\t\tthis._sessions.clear();\n\t\tfor (const [sessionId, session] of sessions) this._sessions.set(sessionId, session);\n\t\tthis._referenceIndex = referenceIndex;\n\t\tfor (const session of restored.sessions) {\n\t\t\tconst retainedIds = retainedThoughtIds.get(session.sessionId) ?? new Set<ThoughtId>();\n\t\t\tconst retainedBranchIds =\n\t\t\t\tretainedBranchThoughtIds.get(session.sessionId) ?? new Set<ThoughtId>();\n\t\t\tfor (const edge of session.edges) {\n\t\t\t\tif (!retainedIds.has(edge.from) || !retainedIds.has(edge.to)) continue;\n\t\t\t\tif (edge.kind === 'branch' && !retainedBranchIds.has(edge.to)) continue;\n\t\t\t\tthis._edgeStore?.addEdge(edge);\n\t\t\t}\n\t\t\tfor (const summary of session.summaries) this._summaryStore?.add(summary);\n\t\t}\n\t\tthis.log(`Restored ${restored.sessions.length} persistence namespaces`);\n\t}\n\n\tpublic isPersistenceEnabled(): boolean {\n\t\treturn this._persistenceEnabled;\n\t}\n\n\tpublic getPersistenceBackend(): PersistenceBackend | null {\n\t\treturn this._persistence;\n\t}\n\n\t/** Sets the event emitter for persistence error events (post-construction wiring). */\n\tpublic setEventEmitter(emitter: PersistenceEventEmitter): void {\n\t\tthis._eventEmitter = emitter;\n\t\tthis._persistenceBuffer?.setEventEmitter(emitter);\n\t}\n\n\t/**\n\t * Binds shutdown to the resource owner responsible for the complete cleanup sequence.\n\t *\n\t * @internal\n\t * @param owner - Callback returning the owner's memoized shutdown promise.\n\t * @throws {TypeError} When a shutdown owner has already been bound.\n\t */\n\tpublic bindShutdownOwner(owner: () => Promise<void>): void {\n\t\tif (this._shutdownOwner !== null) {\n\t\t\tthrow new TypeError('HistoryManager shutdown owner is already bound');\n\t\t}\n\t\tthis._shutdownOwner = owner;\n\t}\n\n\t/** Stops timers, drains writes, and clears live state under one memoized lifecycle settlement. */\n\tpublic shutdown(): Promise<void> {\n\t\tif (this._shutdownOwner !== null) return this._shutdownOwner();\n\t\treturn this._lifecycle.shutdown(async () => {\n\t\t\tawait this.shutdownWithinLifecycle();\n\t\t\tthis.clearLiveStateAfterShutdown();\n\t\t});\n\t}\n\n\t/** Stops timers and drains writes while the caller owns global shutdown. */\n\tpublic async shutdownWithinLifecycle(): Promise<void> {\n\t\tthis._stopFlushTimer();\n\t\tthis._sessionManager.stopCleanupTimer();\n\t\tawait this._flushBuffer();\n\t}\n\n\t/** Clears non-durable state after every shutdown resource has closed successfully. */\n\tpublic clearLiveStateAfterShutdown(): void {\n\t\tfor (const sessionId of this._sessions.keys()) {\n\t\t\tthis._persistenceBuffer?.forgetQuiescentSession(sessionId);\n\t\t}\n\t\tthis._sessions.clear();\n\t\tthis._referenceIndex.clearAll();\n\t\tthis._edgeStore?.clearAll();\n\t\tthis._summaryStore?.clearAll();\n\t\tthis._clearAllAuxiliaryState?.();\n\t}\n\n\t/** Number of coordinator-owned thought writes not yet acknowledged successful. */\n\tpublic getWriteBufferLength(): number {\n\t\treturn this._persistenceBuffer?.pendingThoughtCount ?? 0;\n\t}\n}\n"],"names":["ABSOLUTE_MAX_HISTORY_SIZE","HistoryManager","Map","ThoughtReferenceIndex","config","NullLogger","requestedMaxSize","Math","SessionLifecycleCoordinator","EdgeEmitter","SessionManager","PersistenceBuffer","resetDurability","SessionResetCoordinator","owner","sessionId","sessionIds","Promise","session","undefined","summaries","message","meta","getOwner","key","asSessionId","existing","Date","SessionAccessDeniedError","victims","MaxSessionsReachedError","evicted","persistenceState","results","failures","result","AggregateError","provenance","Set","sessionOwner","firstSessionId","SequentialThinkingError","ERROR_CODES","thought","context","ValidationError","resolvedReferences","edgeAdded","evictedBranchIds","prunedEdges","resolved","resolveThoughtReferencesForAdmission","thoughtNumber","InvalidBacktrackError","branchId","references","targetId","resolvedVerificationTarget","retainedIds","Object","verifierId","retainedBranchThoughtIds","backtrackTargetThoughtId","buffer","ordinaryDeletes","branch","branchIdsToDelete","t","branchThoughts","retained","branchCount","identitiesToRemove","Array","branchesToDelete","removed","opts","history","policy","DehydrationPolicy","canonicalSessionId","thoughts","clearAuxiliaryState","reset","preservedOwner","restored","reconstructVerificationTargets","index","retainedStart","retainedBranches","stagePersistenceRestore","sessions","referenceIndex","retainedThoughtIds","retainedBranchIds","edge","summary","emitter","TypeError"],"mappings":";;;;;;;;;;;;;;;;AAqDO,MAAMA,4BAA4B;AA4DlC,MAAMC;IACZ,OAAwB,iBAAiB,QAAe;IACxD,OAAwB,eAAe,IAAI;IACnC,YAA0C,IAAIC,MAAM;IACpD,gBAAwB;IACxB,aAAqB;IACrB,eAAuB;IACvB,QAAgB;IAChB,aAAwC;IACxC,oBAA6B;IAC7B,SAAoB;IAEpB,WAAwB;IACxB,cAA8B;IAC9B,UAAmB;IAEnB,cAA8C;IAErC,aAA0B;IACnC,kBAAkB,IAAIC,wBAAwB;IAC9C,mBAA6C;IACpC,gBAA8C;IAC9C,kBAAyD;IACzD,aAA4B;IAC5B,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,GA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AAI,CAAC,eAAe,CAAC,QAAQ;QAC7B,IAAI,CAAC,UAAU,EAAE;QACjB,IAAI,CAAC,aAAa,EAAE;QACpB,IAAI,CAAC,uBAAuB;IAC7B;IAGO,uBAA+B;QACrC,OAAO,IAAI,CAAC,kBAAkB,EAAE,uBAAuB;IACxD;AACD"}
1
+ {"version":3,"file":"core/HistoryManager.js","sources":["../../src/core/HistoryManager.ts"],"sourcesContent":["/**\n * History and branch management for sequential thinking.\n *\n * This module provides the `HistoryManager` class which manages thought history,\n * branching, and optional persistence with per-session state isolation.\n *\n * Internally delegates to three focused collaborators:\n * - `EdgeEmitter` — DAG edge emission\n * - `PersistenceBuffer` — buffered persistence + retry/backoff\n * - `SessionManager` — session lifecycle (TTL/LRU eviction)\n *\n * @module HistoryManager\n */\n\nimport type { IEdgeStore, IMetrics, ISessionLock } from '../contracts/interfaces.js';\nimport { asSessionId, type BranchId, type SessionId, type ThoughtId } from '../contracts/ids.js';\nimport type { ISummaryStore } from '../contracts/summary.js';\nimport {\n\tERROR_CODES,\n\tInvalidBacktrackError,\n\tMaxSessionsReachedError,\n\tSequentialThinkingError,\n\tValidationError,\n} from '../errors.js';\nimport { NullLogger } from '../logger/NullLogger.js';\nimport type { Logger } from '../logger/StructuredLogger.js';\nimport type { PersistenceBackend } from '../contracts/PersistenceBackend.js';\nimport {\n\tDehydrationPolicy,\n\ttype DehydrationOptions,\n\ttype HydratedEntry,\n} from './compression/DehydrationPolicy.js';\nimport type { Summary } from './compression/Summary.js';\nimport { SessionAccessDeniedError, 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,OAAO,CAAC,IAAI,CAAC,mDAAmD;YACpE,WAAWM;YACX,SAASN;QACV;QAED,IAAI,CAAC,YAAY,GAAGI,OAAO,WAAW,IAAI;QAC1C,IAAI,CAAC,cAAc,GAAGA,OAAO,aAAa,IAAI;QAC9C,IAAI,CAAC,YAAY,GAAGA,OAAO,WAAW,IAAI;QAC1C,IAAI,CAAC,mBAAmB,GAAG,AAAsB,SAAtB,IAAI,CAAC,YAAY;QAC5C,IAAI,CAAC,QAAQ,GAAGA,OAAO,OAAO;QAC9B,IAAI,CAAC,aAAa,GAAGA,OAAO,YAAY,IAAI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AC;IACvE;IAEO,uBAAgC;QACtC,OAAO,IAAI,CAAC,mBAAmB;IAChC;IAEO,wBAAmD;QACzD,OAAO,IAAI,CAAC,YAAY;IACzB;IAGO,gBAAgBY,OAAgC,EAAQ;QAC9D,IAAI,CAAC,aAAa,GAAGA;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;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
+ /** Checks reset authorization without creating or claiming state; permits expired scopes. */
115
+ assertSessionResetAuthorized(sessionId: string): void;
114
116
  /** Returns the currently materialized session identifiers without binding ownership. */
115
117
  getSessionIds(): string[];
116
118
  /**
@@ -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,SA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,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"}
@@ -16,6 +16,10 @@ export declare class LockTimeoutError extends SequentialThinkingError {
16
16
  readonly timeoutMs: number;
17
17
  constructor(sessionId: SessionId, timeoutMs: number);
18
18
  }
19
+ export declare class SessionExpiredError extends SequentialThinkingError {
20
+ readonly sessionId: SessionId;
21
+ constructor(sessionId: SessionId);
22
+ }
19
23
  /** Error thrown when a session is accessed by a non-owner. */
20
24
  export declare class SessionAccessDeniedError extends SequentialThinkingError {
21
25
  readonly sessionId: SessionId;
@@ -1 +1 @@
1
- {"version":3,"file":"SessionErrors.d.ts","sourceRoot":"","sources":["../../src/core/SessionErrors.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,qBAAqB,CAAC;AACrD,OAAO,EAAe,uBAAuB,EAAE,MAAM,cAAc,CAAC;AAEpE,iEAAiE;AACjE,MAAM,MAAM,2BAA2B,GACpC,WAAW,GACX,cAAc,GACd,UAAU,GACV,iBAAiB,GACjB,eAAe,GACf,SAAS,GACT,iBAAiB,CAAC;AAErB,mFAAmF;AACnF,qBAAa,2BAA4B,SAAQ,uBAAuB;IACvE,wFAAwF;IACxF,SAAgB,SAAS,EAAE,SAAS,GAAG,SAAS,CAAC;IACjD,+CAA+C;IAC/C,SAAgB,KAAK,EAAE,2BAA2B,CAAC;gBAEhC,SAAS,EAAE,SAAS,GAAG,SAAS,EAAE,KAAK,EAAE,2BAA2B;CAUvF;AAED,6EAA6E;AAC7E,qBAAa,gBAAiB,SAAQ,uBAAuB;IAC5D,SAAgB,SAAS,EAAE,SAAS,CAAC;IACrC,SAAgB,SAAS,EAAE,MAAM,CAAC;gBAEtB,SAAS,EAAE,SAAS,EAAE,SAAS,EAAE,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AgB,aAAa,EAAE,MAAM,CAAC;IACtC,SAAgB,WAAW,EAAE,MAAM,GAAG,SAAS,CAAC;gBAEpC,SAAS,EAAE,SAAS,EAAE,aAAa,EAAE,MAAM,EAAE,WAAW,CAAC,EAAE,MAAM;CAU7E"}
@@ -20,6 +20,14 @@ class LockTimeoutError extends SequentialThinkingError {
20
20
  this.timeoutMs = timeoutMs;
21
21
  }
22
22
  }
23
+ class SessionExpiredError extends SequentialThinkingError {
24
+ sessionId;
25
+ constructor(sessionId){
26
+ super(`Session '${sessionId}' has expired. Use an authorized explicit reset or reset_state: true for a fresh chain, or choose a new session_id.`, ERROR_CODES.SESSION_EXPIRED);
27
+ this.name = 'SessionExpiredError';
28
+ this.sessionId = sessionId;
29
+ }
30
+ }
23
31
  class SessionAccessDeniedError extends SequentialThinkingError {
24
32
  sessionId;
25
33
  expectedOwner;
@@ -32,6 +40,6 @@ class SessionAccessDeniedError extends SequentialThinkingError {
32
40
  this.actualOwner = actualOwner;
33
41
  }
34
42
  }
35
- export { LockTimeoutError, SessionAccessDeniedError, SessionLifecycleClosedError };
43
+ export { LockTimeoutError, SessionAccessDeniedError, SessionExpiredError, SessionLifecycleClosedError };
36
44
 
37
45
  //# sourceMappingURL=SessionErrors.js.map