tracelattice 1.3.0 → 1.3.2

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 (75) hide show
  1. package/README.md +2 -0
  2. package/dist/ServerConfig.d.ts +10 -11
  3. package/dist/ServerConfig.d.ts.map +1 -1
  4. package/dist/ServerConfig.js +7 -7
  5. package/dist/ServerConfig.js.map +1 -1
  6. package/dist/__tests__/core/retraction.test.d.ts +2 -0
  7. package/dist/__tests__/core/retraction.test.d.ts.map +1 -0
  8. package/dist/__tests__/helpers/factories.d.ts +2 -0
  9. package/dist/__tests__/helpers/factories.d.ts.map +1 -1
  10. package/dist/cli.js +6 -6
  11. package/dist/core/HistoryManager.d.ts +45 -523
  12. package/dist/core/HistoryManager.d.ts.map +1 -1
  13. package/dist/core/HistoryManager.js +101 -249
  14. package/dist/core/HistoryManager.js.map +1 -1
  15. package/dist/core/IHistoryManager.d.ts +17 -0
  16. package/dist/core/IHistoryManager.d.ts.map +1 -1
  17. package/dist/core/PersistenceBuffer.d.ts +110 -0
  18. package/dist/core/PersistenceBuffer.d.ts.map +1 -0
  19. package/dist/core/PersistenceBuffer.js +141 -0
  20. package/dist/core/PersistenceBuffer.js.map +1 -0
  21. package/dist/core/SessionManager.d.ts +58 -0
  22. package/dist/core/SessionManager.d.ts.map +1 -0
  23. package/dist/core/SessionManager.js +65 -0
  24. package/dist/core/SessionManager.js.map +1 -0
  25. package/dist/core/ThoughtEvaluator.d.ts.map +1 -1
  26. package/dist/core/ThoughtEvaluator.js +16 -4
  27. package/dist/core/ThoughtEvaluator.js.map +1 -1
  28. package/dist/core/ThoughtFormatter.d.ts.map +1 -1
  29. package/dist/core/ThoughtFormatter.js +2 -1
  30. package/dist/core/ThoughtFormatter.js.map +1 -1
  31. package/dist/core/ThoughtProcessor.d.ts +18 -0
  32. package/dist/core/ThoughtProcessor.d.ts.map +1 -1
  33. package/dist/core/ThoughtProcessor.js +47 -16
  34. package/dist/core/ThoughtProcessor.js.map +1 -1
  35. package/dist/core/evaluator/Aggregator.d.ts.map +1 -1
  36. package/dist/core/evaluator/Aggregator.js +6 -2
  37. package/dist/core/evaluator/Aggregator.js.map +1 -1
  38. package/dist/core/evaluator/PatternDetector.js +2 -2
  39. package/dist/core/evaluator/PatternDetector.js.map +1 -1
  40. package/dist/core/evaluator/SignalComputer.d.ts +57 -5
  41. package/dist/core/evaluator/SignalComputer.d.ts.map +1 -1
  42. package/dist/core/evaluator/SignalComputer.js +52 -10
  43. package/dist/core/evaluator/SignalComputer.js.map +1 -1
  44. package/dist/core/graph/EdgeEmitter.d.ts +64 -0
  45. package/dist/core/graph/EdgeEmitter.d.ts.map +1 -0
  46. package/dist/core/graph/EdgeEmitter.js +99 -0
  47. package/dist/core/graph/EdgeEmitter.js.map +1 -0
  48. package/dist/core/reasoning.d.ts +17 -2
  49. package/dist/core/reasoning.d.ts.map +1 -1
  50. package/dist/core/thought.d.ts +7 -0
  51. package/dist/core/thought.d.ts.map +1 -1
  52. package/dist/core/tools/InMemorySuspensionStore.js +1 -1
  53. package/dist/core/tools/InMemorySuspensionStore.js.map +1 -1
  54. package/dist/lib.d.ts.map +1 -1
  55. package/dist/lib.js +11 -0
  56. package/dist/lib.js.map +1 -1
  57. package/dist/persistence/FilePersistence.d.ts +6 -0
  58. package/dist/persistence/FilePersistence.d.ts.map +1 -1
  59. package/dist/persistence/FilePersistence.js +8 -0
  60. package/dist/persistence/FilePersistence.js.map +1 -1
  61. package/dist/persistence/MemoryPersistence.d.ts +6 -0
  62. package/dist/persistence/MemoryPersistence.d.ts.map +1 -1
  63. package/dist/persistence/MemoryPersistence.js +3 -0
  64. package/dist/persistence/MemoryPersistence.js.map +1 -1
  65. package/dist/persistence/PersistenceBackend.d.ts +6 -0
  66. package/dist/persistence/PersistenceBackend.d.ts.map +1 -1
  67. package/dist/persistence/SqlitePersistence.d.ts +6 -0
  68. package/dist/persistence/SqlitePersistence.d.ts.map +1 -1
  69. package/dist/persistence/SqlitePersistence.js +4 -0
  70. package/dist/persistence/SqlitePersistence.js.map +1 -1
  71. package/dist/schema.d.ts +3 -2
  72. package/dist/schema.d.ts.map +1 -1
  73. package/dist/schema.js +8 -7
  74. package/dist/schema.js.map +1 -1
  75. package/package.json +2 -2
