@danielsimonjr/memoryjs 2.8.1 → 2.9.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.
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { z, ZodError, ZodSchema } from 'zod';
2
- import workerpool, { PoolStats, Pool } from '@danielsimonjr/workerpool';
2
+ import { PoolStats, Pool } from '@danielsimonjr/workerpool';
3
3
  import { Database } from 'better-sqlite3';
4
4
  import { EventEmitter } from 'events';
5
5
  import { EventEmitter as EventEmitter$1 } from 'node:events';
@@ -221,6 +221,225 @@ declare class QueryTraceBuilder {
221
221
  complete(resultCount: number, metadata?: Record<string, unknown>): QueryTrace;
222
222
  }
223
223
 
224
+ /**
225
+ * Graph Event Emitter
226
+ *
227
+ * Phase 10 Sprint 2: Provides event-based notifications for graph changes.
228
+ * Enables loose coupling between graph operations and dependent systems
229
+ * like search indexes, analytics, and external integrations.
230
+ *
231
+ * @module core/GraphEventEmitter
232
+ */
233
+
234
+ /**
235
+ * Phase 10 Sprint 2: Event emitter for graph change notifications.
236
+ *
237
+ * Provides a type-safe event system for subscribing to and emitting
238
+ * graph change events. Supports wildcard listeners for all events.
239
+ *
240
+ * @example
241
+ * ```typescript
242
+ * const emitter = new GraphEventEmitter();
243
+ *
244
+ * // Listen to specific event types
245
+ * emitter.on('entity:created', (event) => {
246
+ * console.log(`Entity ${event.entity.name} created`);
247
+ * });
248
+ *
249
+ * // Listen to all events
250
+ * emitter.onAny((event) => {
251
+ * console.log(`Event: ${event.type}`);
252
+ * });
253
+ *
254
+ * // Emit an event
255
+ * emitter.emitEntityCreated(entity);
256
+ *
257
+ * // Remove listener
258
+ * const unsubscribe = emitter.on('entity:deleted', handler);
259
+ * unsubscribe();
260
+ * ```
261
+ */
262
+ declare class GraphEventEmitter {
263
+ /**
264
+ * Map of event types to their registered listeners. The Set stores
265
+ * listeners typed for different specific event subtypes (one Set per
266
+ * GraphEventType key). TS can't express this dependent-key relationship
267
+ * without `any` due to function-parameter contravariance.
268
+ */
269
+ private listeners;
270
+ /**
271
+ * Listeners that receive all events regardless of type.
272
+ */
273
+ private wildcardListeners;
274
+ /**
275
+ * Whether to suppress errors from listeners (default: true).
276
+ * When true, listener errors are logged but don't stop event propagation.
277
+ */
278
+ private suppressListenerErrors;
279
+ /**
280
+ * Create a new GraphEventEmitter instance.
281
+ *
282
+ * @param options - Optional configuration
283
+ */
284
+ constructor(options?: {
285
+ suppressListenerErrors?: boolean;
286
+ });
287
+ /**
288
+ * Subscribe to a specific event type.
289
+ *
290
+ * @template K - The event type key
291
+ * @param eventType - The event type to listen for
292
+ * @param listener - Callback function to invoke when event occurs
293
+ * @returns Unsubscribe function to remove the listener
294
+ *
295
+ * @example
296
+ * ```typescript
297
+ * const unsubscribe = emitter.on('entity:created', (event) => {
298
+ * console.log(`Created: ${event.entity.name}`);
299
+ * });
300
+ *
301
+ * // Later: unsubscribe();
302
+ * ```
303
+ */
304
+ on<K extends GraphEventType>(eventType: K, listener: GraphEventListener<GraphEventMap[K]>): () => void;
305
+ /**
306
+ * Unsubscribe from a specific event type.
307
+ *
308
+ * @template K - The event type key
309
+ * @param eventType - The event type to unsubscribe from
310
+ * @param listener - The listener function to remove
311
+ */
312
+ off<K extends GraphEventType>(eventType: K, listener: GraphEventListener<GraphEventMap[K]>): void;
313
+ /**
314
+ * Subscribe to all event types.
315
+ *
316
+ * @param listener - Callback function to invoke for any event
317
+ * @returns Unsubscribe function to remove the listener
318
+ *
319
+ * @example
320
+ * ```typescript
321
+ * emitter.onAny((event) => {
322
+ * console.log(`Event: ${event.type} at ${event.timestamp}`);
323
+ * });
324
+ * ```
325
+ */
326
+ onAny(listener: GraphEventListener<GraphEvent>): () => void;
327
+ /**
328
+ * Unsubscribe from all events.
329
+ *
330
+ * @param listener - The listener function to remove
331
+ */
332
+ offAny(listener: GraphEventListener<GraphEvent>): void;
333
+ /**
334
+ * Subscribe to an event type, but only receive the first occurrence.
335
+ *
336
+ * @template K - The event type key
337
+ * @param eventType - The event type to listen for once
338
+ * @param listener - Callback function to invoke once
339
+ * @returns Unsubscribe function to cancel before event occurs
340
+ */
341
+ once<K extends GraphEventType>(eventType: K, listener: GraphEventListener<GraphEventMap[K]>): () => void;
342
+ /**
343
+ * Remove all listeners for all event types.
344
+ */
345
+ removeAllListeners(): void;
346
+ /**
347
+ * Get the count of listeners for a specific event type.
348
+ *
349
+ * @param eventType - The event type to count listeners for
350
+ * @returns Number of listeners registered
351
+ */
352
+ listenerCount(eventType?: GraphEventType): number;
353
+ /**
354
+ * Emit an event to all registered listeners.
355
+ *
356
+ * @param event - The event to emit
357
+ */
358
+ emit(event: GraphEvent): void;
359
+ /**
360
+ * Emit an entity:created event.
361
+ *
362
+ * @param entity - The entity that was created
363
+ */
364
+ emitEntityCreated(entity: Entity): void;
365
+ /**
366
+ * Emit an entity:updated event.
367
+ *
368
+ * @param entityName - Name of the updated entity
369
+ * @param changes - The changes that were applied
370
+ * @param previousValues - Optional previous values before update
371
+ */
372
+ emitEntityUpdated(entityName: string, changes: Partial<Entity>, previousValues?: Partial<Entity>): void;
373
+ /**
374
+ * Emit an entity:deleted event.
375
+ *
376
+ * @param entityName - Name of the deleted entity
377
+ * @param entity - Optional entity data before deletion
378
+ */
379
+ emitEntityDeleted(entityName: string, entity?: Entity): void;
380
+ /**
381
+ * Emit an entity:renamed event.
382
+ *
383
+ * Note: `EntityManager.renameEntity` also emits `entity:deleted` (old
384
+ * name) + `entity:created` (renamed entity) immediately after this event
385
+ * so create/delete-only derived views stay consistent.
386
+ *
387
+ * @param oldName - Entity name before the rename
388
+ * @param newName - Entity name after the rename
389
+ * @param entity - The renamed entity (name === newName)
390
+ */
391
+ emitEntityRenamed(oldName: string, newName: string, entity: Entity): void;
392
+ /**
393
+ * Emit a relation:created event.
394
+ *
395
+ * @param relation - The relation that was created
396
+ */
397
+ emitRelationCreated(relation: Relation): void;
398
+ /**
399
+ * Emit a relation:deleted event.
400
+ *
401
+ * @param from - Source entity name
402
+ * @param to - Target entity name
403
+ * @param relationType - Type of the deleted relation
404
+ */
405
+ emitRelationDeleted(from: string, to: string, relationType: string): void;
406
+ /**
407
+ * Emit an observation:added event.
408
+ *
409
+ * @param entityName - Name of the entity
410
+ * @param observations - Observations that were added
411
+ */
412
+ emitObservationAdded(entityName: string, observations: string[]): void;
413
+ /**
414
+ * Emit an observation:deleted event.
415
+ *
416
+ * @param entityName - Name of the entity
417
+ * @param observations - Observations that were deleted
418
+ */
419
+ emitObservationDeleted(entityName: string, observations: string[]): void;
420
+ /**
421
+ * Emit a graph:saved event.
422
+ *
423
+ * @param entityCount - Number of entities in the saved graph
424
+ * @param relationCount - Number of relations in the saved graph
425
+ */
426
+ emitGraphSaved(entityCount: number, relationCount: number): void;
427
+ /**
428
+ * Emit a graph:loaded event.
429
+ *
430
+ * @param entityCount - Number of entities in the loaded graph
431
+ * @param relationCount - Number of relations in the loaded graph
432
+ */
433
+ emitGraphLoaded(entityCount: number, relationCount: number): void;
434
+ /**
435
+ * Safely invoke a listener, optionally catching errors. Listener is
436
+ * typed `<any>` to match the heterogeneous storage in `this.listeners`
437
+ * (see field-level comment).
438
+ * @private
439
+ */
440
+ private invokeListener;
441
+ }
442
+
224
443
  /**
225
444
  * Task Scheduler
226
445
  *
@@ -358,13 +577,10 @@ declare class TaskQueue {
358
577
  private queue;
359
578
  private running;
360
579
  private completed;
361
- private pool;
362
580
  private concurrency;
363
- private defaultTimeout;
364
581
  private isProcessing;
365
582
  private totalExecutionTime;
366
583
  private totalProcessed;
367
- private useWorkerPool;
368
584
  private static readonly MAX_COMPLETED;
369
585
  private static readonly MAX_QUEUE;
370
586
  constructor(options?: {
@@ -372,10 +588,6 @@ declare class TaskQueue {
372
588
  timeout?: number;
373
589
  useWorkerPool?: boolean;
374
590
  });
375
- /**
376
- * Get or create the worker pool.
377
- */
378
- private getPool;
379
591
  /**
380
592
  * Add a task to the queue.
381
593
  *
@@ -571,6 +783,14 @@ declare const ENTITY_STATUS_TRANSITIONS: ReadonlyArray<readonly [EntityStatus, E
571
783
  interface Entity {
572
784
  /** Unique name identifying the entity */
573
785
  name: string;
786
+ /**
787
+ * Stable opaque identifier (UUID), assigned at creation by
788
+ * `EntityManager.createEntities` and preserved across renames
789
+ * (`renameEntity` never touches it). NOT yet used as a reference key —
790
+ * `name` remains the public primary key; `id` is forward-compat
791
+ * infrastructure for v2 stable-id references.
792
+ */
793
+ id?: string;
574
794
  /** Type/category of the entity (e.g., "person", "project", "concept") */
575
795
  entityType: string;
576
796
  /** Array of observation strings describing facts about the entity */
@@ -1628,6 +1848,40 @@ interface IGraphStorage {
1628
1848
  * @returns Promise resolving to true if found and updated
1629
1849
  */
1630
1850
  updateEntity(entityName: string, updates: Partial<Entity>): Promise<boolean>;
1851
+ /**
1852
+ * Atomically rename an entity, rewriting every stored reference to the
1853
+ * old name: `Relation.from`/`Relation.to`, other entities' `parentId`,
1854
+ * and the version-chain fields (`parentEntityName`, `rootEntityName`,
1855
+ * `supersededBy`). The entity's `id`, `createdAt`, and all other fields
1856
+ * are preserved; `lastModified` is updated.
1857
+ *
1858
+ * OPTIONAL member: kept optional so pre-existing third-party / test
1859
+ * implementations of this interface remain valid without changes.
1860
+ * Both first-party backends (`GraphStorage`, `SQLiteStorage`)
1861
+ * implement it; `EntityManager.renameEntity` requires it.
1862
+ *
1863
+ * @param oldName - Current entity name (must exist)
1864
+ * @param newName - New entity name (must not exist)
1865
+ * @returns Promise resolving to the renamed entity
1866
+ * @throws EntityNotFoundError if `oldName` does not exist
1867
+ * @throws DuplicateEntityError if `newName` already exists
1868
+ */
1869
+ renameEntity?(oldName: string, newName: string): Promise<Entity>;
1870
+ /**
1871
+ * Graph event emitter powering event-driven derived views (TF-IDF sync,
1872
+ * rank priors, embedding caches, columnar observation mirroring).
1873
+ *
1874
+ * OPTIONAL member: kept optional so pre-existing third-party / test
1875
+ * implementations of this interface remain valid without changes (same
1876
+ * precedent as `renameEntity`). Both first-party backends
1877
+ * (`GraphStorage`, `SQLiteStorage`) expose one; derived views no-op
1878
+ * gracefully when it is absent.
1879
+ *
1880
+ * Typed via an inline type-only import: `types.ts` is the root of the
1881
+ * module layering (zero imports), so a top-level import from core would
1882
+ * invert it; `import()` in type position is erased at compile time.
1883
+ */
1884
+ readonly events?: GraphEventEmitter;
1631
1885
  /**
1632
1886
  * Compact the storage by removing duplicates.
1633
1887
  *
@@ -2152,7 +2406,7 @@ interface BatchOptions {
2152
2406
  *
2153
2407
  * Used by GraphEventEmitter to categorize graph changes.
2154
2408
  */
2155
- type GraphEventType = 'entity:created' | 'entity:updated' | 'entity:deleted' | 'relation:created' | 'relation:deleted' | 'observation:added' | 'observation:deleted' | 'graph:saved' | 'graph:loaded';
2409
+ type GraphEventType = 'entity:created' | 'entity:updated' | 'entity:deleted' | 'entity:renamed' | 'relation:created' | 'relation:deleted' | 'observation:added' | 'observation:deleted' | 'graph:saved' | 'graph:loaded';
2156
2410
  /**
2157
2411
  * Phase 10 Sprint 2: Base interface for all graph events.
2158
2412
  *
@@ -2210,6 +2464,30 @@ interface EntityDeletedEvent extends GraphEventBase {
2210
2464
  entityName: string;
2211
2465
  entity?: Entity;
2212
2466
  }
2467
+ /**
2468
+ * Event emitted when an entity is renamed via `renameEntity`.
2469
+ *
2470
+ * Note for listeners: a rename ALSO emits `entity:deleted` (for the old
2471
+ * name) followed by `entity:created` (for the renamed entity) so derived
2472
+ * views that only understand create/delete (TF-IDF sync, rank priors,
2473
+ * embedding caches) stay consistent without learning this event. Listeners
2474
+ * therefore observe the sequence: `entity:renamed`, `entity:deleted`,
2475
+ * `entity:created`.
2476
+ *
2477
+ * @example
2478
+ * ```typescript
2479
+ * emitter.on('entity:renamed', (event) => {
2480
+ * console.log(`${event.oldName} -> ${event.newName}`);
2481
+ * });
2482
+ * ```
2483
+ */
2484
+ interface EntityRenamedEvent extends GraphEventBase {
2485
+ type: 'entity:renamed';
2486
+ oldName: string;
2487
+ newName: string;
2488
+ /** The entity after the rename (name === newName). */
2489
+ entity: Entity;
2490
+ }
2213
2491
  /**
2214
2492
  * Phase 10 Sprint 2: Event emitted when a relation is created.
2215
2493
  *
@@ -2305,7 +2583,7 @@ interface GraphLoadedEvent extends GraphEventBase {
2305
2583
  *
2306
2584
  * Use this when handling any type of graph event.
2307
2585
  */
2308
- type GraphEvent = EntityCreatedEvent | EntityUpdatedEvent | EntityDeletedEvent | RelationCreatedEvent | RelationDeletedEvent | ObservationAddedEvent | ObservationDeletedEvent | GraphSavedEvent | GraphLoadedEvent;
2586
+ type GraphEvent = EntityCreatedEvent | EntityUpdatedEvent | EntityDeletedEvent | EntityRenamedEvent | RelationCreatedEvent | RelationDeletedEvent | ObservationAddedEvent | ObservationDeletedEvent | GraphSavedEvent | GraphLoadedEvent;
2309
2587
  /**
2310
2588
  * Phase 10 Sprint 2: Listener function type for graph events.
2311
2589
  *
@@ -2321,6 +2599,7 @@ interface GraphEventMap {
2321
2599
  'entity:created': EntityCreatedEvent;
2322
2600
  'entity:updated': EntityUpdatedEvent;
2323
2601
  'entity:deleted': EntityDeletedEvent;
2602
+ 'entity:renamed': EntityRenamedEvent;
2324
2603
  'relation:created': RelationCreatedEvent;
2325
2604
  'relation:deleted': RelationDeletedEvent;
2326
2605
  'observation:added': ObservationAddedEvent;
@@ -2483,7 +2762,7 @@ interface HybridSearchResult {
2483
2762
  symbolic: number;
2484
2763
  combined: number;
2485
2764
  };
2486
- matchedLayers: ('semantic' | 'lexical' | 'symbolic')[];
2765
+ matchedLayers: ('semantic' | 'lexical' | 'symbolic' | 'graph')[];
2487
2766
  }
2488
2767
  /**
2489
2768
  * An extracted entity from query analysis.
@@ -2882,6 +3161,25 @@ interface DecayEngineConfig {
2882
3161
  * Enable to make low-confidence memories decay faster in importance.
2883
3162
  */
2884
3163
  applyConfidenceToImportance?: boolean;
3164
+ /**
3165
+ * Connectivity protection strength in [0, 1] (default: 0 = off).
3166
+ * Well-connected entities decay slower:
3167
+ * `effectiveDecayFactor = decayFactor + (1 - decayFactor) × connectivityProtection × normalizedDegree`
3168
+ * where `normalizedDegree` is the entity's relation degree divided by
3169
+ * the maximum degree in the graph. At protection 1 a max-degree entity
3170
+ * does not decay at all; at 0 behavior is unchanged. Values outside
3171
+ * [0, 1] are clamped. Applies only to the legacy
3172
+ * `calculateEffectiveImportance` path, never to
3173
+ * `calculatePrdEffectiveImportance`.
3174
+ *
3175
+ * Because `calculateEffectiveImportance` is synchronous, degrees are
3176
+ * read from a cached snapshot that is refreshed by the batch
3177
+ * operations (`applyDecay`, `getDecayedMemories`, `getMemoriesAtRisk`,
3178
+ * `forgetWeakMemories`) or explicitly via
3179
+ * `refreshConnectivitySnapshot()`. Before the first refresh no
3180
+ * protection is applied.
3181
+ */
3182
+ connectivityProtection?: number;
2885
3183
  /**
2886
3184
  * PRD `decay_rate`: exponential decay rate per second for the recency
2887
3185
  * term in `calculatePrdEffectiveImportance`. When absent, derived from
@@ -2952,6 +3250,8 @@ declare class DecayEngine {
2952
3250
  private readonly accessTracker;
2953
3251
  private readonly config;
2954
3252
  private readonly freshnessManager;
3253
+ /** Degree snapshot for connectivity protection (see refreshConnectivitySnapshot). */
3254
+ private _connectivityDegrees;
2955
3255
  constructor(storage: IGraphStorage, accessTracker: AccessTracker, config?: DecayEngineConfig);
2956
3256
  /**
2957
3257
  * Calculate decay factor based on time since last access.
@@ -3000,7 +3300,9 @@ declare class DecayEngine {
3000
3300
  * Formula: base_importance * decay_factor * strength_multiplier * confidence_factor
3001
3301
  *
3002
3302
  * - base_importance: Entity's stated importance (0-10)
3003
- * - decay_factor: Time-based decay (0-1), accelerated for past-TTL entities
3303
+ * - decay_factor: Time-based decay (0-1), accelerated for past-TTL entities;
3304
+ * when `connectivityProtection` > 0 and a degree snapshot is available,
3305
+ * lifted toward 1 for well-connected entities (see DecayEngineConfig)
3004
3306
  * - strength_multiplier: Boost from confirmations and accesses
3005
3307
  * - confidence_factor: Decayed confidence based on entity age
3006
3308
  *
@@ -3027,6 +3329,23 @@ declare class DecayEngine {
3027
3329
  * Exposed for callers that need freshness calculations alongside decay.
3028
3330
  */
3029
3331
  getFreshnessManager(): FreshnessManager;
3332
+ /**
3333
+ * Refresh the degree snapshot used for connectivity protection.
3334
+ *
3335
+ * `calculateEffectiveImportance` is synchronous, so it reads entity
3336
+ * degrees from this cached snapshot. The batch operations
3337
+ * (`applyDecay`, `getDecayedMemories`, `getMemoriesAtRisk`,
3338
+ * `forgetWeakMemories`) refresh it automatically from the graph they
3339
+ * already load; call this method directly before ad-hoc single-entity
3340
+ * scoring when relations may have changed. No-op cost when
3341
+ * `connectivityProtection` is 0 apart from the graph load.
3342
+ */
3343
+ refreshConnectivitySnapshot(): Promise<void>;
3344
+ /**
3345
+ * Refresh the degree snapshot from an already-loaded graph.
3346
+ * Skipped entirely when connectivity protection is disabled.
3347
+ */
3348
+ private maybeRefreshConnectivity;
3030
3349
  /**
3031
3350
  * Calculate effective importance using the Context Engine PRD formula.
3032
3351
  *
@@ -3173,6 +3492,13 @@ interface SalienceEngineConfig {
3173
3492
  * The freshness factor is subtracted from the final score proportionally.
3174
3493
  */
3175
3494
  freshnessWeight?: number;
3495
+ /**
3496
+ * Weight for graph connectivity boost (default: 0 = disabled).
3497
+ * The connectivity signal is an entity's relation degree normalized
3498
+ * by the maximum degree in the graph, in [0, 1]. With the default
3499
+ * weight of 0 the signal is never computed and scores are unchanged.
3500
+ */
3501
+ connectivityWeight?: number;
3176
3502
  }
3177
3503
  /**
3178
3504
  * Calculates multi-factor salience scores for memories.
@@ -3203,6 +3529,7 @@ declare class SalienceEngine {
3203
3529
  private readonly freshnessManager;
3204
3530
  private readonly config;
3205
3531
  private _cachedMaxAccessCount;
3532
+ private _cachedDegreeMap;
3206
3533
  constructor(storage: IGraphStorage, accessTracker: AccessTracker, decayEngine: DecayEngine, config?: SalienceEngineConfig);
3207
3534
  /**
3208
3535
  * Calculate salience score for an entity in the given context.
@@ -3213,6 +3540,7 @@ declare class SalienceEngine {
3213
3540
  * - Frequency: Log-normalized access count relative to max
3214
3541
  * - Context: Text similarity to current task/session/query
3215
3542
  * - Novelty: Inverse of recency (rewards less recently accessed)
3543
+ * - Connectivity: Relation degree normalized by max degree (opt-in, weight 0 by default)
3216
3544
  *
3217
3545
  * @param entity - AgentEntity to calculate salience for
3218
3546
  * @param context - Context information for relevance scoring
@@ -3337,6 +3665,21 @@ declare class SalienceEngine {
3337
3665
  * @returns Score between 0 and 1
3338
3666
  */
3339
3667
  private calculateObservationUniqueness;