@@ -4,6 +4,11 @@
4
4
  * This module provides the `HistoryManager` class which manages thought history,
5
5
  * branching, and optional persistence with per-session state isolation.
6
6
  *
7
+ * Internally delegates to three focused collaborators:
8
+ * - `EdgeEmitter` — DAG edge emission
9
+ * - `PersistenceBuffer` — buffered persistence + retry/backoff
10
+ * - `SessionManager` — session lifecycle (TTL/LRU eviction)
11
+ *
7
12
  * @module HistoryManager
8
13
  */
9
14
  import type { IMetrics } from '../contracts/index.js';
@@ -11,595 +16,112 @@ import type { IEdgeStore } from '../contracts/interfaces.js';
11
16
  import type { ISummaryStore } from '../contracts/summary.js';
12
17
  import type { Logger } from '../logger/StructuredLogger.js';
13
18
  import type { PersistenceBackend } from '../persistence/PersistenceBackend.js';
19
+ import { type DehydrationOptions, type HydratedEntry } from './compression/DehydrationPolicy.js';
14
20
  import type { IHistoryManager } from './IHistoryManager.js';
21
+ import { type PersistenceEventEmitter } from './PersistenceBuffer.js';
15
22
  import type { ThoughtData } from './thought.js';
16
- import { type DehydrationOptions, type HydratedEntry } from './compression/DehydrationPolicy.js';
17
- /**
18
- * Absolute maximum history size. Cannot be overridden by configuration.
19
- * Prevents unbounded memory growth from misconfiguration.
20
- * At ~2KB per thought, 10K thoughts ≈ ~20MB — reasonable for server-side.
21
- * @constant
22
- */
23
+ export type { PersistenceEventEmitter } from './PersistenceBuffer.js';
24
+ /** Absolute maximum history size (~20MB at 2KB/thought). Cannot be overridden. */
23
25
  export declare const ABSOLUTE_MAX_HISTORY_SIZE = 10000;
24
- /**
25
- * Interface for emitting persistence error events.
26
- * Compatible with EventEmitter's emit method signature.
27
- */
28
- export interface PersistenceEventEmitter {
29
- emit(event: 'persistenceError', payload: {
30
- operation: string;
31
- error: Error;
32
- }): boolean;
33
- }
34
- /**
35
- * Configuration options for creating a `HistoryManager` instance.
36
- *
37
- * @example
38
- * ```typescript
39
- * const config: HistoryManagerConfig = {
40
- * maxHistorySize: 500,
41
- * maxBranches: 25,
42
- * maxBranchSize: 50,
43
- * logger: new StructuredLogger(),
44
- * persistence: filePersistence
45
- * };
46
- * ```
47
- */
48
26
  export interface HistoryManagerConfig {
49
- /**
50
- * Maximum number of thoughts to keep in main history.
51
- * @default 1000
52
- */
27
+ /** Maximum number of thoughts to keep in main history. @default 1000 */
53
28
  maxHistorySize?: number;
54
- /**
55
- * Maximum number of branches to maintain.
56
- * @default 50
57
- */
29
+ /** Maximum number of branches to maintain. @default 50 */
58
30
  maxBranches?: number;
59
- /**
60
- * Maximum size of each branch.
61
- * @default 100
62
- */
31
+ /** Maximum size of each branch. @default 100 */
63
32
  maxBranchSize?: number;
64
- /** Optional logger for diagnostics. */
65
33
  logger?: Logger;
66
- /** Optional persistence backend for saving/loading history. */
67
34
  persistence?: PersistenceBackend | null;
68
35
  metrics?: IMetrics;
69
- /**
70
- * Maximum number of thoughts to buffer before flushing to persistence.
71
- * @default 100
72
- */
36
+ /** Maximum number of thoughts to buffer before flushing. @default 100 */
73
37
  persistenceBufferSize?: number;
74
- /**
75
- * Interval in milliseconds between periodic persistence flushes.
76
- * @default 1000
77
- */
38
+ /** Periodic flush interval in ms. @default 1000 */
78
39
  persistenceFlushInterval?: number;
79
- /**
80
- * Maximum number of retries for failed persistence flushes.
81
- * @default 3
82
- */
40
+ /** Max retries for failed persistence flushes. @default 3 */
83
41
  persistenceMaxRetries?: number;
84
- /**
85
- * Event emitter for persistence error events.
86
- * When provided, persistenceError events are emitted on persistent failures.
87
- */
88
42
  eventEmitter?: PersistenceEventEmitter;
89
- /**
90
- * Optional EdgeStore for capturing thought DAG edges.
91
- * When provided, edge emission strategies can record relationships between thoughts.
92
- * @default undefined
93
- */
94
43
  edgeStore?: IEdgeStore;
95
- /**
96
- * Optional summary store for dehydrated history views.
97
- * When provided alongside the `dagEdges` flag, `getHistoryHydrated()`
98
- * uses it to replace cold thoughts with summary references.
99
- * @default undefined
100
- */
101
44
  summaryStore?: ISummaryStore;
102
- /**
103
- * Whether to emit DAG edges when an EdgeStore is provided.
104
- * When false (default), no edges are emitted even if edgeStore is set.
105
- * Gated independently from edgeStore so that EdgeStore can be registered
106
- * unconditionally in DI while writes remain feature-flagged.
107
- * @default false
108
- */
45
+ /** Whether to emit DAG edges (gated independently of edgeStore). @default false */
109
46
  dagEdges?: boolean;
110
47
  }
111
48
  /**
112
49
  * Manages thought history and branching for sequential thinking.
113
50
  *
114
- * This class is the central component for managing the state of sequential thinking
115
- * operations. It handles thought storage, branch management, and optional persistence
116
- * for state recovery. State is isolated per session via a `Map<string, SessionState>`.
117
- *
118
- * @remarks
119
- * **History Management:**
120
- * - Thoughts are stored in a linear history array per session
121
- * - Auto-trimming occurs when `maxHistorySize` is exceeded
122
- * - Oldest thoughts are removed first (FIFO eviction)
123
- *
124
- * **Session Isolation:**
125
- * - Each session maintains its own thought history, branches, and cached tools/skills
126
- * - Sessions are identified by optional `session_id` on ThoughtData
127
- * - Default (undefined) session_id maps to `__global__`
128
- * - TTL-based cleanup prevents unbounded memory growth
129
- * - LRU eviction when MAX_SESSIONS exceeded
130
- *
131
- * **Branch Management:**
132
- * - Branches allow exploring alternative reasoning paths
133
- * - Each branch has its own thought array within a session
134
- * - Branches are created when `branch_from_thought` and `branch_id` are set
135
- * - Branch count and size are limited by `maxBranches` and `maxBranchSize`
136
- *
137
- * **Persistence:**
138
- * - Optional persistence backend for saving/loading state
139
- * - Persists thoughts and branches asynchronously (fire-and-forget)
140
- * - Does not block on persistence failures
141
- *
142
- * @example
143
- * ```typescript
144
- * const manager = new HistoryManager({
145
- * maxHistorySize: 500,
146
- * maxBranches: 25,
147
- * logger: new StructuredLogger({ context: 'History' })
148
- * });
149
- *
150
- * // Add a thought
151
- * manager.addThought({
152
- * thought: 'I need to analyze the problem',
153
- * thought_number: 1,
154
- * total_thoughts: 5,
155
- * next_thought_needed: true
156
- * });
157
- *
158
- * // Get history
159
- * const history = manager.getHistory();
160
- * console.log(`Thoughts: ${history.length}`);
161
- *
162
- * // Get branches
163
- * const branches = manager.getBranches();
164
- * console.log(`Branches: ${Object.keys(branches).length}`);
165
- *
166
- * // Clear all state
167
- * manager.clear();
168
- * ```
51
+ * Owns the per-session `Map<string, SessionState>`. Delegates DAG edge emission,
52
+ * buffered persistence, and session TTL/LRU eviction to focused collaborators while
53
+ * preserving test-coupled private member names (`_flushTimer`, `_startFlushTimer`,
54
+ * `_flushBuffer`, `_sessions`).
169
55
  */