3668
+ /**
3669
+ * Calculate connectivity boost component.
3670
+ * Relation degree of the entity normalized by the maximum degree
3671
+ * in the graph. Well-connected (hub) entities score closer to 1;
3672
+ * isolated entities score 0.
3673
+ *
3674
+ * @param entity - Entity to calculate for
3675
+ * @returns Score between 0 and 1
3676
+ */
3677
+ private calculateConnectivityBoost;
3678
+ /**
3679
+ * Compute the relation degree map for the current graph.
3680
+ * Used for normalizing connectivity scores.
3681
+ */
3682
+ private getDegreeMap;
3340
3683
  /**
3341
3684
  * Get the maximum access count across all entities.
3342
3685
  * Used for normalizing frequency scores.
@@ -4651,6 +4994,12 @@ interface SalienceComponents {
4651
4994
  contextRelevance: number;
4652
4995
  /** Novelty contribution */
4653
4996
  noveltyBoost: number;
4997
+ /**
4998
+ * Graph connectivity contribution (relation degree normalized by max
4999
+ * degree). Optional for backwards compatibility; 0 when the
5000
+ * connectivity signal is disabled (connectivityWeight = 0).
5001
+ */
5002
+ connectivityBoost?: number;
4654
5003
  }
4655
5004
  /**
4656
5005
  * Entity with calculated salience score.
@@ -6059,12 +6408,185 @@ declare function createDetailedProgressReporter(total: number, callback?: Progre
6059
6408
  };
6060
6409
 
6061
6410
  /**
6062
- * Result<T, E> discriminated-union return type for operations with
6063
- * *expected* domain failures.
6411
+ * Types for the Cue–Tag–Content associative memory graph and active memory
6412
+ * reconstruction, implementing the MRAgent design from
6413
+ * "Memory is Reconstructed, Not Retrieved: Graph Memory for LLM Agents"
6414
+ * (Ji, Li & Hooi, ICML 2026).
6064
6415
  *
6065
- * Per the MemoryJS error-handling policy (see CONTRIBUTING.md > Error
6066
- * Handling):
6067
- * - **throw** for programmer errorsbad arguments, invariant violations,
6416
+ * The memory system is modelled as a heterogeneous graph `M = (C, V, R)`:
6417
+ * - Cues `c ∈ C` — fine-grained keywords (entities, attributes, descriptors)
6418
+ * - Contents `v V`memory items, organised into multi-granular layers
6419
+ * - Relations `R ⊆ C × G × V` — typed `(cue, tag, content)` triples where the
6420
+ * associative **tag** `g ∈ G` is the semantic bridge between cue and content.
6421
+ *
6422
+ * @module types/reconstruction
6423
+ * @experimental
6424
+ */
6425
+ /**
6426
+ * Multi-granular memory layers (paper §3.2).
6427
+ *
6428
+ * - `episodic` — event-specific units grounded in a particular time/context.
6429
+ * - `semantic` — stable knowledge (attributes, preferences, facts) anchored to
6430
+ * an entity-level cue via an aspect-level tag.
6431
+ * - `topic` — higher-level abstractions summarising recurring patterns across a
6432
+ * coherent set of episodes.
6433
+ */
6434
+ type ContentLayer = 'episodic' | 'semantic' | 'topic';
6435
+ /** A fine-grained retrieval cue (entity, attribute, or salient descriptor). */
6436
+ interface CueNode {
6437
+ /** Stable identifier (normalised cue text). */
6438
+ id: string;
6439
+ /** Human-readable cue surface form. */
6440
+ text: string;
6441
+ }
6442
+ /**
6443
+ * An associative tag — a short phrase summarising the relational pattern that
6444
+ * links a cue to memory content. Tags are the controllable intermediate that
6445
+ * lets the agent prune traversal branches before touching expensive content.
6446
+ */
6447
+ interface TagNode {
6448
+ /** Stable identifier (normalised tag text). */
6449
+ id: string;
6450
+ /** Human-readable tag surface form (≤ ~2 words). */
6451
+ text: string;
6452
+ }
6453
+ /** A memory content node — an episode, a semantic fact, or a topic abstraction. */
6454
+ interface ContentNode {
6455
+ /** Stable identifier (e.g. `e1`, `s2`, `t3`). */
6456
+ id: string;
6457
+ /** Which multi-granular layer this content belongs to. */
6458
+ layer: ContentLayer;
6459
+ /** The content text (episode description, fact, or topic summary). */
6460
+ text: string;
6461
+ /** ISO `YYYY-MM-DD` conversation timestamp (episodic layer). */
6462
+ timestamp?: string;
6463
+ /** Topic ids this episode belongs to (episodic → topic links). */
6464
+ topicIds?: string[];
6465
+ /** Entity-level anchor for semantic content (the person/subject the fact is about). */
6466
+ person?: string;
6467
+ /** Free-form provenance (e.g. originating dialogue id). */
6468
+ origin?: string;
6469
+ /**
6470
+ * Name of the persisted MemoryJS entity backing this content node, set when the
6471
+ * graph is bridged to the live store (episodic→`EpisodicMemoryManager` timeline,
6472
+ * semantic→entity/observation graph, topic→topic entity). Absent when running
6473
+ * the self-contained in-memory graph.
6474
+ */
6475
+ entityName?: string;
6476
+ }
6477
+ /** A `(cue, tag, content)` association — one edge of the relation set `R`. */
6478
+ interface CTCTriple {
6479
+ /** Cue id. */
6480
+ cue: string;
6481
+ /** Tag id. */
6482
+ tag: string;
6483
+ /** Content id. */
6484
+ content: string;
6485
+ }
6486
+ /** Serialisable snapshot of a {@link CueTagContentGraph}. */
6487
+ interface CTCGraphSnapshot {
6488
+ cues: CueNode[];
6489
+ tags: TagNode[];
6490
+ contents: ContentNode[];
6491
+ triples: CTCTriple[];
6492
+ }
6493
+ /** A single processed/rewritten dialogue sentence produced by distillation. */
6494
+ interface DistilledSentence {
6495
+ /** Sentence id (e.g. `D1:1-1`). */
6496
+ id: string;
6497
+ /** Rewritten, self-contained text (pronouns resolved, time normalised). */
6498
+ text: string;
6499
+ /** Short associative tag (≤ ~2 words). */
6500
+ tag: string;
6501
+ /** Originating raw sentence id. */
6502
+ origin?: string;
6503
+ /** Topic ids this sentence belongs to. */
6504
+ topics?: string[];
6505
+ /** ISO `YYYY-MM-DD` timestamp. */
6506
+ time?: string;
6507
+ }
6508
+ /** A person-anchored semantic fact extracted during distillation. */
6509
+ interface PersonalFact {
6510
+ /** Fact id (e.g. `p1`). */
6511
+ id: string;
6512
+ /** Normalised fact text. */
6513
+ text: string;
6514
+ /** Aspect-level tag (e.g. `preference`, `occupation`). */
6515
+ tag: string;
6516
+ /** The person/entity the fact is about. */
6517
+ person: string;
6518
+ /** Originating raw sentence id. */
6519
+ origin?: string;
6520
+ }
6521
+ /** Result of running the LLM distillation pipeline over a dialogue. */
6522
+ interface DistillationResult$1 {
6523
+ /** Conversation reference date (ISO `YYYY-MM-DD`). */
6524
+ conversationTime?: string;
6525
+ /** Rewritten episodic sentences. */
6526
+ sentences: DistilledSentence[];
6527
+ /** topic-id → topic description. */
6528
+ topics: Record<string, string>;
6529
+ /** Extracted person-anchored semantic facts. */
6530
+ personalFacts: PersonalFact[];
6531
+ /** sentence-id → extracted cue surface forms. */
6532
+ keywords: Record<string, string[]>;
6533
+ }
6534
+ /** Raw dialogue input accepted by the distiller. */
6535
+ interface DialogueTurn {
6536
+ /** Stable id for the turn (e.g. `D1:1`). */
6537
+ id: string;
6538
+ /** Speaker name, if known. */
6539
+ speaker?: string;
6540
+ /** Raw utterance text. */
6541
+ text: string;
6542
+ /** ISO timestamp for the turn, if known. */
6543
+ timestamp?: string;
6544
+ }
6545
+ /** A traversal action the agent may take over the memory graph (paper §4.1). */
6546
+ type TraversalActionType = 'cue->tag' | 'cuetag->content' | 'content->cuetag' | 'topic->episode';
6547
+ /** One executed traversal action and the candidates it produced. */
6548
+ interface TraversalStep {
6549
+ /** 0-based reconstruction step index. */
6550
+ step: number;
6551
+ /** The action(s) the policy selected this step. */
6552
+ actions: TraversalActionType[];
6553
+ /** Content nodes routed into the reconstructed context this step. */
6554
+ routed: ContentNode[];
6555
+ /** Short rationale for the step (policy- or LLM-supplied). */
6556
+ rationale?: string;
6557
+ }
6558
+ /** Final output of an active reconstruction run (Algorithm 1). */
6559
+ interface ReconstructionResult {
6560
+ /** The query that was reconstructed against. */
6561
+ query: string;
6562
+ /** Final answer, when an answering policy is supplied. */
6563
+ answer?: string;
6564
+ /** Confidence in `[0, 1]`, when available. */
6565
+ confidence?: number;
6566
+ /** Accumulated evidence (the reconstructed context `H`). */
6567
+ evidence: ContentNode[];
6568
+ /** The step-by-step traversal trajectory. */
6569
+ trajectory: TraversalStep[];
6570
+ /** Whether the loop stopped on a satisfied stopping condition (vs. budget). */
6571
+ stoppedEarly: boolean;
6572
+ }
6573
+ /** Tunables for the reconstruction loop. */
6574
+ interface ReconstructionOptions {
6575
+ /** Max reasoning turns `T` (paper caps at 8). Default 8. */
6576
+ maxSteps?: number;
6577
+ /** Max content nodes routed per step (per-turn retrieval budget `K`). Default 10. */
6578
+ perStepBudget?: number;
6579
+ /** Stop once this many distinct evidence items are accumulated. Default 12. */
6580
+ evidenceTarget?: number;
6581
+ }
6582
+
6583
+ /**
6584
+ * Result<T, E> — discriminated-union return type for operations with
6585
+ * *expected* domain failures.
6586
+ *
6587
+ * Per the MemoryJS error-handling policy (see CONTRIBUTING.md > Error
6588
+ * Handling):
6589
+ * - **throw** for programmer errors — bad arguments, invariant violations,
6068
6590
  * "this should never happen" states;
6069
6591
  * - **return `Result<T, E>`** for expected, recoverable failures the caller
6070
6592
  * is meant to branch on (not found, validation failed, conflict, ...);
@@ -6970,6 +7492,18 @@ declare function levenshteinDistance(str1: string, str2: string): number;
6970
7492
  * @returns Term frequency (0.0 to 1.0)
6971
7493
  */
6972
7494
  declare function calculateTF(term: string, document: string): number;
7495
+ /**
7496
+ * Calculate Term Frequency (TF) from pre-tokenized documents.
7497
+ *
7498
+ * TF = (Number of times term appears in document) / (Total terms in document)
7499
+ *
7500
+ * **Optimized**: Avoids re-tokenizing the document text for each term.
7501
+ *
7502
+ * @param term - The search term (should already be lowercase if possible)
7503
+ * @param tokens - Pre-tokenized lowercase tokens for the document
7504
+ * @returns Term frequency (0.0 to 1.0)
7505
+ */
7506
+ declare function calculateTFFromTokens(term: string, tokens: string[]): number;
6973
7507
  /**
6974
7508
  * Calculate Inverse Document Frequency (IDF) for a term across documents.
6975
7509
  *
@@ -7206,6 +7740,7 @@ declare function cleanupAllCaches(): void;
7206
7740
  * Used for validating full entity objects including timestamps.
7207
7741
  */