170
56
  export declare class HistoryManager implements IHistoryManager {
171
- /** Default session key for backward-compatible global state. */
172
57
  private static readonly DEFAULT_SESSION;
173
- /** TTL for inactive sessions in milliseconds (default: 30 minutes). */
174
58
  private static readonly SESSION_TTL_MS;
175
- /** Maximum number of concurrent sessions before eviction. */
176
59
  private static readonly MAX_SESSIONS;
177
- /** Session state storage. */
178
60
  private _sessions;
179
- /** Timer for periodic session cleanup. */
180
- private _sessionCleanupTimer;
181
- /** Maximum history size before auto-trimming. */
182
61
  private _maxHistorySize;
183
- /** Maximum number of branches before cleanup. */
184
62
  private _maxBranches;
185
- /** Maximum size of each branch. */
186
63
  private _maxBranchSize;
187
- /** Logger for diagnostics. */
188
64
  private _logger;
189
- /** Persistence backend for saving/loading state. */
190
65
  private _persistence;
191
- /** Whether persistence is enabled. */
192
66
  private _persistenceEnabled;
193
67
  private _metrics?;
194
- /** Timer for periodic buffer flushes. */
195
- private _flushTimer;
196
- /** Guard to prevent concurrent flushes. */
197
- private _isFlushing;
198
- /** Tracks consecutive flush failures for backoff. */
199
- private _flushRetryCount;
200
- /** Maximum buffer size before triggering immediate flush. */
201
- private _persistenceBufferSize;
202
- /** Interval in milliseconds between periodic flushes. */
203
- private _persistenceFlushInterval;
204
- /** Maximum number of retries for failed flushes. */
205
- private _persistenceMaxRetries;
206
- /** Event emitter for persistence error events. */
207
- private _eventEmitter;
208
- /** Optional EdgeStore for capturing thought DAG edges. */
209
68
  private _edgeStore?;
210
- /** Optional SummaryStore used by getHistoryHydrated(). */
211
69
  private _summaryStore?;
212
- /** Whether to emit DAG edges (gated by features.dagEdges flag). */
213
70
  private _dagEdges;
214
- /**
215
- * Creates a new HistoryManager instance.
216
- *
217
- * @param config - Configuration options for the history manager
218
- *
219
- * @example
220
- * ```typescript
221
- * const manager = new HistoryManager({
222
- * maxHistorySize: 500,
223
- * maxBranches: 25,
224
- * logger: new StructuredLogger(),
225
- * persistence: filePersistence
226
- * });
227
- * ```
228
- */
71
+ private _eventEmitter;
72
+ private readonly _edgeEmitter;
73
+ private _persistenceBuffer;
74
+ private readonly _sessionManager;
229
75
  constructor(config?: HistoryManagerConfig);
230
- /**
231
- * Get the EdgeStore instance, if configured.
232
- * Returns undefined when no EdgeStore was injected.
233
- * @public Used by ThoughtProcessor to build StrategyContext for reasoning strategies.
234
- */
76
+ private get _flushTimer();
77
+ private _startFlushTimer;
78
+ private _stopFlushTimer;
79
+ /** @internal Public for backward-compatible test coupling. */
80
+ _flushBuffer(): Promise<void>;
81
+ /** EdgeStore instance, if configured. Used by ThoughtProcessor for StrategyContext. */
235
82
  getEdgeStore(): IEdgeStore | undefined;
236
- /**
237
- * Internal logging method.
238
- * @param message - The message to log
239
- * @param meta - Optional metadata
240
- * @private
241
- */
242
83
  private log;
243
- /**
244
- * Gets or creates the session state for a given session ID.
245
- * Creates a new SessionState if one doesn't exist.
246
- * Updates lastAccessedAt on every access.
247
- *
248
- * @param sessionId - Optional session ID (defaults to `__global__`)
249
- * @returns The session state
250
- * @private
251
- */
84
+ /** Gets or creates session state; updates lastAccessedAt. */
252
85
  private _getSession;
253
86
  /**
254
- * Adds a thought to the history.
255
- *
256
- * The thought is appended to the session's history array. If history exceeds
257
- * `maxHistorySize`, the oldest thoughts are removed. If the thought
258
- * has `branch_from_thought` and `branch_id` set, it's also added to
259
- * the appropriate branch. The thought is persisted asynchronously if
260
- * persistence is enabled.
261
- *
262
- * @param thought - The thought data to add
263
- *
264
- * @example
265
- * ```typescript
266
- * manager.addThought({
267
- * thought: 'I should read the README file',
268
- * thought_number: 1,
269
- * total_thoughts: 3,
270
- * next_thought_needed: true
271
- * });
272
- * ```
87
+ * Adds a thought to the history. Routes per-session, applies retraction for backtrack,
88
+ * caches tools/skills, trims, branches, emits DAG edges, and buffers for persistence.
273
89
  */
274
90
  addThought(thought: ThoughtData): void;
275
- /**
276
- * Emits DAG edges for a thought based on its metadata fields.
277
- *
278
- * Edge kinds (in priority order):
279
- * - branch: branch_from_thought + branch_id → parent.id → current.id
280
- * - merge: merge_from_thoughts → source.id → current.id (per source)
281
- * - verifies: verification_target + thought_type=verification → current.id → target.id
282
- * - critiques: verification_target + thought_type=critique → current.id → target.id
283
- * - derives_from: synthesis_sources → source.id → current.id (per source)
284
- * - revises: revises_thought → current.id → target.id
285
- * - sequence: default chronological link from previous thought (if none of the above)
286
- *
287
- * No-op when edgeStore is absent, dagEdges flag is off, or thought has no id.
288
- * @param session - The session state
289
- * @param thought - The current thought being added
290
- * @private
291
- */
292
- private _emitEdgesForThought;
293
- /**
294
- * Resolves a thought_number to its stable id within the given session.
295
- * @param session - The session state to search
296
- * @param thoughtNumber - The thought_number to look up
297
- * @returns The thought's id if found and non-empty, undefined otherwise
298
- * @private
299
- */
300
- private _resolveThoughtId;
301
- /**
302
- * Adds an edge to the edge store if both endpoints are non-empty strings.
303
- * Returns true if added, false if skipped (missing endpoint).
304
- * Failures (e.g. self-edge) are caught and logged.
305
- * @private
306
- */
307
- private _addEdgeIfValid;
308
- /**
309
- * Buffers a thought for persistence if enabled.
310
- * @param session - The session state to buffer into
311
- * @param thought - The thought to buffer
312
- * @private
313
- */
314
- private _bufferForPersistence;
315
- /**
316
- * Adds a thought to a branch within a specific session.
317
- * @param session - The session state
318
- * @param branchId - The branch identifier
319
- * @param thought - The thought data to add
320
- * @private
321
- */
91
+ /** Marks the thought as retracted within the session (append-only). */
92
+ private _applyRetraction;
322
93
  private _addToSessionBranch;
323
- /**
324
- * Removes old branches when count exceeds maxBranches within a session.
325
- * @param session - The session state
326
- * @private
327
- */
328
94
  private _cleanupSessionBranches;
329
- /**
330
- * Trims a branch to maxBranchSize within a session.
331
- * @param session - The session state
332
- * @param branchId - The branch identifier to trim
333
- * @private
334
- */
335
95
  private _trimSessionBranchSize;
336
- /**
337
- * Gets the complete thought history.
338
- *
339
- * @param sessionId - Optional session ID for session-scoped results
340
- * @returns An array of all thoughts in chronological order
341
- *
342
- * @example
343
- * ```typescript
344
- * const history = manager.getHistory();
345
- * history.forEach(thought => {
346
- * console.log(`${thought.thought_number}: ${thought.thought}`);
347
- * });
348
- * ```
349
- */
350
96
  getHistory(sessionId?: string): ThoughtData[];
351
97
  /**
352
- * Gets the thought history with optional sliding-window dehydration applied.
353
- *
354
- * Non-mutating view: the underlying history is never modified. When the
355
- * `dagEdges` feature flag is off OR no `ISummaryStore` is configured, this
356
- * method returns the same `ThoughtData[]` as {@link getHistory}. Otherwise,
357
- * a {@link DehydrationPolicy} is applied that replaces older thoughts (cold
358
- * prefix beyond `keepLastK`) with {@link SummaryRef} placeholders pointing
359
- * at existing summaries in the store.
360
- *
361
- * @param sessionId - Optional session ID for session-scoped results
362
- * @param opts - Optional dehydration options (e.g. `keepLastK`)
363
- * @returns Mixed array of original thoughts and summary refs (or the raw
364
- * history when dehydration is disabled)
98
+ * Returns history with optional sliding-window dehydration. Non-mutating: when
99
+ * `dagEdges` is off OR no `ISummaryStore` is configured, returns same as getHistory.
365
100
  */
366
101
  getHistoryHydrated(sessionId?: string, opts?: DehydrationOptions): HydratedEntry[];
367
- /**
368
- * Gets the current length of the thought history.
369
- *
370
- * @param sessionId - Optional session ID for session-scoped results
371
- * @returns The number of thoughts in history
372
- *
373
- * @example
374
- * ```typescript
375
- * console.log(`Total thoughts: ${manager.getHistoryLength()}`);
376
- * ```
377
- */
378
102
  getHistoryLength(sessionId?: string): number;
379
- /**
380
- * Gets all branches.
381
- *
382
- * @param sessionId - Optional session ID for session-scoped results
383
- * @returns A record mapping branch IDs to their thought arrays
384
- *
385
- * @example
386
- * ```typescript
387
- * const branches = manager.getBranches();
388
- * for (const [branchId, thoughts] of Object.entries(branches)) {
389
- * console.log(`Branch ${branchId}: ${thoughts.length} thoughts`);
390
- * }
391
- * ```
392
- */
393
103
  getBranches(sessionId?: string): Record<string, ThoughtData[]>;
394
- /**
395
- * Gets all branch IDs.
396
- *
397
- * @param sessionId - Optional session ID for session-scoped results
398
- * @returns An array of branch identifiers
399
- *
400
- * @example
401
- * ```typescript
402
- * const branchIds = manager.getBranchIds();
403
- * console.log(`Active branches: ${branchIds.join(', ')}`);
404
- * ```
405
- */
406
104
  getBranchIds(sessionId?: string): string[];
407
- /**
408
- * Gets the most recently available MCP tools from the session.
409
- *
410
- * @param sessionId - Optional session ID for session-scoped results
411
- * @returns The last-seen array of MCP tool names, or undefined if never set
412
- *
413
- * @example
414
- * ```typescript
415
- * const tools = manager.getAvailableMcpTools();
416
- * // ['Read', 'Grep', 'Glob'] or undefined
417
- * ```
418
- */
105
+ /** @throws {ValidationError} If branchId is empty or already exists. */
106
+ registerBranch(sessionId: string | undefined, branchId: string): void;
107
+ branchExists(sessionId: string | undefined, branchId: string): boolean;
419
108
  getAvailableMcpTools(sessionId?: string): string[] | undefined;
420
- /**
421
- * Gets the most recently available skills from the session.
422
- *
423
- * @param sessionId - Optional session ID for session-scoped results
424
- * @returns The last-seen array of skill names, or undefined if never set
425
- *
426
- * @example
427
- * ```typescript
428
- * const skills = manager.getAvailableSkills();
429
- * // ['commit', 'review-pr'] or undefined
430
- * ```
431
- */
432
109
  getAvailableSkills(sessionId?: string): string[] | undefined;
433
- /**
434
- * Gets a specific branch by ID.
435
- *
436
- * @param branchId - The branch identifier
437
- * @param sessionId - Optional session ID for session-scoped results
438
- * @returns The branch's thought array, or undefined if not found
439
- *
440
- * @example
441
- * ```typescript
442
- * const branch = manager.getBranch('alternative-approach');
443
- * if (branch) {
444
- * console.log(`Branch has ${branch.length} thoughts`);
445
- * } else {
446
- * console.log('Branch not found');
447
- * }
448
- * ```
449
- */
450
110
  getBranch(branchId: string, sessionId?: string): ThoughtData[] | undefined;
451
- /**
452
- * Clears history and branches.
453
- * If sessionId is provided, clears only that session.
454
- * If omitted, clears all sessions.
455
- *
456
- * @param sessionId - Optional session ID to clear
457
- *
458
- * @example
459
- * ```typescript
460
- * manager.clear();
461
- * console.log('All history and branches cleared');
462
- * ```
463
- */
111
+ /** Clears history and branches. If sessionId provided, clears only that session. */
464
112
  clear(sessionId?: string): void;
465
- /** Clears state for a specific session. Alias for clear(sessionId). */
466
113
  clearSession(sessionId: string): void;
467
- /** Gets all active session IDs. */
468
114
  getSessionIds(): string[];
469
- /** Gets the number of active sessions. */
470
115
  getSessionCount(): number;
471
- /**
472
- * Loads history from the persistence backend.
473
- *
474
- * This should be called during initialization to restore previous state.
475
- * Only loads if persistence is enabled and the backend is healthy.
476
- * Loads into the global session.
477
- *
478
- * @returns Promise that resolves when loading is complete
479
- *
480
- * @example
481
- * ```typescript
482
- * await manager.loadFromPersistence();
483
- * console.log(`Loaded ${manager.getHistoryLength()} thoughts`);
484
- * ```
485
- */
116
+ /** Loads history from persistence into the global session. Call at init. */
486
117
  loadFromPersistence(): Promise<void>;
487
- /**
488
- * Checks if persistence is enabled.
489
- *
490
- * @returns true if persistence is enabled, false otherwise
491
- *
492
- * @example
493
- * ```typescript
494
- * if (manager.isPersistenceEnabled()) {
495
- * console.log('Persistence is active');
496
- * }
497
- * ```
498
- */
499
118
  isPersistenceEnabled(): boolean;
500
- /**
501
- * Gets the persistence backend instance.
502
- *
503
- * @returns The persistence backend, or null if not configured
504
- *
505
- * @example
506
- * ```typescript
507
- * const backend = manager.getPersistenceBackend();
508
- * if (backend) {
509
- * await backend.healthy();
510
- * }
511
- * ```
512
- */
513
119
  getPersistenceBackend(): PersistenceBackend | null;
514
- /**
515
- * Sets the event emitter for persistence error events.
516
- * This allows wiring up the event emitter after construction
517
- * (e.g., when the server instance is the emitter).
518
- *
519
- * @param emitter - The event emitter to use for persistence error events
520
- */
120
+ /** Sets the event emitter for persistence error events (post-construction wiring). */
521
121
  setEventEmitter(emitter: PersistenceEventEmitter): void;
522
- /**
523
- * Gracefully shuts down the write buffer and session cleanup.
524
- * Stops the periodic flush timer and session cleanup timer,
525
- * then flushes any remaining buffered writes.
526
- * Should be called during server shutdown before closing the persistence backend.
527
- */
122
+ /** Stops timers and flushes any remaining buffered writes. */
528
123
  shutdown(): Promise<void>;
529
- /**
530
- * Starts the periodic flush timer for the write buffer.
531
- * @private
532
- */
533
- private _startFlushTimer;
534
- /**
535
- * Stops the periodic flush timer.
536
- * @private
537
- */
538
- private _stopFlushTimer;
539
- /**
540
- * Starts the periodic session cleanup timer.
541
- * Runs every 5 minutes to evict sessions that exceeded TTL.
542
- * @private
543
- */
544
- private _startSessionCleanupTimer;
545
- /**
546
- * Stops the periodic session cleanup timer.
547
- * @private
548
- */
549
- private _stopSessionCleanupTimer;
550
- /**
551
- * Evicts sessions that have been inactive longer than SESSION_TTL_MS.
552
- * The global session is never evicted.
553
- * @private
554
- */
555
- private _cleanupStaleSessions;
556
- /**
557
- * Evicts oldest sessions when MAX_SESSIONS is exceeded (LRU).
558
- * The global session is never evicted.
559
- * @private
560
- */
561
- private _evictExcessSessions;
562
- /**
563
- * Flushes the write buffer to the persistence backend.
564
- *
565
- * Collects all buffered thoughts across all sessions and saves them
566
- * individually with retry logic. On persistent failure (all retries exhausted),
567
- * emits a `persistenceError` event and re-queues failed items.
568
- *
569
- * This method is safe to call concurrently — duplicate calls are skipped.
570
- * @internal
571
- */
572
- _flushBuffer(): Promise<void>;
573
- /**
574
- * Flushes edges for all known sessions to the persistence backend.
575
- * No-op when EdgeStore or persistence is unavailable.
576
- * @private
577
- */
578
- private _flushEdges;
579
- /**
580
- * Flushes a single thought to persistence with retry logic.
581
- * @param thought - The thought to flush
582
- * @returns true if saved successfully, false otherwise
583
- * @private
584
- */
585
- private _flushSingleThought;
586
- /**
587
- * Handles the result of a flush operation, re-queuing failures.
588
- * @param failedItems - Thoughts that failed to persist
589
- * @param totalCount - Total number of thoughts attempted
590
- * @private
591
- */
592
- private _handleFlushResult;
593
- /**
594
- * Returns a promise that resolves after the specified delay.
595
- * @param ms - Delay in milliseconds
596
- * @private
597
- */
598
- private _delay;
599
- /**
600
- * Gets the current write buffer length across all sessions.
601
- * Useful for monitoring and testing.
602
- */
124
+ /** Total write buffer length across all sessions. */
603
125
  getWriteBufferLength(): number;
604
126
  }
605
127
  //# sourceMappingURL=HistoryManager.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"HistoryManager.d.ts","sourceRoot":"","sources":["../../src/core/HistoryManager.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,uBAAuB,CAAC;AAEtD,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,4BAA4B,CAAC;AAC7D,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,yBAAyB,CAAC;AAI7D,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,+BAA+B,CAAC;AAC5D,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,sCAAsC,CAAC;AAC/E,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AAC5D,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAChD,OAAO,EAEN,KAAK,kBAAkB,EACvB,KAAK,aAAa,EAClB,MAAM,oCAAoC,CAAC;AAE5C;;;;;GAKG;AACH,eAAO,MAAM,yBAAyB,QAAS,CAAC;AAEhD;;;GAGG;AACH,MAAM,WAAW,uBAAuB;IACvC,IAAI,CAAC,KAAK,EAAE,kBAAkB,EAAE,OAAO,EAAE;QAAE,SAAS,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,KAAK,CAAA;KAAE,GAAG,OAAO,CAAC;CACvF;AAYD;;;;;;;;;;;;;GAaG;AACH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