7208
7742
  declare const EntitySchema: z.ZodObject<{
7743
+ id: z.ZodOptional<z.ZodString>;
7209
7744
  name: z.ZodString;
7210
7745
  entityType: z.ZodString;
7211
7746
  observations: z.ZodArray<z.ZodString>;
@@ -7222,6 +7757,7 @@ declare const EntitySchema: z.ZodObject<{
7222
7757
  * Timestamps are optional and will be auto-generated if not provided.
7223
7758
  */
7224
7759
  declare const CreateEntitySchema: z.ZodObject<{
7760
+ id: z.ZodOptional<z.ZodString>;
7225
7761
  name: z.ZodString;
7226
7762
  entityType: z.ZodString;
7227
7763
  observations: z.ZodArray<z.ZodString>;
@@ -7348,6 +7884,7 @@ declare const ExportFormatSchema: z.ZodEnum<{
7348
7884
  * Empty arrays are allowed (no-op).
7349
7885
  */
7350
7886
  declare const BatchCreateEntitiesSchema: z.ZodArray<z.ZodObject<{
7887
+ id: z.ZodOptional<z.ZodString>;
7351
7888
  name: z.ZodString;
7352
7889
  entityType: z.ZodString;
7353
7890
  observations: z.ZodArray<z.ZodString>;
@@ -7636,6 +8173,10 @@ declare function validateRelation(relation: unknown): ValidationResult$1;
7636
8173
  declare function validateImportance(importance: number): boolean;
7637
8174
  /** Validate an array of tags. */
7638
8175
  declare function validateTags(tags: unknown): ValidationResult$1;
8176
+ /** Validate a non-empty string with detailed error reporting. */
8177
+ declare function validateNonEmpty(value: unknown, fieldName: string, contextName?: string): void;
8178
+ /** Validate a non-empty array with detailed error reporting. */
8179
+ declare function validateNonEmptyArray(value: unknown, fieldName: string, contextName?: string): void;
7639
8180
 
7640
8181
  /**
7641
8182
  * Response and Pagination Formatters
@@ -8167,16 +8708,15 @@ declare function ensureMemoryFilePath(): Promise<string>;
8167
8708
  /**
8168
8709
  * Parallel Utilities
8169
8710
  *
8170
- * Utilities for parallel array operations using workerpool.
8711
+ * Utilities for parallel array operations.
8171
8712
  * Phase 8 Sprint 3: Parallel array operations for improved performance.
8172
8713
  *
8173
- * **SECURITY WARNING:** These functions use `new Function()` internally for worker serialization.
8174
- * The `fn` parameter MUST be a real function object, never a user-provided string.
8175
- * Runtime validation ensures only function objects are accepted.
8714
+ * Note: Actual multiprocessing capabilities have been removed for security reasons
8715
+ * (preventing dynamic function execution) and to use the unified WorkerTaskManager.
8716
+ * These utilities now execute sequentially but asynchronously via Promise.all.
8176
8717
  *
8177
8718
  * @module utils/parallelUtils
8178
8719
  */
8179
-
8180
8720
  /**
8181
8721
  * Shutdown the shared worker pool and clean up resources.
8182
8722
  * Should be called when parallel utilities are no longer needed.
@@ -8207,7 +8747,7 @@ declare function shutdownParallelUtils(): Promise<void>;
8207
8747
  * // Result: [1, 4, 9, 16, 25]
8208
8748
  * ```
8209
8749
  */
8210
- declare function parallelMap<T, R>(items: T[], fn: (item: T) => R, chunkSize?: number): Promise<R[]>;
8750
+ declare function parallelMap<T, R>(items: T[], fn: (item: T) => R | Promise<R>, _chunkSize?: number): Promise<R[]>;
8211
8751
  /**
8212
8752
  * Filter items in parallel using workerpool.
8213
8753
  *
@@ -8232,13 +8772,19 @@ declare function parallelMap<T, R>(items: T[], fn: (item: T) => R, chunkSize?: n
8232
8772
  * // Result: [2, 4, 6]
8233
8773
  * ```
8234
8774
  */
8235
- declare function parallelFilter<T>(items: T[], predicate: (item: T) => boolean, chunkSize?: number): Promise<T[]>;
8775
+ declare function parallelFilter<T>(items: T[], predicate: (item: T) => boolean | Promise<boolean>, _chunkSize?: number): Promise<T[]>;
8236
8776
  /**
8237
8777
  * Get statistics about the worker pool.
8238
8778
  *
8239
8779
  * @returns Pool statistics or null if pool is not initialized
8240
8780
  */
8241
- declare function getPoolStats(): workerpool.PoolStats | null;
8781
+ declare function getPoolStats(): {
8782
+ totalWorkers: number;
8783
+ busyWorkers: number;
8784
+ idleWorkers: number;
8785
+ pendingTasks: number;
8786
+ activeTasks: number;
8787
+ } | null;
8242
8788
 
8243
8789
  /**
8244
8790
  * Operation Utilities
@@ -9818,213 +10364,6 @@ declare class BatchTransaction {
9818
10364
  private applyBatchOperation;
9819
10365
  }
9820
10366
 
9821
- /**
9822
- * Graph Event Emitter
9823
- *
9824
- * Phase 10 Sprint 2: Provides event-based notifications for graph changes.
9825
- * Enables loose coupling between graph operations and dependent systems
9826
- * like search indexes, analytics, and external integrations.
9827
- *
9828
- * @module core/GraphEventEmitter
9829
- */
9830
-
9831
- /**
9832
- * Phase 10 Sprint 2: Event emitter for graph change notifications.
9833
- *
9834
- * Provides a type-safe event system for subscribing to and emitting
9835
- * graph change events. Supports wildcard listeners for all events.
9836
- *
9837
- * @example
9838
- * ```typescript
9839
- * const emitter = new GraphEventEmitter();
9840
- *
9841
- * // Listen to specific event types
9842
- * emitter.on('entity:created', (event) => {
9843
- * console.log(`Entity ${event.entity.name} created`);
9844
- * });
9845
- *
9846
- * // Listen to all events
9847
- * emitter.onAny((event) => {
9848
- * console.log(`Event: ${event.type}`);
9849
- * });
9850
- *
9851
- * // Emit an event
9852
- * emitter.emitEntityCreated(entity);
9853
- *
9854
- * // Remove listener
9855
- * const unsubscribe = emitter.on('entity:deleted', handler);
9856
- * unsubscribe();
9857
- * ```
9858
- */
9859
- declare class GraphEventEmitter {
9860
- /**
9861
- * Map of event types to their registered listeners. The Set stores
9862
- * listeners typed for different specific event subtypes (one Set per
9863
- * GraphEventType key). TS can't express this dependent-key relationship
9864
- * without `any` due to function-parameter contravariance.
9865
- */
9866
- private listeners;
9867
- /**
9868
- * Listeners that receive all events regardless of type.
9869
- */
9870
- private wildcardListeners;
9871
- /**
9872
- * Whether to suppress errors from listeners (default: true).
9873
- * When true, listener errors are logged but don't stop event propagation.
9874
- */
9875
- private suppressListenerErrors;
9876
- /**
9877
- * Create a new GraphEventEmitter instance.
9878
- *
9879
- * @param options - Optional configuration
9880
- */
9881
- constructor(options?: {
9882
- suppressListenerErrors?: boolean;
9883
- });
9884
- /**
9885
- * Subscribe to a specific event type.
9886
- *
9887
- * @template K - The event type key
9888
- * @param eventType - The event type to listen for
9889
- * @param listener - Callback function to invoke when event occurs
9890
- * @returns Unsubscribe function to remove the listener
9891
- *
9892
- * @example
9893
- * ```typescript
9894
- * const unsubscribe = emitter.on('entity:created', (event) => {
9895
- * console.log(`Created: ${event.entity.name}`);
9896
- * });
9897
- *
9898
- * // Later: unsubscribe();
9899
- * ```
9900
- */
9901
- on<K extends GraphEventType>(eventType: K, listener: GraphEventListener<GraphEventMap[K]>): () => void;
9902
- /**
9903
- * Unsubscribe from a specific event type.
9904
- *
9905
- * @template K - The event type key
9906
- * @param eventType - The event type to unsubscribe from
9907
- * @param listener - The listener function to remove
9908
- */
9909
- off<K extends GraphEventType>(eventType: K, listener: GraphEventListener<GraphEventMap[K]>): void;
9910
- /**
9911
- * Subscribe to all event types.
9912
- *
9913
- * @param listener - Callback function to invoke for any event
9914
- * @returns Unsubscribe function to remove the listener
9915
- *
9916
- * @example
9917
- * ```typescript
9918
- * emitter.onAny((event) => {
9919
- * console.log(`Event: ${event.type} at ${event.timestamp}`);
9920
- * });
9921
- * ```
9922
- */
9923
- onAny(listener: GraphEventListener<GraphEvent>): () => void;
9924
- /**
9925
- * Unsubscribe from all events.
9926
- *
9927
- * @param listener - The listener function to remove
9928
- */
9929
- offAny(listener: GraphEventListener<GraphEvent>): void;
9930
- /**
9931
- * Subscribe to an event type, but only receive the first occurrence.
9932
- *
9933
- * @template K - The event type key
9934
- * @param eventType - The event type to listen for once
9935
- * @param listener - Callback function to invoke once
9936
- * @returns Unsubscribe function to cancel before event occurs
9937
- */
9938
- once<K extends GraphEventType>(eventType: K, listener: GraphEventListener<GraphEventMap[K]>): () => void;
9939
- /**
9940
- * Remove all listeners for all event types.
9941
- */
9942
- removeAllListeners(): void;
9943
- /**
9944
- * Get the count of listeners for a specific event type.
9945
- *
9946
- * @param eventType - The event type to count listeners for
9947
- * @returns Number of listeners registered
9948
- */
9949
- listenerCount(eventType?: GraphEventType): number;
9950
- /**
9951
- * Emit an event to all registered listeners.
9952
- *
9953
- * @param event - The event to emit
9954
- */
9955
- emit(event: GraphEvent): void;
9956
- /**
9957
- * Emit an entity:created event.
9958
- *
9959
- * @param entity - The entity that was created
9960
- */
9961
- emitEntityCreated(entity: Entity): void;
9962
- /**
9963
- * Emit an entity:updated event.
9964
- *
9965
- * @param entityName - Name of the updated entity
9966
- * @param changes - The changes that were applied
9967
- * @param previousValues - Optional previous values before update
9968
- */
9969
- emitEntityUpdated(entityName: string, changes: Partial<Entity>, previousValues?: Partial<Entity>): void;
9970
- /**
9971
- * Emit an entity:deleted event.
9972
- *
9973
- * @param entityName - Name of the deleted entity
9974
- * @param entity - Optional entity data before deletion
9975
- */
9976
- emitEntityDeleted(entityName: string, entity?: Entity): void;
9977
- /**
9978
- * Emit a relation:created event.
9979
- *
9980
- * @param relation - The relation that was created
9981
- */
9982
- emitRelationCreated(relation: Relation): void;
9983
- /**
9984
- * Emit a relation:deleted event.
9985
- *
9986
- * @param from - Source entity name
9987
- * @param to - Target entity name
9988
- * @param relationType - Type of the deleted relation
9989
- */
9990
- emitRelationDeleted(from: string, to: string, relationType: string): void;
9991
- /**
9992
- * Emit an observation:added event.
9993
- *
9994
- * @param entityName - Name of the entity
9995
- * @param observations - Observations that were added
9996
- */
9997
- emitObservationAdded(entityName: string, observations: string[]): void;
9998
- /**
9999
- * Emit an observation:deleted event.
10000
- *
10001
- * @param entityName - Name of the entity
10002
- * @param observations - Observations that were deleted
10003
- */
10004
- emitObservationDeleted(entityName: string, observations: string[]): void;
10005
- /**
10006
- * Emit a graph:saved event.
10007
- *
10008
- * @param entityCount - Number of entities in the saved graph
10009
- * @param relationCount - Number of relations in the saved graph
10010
- */
10011
- emitGraphSaved(entityCount: number, relationCount: number): void;
10012
- /**
10013
- * Emit a graph:loaded event.
10014
- *
10015
- * @param entityCount - Number of entities in the loaded graph
10016
- * @param relationCount - Number of relations in the loaded graph
10017
- */
10018
- emitGraphLoaded(entityCount: number, relationCount: number): void;
10019
- /**
10020
- * Safely invoke a listener, optionally catching errors. Listener is
10021
- * typed `<any>` to match the heterogeneous storage in `this.listeners`
10022
- * (see field-level comment).
10023
- * @private
10024
- */
10025
- private invokeListener;
10026
- }
10027
-
10028
10367
  /**
10029
10368
  * Graph Storage
10030
10369
  *
@@ -10355,6 +10694,41 @@ declare class GraphStorage implements IGraphStorage {
10355
10694
  * @returns Promise resolving to true if entity was found and updated, false otherwise
10356
10695
  */
10357
10696
  updateEntity(entityName: string, updates: Partial<Entity>): Promise<boolean>;
10697
+ /**
10698
+ * Atomically rename an entity, rewriting every stored reference to the
10699
+ * old name:
10700
+ * - `Relation.from` / `Relation.to`
10701
+ * - other entities' `parentId`
10702
+ * - version-chain fields on all entities (`parentEntityName`,
10703
+ * `rootEntityName`, `supersededBy`) — including self-references on
10704
+ * the renamed entity itself.
10705
+ *
10706
+ * The entity's `id`, `createdAt`, and all other fields are preserved;
10707
+ * only `lastModified` is bumped. Referencing entities/relations keep
10708
+ * their own timestamps (a rename is a pure reference rewrite, their
10709
+ * content did not change).
10710
+ *
10711
+ * Implementation: load-mutate-save via `saveGraphInternal`, which fully
10712
+ * rewrites the file and rebuilds every in-memory index (NameIndex /
10713
+ * TypeIndex / LowercaseCache / RelationIndex / ObservationIndex) — the
10714
+ * same pattern other bulk mutations use. This also makes segment mode
10715
+ * (`MEMORY_STORAGE_SEGMENT_COUNT >= 2`) correct for free: `saveAll`
10716
+ * re-routes every entity through `fnv1a32(name) % N`, so the renamed
10717
+ * entity migrates to its new owning segment atomically (manifest-based
10718
+ * multi-file commit).
10719
+ *
10720
+ * Does NOT emit entity events itself — `EntityManager.renameEntity`
10721
+ * emits `entity:renamed` + `entity:deleted` + `entity:created` after
10722
+ * the storage write succeeds. (`saveGraphInternal` still emits its
10723
+ * usual `graph:saved`.)
10724
+ *
10725
+ * @param oldName - Current entity name (must exist)
10726
+ * @param newName - New entity name (must not exist)
10727
+ * @returns The renamed entity
10728
+ * @throws {EntityNotFoundError} If `oldName` does not exist
10729
+ * @throws {DuplicateEntityError} If `newName` already exists
10730
+ */
10731
+ renameEntity(oldName: string, newName: string): Promise<Entity>;
10358
10732
  /**
10359
10733
  * Manually clear the cache.
10360
10734
  *
@@ -10657,6 +11031,15 @@ declare class SQLiteStorage implements IGraphStorage {
10657
11031
  * to protect our in-memory cache and index operations.
10658
11032
  */
10659
11033
  private mutex;
11034
+ /**
11035
+ * Application-level mutex for managers to serialize validate+mutate+save.
11036
+ * Mirrors `GraphStorage.graphMutex` — `EntityManager` / `RelationManager` /
11037
+ * `ObservationManager` acquire it around their read-modify-write cycles,
11038
+ * so it must exist on every backend those managers can be handed.
11039
+ * (Previously missing here, which made manager-level batch mutations
11040
+ * crash on the SQLite backend.)
11041
+ */
11042
+ readonly graphMutex: AsyncMutex;
10660
11043
  /**
10661
11044
  * SQLite database instance for writes and write-transaction reads.
10662
11045
  */
@@ -10727,6 +11110,14 @@ declare class SQLiteStorage implements IGraphStorage {
10727
11110
  * Maps entity name -> all relations involving that entity (both incoming and outgoing).
10728
11111
  */
10729
11112
  private bidirectionalRelationCache;
11113
+ /**
11114
+ * Event emitter for graph change notifications. Mirrors
11115
+ * `GraphStorage.eventEmitter` so event-driven derived views
11116
+ * (`TFIDFEventSync`, `GraphRankPrior`, embedding caches, the columnar
11117
+ * observation shadow store, `TransitionLedger`) work identically on the
11118
+ * SQLite backend.
11119
+ */
11120
+ private eventEmitter;
10730
11121
  /**
10731
11122
  * Validated database file path (after path traversal checks).
10732
11123
  */
@@ -10738,6 +11129,33 @@ declare class SQLiteStorage implements IGraphStorage {
10738
11129
  * @throws {FileOperationError} If path traversal is detected
10739
11130
  */
10740
11131
  constructor(dbFilePath: string);
11132
+ /**
11133
+ * Get the event emitter for subscribing to graph changes.
11134
+ *
11135
+ * Emission parity with `GraphStorage` (one-for-one at the equivalent
11136
+ * mutation points):
11137
+ * - `graph:loaded` — after `loadCache()` populates the in-memory cache
11138
+ * - `graph:saved` — after `saveGraph()` commits a full-graph write
11139
+ * - `entity:created` — `appendEntity()`
11140
+ * - `relation:created` — `appendRelation()`
11141
+ * - `entity:updated` — `updateEntity()` (with `previousValues`)
11142
+ * - rename events (`entity:renamed` → `entity:deleted` → `entity:created`)
11143
+ * are emitted by `EntityManager.renameEntity` (manager level, same as
11144
+ * the JSONL path) — `renameEntity()` here intentionally emits nothing
11145
+ * so each event fires exactly once.
11146
+ *
11147
+ * @returns GraphEventEmitter instance
11148
+ *
11149
+ * @example
11150
+ * ```typescript
11151
+ * const storage = new SQLiteStorage('/data/memory.db');
11152
+ *
11153
+ * storage.events.on('entity:created', (event) => {
11154
+ * console.log(`Entity ${event.entity.name} created`);
11155
+ * });
11156
+ * ```
11157
+ */
11158
+ get events(): GraphEventEmitter;
10741
11159
  /**
10742
11160
  * Initialize the database connection and schema.
10743
11161
  */
@@ -10851,6 +11269,43 @@ declare class SQLiteStorage implements IGraphStorage {
10851
11269
  * @returns Promise resolving to true if found and updated
10852
11270
  */
10853
11271
  updateEntity(entityName: string, updates: Partial<Entity>): Promise<boolean>;
11272
+ /**
11273
+ * Atomically rename an entity, rewriting every stored reference to the
11274
+ * old name inside a single SQLite transaction:
11275
+ * - `entities.name` (+ `lastModified` bump on the renamed row)
11276
+ * - `relations.fromEntity` / `relations.toEntity`
11277
+ * - other entities' `parentId`
11278
+ * - version-chain columns (`parentEntityName`, `rootEntityName`,
11279
+ * `supersededBy` — all native columns, not JSON fields)
11280
+ * - `embeddings.entityName` (when the embeddings table exists)
11281
+ *
11282
+ * FTS5 stays in sync automatically: the `entities_au` AFTER UPDATE
11283
+ * trigger re-indexes each touched row (delete old values / insert new).
11284
+ *
11285
+ * Foreign keys are toggled OFF around the transaction (same pattern as
11286
+ * `saveGraph`): `relations.fromEntity/toEntity` and `entities.parentId`
11287
+ * reference `entities(name)` with no ON UPDATE action, so renaming the
11288
+ * parent key first would otherwise fail the FK check mid-flight.
11289
+ *
11290
+ * Referencing rows keep their own timestamps (a rename is a pure
11291
+ * reference rewrite; their content did not change).
11292
+ *
11293
+ * Does NOT emit entity events itself — `EntityManager.renameEntity`
11294
+ * emits `entity:renamed` + `entity:deleted` + `entity:created` after
11295
+ * the storage write succeeds (same division of responsibility as the
11296
+ * JSONL path). Emitting here as well would double-fire those events.
11297
+ * Unlike `GraphStorage.renameEntity` (which routes through
11298
+ * `saveGraphInternal` and therefore also emits `graph:saved` as an
11299
+ * implementation artifact of the full-file rewrite), this targeted SQL
11300
+ * transaction emits no `graph:saved` — no full-graph write happens.
11301
+ *
11302
+ * @param oldName - Current entity name (must exist)
11303
+ * @param newName - New entity name (must not exist)
11304
+ * @returns The renamed entity
11305
+ * @throws {EntityNotFoundError} If `oldName` does not exist
11306
+ * @throws {DuplicateEntityError} If `newName` already exists
11307
+ */
11308
+ renameEntity(oldName: string, newName: string): Promise<Entity>;
10854
11309
  /**
10855
11310
  * Compact the storage (runs VACUUM to reclaim space).
10856
11311
  *
@@ -11162,6 +11617,17 @@ declare class RefIndex {
11162
11617
  * @returns Number of refs removed
11163
11618
  */
11164
11619
  purgeEntity(entityName: string): Promise<number>;
11620
+ /**
11621
+ * Remap every alias pointing at `oldName` to point at `newName`.
11622
+ * Called by `EntityManager.renameEntity` so registered refs survive
11623
+ * entity renames (the reason this index exists). Silent no-op when no
11624
+ * refs point at `oldName`.
11625
+ *
11626
+ * @param oldName - Entity name before the rename
11627
+ * @param newName - Entity name after the rename
11628
+ * @returns Number of refs remapped
11629
+ */
11630
+ renameEntity(oldName: string, newName: string): Promise<number>;
11165
11631
  /**
11166
11632
  * Batch {@link purgeEntity} — rewrites the JSONL sidecar once for the
11167
11633
  * whole set instead of once per name.
@@ -11396,6 +11862,39 @@ declare class EntityManager {
11396
11862
  * ```
11397
11863
  */
11398
11864
  getEntity(name: string, options?: GetEntityOptions): Promise<Entity | null>;
11865
+ /**
11866
+ * List all entities in the graph, optionally filtered by entity type.
11867
+ *
11868
+ * This is the public bulk-enumeration API — use it instead of reaching
11869
+ * into the storage layer (`entityManager['storage'].loadGraph()`).
11870
+ *
11871
+ * Performance: when an `entityType` filter is given, the storage layer's
11872
+ * TypeIndex fast path (`getEntitiesByType`) resolves matches in O(k) for
11873
+ * k matching entities. Without a filter the full graph is loaded — O(n)
11874
+ * in graph size — so avoid unfiltered calls in hot paths on large graphs.
11875
+ *
11876
+ * The returned array is always a fresh copy (safe to sort/mutate), but
11877
+ * the Entity objects inside are the storage layer's live references —
11878
+ * treat them as read-only, same as `getEntity` results.
11879
+ *
11880
+ * @param filter - Optional filter. `entityType` matches case-insensitively
11881
+ * (TypeIndex semantics, same as `storage.getEntitiesByType`).
11882
+ * @returns Array of matching entities (empty when nothing matches)
11883
+ *
11884
+ * @example
11885
+ * ```typescript
11886
+ * const manager = new EntityManager(storage);
11887
+ *
11888
+ * // All entities
11889
+ * const all = await manager.listEntities();
11890
+ *
11891
+ * // Only procedures (O(k) via TypeIndex)
11892
+ * const procedures = await manager.listEntities({ entityType: 'procedure' });
11893
+ * ```
11894
+ */
11895
+ listEntities(filter?: {
11896
+ entityType?: string;
11897
+ }): Promise<Entity[]>;
11399
11898
  /**
11400
11899
  * List all distinct project IDs in the graph (excluding global entities).
11401
11900
  *
@@ -11505,6 +12004,55 @@ declare class EntityManager {
11505
12004
  updateEntity(name: string, updates: Partial<Entity>, options?: {
11506
12005
  expectedVersion?: number;
11507
12006
  }): Promise<Entity>;
12007
+ /**
12008
+ * Rename an entity, atomically rewriting every core-graph reference to
12009
+ * the old name.
12010
+ *
12011
+ * Delegates to the storage-level `renameEntity` primitive (implemented
12012
+ * by both `GraphStorage` and `SQLiteStorage`), which rewrites:
12013
+ * - `Relation.from` / `Relation.to`
12014
+ * - other entities' `parentId`
12015
+ * - version-chain fields (`parentEntityName`, `rootEntityName`,
12016
+ * `supersededBy`)
12017
+ *
12018
+ * The entity's `id`, `createdAt`, and all other fields are preserved;
12019
+ * `lastModified` is bumped. Registered `RefIndex` aliases pointing at
12020
+ * the old name are remapped to the new name (when a RefIndex is
12021
+ * configured via `setRefIndex` — `ManagerContext` wires this
12022
+ * automatically).
12023
+ *
12024
+ * **Events**: on backends with an event emitter (JSONL `GraphStorage`),
12025
+ * emits a typed `entity:renamed` event, followed by `entity:deleted`
12026
+ * (old name) and `entity:created` (renamed entity) so create/delete-only
12027
+ * derived views (TF-IDF event sync, rank priors, embedding caches) stay
12028
+ * consistent without learning the new event type. Listeners therefore
12029
+ * observe: `entity:renamed`, `entity:deleted`, `entity:created`.
12030
+ * Both first-party backends expose an emitter (`storage.events`), so
12031
+ * this sequence fires on JSONL and SQLite alike; the guard below only
12032
+ * protects third-party storage implementations without one.
12033
+ *
12034
+ * **Known limitations (intentionally out of scope)**:
12035
+ * - Archived snapshots (`ArchiveManager` compressed archives) keep the
12036
+ * old name — they are point-in-time exports, not live references.
12037
+ * - The audit log is immutable by design; historical records keep the
12038
+ * old name.
12039
+ * - Agent-memory soft references stored inside `agentMetadata` blobs or
12040
+ * observation text (e.g. `promotedFrom`, `previousSessionId`,
12041
+ * free-text mentions) are not rewritten.
12042
+ * - JSONL-backend vector-store sidecars are not rewritten; the emitted
12043
+ * delete+create events let embedding caches re-index the new name.
12044
+ *
12045
+ * @param oldName - Current entity name (must exist)
12046
+ * @param newName - New entity name (must not exist; must pass the same
12047
+ * validation as `createEntities`, including the reserved `profile-` /
12048
+ * `diary-` namespace rules)
12049
+ * @returns The renamed entity
12050
+ * @throws {ValidationError} If `newName` fails name validation or
12051
+ * violates a reserved namespace
12052
+ * @throws {EntityNotFoundError} If `oldName` does not exist
12053
+ * @throws {DuplicateEntityError} If `newName` already exists
12054
+ */
12055
+ renameEntity(oldName: string, newName: string): Promise<Entity>;
11508
12056
  /**
11509
12057
  * Update multiple entities in a single batch operation.
11510
12058
  *
@@ -14359,6 +14907,137 @@ declare class BasicSearch {
14359
14907
  searchByDateRange(startDate?: string, endDate?: string, entityType?: string, tags?: string[], offset?: number, limit?: number): Promise<KnowledgeGraph>;
14360
14908
  }
14361
14909
 
14910
+ /**
14911
+ * Graph Rank Prior
14912
+ *
14913
+ * Cached graph-connectivity signal provider for search ranking. Exposes
14914
+ * PageRank and degree centrality as ranking priors so that well-connected
14915
+ * entities can be boosted over isolated ones. The full-graph computation is
14916
+ * cached and lazily invalidated on graph mutation via GraphEventEmitter
14917
+ * subscription (entity created/updated/deleted, relation created/deleted,
14918
+ * and graph saved — the latter covers manager-level batch mutations like
14919
+ * `EntityManager.createEntities` / `RelationManager.createRelations`,
14920
+ * which persist via `storage.saveGraph` and emit only `graph:saved`) —
14921
+ * recomputation happens on next access, not eagerly per event.
14922
+ *
14923
+ * Cost guard: when the graph exceeds `maxPageRankEntities` (default 50 000),
14924
+ * PageRank is skipped and the normalized signal falls back to degree
14925
+ * centrality, which is a single O(V + E) pass.
14926
+ *
14927
+ * @module search/GraphRankPrior
14928
+ * @experimental
14929
+ */
14930
+
14931
+ /**
14932
+ * Options for {@link GraphRankPrior}.
14933
+ */
14934
+ interface GraphRankPriorOptions {
14935
+ /**
14936
+ * Entity-count threshold above which the PageRank computation is skipped
14937
+ * and the normalized connectivity signal falls back to degree centrality.
14938
+ * Default: 50 000.
14939
+ */
14940
+ maxPageRankEntities?: number;
14941
+ /** PageRank damping factor (default: 0.85). */
14942
+ dampingFactor?: number;
14943
+ /**
14944
+ * Event emitter to subscribe to for cache invalidation. When provided,
14945
+ * entity:created/updated/deleted, relation:created/deleted, and
14946
+ * graph:saved events mark the cached scores stale (lazy recompute on
14947
+ * next access). graph:saved matters because manager-level batch
14948
+ * mutations (create/delete entities and relations) persist via a full
14949
+ * `saveGraph` and emit no per-item events.
14950
+ */
14951
+ events?: GraphEventEmitter;
14952
+ }
14953
+ /** Default entity-count threshold for skipping PageRank. */
14954
+ declare const DEFAULT_MAX_PAGERANK_ENTITIES = 50000;
14955
+ /**
14956
+ * Provides cached graph-connectivity ranking signals (PageRank + degree).
14957
+ *
14958
+ * @example
14959
+ * ```typescript
14960
+ * const prior = new GraphRankPrior(ctx.graphTraversal, { events: storage.events });
14961
+ * const scores = await prior.getScores(['Alice', 'Bob']); // normalized [0, 1]
14962
+ * prior.dispose(); // unsubscribe from events when done
14963
+ * ```
14964
+ */
14965
+ declare class GraphRankPrior {
14966
+ private readonly traversal;
14967
+ private readonly maxPageRankEntities;
14968
+ private readonly dampingFactor;
14969
+ /** Cached scores, or null when stale/uncomputed. */
14970
+ private cache;
14971
+ /** In-flight computation, deduplicating concurrent accesses. */
14972
+ private pending;
14973
+ private unsubscribers;
14974
+ /**
14975
+ * Create a new GraphRankPrior.
14976
+ *
14977
+ * @param source - A GraphTraversal instance (preferred — reuses its
14978
+ * PageRank/degree implementations) or a GraphStorage, which is wrapped
14979
+ * in a private GraphTraversal.
14980
+ * @param options - Threshold, damping, and event-subscription options
14981
+ */
14982
+ constructor(source: GraphTraversal | GraphStorage, options?: GraphRankPriorOptions);
14983
+ /**
14984
+ * Get the raw PageRank score for an entity.
14985
+ *
14986
+ * Returns 0 for unknown entities, and 0 for all entities when the graph
14987
+ * exceeded `maxPageRankEntities` (degree-only fallback — use
14988
+ * {@link getScores} for the fallback-aware normalized signal).
14989
+ */
14990
+ getPageRank(entityName: string): Promise<number>;
14991
+ /**
14992
+ * Get the raw degree (incident relation count, both directions) for an
14993
+ * entity. Returns 0 for unknown entities.
14994
+ */
14995
+ getDegree(entityName: string): Promise<number>;
14996
+ /**
14997
+ * Get min-max-normalized connectivity scores (in [0, 1], normalized over
14998
+ * the whole graph) for the given entity names. Uses PageRank when the
14999
+ * graph is within `maxPageRankEntities`, degree centrality otherwise.
15000
+ * Unknown entities map to 0.
15001
+ */
15002
+ getScores(names: string[]): Promise<Map<string, number>>;
15003
+ /**
15004
+ * Get the unique one-hop neighbor names of an entity (both directions).
15005
+ * Reads the live relation index — not part of the cached computation.
15006
+ */
15007
+ neighbors(entityName: string): string[];
15008
+ /**
15009
+ * Whether the last computed signal used the degree-only fallback
15010
+ * (graph exceeded `maxPageRankEntities`). Undefined before first compute.
15011
+ */
15012
+ isDegreeFallback(): boolean | undefined;
15013
+ /**
15014
+ * Mark the cached scores stale. The next access recomputes lazily.
15015
+ */
15016
+ invalidate(): void;
15017
+ /**
15018
+ * Unsubscribe from all graph events and drop cached scores. The instance
15019
+ * remains usable (scores recompute on demand) but no longer auto-invalidates.
15020
+ */
15021
+ dispose(): void;
15022
+ /**
15023
+ * Return the cached scores, computing them if stale. Concurrent callers
15024
+ * share a single in-flight computation.
15025
+ * @internal
15026
+ */
15027
+ private ensureComputed;
15028
+ /**
15029
+ * Run the full-graph connectivity computation.
15030
+ * @internal
15031
+ */
15032
+ private compute;
15033
+ /**
15034
+ * Min-max normalize scores to [0, 1]. All-equal non-zero scores map to 1;
15035
+ * all-zero scores stay 0 (mirrors HybridScorer.minMaxNormalize semantics).
15036
+ * @internal
15037
+ */
15038
+ private minMaxNormalize;
15039
+ }
15040
+
14362
15041
  /**
14363
15042
  * Ranked Search
14364
15043
  *
@@ -14373,6 +15052,12 @@ declare class BasicSearch {
14373
15052
  declare class RankedSearch {
14374
15053
  private storage;
14375
15054
  private indexManager;
15055
+ /**
15056
+ * Optional graph-connectivity prior. When set with a positive boost, final
15057
+ * scores are multiplied by `(1 + boost * normalizedPageRank)`. Default off.
15058
+ */
15059
+ private graphPrior;
15060
+ private graphBoost;
14376
15061
  /**
14377
15062
  * Phase 4 Sprint 2: Fallback token cache for entities.
14378
15063
  * Maps entity name -> pre-tokenized entity data.
@@ -14382,6 +15067,18 @@ declare class RankedSearch {
14382
15067
  private cachedEntityCount;
14383
15068
  private cachedEntityNames;
14384
15069
  constructor(storage: GraphStorage, storageDir?: string);
15070
+ /**
15071
+ * Attach (or detach) a graph-connectivity prior for score boosting.
15072
+ *
15073
+ * When both a prior and a positive boost are set, `searchNodesRanked`
15074
+ * multiplies each result's score by `(1 + boost * normalizedPageRank)`
15075
+ * and re-sorts. A boost of 0 (the default) disables the behavior entirely.
15076
+ *
15077
+ * @param prior - GraphRankPrior instance, or null to detach
15078
+ * @param boost - Multiplicative boost factor (default 0 = off)
15079
+ * @experimental
15080
+ */
15081
+ setGraphPrior(prior: GraphRankPrior | null, boost?: number): void;
14385
15082
  /**
14386
15083
  * Phase 4 Sprint 2: Clear the fallback token cache.
14387
15084
  * Called when graph changes are detected or explicitly by external code.
@@ -14422,6 +15119,11 @@ declare class RankedSearch {
14422
15119
  * @returns Array of search results sorted by relevance
14423
15120
  */
14424
15121
  searchNodesRanked(query: string, tags?: string[], minImportance?: number, maxImportance?: number, limit?: number, projectId?: string): Promise<SearchResult[]>;
15122
+ /**
15123
+ * Multiply each result's score by `(1 + boost * normalizedPageRank)` and
15124
+ * re-sort. No-op when no prior/boost is configured (the default).
15125
+ */
15126
+ private applyGraphBoost;
14425
15127
  /**
14426
15128
  * Search using pre-calculated TF-IDF index (fast path).
14427
15129
  */
@@ -15447,31 +16149,184 @@ declare class SearchManager {
15447
16149
  /** Get cost estimates for all search methods. */
15448
16150
  getSearchCostEstimates(query: string): Promise<QueryCostEstimate[]>;
15449
16151
  /**
15450
- * Phase 10 Sprint 4: Get the query cost estimator instance.
15451
- *
15452
- * @returns The QueryCostEstimator instance
16152
+ * Phase 10 Sprint 4: Get the query cost estimator instance.
16153
+ *
16154
+ * @returns The QueryCostEstimator instance
16155
+ */
16156
+ getQueryEstimator(): QueryCostEstimator;
16157
+ /**
16158
+ * Feature 3 (Must-Have): Search entities by a natural language time expression.
16159
+ *
16160
+ * Parses the query using chrono-node and returns entities whose
16161
+ * `createdAt` or `lastModified` timestamp falls within the resolved range.
16162
+ *
16163
+ * Returns an empty array if the expression cannot be parsed.
16164
+ *
16165
+ * @param query - Natural language temporal expression, e.g. "last hour", "since yesterday"
16166
+ * @param options - Optional field and undated-entity configuration
16167
+ * @returns Entities matching the time range, sorted oldest-first
16168
+ *
16169
+ * @example
16170
+ * ```typescript
16171
+ * const recentEntities = await manager.searchByTime('last 10 minutes');
16172
+ * const todayEntities = await manager.searchByTime('today');
16173
+ * const rangedEntities = await manager.searchByTime('between Monday and Wednesday');
16174
+ * ```
16175
+ */
16176
+ searchByTime(query: string, options?: TemporalSearchOptions): Promise<Entity[]>;
16177
+ }
16178
+
16179
+ /**
16180
+ * Symbolic Search Layer - metadata-based filtering using structured predicates.
16181
+ * @module search/SymbolicSearch
16182
+ */
16183
+
16184
+ /**
16185
+ * Result from symbolic search with match score.
16186
+ */
16187
+ interface SymbolicResult {
16188
+ entity: Entity;
16189
+ score: number;
16190
+ matchedFilters: string[];
16191
+ }
16192
+ /** Filters entities using structured metadata predicates (tags, types, dates, importance, hierarchy). */
16193
+ declare class SymbolicSearch {
16194
+ /** Filter entities using AND-combined metadata predicates. */
16195
+ search(entities: readonly Entity[], filters: SymbolicFilters): SymbolicResult[];
16196
+ /** @internal Evaluate all filters against an entity. */
16197
+ private evaluateFilters;
16198
+ /** Get entities matching a specific tag. */
16199
+ byTag(entities: readonly Entity[], tag: string): Entity[];
16200
+ /** Get entities of a specific type. */
16201
+ byType(entities: readonly Entity[], entityType: string): Entity[];
16202
+ /** Get entities within importance range. */
16203
+ byImportance(entities: readonly Entity[], min: number, max: number): Entity[];
16204
+ }
16205
+
16206
+ /**
16207
+ * Hybrid Search Manager - orchestrates semantic, lexical, symbolic, and
16208
+ * (optionally) graph-connectivity search layers.
16209
+ * @module search/HybridSearchManager
16210
+ */
16211
+
16212
+ declare const DEFAULT_HYBRID_WEIGHTS: {
16213
+ semantic: number;
16214
+ lexical: number;
16215
+ symbolic: number;
16216
+ };
16217
+ /** Default number of top results whose neighbors are expanded. */
16218
+ declare const DEFAULT_NEIGHBOR_TOP_K = 10;
16219
+ /** Default damping applied to a neighbor's inherited combined score. */
16220
+ declare const DEFAULT_NEIGHBOR_DAMPING = 0.3;
16221
+ /**
16222
+ * Matched-layer union including the graph-connectivity channel.
16223
+ *
16224
+ * @deprecated The canonical `HybridSearchResult['matchedLayers']` union
16225
+ * (src/types) now includes `'graph'`. Use
16226
+ * `HybridSearchResult['matchedLayers'][number]` instead. Kept as an alias
16227
+ * for back-compat (exported from the search barrel).
16228
+ */
16229
+ type HybridSearchLayer = HybridSearchResult['matchedLayers'][number];
16230
+ /**
16231
+ * HybridSearchResult variant whose scores may carry the normalized
16232
+ * graph-connectivity score. Now that the canonical `matchedLayers` union
16233
+ * includes `'graph'`, this type differs from HybridSearchResult only by
16234
+ * the optional `scores.graph` field, so every GraphHybridSearchResult is a
16235
+ * valid HybridSearchResult (and vice versa when the graph layer did not
16236
+ * run). Results produced with the graph channel enabled conform to this
16237
+ * shape.
16238
+ */
16239
+ interface GraphHybridSearchResult extends HybridSearchResult {
16240
+ scores: HybridSearchResult['scores'] & {
16241
+ /** Normalized graph-connectivity score. Present when the graph layer ran. */
16242
+ graph?: number;
16243
+ };
16244
+ }
16245
+ /** One-hop neighbor expansion options (only a single hop is supported). */
16246
+ interface NeighborExpansionOptions {
16247
+ /** Number of hops to expand. Only 1 is supported. */
16248
+ hops: 1;
16249
+ /** Number of top-ranked results to expand from (default: 10). */
16250
+ topK?: number;
16251
+ /** Damping factor applied to the parent's combined score (default: 0.3). */
16252
+ damping?: number;
16253
+ }
16254
+ /** Additive graph-channel options for hybrid search. All default off. */
16255
+ interface GraphHybridOptions {
16256
+ /**
16257
+ * Weight for the graph-connectivity channel (normalized PageRank via
16258
+ * GraphRankPrior). Default 0 = channel disabled. Requires a GraphRankPrior
16259
+ * to have been passed to the constructor.
16260
+ */
16261
+ graphWeight?: number;
16262
+ /**
16263
+ * One-hop neighbor expansion: after scoring, neighbors of the top-K
16264
+ * results are appended with a damped combined score and re-sorted.
16265
+ * Requires a GraphRankPrior. Off unless provided.
16266
+ */
16267
+ expandNeighbors?: NeighborExpansionOptions;
16268
+ }
16269
+ /**
16270
+ * Combines semantic, lexical, symbolic, and (optionally) graph-connectivity
16271
+ * search layers with configurable weights.
16272
+ */
16273
+ declare class HybridSearchManager {
16274
+ private semanticSearch;
16275
+ private rankedSearch;
16276
+ private graphPrior;
16277
+ private defaults;
16278
+ private symbolicSearch;
16279
+ /**
16280
+ * @param semanticSearch - Semantic layer (null = layer disabled)
16281
+ * @param rankedSearch - Lexical layer (TF-IDF/BM25)
16282
+ * @param graphPrior - Optional graph-connectivity signal provider; when
16283
+ * absent, the graph channel and neighbor expansion are inert
16284
+ * @param defaults - Default per-search graph options (e.g. env-configured
16285
+ * graphWeight); per-call options override these
16286
+ */
16287
+ constructor(semanticSearch: SemanticSearch | null, rankedSearch: RankedSearch, graphPrior?: GraphRankPrior | null, defaults?: GraphHybridOptions);
16288
+ /**
16289
+ * Perform hybrid search combining all layers.
16290
+ *
16291
+ * When the graph channel or expandNeighbors is enabled, matchedLayers may
16292
+ * include 'graph' and results additionally conform to
16293
+ * GraphHybridSearchResult (`scores.graph` carries the normalized
16294
+ * graph-connectivity score).
16295
+ */
16296
+ search(graph: ReadonlyKnowledgeGraph, query: string, options?: Partial<HybridSearchOptions> & GraphHybridOptions): Promise<HybridSearchResult[]>;
16297
+ /**
16298
+ * Execute semantic search layer.
16299
+ */
16300
+ private executeSemanticSearch;
16301
+ /**
16302
+ * Execute lexical search layer (TF-IDF/BM25).
16303
+ */
16304
+ private executeLexicalSearch;
16305
+ /**
16306
+ * Execute symbolic search layer.
16307
+ */
16308
+ private executeSymbolicSearch;
16309
+ /**
16310
+ * Merge results from all layers.
15453
16311
  */
15454
- getQueryEstimator(): QueryCostEstimator;
16312
+ private mergeResults;
15455
16313
  /**
15456
- * Feature 3 (Must-Have): Search entities by a natural language time expression.
15457
- *
15458
- * Parses the query using chrono-node and returns entities whose
15459
- * `createdAt` or `lastModified` timestamp falls within the resolved range.
15460
- *
15461
- * Returns an empty array if the expression cannot be parsed.
15462
- *
15463
- * @param query - Natural language temporal expression, e.g. "last hour", "since yesterday"
15464
- * @param options - Optional field and undated-entity configuration
15465
- * @returns Entities matching the time range, sorted oldest-first
16314
+ * One-hop neighbor expansion: append unseen neighbors of the top-K results
16315
+ * with a damped combined score (`damping * parent.combined`), tagged with
16316
+ * matchedLayers ['graph'], then re-sort and re-apply the limit.
15466
16317
  *
15467
- * @example
15468
- * ```typescript
15469
- * const recentEntities = await manager.searchByTime('last 10 minutes');
15470
- * const todayEntities = await manager.searchByTime('today');
15471
- * const rangedEntities = await manager.searchByTime('between Monday and Wednesday');
15472
- * ```
16318
+ * Neighbors already present in the result set are never duplicated.
15473
16319
  */
15474
- searchByTime(query: string, options?: TemporalSearchOptions): Promise<Entity[]>;
16320
+ private expandOneHop;
16321
+ /**
16322
+ * Search with full entity resolution.
16323
+ * Alias for search() since we now always resolve entities.
16324
+ */
16325
+ searchWithEntities(graph: ReadonlyKnowledgeGraph, query: string, options?: Partial<HybridSearchOptions> & GraphHybridOptions): Promise<HybridSearchResult[]>;
16326
+ /**
16327
+ * Get the symbolic search instance for direct access.
16328
+ */
16329
+ getSymbolicSearch(): SymbolicSearch;
15475
16330
  }
15476
16331
 
15477
16332
  /**
@@ -16752,78 +17607,6 @@ declare class TFIDFEventSync {
16752
17607
  private handleEntityDeleted;
16753
17608
  }
16754
17609
 
16755
- /**
16756
- * Symbolic Search Layer - metadata-based filtering using structured predicates.
16757
- * @module search/SymbolicSearch
16758
- */
16759
-
16760
- /**
16761
- * Result from symbolic search with match score.
16762
- */
16763
- interface SymbolicResult {
16764
- entity: Entity;
16765
- score: number;
16766
- matchedFilters: string[];
16767
- }
16768
- /** Filters entities using structured metadata predicates (tags, types, dates, importance, hierarchy). */
16769
- declare class SymbolicSearch {
16770
- /** Filter entities using AND-combined metadata predicates. */
16771
- search(entities: readonly Entity[], filters: SymbolicFilters): SymbolicResult[];
16772
- /** @internal Evaluate all filters against an entity. */
16773
- private evaluateFilters;
16774
- /** Get entities matching a specific tag. */
16775
- byTag(entities: readonly Entity[], tag: string): Entity[];
16776
- /** Get entities of a specific type. */
16777
- byType(entities: readonly Entity[], entityType: string): Entity[];
16778
- /** Get entities within importance range. */
16779
- byImportance(entities: readonly Entity[], min: number, max: number): Entity[];
16780
- }
16781
-
16782
- /**
16783
- * Hybrid Search Manager - orchestrates semantic, lexical, and symbolic search.
16784
- * @module search/HybridSearchManager
16785
- */
16786
-
16787
- declare const DEFAULT_HYBRID_WEIGHTS: {
16788
- semantic: number;
16789
- lexical: number;
16790
- symbolic: number;
16791
- };
16792
- /** Combines semantic, lexical, and symbolic search layers with configurable weights. */
16793
- declare class HybridSearchManager {
16794
- private semanticSearch;
16795
- private rankedSearch;
16796
- private symbolicSearch;
16797
- constructor(semanticSearch: SemanticSearch | null, rankedSearch: RankedSearch);
16798
- /** Perform hybrid search combining all three layers. */
16799
- search(graph: ReadonlyKnowledgeGraph, query: string, options?: Partial<HybridSearchOptions>): Promise<HybridSearchResult[]>;
16800
- /**
16801
- * Execute semantic search layer.
16802
- */
16803
- private executeSemanticSearch;
16804
- /**
16805
- * Execute lexical search layer (TF-IDF/BM25).
16806
- */
16807
- private executeLexicalSearch;
16808
- /**
16809
- * Execute symbolic search layer.
16810
- */
16811
- private executeSymbolicSearch;
16812
- /**
16813
- * Merge results from all three layers.
16814
- */
16815
- private mergeResults;
16816
- /**
16817
- * Search with full entity resolution.
16818
- * Alias for search() since we now always resolve entities.
16819
- */
16820
- searchWithEntities(graph: ReadonlyKnowledgeGraph, query: string, options?: Partial<HybridSearchOptions>): Promise<HybridSearchResult[]>;
16821
- /**
16822
- * Get the symbolic search instance for direct access.
16823
- */
16824
- getSymbolicSearch(): SymbolicSearch;
16825
- }
16826
-
16827
17610
  /**
16828
17611
  * Query Analyzer
16829
17612
  *
@@ -17426,6 +18209,11 @@ interface SymbolicSearchResult {
17426
18209
  score: number;
17427
18210
  entity?: Entity;
17428
18211
  }
18212
+ /**
18213
+ * Result from the graph-connectivity layer (e.g. normalized PageRank from
18214
+ * GraphRankPrior). Same shape as the symbolic layer results.
18215
+ */
18216
+ type GraphLayerResult = SymbolicSearchResult;
17429
18217
  interface ScoredResult {
17430
18218
  entityName: string;
17431
18219
  entity: Entity;
@@ -17433,19 +18221,23 @@ interface ScoredResult {
17433
18221
  semantic: number;
17434
18222
  lexical: number;
17435
18223
  symbolic: number;
18224
+ graph: number;
17436
18225
  combined: number;
17437
18226
  };
17438
- matchedLayers: ('semantic' | 'lexical' | 'symbolic')[];
18227
+ matchedLayers: ('semantic' | 'lexical' | 'symbolic' | 'graph')[];
17439
18228
  rawScores: {
17440
18229
  semantic?: number;
17441
18230
  lexical?: number;
17442
18231
  symbolic?: number;
18232
+ graph?: number;
17443
18233
  };
17444
18234
  }
17445
18235
  interface HybridWeights {
17446
18236
  semantic: number;
17447
18237
  lexical: number;
17448
18238
  symbolic: number;
18239
+ /** Graph-connectivity channel weight. Default 0 = disabled (legacy behavior). */
18240
+ graph: number;
17449
18241
  }
17450
18242
  declare const DEFAULT_SCORER_WEIGHTS: HybridWeights;
17451
18243
  interface HybridScorerOptions {
@@ -17465,14 +18257,23 @@ declare class HybridScorer {
17465
18257
  setWeights(weights: Partial<HybridWeights>): void;
17466
18258
  /** Min-max normalize scores to 0-1 range. */
17467
18259
  minMaxNormalize(scores: Map<string, number>): Map<string, number>;
17468
- /** Combine results from all three search layers. */
17469
- combine(semanticResults: SemanticLayerResult[], lexicalResults: LexicalSearchResult[], symbolicResults: SymbolicSearchResult[], entityMap: Map<string, Entity>): ScoredResult[];
18260
+ /**
18261
+ * Combine results from all search layers.
18262
+ *
18263
+ * @param semanticResults - Semantic similarity layer results
18264
+ * @param lexicalResults - Lexical (TF-IDF/BM25) layer results
18265
+ * @param symbolicResults - Symbolic/metadata layer results
18266
+ * @param entityMap - Entity lookup map by name
18267
+ * @param graphResults - Optional graph-connectivity layer results
18268
+ * (default: empty — legacy three-layer behavior)
18269
+ */
18270
+ combine(semanticResults: SemanticLayerResult[], lexicalResults: LexicalSearchResult[], symbolicResults: SymbolicSearchResult[], entityMap: Map<string, Entity>, graphResults?: GraphLayerResult[]): ScoredResult[];
17470
18271
  /** Get weights normalized to sum to 1, redistributing for missing layers. */
17471
- getNormalizedWeights(hasSemantic: boolean, hasLexical: boolean, hasSymbolic: boolean): HybridWeights;
18272
+ getNormalizedWeights(hasSemantic: boolean, hasLexical: boolean, hasSymbolic: boolean, hasGraph?: boolean): HybridWeights;
17472
18273
  /** Combine scores from maps directly (alternative interface). */
17473
- combineFromMaps(semanticScores: Map<string, number>, lexicalScores: Map<string, number>, symbolicScores: Map<string, number>, entityMap: Map<string, Entity>): ScoredResult[];
18274
+ combineFromMaps(semanticScores: Map<string, number>, lexicalScores: Map<string, number>, symbolicScores: Map<string, number>, entityMap: Map<string, Entity>, graphScores?: Map<string, number>): ScoredResult[];
17474
18275
  /** Calculate combined score for a single entity. */
17475
- calculateScore(semanticScore: number, lexicalScore: number, symbolicScore: number): number;
18276
+ calculateScore(semanticScore: number, lexicalScore: number, symbolicScore: number, graphScore?: number): number;
17476
18277
  }
17477
18278
 
17478
18279
  /**
@@ -20460,6 +21261,16 @@ declare class PatternDetector {
20460
21261
  * @module agent/RuleEvaluator
20461
21262
  */
20462
21263
 
21264
+ /**
21265
+ * Simple rule interface for demonstration.
21266
+ */
21267
+ interface Rule$1 {
21268
+ condition: {
21269
+ type: string;
21270
+ field: string;
21271
+ value: unknown;
21272
+ };
21273
+ }
20463
21274
  /**
20464
21275
  * Evaluates rule conditions against entities.
20465
21276
  *
@@ -20499,6 +21310,14 @@ declare class RuleEvaluator {
20499
21310
  * Get cache size for monitoring.
20500
21311
  */
20501
21312
  getCacheSize(): number;
21313
+ /**
21314
+ * Evaluates a simple rule against a set of facts.
21315
+ *
21316
+ * @param rule - Rule to evaluate
21317
+ * @param facts - Facts to check against
21318
+ * @returns True if the rule evaluates to true
21319
+ */
21320
+ evaluateRule(rule: Rule$1, facts: Record<string, unknown>): boolean;
20502
21321
  }
20503
21322
 
20504
21323
  /**
@@ -22789,9 +23608,37 @@ declare class MultiAgentMemoryManager extends EventEmitter {
22789
23608
  * Session Checkpoint Manager
22790
23609
  *
22791
23610
  * Provides session checkpointing, crash recovery, and sleep/wake
22792
- * functionality for agent memory sessions. Checkpoints capture
22793
- * working memory state and decay snapshots, stored as observations
22794
- * on the session entity.
23611
+ * functionality for agent memory sessions. Checkpoints are persisted as
23612
+ * real graph structure instead of JSON blobs, so checkpoint content is
23613
+ * queryable and traversable:
23614
+ *
23615
+ * - Each checkpoint is its own `entityType: 'session-checkpoint'` entity
23616
+ * (name = checkpoint id `checkpoint_{sessionId}_{timestamp}`), with
23617
+ * `parentId` set to the session entity for hierarchy integration.
23618
+ * - Scalar fields are human-readable observation lines:
23619
+ * `[session-id]: <id>`, `[label]: <name>` (when present), and
23620
+ * `[created-at]: <ISO timestamp>`.
23621
+ * - The working-memory snapshot is one line per memory:
23622
+ * `[working-memory]: <JSON-name>` for membership (order-preserving) and
23623
+ * `[decay]: <JSON-name>=<importance>` for the importance snapshot —
23624
+ * names are JSON-encoded so arbitrary strings (equals signs, newlines,
23625
+ * unicode) roundtrip.
23626
+ * - Arbitrary metadata roundtrips via `[meta]: <JSON-key>=<JSON-value>`
23627
+ * lines (key and value JSON-encoded separately).
23628
+ * - Relations wire it together: session —`has_checkpoint`→ checkpoint,
23629
+ * and checkpoint —`snapshots`→ each working-memory entity that still
23630
+ * exists at write time. Observation lines remain the source of truth
23631
+ * for the snapshot content (so a checkpoint survives working-memory
23632
+ * deletion, whose cascade drops the `snapshots` relation).
23633
+ *
23634
+ * Ordering: `listCheckpoints` sorts by the `[created-at]` scalar (newest
23635
+ * first, ties broken by the numeric id suffix) — the module only ever
23636
+ * needs "latest checkpoint", so no `precedes` chain is maintained.
23637
+ *
23638
+ * Legacy `[CHECKPOINT] {json}` observations on session entities remain
23639
+ * decodable via `decodeLegacyCheckpoint` and are auto-migrated to the
23640
+ * decomposed shape on read; use `migrateLegacySessionCheckpoints` for
23641
+ * bulk migration.
22795
23642
  *
22796
23643
  * @module agent/SessionCheckpoint
22797
23644
  */
@@ -22818,16 +23665,26 @@ interface SessionCheckpointData {
22818
23665
  metadata: Record<string, unknown>;
22819
23666
  };
22820
23667
  }
23668
+ /** Entity type for decomposed checkpoint entities. */
23669
+ declare const SESSION_CHECKPOINT_ENTITY_TYPE = "session-checkpoint";
23670
+ /** Relation type: session —has_checkpoint→ checkpoint entity. */
23671
+ declare const HAS_CHECKPOINT_RELATION = "has_checkpoint";
23672
+ /** Relation type: checkpoint —snapshots→ working-memory entity. */
23673
+ declare const SNAPSHOTS_RELATION = "snapshots";
22821
23674
  /**
22822
23675
  * Manages session checkpoints for crash recovery and sleep/wake.
22823
23676
  *
22824
- * Stores checkpoint data as JSON-serialized observations on the
22825
- * session entity, prefixed with `[CHECKPOINT]`. This avoids
22826
- * requiring a separate storage mechanism.
23677
+ * Persists each checkpoint as a dedicated `session-checkpoint` entity
23678
+ * linked to its session via a `has_checkpoint` relation (see the module
23679
+ * doc for the full decomposed schema). Legacy JSON-blob checkpoints
23680
+ * stored as `[CHECKPOINT]` observations on session entities are
23681
+ * auto-migrated on read.
22827
23682
  *
22828
23683
  * @example
22829
23684
  * ```typescript
22830
- * const mgr = new SessionCheckpointManager(storage, workingMemory, decayEngine);
23685
+ * const mgr = new SessionCheckpointManager(
23686
+ * storage, workingMemory, decayEngine, entityManager, relationManager
23687
+ * );
22831
23688
  *
22832
23689
  * // Create a checkpoint
22833
23690
  * const cp = await mgr.checkpoint('session_123', 'before-experiment');
@@ -22846,13 +23703,15 @@ declare class SessionCheckpointManager {
22846
23703
  private readonly storage;
22847
23704
  private readonly workingMemoryManager;
22848
23705
  private readonly decayEngine;
22849
- constructor(storage: IGraphStorage, workingMemoryManager: WorkingMemoryManager, decayEngine: DecayEngine);
23706
+ private readonly entityManager;
23707
+ private readonly relationManager;
23708
+ constructor(storage: IGraphStorage, workingMemoryManager: WorkingMemoryManager, decayEngine: DecayEngine, entityManager: EntityManager, relationManager: RelationManager);
22850
23709
  /**
22851
23710
  * Create a checkpoint for a session.
22852
23711
  *
22853
23712
  * Captures the current working memory entity names and their
22854
- * importance values, storing the data as a JSON-serialized
22855
- * observation on the session entity.
23713
+ * importance values, persisting them as a dedicated
23714
+ * `session-checkpoint` entity plus linking relations.
22856
23715
  *
22857
23716
  * @param sessionId - Session to checkpoint
22858
23717
  * @param name - Optional user-provided label
@@ -22875,8 +23734,10 @@ declare class SessionCheckpointManager {
22875
23734
  /**
22876
23735
  * List all checkpoints for a session.
22877
23736
  *
22878
- * Parses checkpoint observations from the session entity and
22879
- * returns them sorted by timestamp (newest first).
23737
+ * Collects `session-checkpoint` entities linked to the session via
23738
+ * `has_checkpoint` relations and returns them sorted by creation time
23739
+ * (newest first). Legacy `[CHECKPOINT]` blob observations found on the
23740
+ * session entity are auto-migrated to the decomposed shape first.
22880
23741
  *
22881
23742
  * @param sessionId - Session to list checkpoints for
22882
23743
  * @returns Array of checkpoint data, newest first
@@ -22923,24 +23784,71 @@ declare class SessionCheckpointManager {
22923
23784
  */
22924
23785
  private getSessionEntity;
22925
23786
  /**
22926
- * Parse checkpoint observations from a session entity.
22927
- * Returns checkpoints sorted newest first.
23787
+ * Collect decomposed checkpoint entities for a session via its
23788
+ * `has_checkpoint` relations. Returns checkpoints sorted newest first.
23789
+ * @internal
23790
+ */
23791
+ private collectCheckpoints;
23792
+ /**
23793
+ * Auto-migrate any legacy `[CHECKPOINT]` blob observations on the given
23794
+ * session entity to the decomposed shape, stripping the migrated blobs
23795
+ * from the session's observations. Malformed blobs are left in place
23796
+ * (they were already skipped by the legacy parser). Returns the
23797
+ * migrated checkpoints (empty when nothing was migrated).
22928
23798
  * @internal
22929
23799
  */
22930
- private parseCheckpoints;
23800
+ private migrateSessionLegacyCheckpoints;
22931
23801
  /**
22932
- * Find a checkpoint by ID across all sessions.
23802
+ * Find a checkpoint by ID. Checkpoint IDs double as entity names, so
23803
+ * the decomposed lookup is O(1); when the entity is missing, sessions
23804
+ * still carrying legacy blobs are migrated and re-checked.
22933
23805
  * @internal
22934
23806
  */
22935
23807
  private findCheckpointById;
22936
23808
  }
23809
+ /**
23810
+ * Scan every session entity and migrate any legacy `[CHECKPOINT] {json}`
23811
+ * blob observations to the decomposed graph shape (checkpoint entities +
23812
+ * `has_checkpoint` / `snapshots` relations), mirroring
23813
+ * `migrateLegacyProcedures`.
23814
+ *
23815
+ * @returns Number of checkpoints migrated.
23816
+ */
23817
+ declare function migrateLegacySessionCheckpoints(entityManager: EntityManager, relationManager: RelationManager): Promise<number>;
23818
+ /**
23819
+ * Pure decoder for a single legacy `[CHECKPOINT] {json}` observation
23820
+ * line. Returns null when the line is not a well-formed legacy blob.
23821
+ *
23822
+ * @deprecated Legacy decoder — kept for reading pre-decomposition
23823
+ * observations. `SessionCheckpointManager` auto-migrates such blobs on
23824
+ * read; new code should go through `SessionCheckpointManager`.
23825
+ */
23826
+ declare function decodeLegacyCheckpoint(observation: string): SessionCheckpointData | null;
22937
23827
 
22938
23828
  /**
22939
23829
  * Work Thread Manager
22940
23830
  *
22941
- * Manages work threads for coordinating tasks across agents.
22942
- * Threads are stored as entities with entityType 'work_thread',
22943
- * using relations for parent-child and blocking relationships.
23831
+ * Manages work threads for coordinating tasks across agents. Threads are
23832
+ * persisted as real graph structure instead of JSON blobs, so thread
23833
+ * content is queryable and traversable:
23834
+ *
23835
+ * - Each thread is an `entityType: 'work_thread'` entity (name =
23836
+ * `thread.id`). Its observations carry human-readable scalar lines
23837
+ * (`[title]: Ship feature X`, `[status]: active`, `[owner]: agent_1`,
23838
+ * `[priority]: 8`, `[created-at]: …`, `[updated-at]: …`) plus the
23839
+ * free-text description as a plain observation.
23840
+ * - Custom metadata encodes one `[meta]: <JSON-key>=<JSON-value>` line per
23841
+ * entry — key and value are JSON-encoded separately so arbitrary strings
23842
+ * (equals signs, newlines, unicode) roundtrip.
23843
+ * - Cross-thread references are real relations, not payload fields:
23844
+ * thread —`child_of`→ parent thread, and thread —`blocked_by`→ each
23845
+ * blocker thread. `load()` rehydrates `parentId` / `blockedBy` from
23846
+ * those relations.
23847
+ *
23848
+ * Legacy single-JSON-observation threads (the pre-decomposition shape)
23849
+ * remain decodable via `decodeLegacyWorkThread` and are auto-migrated to
23850
+ * the decomposed shape on `load()`; use `migrateLegacyWorkThreads` for
23851
+ * bulk migration.
22944
23852
  *
22945
23853
  * @module agent/WorkThreadManager
22946
23854
  */
@@ -23005,6 +23913,12 @@ interface CreateWorkThreadOptions {
23005
23913
  /** Custom metadata */
23006
23914
  metadata?: Record<string, unknown>;
23007
23915
  }
23916
+ /** Relation type for parent-child thread relationships */
23917
+ declare const CHILD_OF_RELATION = "child_of";
23918
+ /** Relation type for blocking relationships */
23919
+ declare const BLOCKED_BY_RELATION = "blocked_by";
23920
+ /** Entity type for work thread entities */
23921
+ declare const WORK_THREAD_ENTITY_TYPE = "work_thread";
23008
23922
  /**
23009
23923
  * Manages work thread lifecycle and coordination.
23010
23924
  *
@@ -23031,8 +23945,15 @@ declare class WorkThreadManager {
23031
23945
  * Load existing work threads from storage into memory.
23032
23946
  *
23033
23947
  * Scans the graph for entities with entityType 'work_thread' and
23034
- * rehydrates the in-memory Map from their serialized observations.
23035
- * Must be called after construction to restore state from a previous session.
23948
+ * rehydrates the in-memory Map from their scalar observation lines,
23949
+ * deriving `parentId` / `blockedBy` from `child_of` / `blocked_by`
23950
+ * relations. Must be called after construction to restore state from a
23951
+ * previous session.
23952
+ *
23953
+ * **Side effect (auto-migration):** threads still stored in the legacy
23954
+ * single-JSON-observation shape are decoded with the legacy decoder and
23955
+ * rewritten in place to the decomposed shape (scalar lines + relations)
23956
+ * before returning.
23036
23957
  *
23037
23958
  * @returns Number of threads loaded
23038
23959
  */
@@ -23136,14 +24057,30 @@ declare class WorkThreadManager {
23136
24057
  */
23137
24058
  private detectCycles;
23138
24059
  /**
23139
- * Persist a thread's state to storage by updating its entity observation.
24060
+ * Persist a thread's state to storage by rewriting its scalar
24061
+ * observation lines. Relations (`child_of` / `blocked_by`) are managed
24062
+ * by `create` / `block` / `unblock`, not here.
23140
24063
  */
23141
24064
  private persistThread;
23142
- /**
23143
- * Serialize a thread to a plain object for JSON storage.
23144
- */
23145
- private serializeThread;
23146
24065
  }
24066
+ /**
24067
+ * Scan every `entityType: 'work_thread'` entity and migrate any that
24068
+ * still use the legacy single-JSON-observation encoding to the
24069
+ * decomposed shape (scalar observation lines + `child_of` / `blocked_by`
24070
+ * relations). Mirrors `migrateLegacyProcedures`.
24071
+ *
24072
+ * @returns Number of threads migrated.
24073
+ */
24074
+ declare function migrateLegacyWorkThreads(storage: IGraphStorage): Promise<number>;
24075
+ /**
24076
+ * Pure decoder for the legacy single-JSON-observation thread shape
24077
+ * (`JSON.stringify({ title, status, … })` in `observations[0]`).
24078
+ *
24079
+ * @deprecated Legacy decoder — kept for reading pre-decomposition
24080
+ * entities. `WorkThreadManager.load()` auto-migrates such entities; new
24081
+ * code should go through `WorkThreadManager`.
24082
+ */
24083
+ declare function decodeLegacyWorkThread(id: string, observations: string[]): WorkThread | null;
23147
24084
 
23148
24085
  /**
23149
24086
  * Collaborative Memory Synthesis
@@ -23320,6 +24257,13 @@ declare class CollaborativeSynthesis {
23320
24257
  * Manages user profiles stored as Entity instances with entityType 'profile'.
23321
24258
  * Observations are tagged [static] or [dynamic] to classify facts.
23322
24259
  *
24260
+ * **Contract (graph-core):** the `[static]`/`[dynamic]` prefixes are the
24261
+ * accepted line-per-observation format — one human-readable fact per
24262
+ * observation, individually indexable and searchable. This is NOT the
24263
+ * JSON-blob antipattern that ProcedureStore/WorkThreadManager/
24264
+ * SessionCheckpoint were migrated away from (a whole structured record
24265
+ * serialized into a single opaque observation); no decomposition needed.
24266
+ *
23323
24267
  * @module agent/ProfileManager
23324
24268
  */
23325
24269
 
@@ -23654,6 +24598,7 @@ declare class AgentMemoryManager extends EventEmitter {
23654
24598
  private _profileManager?;
23655
24599
  private _entityManager?;
23656
24600
  private _observationManager?;
24601
+ private _relationManager?;
23657
24602
  private _workThreadManager?;
23658
24603
  private _checkpointManager?;
23659
24604
  constructor(storage: IGraphStorage, config?: AgentMemoryConfig);
@@ -23682,6 +24627,10 @@ declare class AgentMemoryManager extends EventEmitter {
23682
24627
  * Internal ObservationManager, created on demand from the underlying storage.
23683
24628
  */
23684
24629
  private get observationManager();
24630
+ /**
24631
+ * Internal RelationManager, created on demand from the underlying storage.
24632
+ */
24633
+ private get relationManager();
23685
24634
  /** Profile manager for persistent user/agent profile facts */
23686
24635
  get profileManager(): ProfileManager;
23687
24636
  /**
@@ -24827,7 +25776,10 @@ declare class ToolCallObserver {
24827
25776
  * First-class type definitions for stored, executable procedures —
24828
25777
  * skills / how-to sequences distinct from semantic facts and episodic
24829
25778
  * events. Procedures are persisted as `entityType: 'procedure'` entities
24830
- * with the step list encoded in `observations` as JSON.
25779
+ * whose steps are decomposed into `entityType: 'procedure-step'` child
25780
+ * entities linked via `has_step` / `precedes` / `has_fallback` relations
25781
+ * (see `agent/procedural/ProcedureStore`); step fields are stored as
25782
+ * one human-readable observation line each, not JSON blobs.
24831
25783
  *
24832
25784
  * @module types/procedure
24833
25785
  */
@@ -24977,7 +25929,7 @@ type InvocationResult = {
24977
25929
  declare class ProcedureManager {
24978
25930
  private readonly store;
24979
25931
  private readonly successRateAlpha;
24980
- constructor(entityManager: EntityManager, config?: ProcedureManagerConfig);
25932
+ constructor(entityManager: EntityManager, relationManager: RelationManager, config?: ProcedureManagerConfig);
24981
25933
  /**
24982
25934
  * Persist a new procedure. Auto-generates `id` (and falls back to it
24983
25935
  * for `name`) when caller omits them. Throws if the id collides — the
@@ -25971,6 +26923,417 @@ declare class ActiveRetrievalController {
25971
26923
  private estimateCoverage;
25972
26924
  }
25973
26925
 
26926
+ /**
26927
+ * Cue–Tag–Content (CTC) associative memory graph.
26928
+ *
26929
+ * Implements the heterogeneous memory graph `M = (C, V, R)` of MRAgent
26930
+ * ("Memory is Reconstructed, Not Retrieved", §3.1). Cues and contents are nodes;
26931
+ * associations are typed `(cue, tag, content)` triples where the **tag** mediates
26932
+ * retrieval. The class exposes the paper's induced mapping operators (Eq. 5/8/9)
26933
+ * that the active reconstruction loop composes into traversal actions.
26934
+ *
26935
+ * @module agent/reconstruction/CueTagContentGraph
26936
+ * @experimental
26937
+ */
26938
+
26939
+ /** Normalise cue/tag surface text into a stable lookup id. */
26940
+ declare function normalizeKey(text: string): string;
26941
+ /**
26942
+ * In-memory associative memory graph with O(1) mapping operators.
26943
+ *
26944
+ * Indexes are maintained incrementally on `addTriple`, so traversal operators
26945
+ * never scan the full relation set.
26946
+ */
26947
+ declare class CueTagContentGraph {
26948
+ private readonly cues;
26949
+ private readonly tags;
26950
+ private readonly contents;
26951
+ private readonly tripleSet;
26952
+ /** φ_{c→g}: cue id → set of associated tag ids. */
26953
+ private readonly cueTags;
26954
+ /** φ_{(c,g)→v}: (cue,tag) key → set of content ids. */
26955
+ private readonly cueTagContents;
26956
+ /** φ_{v→(c,g)}: content id → list of (cue,tag) pairs (reverse traversal). */
26957
+ private readonly contentCueTags;
26958
+ /** φ_{τ→e}: topic content id → set of episode content ids. */
26959
+ private readonly topicEpisodes;
26960
+ /** Insert (or fetch) a cue node, returning its id. */
26961
+ addCue(text: string): string;
26962
+ /** Insert (or fetch) a tag node, returning its id. */
26963
+ addTag(text: string): string;
26964
+ /**
26965
+ * Insert (or replace) a content node. The caller supplies a stable id so that
26966
+ * episodic/semantic/topic nodes can be cross-referenced (timeline, topic links).
26967
+ */
26968
+ addContent(node: ContentNode): ContentNode;
26969
+ /** Connect a topic node to one of its constituent episodes (topic → episode). */
26970
+ linkTopicEpisode(topicId: string, episodeId: string): void;
26971
+ /**
26972
+ * Add a `(cue, tag, content)` association. Cue and tag are created on demand;
26973
+ * the content node must already exist (added via {@link addContent}).
26974
+ */
26975
+ addTriple(cueText: string, tagText: string, contentId: string): void;
26976
+ /**
26977
+ * φ_{c→g}(c) — activate candidate associative tags from a cue.
26978
+ * Accepts a cue surface form or id.
26979
+ */
26980
+ tagsForCue(cue: string): TagNode[];
26981
+ /**
26982
+ * φ_{(c,g)→v}(c, g) — retrieve content conditioned on a cue and a selected tag.
26983
+ * Optionally restrict to a single memory layer.
26984
+ */
26985
+ contentsForCueTag(cue: string, tag: string, layer?: ContentLayer): ContentNode[];
26986
+ /**
26987
+ * φ_{v→(c,g)}(v) — reverse traversal: surface the cues and tags associated with
26988
+ * a retrieved content node, enabling the agent to redirect its trajectory.
26989
+ */
26990
+ cueTagsForContent(contentId: string): Array<{
26991
+ cue: CueNode;
26992
+ tag: TagNode;
26993
+ }>;
26994
+ /** φ_{τ→e}(τ) — descend from a topic node to its constituent episodes. */
26995
+ episodesForTopic(topicId: string): ContentNode[];
26996
+ /** Fetch a content node by id. */
26997
+ getContent(id: string): ContentNode | undefined;
26998
+ /** Look up a cue node by surface form or id. */
26999
+ getCue(text: string): CueNode | undefined;
27000
+ /** All content nodes in a given layer (timeline order for episodic). */
27001
+ contentsByLayer(layer: ContentLayer): ContentNode[];
27002
+ /**
27003
+ * Match a free-form cue phrase against the stored cue set, returning ids of
27004
+ * cues whose surface form exactly equals or contains the (normalised) phrase.
27005
+ * Used to build the initial active set `Z(0)` from a query.
27006
+ */
27007
+ matchCues(phrase: string): CueNode[];
27008
+ /** Number of cues / tags / contents / triples currently stored. */
27009
+ stats(): {
27010
+ cues: number;
27011
+ tags: number;
27012
+ contents: number;
27013
+ triples: number;
27014
+ };
27015
+ /** Export a structural snapshot (e.g. to persist alongside JSONL storage). */
27016
+ toSnapshot(): CTCGraphSnapshot;
27017
+ /** Rebuild a graph from a snapshot produced by {@link toSnapshot}. */
27018
+ static fromSnapshot(snap: CTCGraphSnapshot): CueTagContentGraph;
27019
+ }
27020
+
27021
+ /**
27022
+ * Memory toolkit for controlled traversal of the Cue–Tag–Content graph.
27023
+ *
27024
+ * Implements the seven typed traversal operators of MRAgent (paper Table 4).
27025
+ * Each tool corresponds to a typed mapping between memory components, letting an
27026
+ * agent (LLM- or heuristic-driven) explicitly control the direction and
27027
+ * granularity of memory access rather than retrieving a fixed similarity set.
27028
+ *
27029
+ * @module agent/reconstruction/MemoryToolkit
27030
+ * @experimental
27031
+ */
27032
+
27033
+ /** Result of the keyword/context introspection tools. */
27034
+ interface EventKeywords {
27035
+ cues: string[];
27036
+ tags: string[];
27037
+ }
27038
+ /**
27039
+ * The MRAgent traversal toolkit. Stateless over the graph — each call is a pure
27040
+ * mapping operator invocation, which keeps memory access interpretable.
27041
+ */
27042
+ declare class MemoryToolkit {
27043
+ private readonly graph;
27044
+ constructor(graph: CueTagContentGraph);
27045
+ /**
27046
+ * `query_tag_events` — φ_{(c,g)→e}: retrieve episodic events associated with a
27047
+ * cue–tag pair. The workhorse for multi-hop questions (paper Table 6).
27048
+ */
27049
+ queryTagEvents(cue: string, tag: string): ContentNode[];
27050
+ /**
27051
+ * `query_conversation_time` — φ_{e→t}: return the conversation timestamp of an
27052
+ * episodic event. Primary operator for temporal questions.
27053
+ */
27054
+ queryConversationTime(eventId: string): string | undefined;
27055
+ /**
27056
+ * `query_event_keywords` — φ_{e→(c,g)}: extract the cues and tags associated
27057
+ * with an episodic event (reverse traversal to discover new retrieval paths).
27058
+ */
27059
+ queryEventKeywords(eventId: string): EventKeywords;
27060
+ /**
27061
+ * `query_event_context` — φ_{e→ctx}: retrieve the textual context surrounding
27062
+ * an episodic event (the event's own text plus its temporal neighbours on the
27063
+ * unified timeline).
27064
+ */
27065
+ queryEventContext(eventId: string, window?: number): string;
27066
+ /**
27067
+ * `query_personal_information` — φ_{cs→gs}: return the semantic aspects (tags)
27068
+ * associated with a person entity, e.g. `preference`, `occupation`.
27069
+ */
27070
+ queryPersonalInformation(person: string): TagNode[];
27071
+ /**
27072
+ * `query_personal_aspect` — φ_{(cs,gs)→vs}: retrieve the semantic content for a
27073
+ * `(person, aspect)` pair without scanning long episodic histories.
27074
+ */
27075
+ queryPersonalAspect(person: string, aspect: string): ContentNode[];
27076
+ /**
27077
+ * `query_topic_events` — φ_{τ→e}: retrieve episodic events associated with a
27078
+ * topic node, enabling efficient top-down localisation.
27079
+ */
27080
+ queryTopicEvents(topicId: string): ContentNode[];
27081
+ }
27082
+
27083
+ /**
27084
+ * Memory distillation pipeline — populates the Cue–Tag–Content graph from raw
27085
+ * dialogue (MRAgent §3.3 / Appendix B.1).
27086
+ *
27087
+ * The pipeline mirrors the paper's element-generation phase:
27088
+ * 1. **Rewrite** raw turns into self-contained sentences — pronoun resolution,
27089
+ * temporal normalisation (`YYYY-MM-DD`), and episodic segmentation.
27090
+ * 2. **Tag** each episode with a short associative phrase (`T_LLM`).
27091
+ * 3. **Cue** extraction — fine-grained entities/attributes (`K_LLM`).
27092
+ * 4. **Semantic** extraction — person-anchored stable facts (`S_LLM`).
27093
+ * 5. **Topic** abstraction — recurring patterns across episodes (`A_LLM`).
27094
+ *
27095
+ * When an {@link LLMProvider} is supplied the pipeline uses the paper's prompts
27096
+ * (Appendix E); otherwise it falls back to deterministic heuristics so the
27097
+ * feature works with zero configuration — matching the LLM-optional pattern used
27098
+ * elsewhere in the codebase (e.g. `LLMQueryPlanner`).
27099
+ *
27100
+ * @module agent/reconstruction/MemoryDistiller
27101
+ * @experimental
27102
+ */
27103
+
27104
+ declare class MemoryDistiller {
27105
+ private readonly llm?;
27106
+ private readonly keywords;
27107
+ constructor(llm?: LLMProvider | undefined);
27108
+ /** Run the full distillation pipeline over a dialogue. */
27109
+ distill(turns: DialogueTurn[]): Promise<DistillationResult$1>;
27110
+ /**
27111
+ * Build (or extend) a {@link CueTagContentGraph} from a distillation result.
27112
+ * Episodic, semantic and topic layers are populated in one pass.
27113
+ */
27114
+ buildGraph(result: DistillationResult$1, graph?: CueTagContentGraph): CueTagContentGraph;
27115
+ private distillWithLLM;
27116
+ private distillHeuristic;
27117
+ /** Cluster episodes by their most salient shared cue into topic nodes. */
27118
+ private deriveTopics;
27119
+ }
27120
+ /** Extract the first JSON object/array from a possibly noisy LLM completion. */
27121
+ declare function extractJson<T>(raw: string): T | undefined;
27122
+
27123
+ /**
27124
+ * Active memory reconstruction (MRAgent §4 / Algorithm 1).
27125
+ *
27126
+ * Rather than a one-shot "retrieve-then-reason" lookup, the reconstructor
27127
+ * formulates memory access as a stateful, multi-step process over the
27128
+ * Cue–Tag–Content graph. It maintains a reconstruction state `S(t) = (Z(t),
27129
+ * H(t))` — an active set of candidate elements `Z` and the accumulated
27130
+ * reconstructed context `H` — and iterates:
27131
+ *
27132
+ * 1. **Action selection** `f_select(x, H, Z)` — choose promising traversal
27133
+ * directions (forward cue→tag / (cue,tag)→content, reverse content→(cue,tag),
27134
+ * top-down topic→episode), reducing noise vs. exhaustive expansion.
27135
+ * 2. **Controlled traversal** — execute the selected actions to produce
27136
+ * candidates `Z̃(t+1)`.
27137
+ * 3. **Routing + state update** `f_route(x, H, Z̃)` — keep the candidates most
27138
+ * relevant to the query and prune the rest, then fold them into `H`.
27139
+ * 4. **Stopping** — terminate once accumulated evidence suffices.
27140
+ *
27141
+ * The default policy is a deterministic, embedding-free heuristic so the feature
27142
+ * works with zero configuration. When an {@link LLMProvider} is supplied the
27143
+ * final answer is synthesised by the LLM under the paper's QA prompt (Appendix E),
27144
+ * and routing is LLM-assisted; otherwise an extractive answer is returned.
27145
+ *
27146
+ * @module agent/reconstruction/MemoryReconstructor
27147
+ * @experimental
27148
+ */
27149
+
27150
+ declare class MemoryReconstructor {
27151
+ private readonly graph;
27152
+ private readonly llm?;
27153
+ /**
27154
+ * Optional semantic similarity in `[0, 1]` (e.g. `SemanticSearch`), used to
27155
+ * rank candidates during routing/answer when a live-store backing supplies
27156
+ * it. Falls back to lexical overlap when absent.
27157
+ */
27158
+ private readonly similarityFn?;
27159
+ private readonly toolkit;
27160
+ private readonly keywords;
27161
+ constructor(graph: CueTagContentGraph, llm?: LLMProvider | undefined,
27162
+ /**
27163
+ * Optional semantic similarity in `[0, 1]` (e.g. `SemanticSearch`), used to
27164
+ * rank candidates during routing/answer when a live-store backing supplies
27165
+ * it. Falls back to lexical overlap when absent.
27166
+ */
27167
+ similarityFn?: ((query: string, text: string) => Promise<number>) | undefined);
27168
+ /** Run active reconstruction for a query (Algorithm 1). */
27169
+ reconstruct(query: string, options?: ReconstructionOptions): Promise<ReconstructionResult>;
27170
+ private extractQueryCues;
27171
+ /**
27172
+ * Select promising traversal directions from the current active set. The
27173
+ * heuristic prefers to advance cues → tags → content, expands retrieved
27174
+ * content both reverse (new cues/tags) and top-down (topic → episode).
27175
+ */
27176
+ private selectActions;
27177
+ private traverse;
27178
+ /**
27179
+ * Rank candidate content by lexical relevance to the query, drop already-seen
27180
+ * nodes, and keep the top `budget`. This is the noise-pruning step that keeps
27181
+ * the reconstructed context focused.
27182
+ */
27183
+ private route;
27184
+ /**
27185
+ * Relevance of a candidate to the query. Uses semantic similarity when a
27186
+ * backing supplies it (embedding-based, captures paraphrase), otherwise falls
27187
+ * back to lexical keyword overlap.
27188
+ */
27189
+ private relevance;
27190
+ private shouldStop;
27191
+ private answer;
27192
+ }
27193
+
27194
+ /**
27195
+ * Bridge between the Cue–Tag–Content graph and MemoryJS's live memory modules.
27196
+ *
27197
+ * The paper organises memory into multi-granular layers (episodic / semantic /
27198
+ * topic) that mirror cognitive memory types (§3.2). MemoryJS already implements
27199
+ * those types, so the bridge persists each CTC content node into the
27200
+ * corresponding module so reconstructed memory is durable and visible to the
27201
+ * rest of the stack:
27202
+ *
27203
+ * - **Episodic** → first-class `memoryType: 'episodic'` entities stamped with
27204
+ * the conversation timestamp, so they land on the
27205
+ * {@link EpisodicMemoryManager} timeline and are temporally linked
27206
+ * (`precedes`/`follows`).
27207
+ * - **Semantic** → `memoryType: 'semantic'` fact entities anchored to their
27208
+ * person entity via a typed relation, and indexed for `SemanticSearch`.
27209
+ * - **Topic** → topic entities linked to their constituent episodes via a
27210
+ * `summarizes` relation (queryable through `GraphTraversal`).
27211
+ *
27212
+ * The bridge writes through narrow structural interfaces so it can be driven by
27213
+ * the real `ManagerContext` managers or by fakes in tests.
27214
+ *
27215
+ * @module agent/reconstruction/MemoryGraphBridge
27216
+ * @experimental
27217
+ */
27218
+
27219
+ /** Relation type connecting a topic entity to one of its episodes. */
27220
+ declare const TOPIC_SUMMARIZES = "summarizes";
27221
+ /**
27222
+ * The live-store dependencies the bridge writes through. Satisfied by the
27223
+ * `ManagerContext` managers (`entityManager`, `relationManager`,
27224
+ * `semanticSearch`) or by test doubles.
27225
+ */
27226
+ interface ReconstructiveBacking {
27227
+ /** Persist entities (existing names are skipped by `EntityManager`). */
27228
+ createEntities(entities: Entity[]): Promise<unknown>;
27229
+ /** Persist relations. */
27230
+ createRelations(relations: Relation[]): Promise<unknown>;
27231
+ /** Optional semantic similarity in `[0, 1]` for routing/answer ranking. */
27232
+ similarity?(a: string, b: string): Promise<number>;
27233
+ /** Optional: index a freshly-created entity for semantic search. */
27234
+ indexEntity?(entity: Entity): Promise<unknown>;
27235
+ /** Session id used to scope episodes onto the timeline. Default `mragent`. */
27236
+ sessionId?: string;
27237
+ }
27238
+ /** Summary of what a {@link MemoryGraphBridge.persist} call wrote. */
27239
+ interface BridgePersistResult {
27240
+ episodes: number;
27241
+ semanticFacts: number;
27242
+ topics: number;
27243
+ relations: number;
27244
+ }
27245
+ declare class MemoryGraphBridge {
27246
+ private readonly backing;
27247
+ private readonly sessionId;
27248
+ constructor(backing: ReconstructiveBacking);
27249
+ /** The session id episodes are written under (use with `getTimeline`). */
27250
+ get session(): string;
27251
+ /**
27252
+ * Persist a distillation result into the live store and annotate the in-memory
27253
+ * graph's content nodes with their backing entity names.
27254
+ */
27255
+ persist(result: DistillationResult$1, graph: CueTagContentGraph): Promise<BridgePersistResult>;
27256
+ }
27257
+
27258
+ /**
27259
+ * Reconstructive memory facade — the public entry point for the MRAgent-style
27260
+ * Cue–Tag–Content associative memory and active reconstruction.
27261
+ *
27262
+ * Wraps the construction pipeline ({@link MemoryDistiller}), the associative
27263
+ * graph ({@link CueTagContentGraph}), the traversal {@link MemoryToolkit}, and
27264
+ * the active {@link MemoryReconstructor} behind one cohesive API:
27265
+ *
27266
+ * ```typescript
27267
+ * const rm = new ReconstructiveMemory();
27268
+ * await rm.ingest([
27269
+ * { id: 'D1:1', speaker: 'Nate', text: "I won a video game tournament in July." },
27270
+ * { id: 'D1:2', speaker: 'Caroline', text: "I started a new painting class that month." },
27271
+ * ]);
27272
+ * const result = await rm.reconstruct("What did Caroline do in July?");
27273
+ * console.log(result.answer, result.evidence);
27274
+ * ```
27275
+ *
27276
+ * **Contract (graph-core):** the in-memory {@link CueTagContentGraph} is a
27277
+ * specialized associative *index*, not a second system-of-record. Durability
27278
+ * and graph queryability come from persisting through
27279
+ * {@link MemoryGraphBridge} into the Entity/Relation graph — which is the
27280
+ * default when constructed via `ctx.reconstructiveMemory()` (the context
27281
+ * wires its own `entityManager`/`relationManager`/`semanticSearch` as the
27282
+ * backing). Passing `backing: undefined` opts out and makes the instance
27283
+ * ephemeral; treat that as a testing/short-lived-process mode.
27284
+ *
27285
+ * @module agent/reconstruction/ReconstructiveMemory
27286
+ * @experimental
27287
+ */
27288
+
27289
+ /** Configuration for {@link ReconstructiveMemory}. */
27290
+ interface ReconstructiveMemoryConfig {
27291
+ /** Optional LLM provider for distillation + answer synthesis. */
27292
+ llmProvider?: LLMProvider;
27293
+ /** Pre-existing graph snapshot to restore from. */
27294
+ snapshot?: CTCGraphSnapshot;
27295
+ /**
27296
+ * Optional live-store backing. When supplied, ingested memory is persisted
27297
+ * into MemoryJS's episodic / semantic / topic modules (durable + searchable),
27298
+ * and semantic similarity is reused for reconstruction routing. When absent,
27299
+ * the facade runs the self-contained in-memory graph.
27300
+ */
27301
+ backing?: ReconstructiveBacking;
27302
+ }
27303
+ declare class ReconstructiveMemory {
27304
+ private graph;
27305
+ private readonly distiller;
27306
+ private readonly llm?;
27307
+ private readonly bridge?;
27308
+ private lastPersist?;
27309
+ constructor(config?: ReconstructiveMemoryConfig);
27310
+ private readonly backing?;
27311
+ /**
27312
+ * Construction phase: distil raw dialogue into Cue–Tag–Content structure and
27313
+ * merge it into the in-memory graph. When a live-store backing is configured,
27314
+ * the episodic / semantic / topic layers are also persisted into the
27315
+ * corresponding MemoryJS modules. Multiple `ingest` calls accumulate.
27316
+ */
27317
+ ingest(turns: DialogueTurn[]): Promise<DistillationResult$1>;
27318
+ /** Summary of what the most recent `ingest` persisted to the live store. */
27319
+ get lastPersistResult(): BridgePersistResult | undefined;
27320
+ /**
27321
+ * Reconstruction phase: answer a query via active, multi-step traversal of the
27322
+ * memory graph (Algorithm 1).
27323
+ */
27324
+ reconstruct(query: string, options?: ReconstructionOptions): Promise<ReconstructionResult>;
27325
+ /** Direct access to the traversal toolkit for manual graph exploration. */
27326
+ get toolkit(): MemoryToolkit;
27327
+ /** The underlying associative graph (read/inspect cues, tags, contents). */
27328
+ get memoryGraph(): CueTagContentGraph;
27329
+ /** Graph size statistics. */
27330
+ stats(): ReturnType<CueTagContentGraph['stats']>;
27331
+ /** Serialise the current graph (e.g. to persist alongside the knowledge base). */
27332
+ toSnapshot(): CTCGraphSnapshot;
27333
+ /** Replace the current graph with a restored snapshot. */
27334
+ loadSnapshot(snapshot: CTCGraphSnapshot): void;
27335
+ }
27336
+
25974
27337
  /**
25975
27338
  * Options for constructing a ManagerContext.
25976
27339
  */
@@ -26009,6 +27372,8 @@ declare class ManagerContext {
26009
27372
  private _graphTraversal?;
26010
27373
  private _searchManager?;
26011
27374
  private _rankedSearch?;
27375
+ private _graphRankPrior?;
27376
+ private _hybridSearchManager?;
26012
27377
  private _ioManager?;
26013
27378
  private _tagManager?;
26014
27379
  private _analyticsManager?;
@@ -26055,6 +27420,7 @@ declare class ManagerContext {
26055
27420
  private _roleAssignmentStore?;
26056
27421
  private _worldModelManager?;
26057
27422
  private _activeRetrieval?;
27423
+ private _reconstructiveMemory?;
26058
27424
  private _accessTracker?;
26059
27425
  private _decayEngine?;
26060
27426
  private _decayScheduler?;
@@ -26178,6 +27544,19 @@ declare class ManagerContext {
26178
27544
  get searchManager(): SearchManager;
26179
27545
  /** RankedSearch - TF-IDF/BM25 ranked search */
26180
27546
  get rankedSearch(): RankedSearch;
27547
+ /**
27548
+ * GraphRankPrior — cached graph-connectivity ranking signal (normalized
27549
+ * PageRank with degree fallback). Built over the existing GraphTraversal
27550
+ * and auto-invalidated via the storage GraphEventEmitter.
27551
+ * @experimental
27552
+ */
27553
+ get graphRankPrior(): GraphRankPrior;
27554
+ /**
27555
+ * HybridSearchManager — semantic + lexical + symbolic (+ optional graph)
27556
+ * layered search. Reads MEMORY_HYBRID_GRAPH_WEIGHT at first access; when
27557
+ * 0/unset (the default), the GraphRankPrior is not attached — zero overhead.
27558
+ */
27559
+ get hybridSearchManager(): HybridSearchManager;
26181
27560
  /**
26182
27561
  * Materialised search views — pre-computed result sets for repeated
26183
27562
  * filter-based queries. Lazy: only constructed on first access (which
@@ -26449,6 +27828,25 @@ declare class ManagerContext {
26449
27828
  * LLM-driven decomposition use `ctx.llmQueryPlanner`.
26450
27829
  */
26451
27830
  get activeRetrieval(): ActiveRetrievalController;
27831
+ /**
27832
+ * `ReconstructiveMemory` — MRAgent-style associative memory ("Memory is
27833
+ * Reconstructed, Not Retrieved"). Builds a Cue–Tag–Content graph from
27834
+ * dialogue (`ingest`) and answers queries via active, multi-step memory
27835
+ * reconstruction (`reconstruct`). Lazy; works zero-config with heuristic
27836
+ * distillation/reconstruction, or pass an `LLMProvider` for the paper's
27837
+ * LLM-driven distillation and answer synthesis.
27838
+ *
27839
+ * @param config Optional LLM provider / restored graph snapshot. Passing a
27840
+ * config re-instantiates the facade (invalidates the cached instance).
27841
+ */
27842
+ reconstructiveMemory(config?: ReconstructiveMemoryConfig): ReconstructiveMemory;
27843
+ /**
27844
+ * Build a {@link ReconstructiveBacking} that bridges the Cue–Tag–Content
27845
+ * layers to this context's live modules: episodic episodes onto the
27846
+ * `EpisodicMemoryManager` timeline, semantic facts into the entity graph +
27847
+ * `SemanticSearch`, and topic links as relations.
27848
+ */
27849
+ private buildReconstructiveBacking;
26452
27850
  /**
26453
27851
  * TransitionLedger - Append-only audit trail for state changes.
26454
27852
  * Returns null if not enabled via MEMORY_TRANSITION_LEDGER env var.
@@ -26512,6 +27910,7 @@ declare class ManagerContext {
26512
27910
  * - MEMORY_SALIENCE_FREQUENCY_WEIGHT (default: 0.2)
26513
27911
  * - MEMORY_SALIENCE_CONTEXT_WEIGHT (default: 0.2)
26514
27912
  * - MEMORY_SALIENCE_NOVELTY_WEIGHT (default: 0.1)
27913
+ * - MEMORY_SALIENCE_CONNECTIVITY_WEIGHT (default: 0 = disabled)
26515
27914
  */
26516
27915
  get salienceEngine(): SalienceEngine;
26517
27916
  /**
@@ -27846,6 +29245,14 @@ declare class VisibilityResolver {
27846
29245
  * persistence. Suitable as the default backend when no SQLite/Postgres
27847
29246
  * configuration exists, and as the fast/clean fixture in unit tests.
27848
29247
  *
29248
+ * **Contract (graph-core):** this backend is *ephemeral by design* — it is
29249
+ * an in-process turn buffer, not part of the knowledge graph's
29250
+ * system-of-record. Anything that must survive the process or be
29251
+ * queryable/traversable as graph content belongs in `SQLiteBackend`,
29252
+ * which routes through `MemoryEngine` into the Entity/Relation graph.
29253
+ * Do not extend this class with durability features; swap backends
29254
+ * instead (`MEMORY_BACKEND=sqlite`).
29255
+ *
27849
29256
  * Scoring delegates to `DecayEngine.calculatePrdEffectiveImportance` so
27850
29257
  * `get_weighted` returns the same PRD-formula scores that
27851
29258
  * `SQLiteBackend` (T13) will produce.
@@ -28005,11 +29412,29 @@ declare class QueryRewriter {
28005
29412
  /**
28006
29413
  * Procedure Store (3B.4)
28007
29414
  *
28008
- * Persists `Procedure` records as memoryjs entities (`entityType:
28009
- * 'procedure'`). Steps + metadata live in `observations` as a single
28010
- * JSON-encoded line; the rest of the entity carries triggers/successRate
28011
- * via observations and tags. This shape lets procedures roundtrip
28012
- * through both the JSONL and SQLite backends without schema changes.
29415
+ * Persists `Procedure` records as real graph structure instead of JSON
29416
+ * blobs, so procedure content is queryable and traversable:
29417
+ *
29418
+ * - The procedure itself is an `entityType: 'procedure'` entity (name =
29419
+ * `procedure.id`). Its observations carry the description plus
29420
+ * human-readable scalar lines (`[success-rate]: 0.85`,
29421
+ * `[execution-count]: 12`). Tags = `['procedure', ...triggers]`.
29422
+ * - Every step is its own `entityType: 'procedure-step'` entity named
29423
+ * `${procedureId}::step-${order}` (fallbacks: `${parentStepName}::fallback`,
29424
+ * recursively). Step observations encode one field per line:
29425
+ * `[order]: <n>`, `[action]: <action>`, `[timeout]: <ms>`, and one
29426
+ * `[param]: <JSON-key>=<JSON-value>` line per parameter — key and value
29427
+ * are JSON-encoded separately so arbitrary strings (equals signs,
29428
+ * newlines, unicode) roundtrip.
29429
+ * - Relations wire it together: procedure —`has_step`→ each top-level
29430
+ * step, step —`precedes`→ the next step in sequence, and step
29431
+ * —`has_fallback`→ its fallback step. Step entities set `parentId` to
29432
+ * the procedure id for hierarchy integration.
29433
+ *
29434
+ * Legacy JSON-blob procedures (`[procedure-steps]:` / `[procedure-meta]:`
29435
+ * observations) remain decodable via `decodeProcedure` and are
29436
+ * auto-migrated to the decomposed shape on `load()`; use
29437
+ * `migrateLegacyProcedures` for bulk migration.
28013
29438
  *
28014
29439
  * @module agent/procedural/ProcedureStore
28015
29440
  */
@@ -28017,28 +29442,61 @@ declare class QueryRewriter {
28017
29442
  declare const PROCEDURE_ENTITY_TYPE = "procedure";
28018
29443
  declare class ProcedureStore {
28019
29444
  private readonly entityManager;
28020
- constructor(entityManager: EntityManager);
29445
+ private readonly relationManager;
29446
+ constructor(entityManager: EntityManager, relationManager: RelationManager);
28021
29447
  /**
28022
- * Persist a new procedure. The entity name = `procedure.id`. Steps and
28023
- * metadata are encoded as JSON observations alongside any caller-supplied
28024
- * description observation. Idempotent on duplicate id (relies on
28025
- * `EntityManager.createEntities` semantics).
29448
+ * Persist a new procedure. The entity name = `procedure.id`; each step
29449
+ * (and recursive fallback) becomes its own `procedure-step` entity
29450
+ * linked via `has_step` / `precedes` / `has_fallback` relations.
29451
+ * Idempotent on duplicate id (relies on `EntityManager.createEntities`
29452
+ * skip-duplicate semantics). Step `order` values are assumed unique
29453
+ * within a procedure (they name the step entities).
28026
29454
  */
28027
29455
  save(procedure: Procedure): Promise<void>;
28028
29456
  /**
28029
- * Load a procedure by id, or undefined if not found. Tolerant of partial
28030
- * encodings — steps default to `[]`, meta to zeroed fields.
29457
+ * Load a procedure by id, or undefined if not found. Tolerant of
29458
+ * partial encodings — steps default to `[]`, scalars to zero.
29459
+ *
29460
+ * **Side effect (auto-migration):** when the entity still uses the
29461
+ * legacy JSON-blob encoding (`[procedure-steps]:` observation), it is
29462
+ * decoded with the legacy decoder and then rewritten in place to the
29463
+ * decomposed graph shape (step entities + relations) before returning.
28031
29464
  */
28032
29465
  load(id: string): Promise<Procedure | undefined>;
28033
29466
  /**
28034
- * Replace an existing procedure's steps + metadata. Throws if the
28035
- * entity doesn't exist or isn't a procedure.
29467
+ * Replace an existing procedure's steps + metadata. Deletes the
29468
+ * procedure's current step entities (cascading their relations — see
29469
+ * `EntityManager.deleteEntities`) and recreates the step graph from
29470
+ * `procedure.steps`. Throws if the entity doesn't exist.
28036
29471
  */
28037
29472
  update(procedure: Procedure): Promise<void>;
29473
+ /** Create step entities + linking relations for `procedure.steps`. */
29474
+ private createStepGraph;
29475
+ /**
29476
+ * All step entity names reachable from the procedure via `has_step`
29477
+ * then recursive `has_fallback` edges.
29478
+ */
29479
+ private collectStepEntityNames;
29480
+ /**
29481
+ * Load top-level steps via `has_step`, ordered by the `precedes` chain
29482
+ * (preserving the original array order); falls back to a numeric sort
29483
+ * on `[order]` when the chain is incomplete.
29484
+ */
29485
+ private loadSteps;
29486
+ /**
29487
+ * Load one step entity plus its recursive fallback chain. Records the
29488
+ * step's `precedes` successor (among `topSet`) into `successor` when
29489
+ * provided. Returns null when the entity is missing or not a step.
29490
+ */
29491
+ private loadStepTree;
28038
29492
  }
28039
29493
  /**
28040
- * Pure decoder: extracts `Procedure` shape from the observation list.
28041
- * Exported for tests and for callers wanting to introspect raw entities.
29494
+ * Pure decoder for the legacy JSON-blob observation shape
29495
+ * (`[procedure-steps]:` / `[procedure-meta]:` lines).
29496
+ *
29497
+ * @deprecated Legacy decoder — kept for reading pre-decomposition
29498
+ * entities. `ProcedureStore.load()` auto-migrates such entities; new
29499
+ * code should go through `ProcedureStore`.
28042
29500
  */
28043
29501
  declare function decodeProcedure(id: string, observations: string[]): Procedure;
28044
29502
 
@@ -28739,4 +30197,4 @@ declare class LangChainMemoryAdapter {
28739
30197
  clear(): Promise<void>;
28740
30198
  }
28741
30199
 
28742
- export { type ABACCondition, type ABACContext, type ABACDecision, type ABACEffect, type ABACOp, ABACPolicy, type ABACRule, APIKeyStore, type ValidationResult as APIKeyValidationResult, type AcceptDecisionResult, type AccessContext, AccessContextBuilder, type AccessPattern, type AccessStats, AccessTracker, type AccessTrackerConfig, type Action, type ActiveRetrievalConfig, ActiveRetrievalController, type AdaptiveDepthConfig, type AdaptiveReductionResult, type AdaptiveResult, type AddExclusionRuleInput, type AddHeuristicOptions, type AddObservationInput, AddObservationInputSchema, AddObservationsInputSchema, type AddTurnOptions, type AddTurnResult, type AdequacyCheck, type AgentEntity, type AgentMemoryConfig, AgentMemoryManager, type AgentObservation, type AgentRole, AnalyticsManager, type ArchiveCriteria, type ArchiveCriteriaInput, ArchiveCriteriaSchema, ArchiveManager, type ArchiveOptions, type ArchiveReflectionResult, type ArchiveResult, type ArchiveResultExtended, type ArtifactEntity, type ArtifactFilter, ArtifactManager, type ArtifactType, AsyncMutex, type AsyncMutexOptions, type AttributionMode, type AuditEntry, type AuditFilter, AuditLog, type AuditOperation, type AuditStats, type AutoLinkOptions, type AutoLinkResult, AutoLinker, type AutoSearchResult, type BM25Config, type BM25DocumentEntry, type BM25Index, BM25Search, type BackupInfo, type BackupInfoExtended, type BackupMetadata, type BackupMetadataExtended, type BackupOptions, type BackupResult, BasicSearch, BatchCreateEntitiesSchema, BatchCreateRelationsSchema, type BatchItemResult, type BatchOperation, type BatchOperationType, type BatchOptions, type BatchProcessResult, BatchProcessor, type BatchProcessorOptions, type BatchProgress, type BatchProgressCallback, type BatchResult, BatchTransaction, type BidirectionalRelation, type BooleanCacheEntry, type BooleanOpNode, type BooleanQueryNode, BooleanSearch, COMPRESSION_CONFIG, type CacheCompressionStats, type CacheStats, type CachedQueryEntry, type CausalChain, type CausalCycle, CausalReasoner, type CausalReasonerConfig, type CausalRelationType, type CentralityResult, type ClusterMethod, CognitiveLoadAnalyzer, type CognitiveLoadConfig, type CognitiveLoadMetrics, CollaborationAuditEnforcer, type CollaborationAuditEnforcerOptions, CollaborativeSynthesis, type CollaborativeSynthesisConfig, type CommonSearchFilters, type ComponentMemoryUsage, CompositeDistillationPolicy, CompressedCache, type CompressedCacheOptions, type CompressedCacheStats, type CompressedMemory, CompressionManager, type CompressionMetadata, type CompressionOptions, type CompressionQuality, type CompressionResult, type ConfirmationResult, type ConflictInfo, ConflictResolver, type ConflictResolverConfig, type ConflictStrategy, type ConnectedComponentsResult, type ConsolidateOptions, type ConsolidationAction, type ConsolidationCycleResult, ConsolidationPipeline, type ConsolidationPipelineConfig, type ConsolidationResult, type ConsolidationRule, ConsolidationScheduler, type ConsolidationSchedulerConfig, type ConsolidationTrigger, type ContextPackage, type ContextProfile, ContextProfileManager, type ContextRetrievalOptions, ContextWindowManager, type ContextWindowManagerConfig, type Contradiction$1 as Contradiction, ContradictionDetector, type CreateArtifactOptions, type CreateEntityInput, CreateEntitySchema, type CreateEpisodeOptions, type CreateMemoryOptions, type CreatePlanOptions, type CreateRelationInput, CreateRelationSchema, type CreateWorkThreadOptions, CycleDetectedError, DEFAULT_BASE_DIR, DEFAULT_BM25_CONFIG, DEFAULT_CAUSAL_RELATION_TYPES, DEFAULT_DUPLICATE_THRESHOLD, DEFAULT_EMBEDDING_CACHE_OPTIONS, DEFAULT_FILE_NAMES, DEFAULT_HYBRID_WEIGHTS, DEFAULT_INDEXER_OPTIONS, DEFAULT_PERMISSION_MATRIX, DEFAULT_PII_PATTERNS, DEFAULT_SCORER_WEIGHTS, DOCUMENT_PREFIX, type DateRange, DateRangeSchema, type DecayCycleResult, DecayEngine, type DecayEngineConfig, type DecayOperationOptions, type DecayOptions, type DecayResult, DecayScheduler, type DecaySchedulerConfig, type DecisionEntityOptions, type DecisionInput, DecisionManager, type DecisionRule, type DedupTier, type DeduplicationOptions, DefaultDistillationPolicy, type DeleteObservationInput, DeleteObservationInputSchema, DeleteObservationsInputSchema, DeleteRelationsSchema, type DistillOptions, type DistillationConfig, DistillationPipeline, type DistillationResult, type DistillationStats, type DistilledLesson, type DistilledMemory, type DocumentVector, type DreamCycleResult, DreamEngine, type DreamEngineCallbacks, type DreamEngineConfig, type DreamPhaseConfig, type DreamPhaseResult, type DuplicateCheckResult, DuplicateEntityError, type DuplicateObservationGroup, type DuplicateObservationOccurrence, type DuplicatePair, ENTITY_STATUS_TRANSITIONS, ENV_VARS, EarlyTerminationManager, type EarlyTerminationOptions, type EarlyTerminationResult, EmbeddingCache, type EmbeddingCacheOptions, type EmbeddingCacheStats, type EmbeddingConfig, type EmbeddingMode, type EmbeddingProgressCallback, type EmbeddingService, type EndSessionResult, type Entity, type EntityCreatedEvent, type EntityDeletedEvent, type EntityInput, EntityManager, type EntityManagerOptions, EntityNamesSchema, EntityNotFoundError, type EntityRuleResult, EntitySchema, type EntityStatus, type EntityUpdatedEvent, type EntityValidationIssue, type EntityValidationResult, type EntityValidationRule, EntityValidator, type EntityValidatorConfig, type EntityWithContext, type EntropyFilterConfig, EntropyFilterStage, type EpisodicMemoryConfig, type EpisodicMemoryEntity, EpisodicMemoryManager, EpisodicRelations, ErrorCode, type ErrorOptions, type ExcludedEntity, type ExclusionCheckResult, ExclusionManager, type Experience, ExperienceExtractor, type ExperienceExtractorConfig, type ExperienceType, type ExplainedSearchResult, ExportError, type ExportFilter, type ExportFilterInput, ExportFilterSchema, type ExportFormat, ExportFormatSchema, type ExportOptions, type ExportResult, type ExtendedExportFormatInput, ExtendedExportFormatSchema, type ExtendedPoolStats, type ExtendedQueryCostEstimate, type ExtractedEntity, type ExtractedFact, FILE_EXTENSIONS, FILE_SUFFIXES, type FactExtractionOptions, type FactExtractionResult, FactExtractor, FailureDistillation, type FailureDistillationConfig, type FailureDistillationResult, type FailureEntityOptions, type GetAllOptions as FailureGetAllOptions, type FailureInput, type LookupOptions as FailureLookupOptions, FailureManager, type FailureManagerConfig, type FieldNode, FileOperationError, type FlushResult, type ForContextOptions, type ForgetOptions, type ForgetResult, FreshnessManager, type FreshnessManagerConfig, type FreshnessReport, type FuzzyCacheKey, FuzzySearch, type FuzzySearchOptions, GRAPH_LIMITS, type GetWeightedOptions, GovernanceManager, type GovernanceOperationOptions, type GovernancePolicy, GovernanceTransaction, type Granularity, type GraphCompressionResult, type GraphEvent, type GraphEventBase, GraphEventEmitter, type GraphEventListener, type GraphEventMap, type GraphEventType, type GraphLoadedEvent, type GraphProjection, type GraphSavedEvent, type GraphStats, GraphStorage, GraphTraversal, type GroupMembership, type GroupingResult, type HeuristicConflict, HeuristicExtractionStage, type HeuristicExtractionStageConfig, type HeuristicGuideline, HeuristicManager, type HeuristicMatch, type HeuristicUpdateResult, HierarchyManager, HybridScorer, type HybridScorerOptions, HybridSearchManager, type HybridSearchOptions, type HybridSearchResult, type HybridWeights, type IDistillationPolicy, type IGraphStorage, IMPORTANCE_RANGE, type IMemoryBackend, IOManager, type ISummarizationProvider, type IVectorStore, ImportError, type ImportFormat, type ImportFormatInput, ImportFormatSchema, type ImportResult, ImportanceScorer, type ImportanceScorerConfig, InMemoryBackend, InMemoryVectorStore, IncrementalIndexer, type IncrementalIndexerOptions, type IndexMemoryUsage, type IndexOperation, type IndexOperationType, type IngestInput, type IngestOptions, type IngestResult, InsufficientEntitiesError, InvalidImportanceError, type IssueOptions, type IssueResult, type JSONValue, type JsonSchema, type KeyRecord, KeywordExtractor, type KnowledgeGraph, KnowledgeGraphError, ManagerContext as KnowledgeGraphManager, type LLMProvider, LLMQueryPlanner, type LLMQueryPlannerConfig, LLMSearchExecutor, type LLMSearchExecutorOptions, LOG_PREFIXES, LangChainMemoryAdapter, type LayerRecommendationOptions, type LayerTiming, type LexicalSearchResult, type ListDecisionsOptions, type ListPlansOptions, type ListReflectionsOptions, LocalEmbeddingService, type LogLevel, type LongRunningOperationOptions, LowEntropyContentError, LowercaseCache, type LowercaseData, MCPToolObserverAdapter, MEMORY_TYPES, ManagerContext, type ManagerContextOptions, type MatchedTerm, type MemoryAcquisitionMethod, type MemoryAlert, type MemoryChangeCallback, MemoryEngine, type MemoryEngineConfig, type MemoryEngineEventName, MemoryFormatter, type MemoryFormatterConfig, type MemoryMergeStrategy, MemoryMonitor, type MemorySource, type MemoryThresholds, type MemoryTurn, type MemoryType, type MemoryUsageStats, type MemoryValidationIssue, type MemoryValidationResult, MemoryValidator, type MemoryValidatorConfig, type Contradiction as MemoryValidatorContradiction, type MemoryVisibility, type MergeResult, type MergeStrategy, type MergeStrategyInput, MergeStrategySchema, MockEmbeddingService, type MultiAgentConfig, MultiAgentMemoryManager, NGramIndex, type NGramIndexStats, NameIndex, NoOpDistillationPolicy, type NormalizationOptions, type NormalizationResult, type ObservableDataModelAdapterOptions, type ObservableDataModelShape, type ObservationAddedEvent, type ObservationDedupFilter, ObservationDedupManager, type ObservationDedupManagerConfig, ObservationDedupReportStage, type ObservationDedupReportStageConfig, type ObservationDeletedEvent, ObservationManager, ObservationNormalizer, type ObservationScore, type ObservationSource, ObserverPipeline, type ObserverPipelineOptions, type ObserverPipelineStats, OpenAIEmbeddingService, OperationCancelledError, type OperationResult, OperationType, OptimizedInvertedIndex, OptionalEntityNamesSchema, OptionalTagsSchema, type Outcome, PROCEDURE_ENTITY_TYPE, type PaginatedCacheEntry, type PaginatedResult, type PaginationParams, ParallelSearchExecutor, type ParallelSearchOptions, type ParallelSearchResult, type ParsePaginationOptions, type ParsedTemporalRange, type PathResult, PatternDetector, type PatternResult, type Permission, type PermissionMatrix, type PermissionMatrixRow, type PhaseDefinition, type PhraseNode, type PiiPattern, PiiRedactor, type PiiRedactorOptions, type PipelineStage, PlanManager, type PlanManagerConfig, type PoolEventCallback, type PostingListResult, type PreparedEntity, type ProceduralMemoryEntity, type ProcedureInvoker, ProcedureManager, type ProcedureManagerConfig, ProcedureStore, type ProfileConfig, type ProfileEntity, ProfileManager, type ProfileManagerConfig, type ProfileOptions, type ProfileResponse, type ProgressCallback, type ProgressInfo, type ProgressInfoCallback, type ProgressOptions, ProjectContextManager, type ProjectContextManagerConfig, type ProjectContextUpsertInput, type PromotionCriteria, type PromotionMarkOptions, type PromotionResult, type ProspectiveMemoryConfig, ProspectiveMemoryManager, ProspectivePromotionStage, type ProximityMatch, type ProximityMatchLocation, type ProximityNode, ProximitySearch, type PushSubGoalOptions, QUERY_LIMITS, QUERY_PREFIX, type QuantizationParams, type QuantizedSearchResult, QuantizedVectorStore, type QuantizedVectorStoreOptions, type QuantizedVectorStoreStats, type QueryAnalysis, QueryAnalyzer, type QueryCostEstimate, QueryCostEstimator, type QueryCostEstimatorOptions, type QueryLogEntry, QueryLogger, type QueryLoggerConfig, type QueryNode, QueryParser, type QueryPlan, QueryPlanCache, type QueryPlanCacheOptions, type QueryPlanCacheStats, QueryPlanner, QueryRewriter, type QueryStage, type QueryTrace, QueryTraceBuilder, type QueueStats, RankedSearch, type RateLimitVerdict, RateLimiter, type RateLimiterConfig, RbacMiddleware, type RbacMiddlewareOptions, type RbacPolicy, ReadOnlyMemoryGraphDataError, type ReadonlyKnowledgeGraph, type RecordOutcomeInput, type RedactionResult, type RedactionStats, type RedundancyGroup, RefConflictError, type RefEntry, RefIndex, type RefIndexStats, RefNotFoundError, type RefinementHistoryEntry, type ReflectionEntityOptions, type ReflectionInput, ReflectionManager$1 as ReflectionManager, ReflectionManager as ReflectionMemoryManager, type ReflectionManagerConfig as ReflectionMemoryManagerConfig, type ReflectionOptions, type ReflectionResult, ReflectionStage, type ReflectionStageConfig, type ReinforcementOptions, type RejectDecisionResult, type Relation, RelationBuilder, type RelationCreatedEvent, type RelationDeletedEvent, RelationIndex, type RelationInput, RelationManager, RelationNotFoundError, type RelationProperties, RelationSchema, type RelationValidationError, type RelationValidationResult, type RelationValidationWarning, type RelevanceOptions, type ResolutionResult, type ResourcePermissionOverrides, type ResourceType, type RestHandler, type RestMethod, type RestRequest, type RestResponse, RestRouter, type RestoreResult, type Result, type RetrievalContext, type RetrievalDecision, type RetrievalRound, type RetrieveContextOptions, type RewriteResult, type Role, type RoleAssignment, RoleAssignmentStore, type RoleAssignmentStoreOptions, type RoleProfile, type RouteDefinition, RowLevelFilter, type RowPredicate, type Rule, type RuleConditions, type RuleEvaluationResult, RuleEvaluator, SEARCH_LIMITS, SIMILARITY_WEIGHTS, SQLiteBackend, type SQLiteBackendOptions, SQLiteStorage, type SQLiteStorageWithEmbeddings, SQLiteVectorStore, STOPWORDS, STREAMING_CONFIG, type SalienceComponents, type SalienceContext, SalienceEngine, type SalienceEngineConfig, type SalienceWeights, type SavedSearch, type SavedSearchInput, SavedSearchInputSchema, SavedSearchManager, type SavedSearchUpdateInput, SavedSearchUpdateSchema, type ScheduleOptions, SchemaValidator, type ScoreBoost, type ScoreOptions, type ScoredEntity, type ScoredKeyword, type ScoredResult, type ScoringSignal, SearchCache, type SearchExplanation, SearchFilterChain, type SearchFilters, type SearchFunction, type SearchLayer, SearchManager, type SearchMethod, type SearchQuery, SearchQuerySchema, type SearchResult, SearchSuggestions, SemanticForget, type SemanticForgetOptions, type SemanticForgetResult, type SemanticIndexOptions, type SemanticLayerResult, type SemanticMemoryEntity, SemanticSearch, type SemanticSearchResult, type SessionCheckpointData, SessionCheckpointManager, type SessionConfig, type SessionEntity, type SessionHistoryOptions, SessionManager, type SessionMemoryFilter, type SessionOutcome, SessionQueryBuilder, type SessionSearchOptions, type SessionStatus, SpellChecker, type SpellCheckerConfig, type SpellSuggestion, type SpilloverResult, type SplitOptions, type SplitResult, type StageResult, type StartSessionOptions, StepSequencer, type StorageConfig, type StreamResult, StreamingExporter, type StructuredQuery, type SubQuery, type SuggestOptions, type SuggestToolOptions, type SummarizationConfig, type SummarizationResult, SummarizationService, type SupersedeDecisionResult, type SymbolicFilters, type SymbolicResult, SymbolicSearch, type SymbolicSearchResult, type SynthesisResult, TFIDFEventSync, type TFIDFIndex, TFIDFIndexManager, type TagAlias, type TagAliasInput, TagAliasSchema, TagManager, type Task, type TaskBatchOptions, type TaskHandle, TaskPriority, TaskQueue, type TaskResult, TaskStatus, type TaskSubmitOptions, type TemporalFilterField, type TemporalFocus, TemporalQueryParser, type TemporalRange, type TemporalRelation, TemporalSearch, type TemporalSearchOptions, type TermNode, type TimelineOptions, type TokenBreakdown, type TokenEstimationOptions, type TokenizedEntity, ToolAffordanceManager, type ToolAffordanceManagerConfig, type ToolAffordanceStats, type ToolCallEvent, ToolCallObserver, type ToolResponse, type ToolSuggestion, type Trajectory, type TrajectoryCluster, TrajectoryCompressor, type TrajectoryCompressorConfig, type TrajectoryMergeStrategy, TransactionManager, type TransactionOperation, type TransactionResult, type TransitionEvent, type TransitionFilter, TransitionLedger, type TraversalOptions, type TraversalResult, TypeIndex, type UpdateEntityInput, UpdateEntitySchema, type ValidatedPagination, ValidationError, type ValidationIssue, type ValidationReport, type ValidationResult$1 as ValidationResult, type ValidationWarning, type VectorSearchResult, VisibilityResolver, type VisualizeOptions, type WakeUpOptions, type WakeUpResult, type WeightedRelation, type WeightedTurn, type WildcardNode, type WorkThread, type WorkThreadFilter, WorkThreadManager, type WorkThreadStatus, type WorkerPoolConfig, WorkerPoolManager, WorkerTaskManager, type WorkerTaskManagerStats, type WorkingMemoryConfig, type WorkingMemoryEntity, WorkingMemoryManager, type WorkingMemoryOptions, WorldModelManager, type WorldModelManagerOptions, type WorldStateChange, type WorldStateEntity, WorldStateSnapshot, addUniqueTags, all, allRelationsValidMetadata, applyPagination, asWarning, batchProcess, batchProcessViaWorkers, buildTFVector, calculateIDF, calculateIDFFromTokenSets, calculateTF, calculateTFIDF, calculateTextSimilarity, checkCancellation, chunkArray, cleanupAllCaches, clearAllSearchCaches, compress, compressFile, compressToBase64, computeEntropy, cosineSimilarity, createCustomProfile, createDetailedProgressReporter, createEmbeddingService, createMetadata, createObservableDataModelFromGraph, createProgress, createProgressInfo, createProgressReporter, createStorage, createStorageFromPath, createThrottledProgress, createUncompressedMetadata, createVectorStore, custom, customSync, debounce, decodeProcedure, decompress, decompressFile, decompressFromBase64, defaultMemoryPath, email, ensureMemoryFilePath, entityExists, entityPassesFilters, entityToText, err, escapeCsvFormula, executeWithPhases, extractToolName, filterByCreatedDate, filterByEntityType, filterByImportance, filterByModifiedDate, filterByTags, filterParallel, findEntitiesByNames, findEntityByName, fnv1aHash, formatErrorResponse, formatRawResponse, formatTextResponse, formatToolResponse, formatZodErrors, generateSuggestions, getAllCacheStats, getCompressionRatio, getCurrentTimestamp, getEntityIndex, getEntityNameSet, getPaginationMeta, getPoolStats, getQuickHint, getRoleProfile, getWorkerPoolManager, getWorkerTaskManager, globalMemoryMonitor, groupEntitiesByType, hasAllTags, hasBrotliExtension, hasConfidence, hasMatchingTag, isAgentEntity, isArtifactEntity, isBidirectionalRelation, isCurrentlyValid, isEpisodicMemory, isErr, isOk, isPrefixPattern, isProceduralMemory, isProfileEntity, isSemanticMemory, isSessionEntity, isTemporalRelation, isValidISODate, isWeightedRelation, isWithinDateRange, isWithinImportanceRange, isWorkingMemory, isoDate, l2Normalize, levenshteinDistance, listRoleProfiles, loadConfigFromEnv, logger, mapOk, mapParallel, matchesPhrase, matchesPrefix, max, maxItems, maxLength, mergeConfig, min, minItems, minLength, normalizeTag, normalizeTags, ok, oneOf, paginate, paginateArray, parallelFilter, parallelLimit, parallelMap, parseDateRange, parsePaginationParams, passesEntropyFilter, pattern, permissionsForRole, processBatch, processBatchesWithProgress, processWithRetry, range, rateLimitedProcess, removeEntityByName, removeTags, required, resolveRoleProfile, sanitizeObject, searchCaches, shutdownParallelUtils, cosineSimilarity$1 as textCosineSimilarity, tokenize as textTokenize, throttle, tokenize$1 as tokenize, touchEntity, typeOf, unwrap, unwrapOr, url, validateArrayWithSchema, validateConfig, validateEntity, validateFilePath, validateImportance, validatePagination, validateRelation, validateRelationMetadata, validateRelationsMetadata, validateSafe, validateTags, validateWithSchema, when, withRetry };
30200
+ export { type ABACCondition, type ABACContext, type ABACDecision, type ABACEffect, type ABACOp, ABACPolicy, type ABACRule, APIKeyStore, type ValidationResult as APIKeyValidationResult, type AcceptDecisionResult, type AccessContext, AccessContextBuilder, type AccessPattern, type AccessStats, AccessTracker, type AccessTrackerConfig, type Action, type ActiveRetrievalConfig, ActiveRetrievalController, type AdaptiveDepthConfig, type AdaptiveReductionResult, type AdaptiveResult, type AddExclusionRuleInput, type AddHeuristicOptions, type AddObservationInput, AddObservationInputSchema, AddObservationsInputSchema, type AddTurnOptions, type AddTurnResult, type AdequacyCheck, type AgentEntity, type AgentMemoryConfig, AgentMemoryManager, type AgentObservation, type AgentRole, AnalyticsManager, type ArchiveCriteria, type ArchiveCriteriaInput, ArchiveCriteriaSchema, ArchiveManager, type ArchiveOptions, type ArchiveReflectionResult, type ArchiveResult, type ArchiveResultExtended, type ArtifactEntity, type ArtifactFilter, ArtifactManager, type ArtifactType, AsyncMutex, type AsyncMutexOptions, type AttributionMode, type AuditEntry, type AuditFilter, AuditLog, type AuditOperation, type AuditStats, type AutoLinkOptions, type AutoLinkResult, AutoLinker, type AutoSearchResult, BLOCKED_BY_RELATION, type BM25Config, type BM25DocumentEntry, type BM25Index, BM25Search, type BackupInfo, type BackupInfoExtended, type BackupMetadata, type BackupMetadataExtended, type BackupOptions, type BackupResult, BasicSearch, BatchCreateEntitiesSchema, BatchCreateRelationsSchema, type BatchItemResult, type BatchOperation, type BatchOperationType, type BatchOptions, type BatchProcessResult, BatchProcessor, type BatchProcessorOptions, type BatchProgress, type BatchProgressCallback, type BatchResult, BatchTransaction, type BidirectionalRelation, type BooleanCacheEntry, type BooleanOpNode, type BooleanQueryNode, BooleanSearch, type BridgePersistResult, CHILD_OF_RELATION, COMPRESSION_CONFIG, type CTCGraphSnapshot, type CTCTriple, type CacheCompressionStats, type CacheStats, type CachedQueryEntry, type CausalChain, type CausalCycle, CausalReasoner, type CausalReasonerConfig, type CausalRelationType, type CentralityResult, type ClusterMethod, CognitiveLoadAnalyzer, type CognitiveLoadConfig, type CognitiveLoadMetrics, CollaborationAuditEnforcer, type CollaborationAuditEnforcerOptions, CollaborativeSynthesis, type CollaborativeSynthesisConfig, type CommonSearchFilters, type ComponentMemoryUsage, CompositeDistillationPolicy, CompressedCache, type CompressedCacheOptions, type CompressedCacheStats, type CompressedMemory, CompressionManager, type CompressionMetadata, type CompressionOptions, type CompressionQuality, type CompressionResult, type ConfirmationResult, type ConflictInfo, ConflictResolver, type ConflictResolverConfig, type ConflictStrategy, type ConnectedComponentsResult, type ConsolidateOptions, type ConsolidationAction, type ConsolidationCycleResult, ConsolidationPipeline, type ConsolidationPipelineConfig, type ConsolidationResult, type ConsolidationRule, ConsolidationScheduler, type ConsolidationSchedulerConfig, type ConsolidationTrigger, type ContentLayer, type ContentNode, type ContextPackage, type ContextProfile, ContextProfileManager, type ContextRetrievalOptions, ContextWindowManager, type ContextWindowManagerConfig, type Contradiction$1 as Contradiction, ContradictionDetector, type CreateArtifactOptions, type CreateEntityInput, CreateEntitySchema, type CreateEpisodeOptions, type CreateMemoryOptions, type CreatePlanOptions, type CreateRelationInput, CreateRelationSchema, type CreateWorkThreadOptions, type CueNode, CueTagContentGraph, CycleDetectedError, DEFAULT_BASE_DIR, DEFAULT_BM25_CONFIG, DEFAULT_CAUSAL_RELATION_TYPES, DEFAULT_DUPLICATE_THRESHOLD, DEFAULT_EMBEDDING_CACHE_OPTIONS, DEFAULT_FILE_NAMES, DEFAULT_HYBRID_WEIGHTS, DEFAULT_INDEXER_OPTIONS, DEFAULT_MAX_PAGERANK_ENTITIES, DEFAULT_NEIGHBOR_DAMPING, DEFAULT_NEIGHBOR_TOP_K, DEFAULT_PERMISSION_MATRIX, DEFAULT_PII_PATTERNS, DEFAULT_SCORER_WEIGHTS, DOCUMENT_PREFIX, type DateRange, DateRangeSchema, type DecayCycleResult, DecayEngine, type DecayEngineConfig, type DecayOperationOptions, type DecayOptions, type DecayResult, DecayScheduler, type DecaySchedulerConfig, type DecisionEntityOptions, type DecisionInput, DecisionManager, type DecisionRule, type DedupTier, type DeduplicationOptions, DefaultDistillationPolicy, type DeleteObservationInput, DeleteObservationInputSchema, DeleteObservationsInputSchema, DeleteRelationsSchema, type DialogueTurn, type DistillOptions, type DistillationConfig, DistillationPipeline, type DistillationResult, type DistillationStats, type DistilledLesson, type DistilledMemory, type DistilledSentence, type DocumentVector, type DreamCycleResult, DreamEngine, type DreamEngineCallbacks, type DreamEngineConfig, type DreamPhaseConfig, type DreamPhaseResult, type DuplicateCheckResult, DuplicateEntityError, type DuplicateObservationGroup, type DuplicateObservationOccurrence, type DuplicatePair, ENTITY_STATUS_TRANSITIONS, ENV_VARS, EarlyTerminationManager, type EarlyTerminationOptions, type EarlyTerminationResult, EmbeddingCache, type EmbeddingCacheOptions, type EmbeddingCacheStats, type EmbeddingConfig, type EmbeddingMode, type EmbeddingProgressCallback, type EmbeddingService, type EndSessionResult, type Entity, type EntityCreatedEvent, type EntityDeletedEvent, type EntityInput, EntityManager, type EntityManagerOptions, EntityNamesSchema, EntityNotFoundError, type EntityRenamedEvent, type EntityRuleResult, EntitySchema, type EntityStatus, type EntityUpdatedEvent, type EntityValidationIssue, type EntityValidationResult, type EntityValidationRule, EntityValidator, type EntityValidatorConfig, type EntityWithContext, type EntropyFilterConfig, EntropyFilterStage, type EpisodicMemoryConfig, type EpisodicMemoryEntity, EpisodicMemoryManager, EpisodicRelations, ErrorCode, type ErrorOptions, type EventKeywords, type ExcludedEntity, type ExclusionCheckResult, ExclusionManager, type Experience, ExperienceExtractor, type ExperienceExtractorConfig, type ExperienceType, type ExplainedSearchResult, ExportError, type ExportFilter, type ExportFilterInput, ExportFilterSchema, type ExportFormat, ExportFormatSchema, type ExportOptions, type ExportResult, type ExtendedExportFormatInput, ExtendedExportFormatSchema, type ExtendedPoolStats, type ExtendedQueryCostEstimate, type ExtractedEntity, type ExtractedFact, FILE_EXTENSIONS, FILE_SUFFIXES, type FactExtractionOptions, type FactExtractionResult, FactExtractor, FailureDistillation, type FailureDistillationConfig, type FailureDistillationResult, type FailureEntityOptions, type GetAllOptions as FailureGetAllOptions, type FailureInput, type LookupOptions as FailureLookupOptions, FailureManager, type FailureManagerConfig, type FieldNode, FileOperationError, type FlushResult, type ForContextOptions, type ForgetOptions, type ForgetResult, FreshnessManager, type FreshnessManagerConfig, type FreshnessReport, type FuzzyCacheKey, FuzzySearch, type FuzzySearchOptions, GRAPH_LIMITS, type GetWeightedOptions, GovernanceManager, type GovernanceOperationOptions, type GovernancePolicy, GovernanceTransaction, type Granularity, type GraphCompressionResult, type GraphEvent, type GraphEventBase, GraphEventEmitter, type GraphEventListener, type GraphEventMap, type GraphEventType, type GraphHybridOptions, type GraphHybridSearchResult, type GraphLayerResult, type GraphLoadedEvent, type GraphProjection, GraphRankPrior, type GraphRankPriorOptions, type GraphSavedEvent, type GraphStats, GraphStorage, GraphTraversal, type GroupMembership, type GroupingResult, HAS_CHECKPOINT_RELATION, type HeuristicConflict, HeuristicExtractionStage, type HeuristicExtractionStageConfig, type HeuristicGuideline, HeuristicManager, type HeuristicMatch, type HeuristicUpdateResult, HierarchyManager, HybridScorer, type HybridScorerOptions, type HybridSearchLayer, HybridSearchManager, type HybridSearchOptions, type HybridSearchResult, type HybridWeights, type IDistillationPolicy, type IGraphStorage, IMPORTANCE_RANGE, type IMemoryBackend, IOManager, type ISummarizationProvider, type IVectorStore, ImportError, type ImportFormat, type ImportFormatInput, ImportFormatSchema, type ImportResult, ImportanceScorer, type ImportanceScorerConfig, InMemoryBackend, InMemoryVectorStore, IncrementalIndexer, type IncrementalIndexerOptions, type IndexMemoryUsage, type IndexOperation, type IndexOperationType, type IngestInput, type IngestOptions, type IngestResult, InsufficientEntitiesError, InvalidImportanceError, type IssueOptions, type IssueResult, type JSONValue, type JsonSchema, type KeyRecord, KeywordExtractor, type KnowledgeGraph, KnowledgeGraphError, ManagerContext as KnowledgeGraphManager, type LLMProvider, LLMQueryPlanner, type LLMQueryPlannerConfig, LLMSearchExecutor, type LLMSearchExecutorOptions, LOG_PREFIXES, LangChainMemoryAdapter, type LayerRecommendationOptions, type LayerTiming, type LexicalSearchResult, type ListDecisionsOptions, type ListPlansOptions, type ListReflectionsOptions, LocalEmbeddingService, type LogLevel, type LongRunningOperationOptions, LowEntropyContentError, LowercaseCache, type LowercaseData, MCPToolObserverAdapter, MEMORY_TYPES, ManagerContext, type ManagerContextOptions, type MatchedTerm, type MemoryAcquisitionMethod, type MemoryAlert, type MemoryChangeCallback, MemoryDistiller, MemoryEngine, type MemoryEngineConfig, type MemoryEngineEventName, MemoryFormatter, type MemoryFormatterConfig, MemoryGraphBridge, type MemoryMergeStrategy, MemoryMonitor, MemoryReconstructor, type MemorySource, type MemoryThresholds, MemoryToolkit, type MemoryTurn, type MemoryType, type MemoryUsageStats, type MemoryValidationIssue, type MemoryValidationResult, MemoryValidator, type MemoryValidatorConfig, type Contradiction as MemoryValidatorContradiction, type MemoryVisibility, type MergeResult, type MergeStrategy, type MergeStrategyInput, MergeStrategySchema, MockEmbeddingService, type MultiAgentConfig, MultiAgentMemoryManager, NGramIndex, type NGramIndexStats, NameIndex, type NeighborExpansionOptions, NoOpDistillationPolicy, type NormalizationOptions, type NormalizationResult, type ObservableDataModelAdapterOptions, type ObservableDataModelShape, type ObservationAddedEvent, type ObservationDedupFilter, ObservationDedupManager, type ObservationDedupManagerConfig, ObservationDedupReportStage, type ObservationDedupReportStageConfig, type ObservationDeletedEvent, ObservationManager, ObservationNormalizer, type ObservationScore, type ObservationSource, ObserverPipeline, type ObserverPipelineOptions, type ObserverPipelineStats, OpenAIEmbeddingService, OperationCancelledError, type OperationResult, OperationType, OptimizedInvertedIndex, OptionalEntityNamesSchema, OptionalTagsSchema, type Outcome, PROCEDURE_ENTITY_TYPE, type PaginatedCacheEntry, type PaginatedResult, type PaginationParams, ParallelSearchExecutor, type ParallelSearchOptions, type ParallelSearchResult, type ParsePaginationOptions, type ParsedTemporalRange, type PathResult, PatternDetector, type PatternResult, type Permission, type PermissionMatrix, type PermissionMatrixRow, type PersonalFact, type PhaseDefinition, type PhraseNode, type PiiPattern, PiiRedactor, type PiiRedactorOptions, type PipelineStage, PlanManager, type PlanManagerConfig, type PoolEventCallback, type PostingListResult, type PreparedEntity, type ProceduralMemoryEntity, type ProcedureInvoker, ProcedureManager, type ProcedureManagerConfig, ProcedureStore, type ProfileConfig, type ProfileEntity, ProfileManager, type ProfileManagerConfig, type ProfileOptions, type ProfileResponse, type ProgressCallback, type ProgressInfo, type ProgressInfoCallback, type ProgressOptions, ProjectContextManager, type ProjectContextManagerConfig, type ProjectContextUpsertInput, type PromotionCriteria, type PromotionMarkOptions, type PromotionResult, type ProspectiveMemoryConfig, ProspectiveMemoryManager, ProspectivePromotionStage, type ProximityMatch, type ProximityMatchLocation, type ProximityNode, ProximitySearch, type PushSubGoalOptions, QUERY_LIMITS, QUERY_PREFIX, type QuantizationParams, type QuantizedSearchResult, QuantizedVectorStore, type QuantizedVectorStoreOptions, type QuantizedVectorStoreStats, type QueryAnalysis, QueryAnalyzer, type QueryCostEstimate, QueryCostEstimator, type QueryCostEstimatorOptions, type QueryLogEntry, QueryLogger, type QueryLoggerConfig, type QueryNode, QueryParser, type QueryPlan, QueryPlanCache, type QueryPlanCacheOptions, type QueryPlanCacheStats, QueryPlanner, QueryRewriter, type QueryStage, type QueryTrace, QueryTraceBuilder, type QueueStats, RankedSearch, type RateLimitVerdict, RateLimiter, type RateLimiterConfig, RbacMiddleware, type RbacMiddlewareOptions, type RbacPolicy, ReadOnlyMemoryGraphDataError, type ReadonlyKnowledgeGraph, type DistillationResult$1 as ReconstructionDistillationResult, type ReconstructionOptions, type ReconstructionResult, type ReconstructiveBacking, ReconstructiveMemory, type ReconstructiveMemoryConfig, type RecordOutcomeInput, type RedactionResult, type RedactionStats, type RedundancyGroup, RefConflictError, type RefEntry, RefIndex, type RefIndexStats, RefNotFoundError, type RefinementHistoryEntry, type ReflectionEntityOptions, type ReflectionInput, ReflectionManager$1 as ReflectionManager, ReflectionManager as ReflectionMemoryManager, type ReflectionManagerConfig as ReflectionMemoryManagerConfig, type ReflectionOptions, type ReflectionResult, ReflectionStage, type ReflectionStageConfig, type ReinforcementOptions, type RejectDecisionResult, type Relation, RelationBuilder, type RelationCreatedEvent, type RelationDeletedEvent, RelationIndex, type RelationInput, RelationManager, RelationNotFoundError, type RelationProperties, RelationSchema, type RelationValidationError, type RelationValidationResult, type RelationValidationWarning, type RelevanceOptions, type ResolutionResult, type ResourcePermissionOverrides, type ResourceType, type RestHandler, type RestMethod, type RestRequest, type RestResponse, RestRouter, type RestoreResult, type Result, type RetrievalContext, type RetrievalDecision, type RetrievalRound, type RetrieveContextOptions, type RewriteResult, type Role, type RoleAssignment, RoleAssignmentStore, type RoleAssignmentStoreOptions, type RoleProfile, type RouteDefinition, RowLevelFilter, type RowPredicate, type Rule, type RuleConditions, type RuleEvaluationResult, RuleEvaluator, SEARCH_LIMITS, SESSION_CHECKPOINT_ENTITY_TYPE, SIMILARITY_WEIGHTS, SNAPSHOTS_RELATION, SQLiteBackend, type SQLiteBackendOptions, SQLiteStorage, type SQLiteStorageWithEmbeddings, SQLiteVectorStore, STOPWORDS, STREAMING_CONFIG, type SalienceComponents, type SalienceContext, SalienceEngine, type SalienceEngineConfig, type SalienceWeights, type SavedSearch, type SavedSearchInput, SavedSearchInputSchema, SavedSearchManager, type SavedSearchUpdateInput, SavedSearchUpdateSchema, type ScheduleOptions, SchemaValidator, type ScoreBoost, type ScoreOptions, type ScoredEntity, type ScoredKeyword, type ScoredResult, type ScoringSignal, SearchCache, type SearchExplanation, SearchFilterChain, type SearchFilters, type SearchFunction, type SearchLayer, SearchManager, type SearchMethod, type SearchQuery, SearchQuerySchema, type SearchResult, SearchSuggestions, SemanticForget, type SemanticForgetOptions, type SemanticForgetResult, type SemanticIndexOptions, type SemanticLayerResult, type SemanticMemoryEntity, SemanticSearch, type SemanticSearchResult, type SessionCheckpointData, SessionCheckpointManager, type SessionConfig, type SessionEntity, type SessionHistoryOptions, SessionManager, type SessionMemoryFilter, type SessionOutcome, SessionQueryBuilder, type SessionSearchOptions, type SessionStatus, SpellChecker, type SpellCheckerConfig, type SpellSuggestion, type SpilloverResult, type SplitOptions, type SplitResult, type StageResult, type StartSessionOptions, StepSequencer, type StorageConfig, type StreamResult, StreamingExporter, type StructuredQuery, type SubQuery, type SuggestOptions, type SuggestToolOptions, type SummarizationConfig, type SummarizationResult, SummarizationService, type SupersedeDecisionResult, type SymbolicFilters, type SymbolicResult, SymbolicSearch, type SymbolicSearchResult, type SynthesisResult, TFIDFEventSync, type TFIDFIndex, TFIDFIndexManager, TOPIC_SUMMARIZES, type TagAlias, type TagAliasInput, TagAliasSchema, TagManager, type TagNode, type Task, type TaskBatchOptions, type TaskHandle, TaskPriority, TaskQueue, type TaskResult, TaskStatus, type TaskSubmitOptions, type TemporalFilterField, type TemporalFocus, TemporalQueryParser, type TemporalRange, type TemporalRelation, TemporalSearch, type TemporalSearchOptions, type TermNode, type TimelineOptions, type TokenBreakdown, type TokenEstimationOptions, type TokenizedEntity, ToolAffordanceManager, type ToolAffordanceManagerConfig, type ToolAffordanceStats, type ToolCallEvent, ToolCallObserver, type ToolResponse, type ToolSuggestion, type Trajectory, type TrajectoryCluster, TrajectoryCompressor, type TrajectoryCompressorConfig, type TrajectoryMergeStrategy, TransactionManager, type TransactionOperation, type TransactionResult, type TransitionEvent, type TransitionFilter, TransitionLedger, type TraversalActionType, type TraversalOptions, type TraversalResult, type TraversalStep, TypeIndex, type UpdateEntityInput, UpdateEntitySchema, type ValidatedPagination, ValidationError, type ValidationIssue, type ValidationReport, type ValidationResult$1 as ValidationResult, type ValidationWarning, type VectorSearchResult, VisibilityResolver, type VisualizeOptions, WORK_THREAD_ENTITY_TYPE, type WakeUpOptions, type WakeUpResult, type WeightedRelation, type WeightedTurn, type WildcardNode, type WorkThread, type WorkThreadFilter, WorkThreadManager, type WorkThreadStatus, type WorkerPoolConfig, WorkerPoolManager, WorkerTaskManager, type WorkerTaskManagerStats, type WorkingMemoryConfig, type WorkingMemoryEntity, WorkingMemoryManager, type WorkingMemoryOptions, WorldModelManager, type WorldModelManagerOptions, type WorldStateChange, type WorldStateEntity, WorldStateSnapshot, addUniqueTags, all, allRelationsValidMetadata, applyPagination, asWarning, batchProcess, batchProcessViaWorkers, buildTFVector, calculateIDF, calculateIDFFromTokenSets, calculateTF, calculateTFFromTokens, calculateTFIDF, calculateTextSimilarity, checkCancellation, chunkArray, cleanupAllCaches, clearAllSearchCaches, compress, compressFile, compressToBase64, computeEntropy, cosineSimilarity, createCustomProfile, createDetailedProgressReporter, createEmbeddingService, createMetadata, createObservableDataModelFromGraph, createProgress, createProgressInfo, createProgressReporter, createStorage, createStorageFromPath, createThrottledProgress, createUncompressedMetadata, createVectorStore, custom, customSync, debounce, decodeLegacyCheckpoint, decodeLegacyWorkThread, decodeProcedure, decompress, decompressFile, decompressFromBase64, defaultMemoryPath, email, ensureMemoryFilePath, entityExists, entityPassesFilters, entityToText, err, escapeCsvFormula, executeWithPhases, extractJson, extractToolName, filterByCreatedDate, filterByEntityType, filterByImportance, filterByModifiedDate, filterByTags, filterParallel, findEntitiesByNames, findEntityByName, fnv1aHash, formatErrorResponse, formatRawResponse, formatTextResponse, formatToolResponse, formatZodErrors, generateSuggestions, getAllCacheStats, getCompressionRatio, getCurrentTimestamp, getEntityIndex, getEntityNameSet, getPaginationMeta, getPoolStats, getQuickHint, getRoleProfile, getWorkerPoolManager, getWorkerTaskManager, globalMemoryMonitor, groupEntitiesByType, hasAllTags, hasBrotliExtension, hasConfidence, hasMatchingTag, isAgentEntity, isArtifactEntity, isBidirectionalRelation, isCurrentlyValid, isEpisodicMemory, isErr, isOk, isPrefixPattern, isProceduralMemory, isProfileEntity, isSemanticMemory, isSessionEntity, isTemporalRelation, isValidISODate, isWeightedRelation, isWithinDateRange, isWithinImportanceRange, isWorkingMemory, isoDate, l2Normalize, levenshteinDistance, listRoleProfiles, loadConfigFromEnv, logger, mapOk, mapParallel, matchesPhrase, matchesPrefix, max, maxItems, maxLength, mergeConfig, migrateLegacySessionCheckpoints, migrateLegacyWorkThreads, min, minItems, minLength, normalizeKey, normalizeTag, normalizeTags, ok, oneOf, paginate, paginateArray, parallelFilter, parallelLimit, parallelMap, parseDateRange, parsePaginationParams, passesEntropyFilter, pattern, permissionsForRole, processBatch, processBatchesWithProgress, processWithRetry, range, rateLimitedProcess, removeEntityByName, removeTags, required, resolveRoleProfile, sanitizeObject, searchCaches, shutdownParallelUtils, cosineSimilarity$1 as textCosineSimilarity, tokenize as textTokenize, throttle, tokenize$1 as tokenize, touchEntity, typeOf, unwrap, unwrapOr, url, validateArrayWithSchema, validateConfig, validateEntity, validateFilePath, validateImportance, validateNonEmpty, validateNonEmptyArray, validatePagination, validateRelation, validateRelationMetadata, validateRelationsMetadata, validateSafe, validateTags, validateWithSchema, when, withRetry };