@danielsimonjr/memoryjs 1.9.1 → 2.1.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/README.md CHANGED
@@ -1,13 +1,14 @@
1
1
  # MemoryJS
2
2
 
3
- [![Version](https://img.shields.io/badge/version-1.8.0-blue.svg)](https://github.com/danielsimonjr/memoryjs)
3
+ [![Version](https://img.shields.io/badge/version-2.1.0-blue.svg)](https://github.com/danielsimonjr/memoryjs)
4
4
  [![NPM](https://img.shields.io/npm/v/@danielsimonjr/memoryjs.svg)](https://www.npmjs.com/package/@danielsimonjr/memoryjs)
5
5
  [![License](https://img.shields.io/badge/license-MIT-green.svg)](LICENSE)
6
6
  [![TypeScript](https://img.shields.io/badge/TypeScript-5.0+-blue.svg)](https://www.typescriptlang.org/)
7
+ [![Tests](https://img.shields.io/badge/tests-7127%20passing-brightgreen.svg)](https://github.com/danielsimonjr/memoryjs)
7
8
 
8
- A **TypeScript knowledge graph library** for managing entities, relations, and observations with **advanced search capabilities**, **hierarchical organization**, and **multiple storage backends**.
9
+ A **TypeScript knowledge graph library** for managing entities, relations, and observations with **advanced search**, **hierarchical organization**, **bitemporal versioning**, **causal reasoning**, **role-based access control**, **multi-agent collaboration**, **memory-mapped I/O**, **segment-sharded JSONL**, **tiered indexing**, and **multiple storage backends**.
9
10
 
10
- > **Core library** powering [@danielsimonjr/memory-mcp](https://www.npmjs.com/package/@danielsimonjr/memory-mcp). Provides **113 TypeScript files**, **~50K lines of code**, dual storage backends (JSONL/SQLite), sophisticated search algorithms (BM25, TF-IDF, fuzzy, semantic, hybrid, temporal, LLM-planned), and a complete **Agent Memory System** for AI agents with role profiles, entropy filtering, recursive consolidation, collaborative synthesis, failure distillation, cognitive load analysis, and shared visibility hierarchies.
11
+ > Core library powering [@danielsimonjr/memory-mcp](https://www.npmjs.com/package/@danielsimonjr/memory-mcp). **235 TypeScript files**, **79,378 lines of code**, **7127+ passing tests**, dual storage backends (JSONL/SQLite + pluggable `IMemoryBackend`), comprehensive search (BM25 with incremental indexing, TF-IDF, fuzzy with N-gram pre-filter, semantic, hybrid, temporal, LLM-planned, active iterative retrieval, minimal SPARQL subset), and a complete **Agent Memory System** for AI agents role profiles, entropy filtering, recursive consolidation, collaborative synthesis with conflict resolution, failure distillation, cognitive load analysis, visibility hierarchies, RBAC, optimistic concurrency, audit attribution, procedural memory, causal reasoning, world-model orchestrator, and the Phase 2 catalog-aligned memory-type slots: **prospective** (intentions-to-act), **failure** (structured pre-task lookup), **plan** (hierarchical goal trees), **reflection** (derived pattern + trajectory summary) + a discriminated `TrustLevel` provenance mixin.
11
12
 
12
13
  ## Table of Contents
13
14
 
@@ -57,41 +58,121 @@ A **TypeScript knowledge graph library** for managing entities, relations, and o
57
58
 
58
59
  | Module | Files | Key Components |
59
60
  |--------|-------|----------------|
60
- | `agent/` | 30 | AgentMemoryManager, SessionManager, DecayEngine, WorkingMemoryManager, ArtifactManager, DistillationPolicy, DistillationPipeline, RoleProfiles, EntropyFilter, ConsolidationScheduler, MemoryFormatter, CollaborativeSynthesis, FailureDistillation, CognitiveLoadAnalyzer, VisibilityResolver |
61
- | `core/` | 13 | EntityManager, GraphStorage, SQLiteStorage, TransactionManager, RefIndex |
62
- | `search/` | 34 | SearchManager, BM25Search, HybridScorer, VectorStore, QueryPlanner, TemporalQueryParser, TemporalSearch, NGramIndex, LLMQueryPlanner, LLMSearchExecutor |
63
- | `features/` | 12 | IOManager, ArchiveManager, CompressionManager, StreamingExporter, FreshnessManager, AuditLog, GovernanceManager |
64
- | `utils/` | 18 | BatchProcessor, CompressedCache, WorkerPoolManager, MemoryMonitor |
65
- | `types/` | 4 | Entity, Relation, AgentEntity, SessionEntity, ArtifactEntity interfaces |
61
+ | `agent/` | 65 | AgentMemoryManager, SessionManager, DecayEngine, WorkingMemoryManager, ArtifactManager, DistillationPipeline, RoleProfiles, EntropyFilter, ConsolidationScheduler, MemoryFormatter, CollaborativeSynthesis, FailureDistillation, CognitiveLoadAnalyzer, VisibilityResolver, **MemoryEngine**, **MemoryValidator**, **TrajectoryCompressor**, **ExperienceExtractor**, **CausalReasoner**, **ProcedureManager**, **WorldModelManager**, **ActiveRetrievalController**, **CollaborationAuditEnforcer**, **RbacMiddleware**, **InMemoryBackend** / **SQLiteBackend**, **ProspectiveMemoryManager**, **FailureManager**, **PlanManager**, **ReflectionManager** (Phase 2 memory-type slots), **ReflectionStage** + **ProspectivePromotionStage** (pipeline stages) |
62
+ | `core/` | 25 | ManagerContext, EntityManager (with OCC), RelationManager (with temporal validity), ObservationManager (with bitemporal axis), HierarchyManager, GraphStorage, SQLiteStorage, GraphTraversal, TransactionManager, RefIndex, **FileSegmentStorage**, **WriteAheadLog** + **EntityProxy**, **JsonlColumnStore**, **TieredIndex** (`LRUHotTier`/`DiskWarmTier`/`BrotliColdTier`), **IMmapBackend** / **BufferMmapBackend** / **FsReadMmapBackend** |
63
+ | `search/` | 55 | SearchManager, RankedSearch (TF-IDF), BM25Search (incremental), BooleanSearch, FuzzySearch, SemanticSearch, HybridSearchManager, NGramIndex, TemporalQueryParser, TemporalSearch, LLMQueryPlanner, LLMSearchExecutor, EmbeddingService, VectorStore, **SparqlExecutor** (minimal subset), **PartialIndexAdvisor** |
64
+ | `features/` | 20 | IOManager (with RDF/Turtle/JSON-LD export), **BackupManager**, ArchiveManager, CompressionManager, StreamingExporter, FreshnessManager, AuditLog, GovernanceManager, ContradictionDetector, SemanticForget, AutoLinker, **CRDT**, **AnomalyDetector** |
65
+ | `utils/` | 34 | BatchProcessor, CompressedCache, WorkerPoolManager, MemoryMonitor, schemas (Zod), **ICompressionAdapter** / **BrotliCompressionAdapter** / **ZlibCompressionAdapter** / **IdentityCompressionAdapter** / **CompressedMap**, structured `logger`, scheduler/explainPlan/indexHealth diagnostics |
66
+ | `types/` | 7 | Entity, Relation, AgentEntity, SessionEntity, ArtifactEntity, Procedure, **ProspectiveEntity** / **FailureEntity** / **PlanEntity** / **ReflectionEntity** (Phase 2 per-type entities), **TrustLevel** mixin on `MemorySource` |
67
+ | `security/` | 5 | **PiiRedactor** + bundled patterns (email/SSN/CC/phone/IP), **ABAC + RLS + API keys** |
68
+ | `cli/` | 16 | `memory` / `memoryjs` binary commands (entity, relation, search, observation, tag, hierarchy, graph, io, maintenance) + pipe support |
69
+ | `adapters/` | 4 | `IDatabaseAdapter` / `IVectorDBAdapter` interfaces, `LangChainMemoryAdapter`, `RestRouter` |
66
70
  | `workers/` | 2 | Levenshtein distance calculations |
67
71
 
68
- **Total:** 113 TypeScript files | ~50,000 lines of code | 720+ exports | 99+ classes | 240+ interfaces
69
-
70
- ### New in 1.7.0
71
-
72
- | Feature | Entry Point |
73
- |---------|-------------|
74
- | Role-Aware Memory Customization | `RoleProfileManager.apply(role)` — salience weights + budget splits |
75
- | Entropy-Aware Filtering | `EntropyFilter` Shannon entropy gate in `ConsolidationPipeline` |
76
- | Recursive Memory Consolidation | `ConsolidationScheduler` background dedup + merge to fixed point |
77
- | Visual Salience Budget Allocation | `MemoryFormatter.formatWithSalienceBudget()` |
78
- | Collaborative Memory Synthesis | `CollaborativeSynthesis.synthesize(entity, hopDepth)` |
79
- | Failure-Driven Memory Distillation | `FailureDistillation.distill(failureEntity)` |
80
- | Cognitive Load Metrics | `CognitiveLoadAnalyzer.analyze(memories)` `CognitiveLoadReport` |
81
- | Shared Memory Visibility Hierarchies | `VisibilityResolver.resolve(agentId, memories)` 5-level model |
82
-
83
- ### New in 1.6.0
84
-
85
- | Feature | Entry Point |
86
- |---------|-------------|
87
- | Stable Index Dereferencing | `ctx.refIndex` — `register` / `resolve` / `deregister` |
88
- | Artifact-Level Granularity | `ctx.agentMemory().artifactManager.createArtifact()` |
89
- | Temporal Range Queries | `ctx.searchManager.searchByTime()` / `ctx.temporalSearch` |
90
- | Memory Distillation Policy | `IDistillationPolicy` wired into `ContextWindowManager` |
91
- | Temporal Governance & Freshness | `ctx.freshnessManager` — TTL, confidence, staleness report |
92
- | N-gram Hashing | Automatic — `FuzzySearch` now pre-filters via `NGramIndex` |
93
- | LLM Query Planner | `ctx.queryNaturalLanguage(query, llmProvider?)` |
94
- | Dynamic Memory Governance | `ctx.governanceManager` `withTransaction` / `GovernancePolicy` |
72
+ **Total:** 235 TypeScript files | 79,378 lines of code | 7127+ passing tests | 11 modules | 1 runtime + 3 type-only circular dependencies (see `docs/architecture/DEPENDENCY_GRAPH.md`)
73
+
74
+ ### Agent Memory
75
+
76
+ | Capability | Entry point |
77
+ |-----------|-------------|
78
+ | Sessions, working memory, episodic memory | `ctx.agentMemory()` — `startSession` / `addWorkingMemory` / `retrieveForContext` |
79
+ | Turn-aware conversation memory with 4-tier dedup (exact / prefix / Jaccard / semantic) | `ctx.memoryEngine.addTurn()` / `getSessionTurns()` |
80
+ | Time-based decay, salience scoring, freshness | `DecayEngine`, `SalienceEngine`, `ctx.freshnessManager` |
81
+ | Role profiles (`researcher` / `planner` / `executor` / `reviewer` / `coordinator`) | `MEMORY_AGENT_ROLE` / `RoleProfileManager.apply(role)` |
82
+ | Memory consolidation, summarization, pattern detection | `ConsolidationPipeline`, `ConsolidationScheduler` |
83
+ | Collaborative synthesis across agents with conflict resolution | `CollaborativeSynthesis.synthesize()` / `resolveConflicts()` |
84
+ | Failure-driven distillation, cognitive load analysis | `FailureDistillation`, `CognitiveLoadAnalyzer` |
85
+ | Procedural memory (executable procedures with feedback refinement) | `ctx.procedureManager.addProcedure()` / `matchProcedure()` / `refineProcedure()` |
86
+ | Active retrieval (iterative query rewriting) | `ctx.activeRetrieval.adaptiveRetrieve()` |
87
+ | Causal reasoning (causes / effects / counterfactuals / cycle detection) | `ctx.causalReasoner.findCauses()` / `findEffects()` / `counterfactual()` |
88
+ | World-state orchestrator | `ctx.worldModelManager.getCurrentState()` / `predictOutcome()` |
89
+ | Per-agent persistent journal | `AgentMemoryManager.writeDiary()` / `readDiary()` |
90
+ | Prospective memory (intentions-to-act with discriminated lifecycle) | `ctx.prospectiveMemory.schedule()` / `fire()` / `cancel()` |
91
+ | Failure memory (pre-task `applicability_hint` lookup) | `ctx.failureManager.record()` / `lookupForTask()` / `markResolved()` |
92
+ | Plan memory (hierarchical goal trees with invariant validation) | `ctx.plan.createPlan()` / `pushSubGoal()` / `transitionNode()` / `getCurrentPath()` |
93
+ | Reflection memory (additive derived insights with content-hash dedup) | `ctx.reflectionManager.create()` / `getRelevantForSession()` / `archive()` |
94
+ | Trust hierarchy (`ground-truth` / `verified` / `inferred` / `unverified`) | `MemorySource.trustLevel?:` + `'trust_level'` `ConflictStrategy` + `inferTrustLevel()` backfill |
95
+
96
+ ### Search & Retrieval
97
+
98
+ | Capability | Entry point |
99
+ |-----------|-------------|
100
+ | Auto-selecting search with method explanation | `ctx.searchManager.autoSearch(query)` |
101
+ | TF-IDF + BM25 ranked search (incremental indexing) | `ctx.rankedSearch`, `BM25Search` |
102
+ | Boolean (AND / OR / NOT) with AST parser | `ctx.searchManager.booleanSearch()` |
103
+ | Fuzzy matching (Levenshtein, N-gram pre-filtered) | `ctx.searchManager.fuzzySearch()` |
104
+ | Semantic search with pluggable embedding provider | `ctx.semanticSearch` (set `MEMORY_EMBEDDING_PROVIDER`) |
105
+ | Hybrid (semantic + lexical + symbolic) | `ctx.hybridSearch` |
106
+ | Temporal range queries with natural-language parsing | `ctx.searchManager.searchByTime("last hour")` |
107
+ | LLM-planned natural-language queries | `ctx.queryNaturalLanguage(query, llmProvider?)` |
108
+ | Minimal SPARQL subset (BGP / FILTER / OPTIONAL / UNION) | `ctx.sparqlExecutor.query()` |
109
+ | Query diagnostics (`explainPlan`, index health) | `ctx.diagnostics` |
110
+
111
+ ### Knowledge Graph
112
+
113
+ | Capability | Entry point |
114
+ |-----------|-------------|
115
+ | Entity / relation / observation CRUD | `ctx.entityManager`, `ctx.relationManager`, `ctx.observationManager` |
116
+ | Optimistic concurrency control on updates | `entityManager.updateEntity(name, updates, { expectedVersion })` |
117
+ | Bitemporal versioning (entities + observations) | `invalidateEntity()` / `entityAsOf()` / `entityTimeline()` |
118
+ | Temporal relations (validity windows) | `relationManager.invalidateRelation()` / `queryAsOf()` / `timeline()` |
119
+ | Memory versioning with contradiction-driven supersession | `Entity.version` / `parentEntityName` / `rootEntityName` / `supersededBy` |
120
+ | Project scoping | `Entity.projectId` + `MEMORY_DEFAULT_PROJECT_ID` |
121
+ | Two-tier deletion (exact match → 0.85 semantic fallback) | `ctx.semanticForget` |
122
+ | Hierarchical nesting + traversal (ancestors / descendants / subtrees) | `ctx.hierarchyManager` |
123
+ | Graph algorithms — shortest path, all paths, BFS / DFS | `ctx.graphTraversal.findShortestPath()` |
124
+ | Centrality — degree, betweenness, PageRank, HITS hub/authority | `ctx.graphTraversal.pageRank()` / `hits()` |
125
+ | Community detection (Louvain), clique enumeration | `ctx.graphTraversal.louvainCommunities()` / `findMaximalCliques()` |
126
+ | Stable named references for entity name changes | `ctx.refIndex.register()` / `resolve()` |
127
+ | Tag aliases, importance scores (0–10) | `ctx.tagManager`, `Entity.importance` |
128
+ | Multi-format import / export — JSON, CSV, GraphML, GEXF, DOT, Markdown, Mermaid | `ctx.ioManager.exportGraph(format)` |
129
+ | W3C Linked Data export — Turtle, RDF/XML, JSON-LD | `ctx.ioManager.exportGraph('turtle' \| 'rdf-xml' \| 'json-ld')` |
130
+ | Conversation ingestion (format-agnostic) | `ctx.ioManager.ingest(input, options)` |
131
+
132
+ ### Storage & Performance
133
+
134
+ | Capability | Entry point |
135
+ |-----------|-------------|
136
+ | JSONL or SQLite backend (FTS5, BM25, WAL mode) | `MEMORY_STORAGE_TYPE=jsonl\|sqlite` |
137
+ | Pluggable Memory Engine backend | `MEMORY_BACKEND=sqlite\|in-memory` |
138
+ | Memory-mapped file loading for stores > 100 MB | `MEMORY_USE_MMAP=true`, `MEMORY_MMAP_THRESHOLD_BYTES` |
139
+ | Segment-sharded JSONL (FNV-routed N-way shards) | `MEMORY_STORAGE_SEGMENT_COUNT=1..1024` |
140
+ | Columnar observation storage | `JsonlColumnStore`, `ObservationColumn` |
141
+ | Tiered index — LRU hot / disk warm / Brotli cold | `LRUHotTier` → `DiskWarmTier` → `BrotliColdTier` via `TieredIndex` |
142
+ | In-memory entity-cache compression (Zlib / Brotli / Identity) | `ctx.compressedEntityCache`, `CompressedMap` |
143
+ | Write-ahead log + entity proxy for durable mutations | `WriteAheadLog`, `EntityProxy` |
144
+ | Backup lifecycle (create / list / restore / delete / cleanOld) with symlink-attack guards | `ctx.ioManager` (delegates to `BackupManager`) |
145
+ | Streaming export with Brotli compression | `ctx.streamingExporter` |
146
+ | Entity archival to compressed storage | `ctx.archiveManager` |
147
+ | Duplicate detection + entity merging | `ctx.compressionManager` |
148
+ | LSH-based anomaly detection | `ctx.anomalyDetector` |
149
+
150
+ ### Governance, Security, Multi-Agent
151
+
152
+ | Capability | Entry point |
153
+ |-----------|-------------|
154
+ | Policy enforcement + transactional rollback | `ctx.governanceManager.withTransaction()` / `GovernancePolicy` |
155
+ | Immutable JSONL audit trail | `ctx.auditLog` |
156
+ | Strict-mode attribution enforcer | `CollaborationAuditEnforcer` (requires `agentId` on every mutation) |
157
+ | RBAC — role / permission / matrix / middleware | `ctx.rbacMiddleware.checkPermission()` / `ctx.roleAssignmentStore` |
158
+ | ABAC + row-level security + API-key scoping | `src/security/abac.ts`, `rls.ts`, `apiKeys.ts` |
159
+ | PII redactor (email / SSN / CC / phone / IP) with per-pattern stats | `new PiiRedactor().redactGraph()` / `redactWithStats()` |
160
+ | Visibility hierarchies — 5-level (`private` / `team` / `org` / `shared` / `public`) | `VisibilityResolver.canAccess()` |
161
+ | Time-window + role-gated visibility | `AgentEntity.visibleFrom` / `visibleUntil` / `allowedRoles[]` |
162
+ | CRDT primitives for multi-writer scenarios | `src/features/CRDT.ts` |
163
+ | Path-traversal protection (defense-in-depth) | `validateFilePath(path, baseDir?, confineToBase=true)` |
164
+
165
+ ## What's New
166
+
167
+ **Unreleased (Phase 2 memory-types expansion, 2026-05)** — Four catalog-aligned `MemoryType` slots and one provenance mixin land on top of v1.15:
168
+ - **Sprint 4 — Failure Memory**: `FailureManager` + `MemoryType: 'failure'` + `ctx.failureManager`. Structured `FailureRecord` with `applicability_hint` retrieval key; pre-task `lookupForTask(taskContext)` scoring; discriminated `MarkResolvedResult`.
169
+ - **Sprint 5 — Plan / Goal Stack**: `PlanManager` + `MemoryType: 'plan'` + `ctx.plan`. Recursive `GoalNode` tree with discriminated `PlanLifecycle` / `GoalNodeLifecycle`, branded `PlanId` / `GoalNodeId`, `validatePlanInvariants` after every mutation, cycle-protected DFS.
170
+ - **Sprint 6 — Trust Hierarchy formalization (partial)**: `TrustLevel` discriminated mixin on `MemorySource` (`'ground-truth' | 'verified' | 'inferred' | 'unverified'`) with `inferTrustLevel` backfill and `'trust_level'` `ConflictStrategy`. `CollaborativeSynthesis.resolveConflicts` ordering integration deferred.
171
+ - **Sprint 8 — Reflection Log scheduled pass**: `ReflectionManager` + `MemoryType: 'reflection'` + `ReflectionStage` pipeline stage + `ctx.reflectionManager` (publicly aliased as `ReflectionMemoryManager`). Additive (no supersession); content-hash dedup at create; session-end scheduling via `runOnSessionEnd(sessionId)` helper.
172
+
173
+ **v1.15.0** — Twelve-phase performance & scale track adding mmap-backed I/O, segment-sharded JSONL, columnar observation storage, tiered indexing, pluggable in-memory compression, a minimal SPARQL subset, write-ahead log, extracted `BackupManager`, CRDT primitives, ABAC + RLS + API keys, HITS / clique / Louvain graph algorithms, and a hardened security baseline (`crypto.randomBytes` for IDs, ReDoS-resistant regex escapes, bounded `TaskQueue`).
174
+
175
+ See [CHANGELOG.md](CHANGELOG.md) for the full per-version history. The roadmap and remaining items live in [`docs/roadmap/ROADMAP.md`](docs/roadmap/ROADMAP.md) and [`docs/roadmap/MEMORY_TYPES_EXPANSION_PHASE_2.md`](docs/roadmap/MEMORY_TYPES_EXPANSION_PHASE_2.md).
95
176
 
96
177
  ## Installation
97
178
 
@@ -158,8 +239,93 @@ const ranked = await ctx.searchManager.searchRanked('runtime environment', { lim
158
239
  // Boolean search
159
240
  const filtered = await ctx.searchManager.booleanSearch('TypeScript AND runtime');
160
241
 
161
- // Fuzzy search (typo-tolerant)
242
+ // Fuzzy search (typo-tolerant; N-gram pre-filtered)
162
243
  const fuzzy = await ctx.searchManager.fuzzySearch('Typscript', { threshold: 0.7 });
244
+
245
+ // Active retrieval — iterative query rewriting until coverage threshold
246
+ const adaptive = await ctx.activeRetrieval.adaptiveRetrieve({ query: 'memory leak' });
247
+ console.log(adaptive.bestResults, adaptive.bestCoverage, adaptive.rounds);
248
+ ```
249
+
250
+ ### 5. Multi-agent collaboration
251
+
252
+ ```typescript
253
+ // Optimistic concurrency control — fail loudly on stale writes
254
+ try {
255
+ await ctx.entityManager.updateEntity('Alice',
256
+ { importance: 9 },
257
+ { expectedVersion: 3 });
258
+ } catch (e) {
259
+ if (e.name === 'VersionConflictError') {
260
+ // Refetch + retry
261
+ }
262
+ }
263
+
264
+ // Detect cross-agent conflicts after collaborative synthesis
265
+ const synth = await ctx.agentMemory().collaborativeSynthesis.synthesize('Alice');
266
+ const winners = ctx.agentMemory().collaborativeSynthesis.resolveConflicts(synth, {
267
+ strategy: 'highest_confidence',
268
+ });
269
+
270
+ // Enforce attribution on every mutation
271
+ import { CollaborationAuditEnforcer, AuditLog } from '@danielsimonjr/memoryjs';
272
+ const enforcer = new CollaborationAuditEnforcer(
273
+ ctx.entityManager,
274
+ new AuditLog('./audit.jsonl'),
275
+ );
276
+ await enforcer.createEntities([{ name: 'X', entityType: 't', observations: ['fact'] }],
277
+ 'agent-alice'); // throws AttributionRequiredError if agentId is missing
278
+ ```
279
+
280
+ ### 6. Bitemporal versioning
281
+
282
+ ```typescript
283
+ // Mark an entity as no longer valid at a specific time
284
+ await ctx.entityManager.invalidateEntity('OldFact', '2025-12-31T00:00:00Z');
285
+
286
+ // Time-travel query
287
+ const past = await ctx.entityManager.entityAsOf('Alice', '2024-06-15T00:00:00Z');
288
+
289
+ // Per-observation validity windows
290
+ await ctx.observationManager.invalidateObservation(
291
+ 'Alice', 'works at Acme', '2024-12-31T00:00:00Z',
292
+ );
293
+ const obsAtTime = await ctx.observationManager.observationsAsOf(
294
+ 'Alice', '2024-06-15T00:00:00Z',
295
+ );
296
+ ```
297
+
298
+ ### 7. Causal reasoning and world model
299
+
300
+ ```typescript
301
+ // Forward inference — "what does X cause?"
302
+ const effects = await ctx.causalReasoner.findEffects('rain', ['flooding', 'erosion']);
303
+ // Counterfactual — "what if we remove this edge?"
304
+ const surviving = await ctx.causalReasoner.counterfactual({
305
+ seed: 'rain', removeFrom: 'rain', removeTo: 'flooding', predict: 'flooding',
306
+ });
307
+
308
+ // World model snapshot + diff
309
+ const before = await ctx.worldModelManager.getCurrentState();
310
+ // ... mutations ...
311
+ const after = await ctx.worldModelManager.getCurrentState();
312
+ const change = ctx.worldModelManager.detectStateChange(before, after);
313
+ ```
314
+
315
+ ### 8. RBAC and PII redaction
316
+
317
+ ```typescript
318
+ // Grant a role
319
+ await ctx.roleAssignmentStore.assign({
320
+ agentId: 'alice', role: 'writer', resourceType: 'entity',
321
+ });
322
+ ctx.rbacMiddleware.checkPermission('alice', 'write', 'entity'); // true
323
+
324
+ // Redact PII from any export
325
+ import { PiiRedactor } from '@danielsimonjr/memoryjs';
326
+ const redactor = new PiiRedactor();
327
+ const cleanGraph = redactor.redactGraph(graph);
328
+ const { text, stats } = redactor.redactWithStats(observation);
163
329
  ```
164
330
 
165
331
  ## Core Concepts
@@ -170,14 +336,39 @@ Primary nodes in the knowledge graph.
170
336
 
171
337
  ```typescript
172
338
  interface Entity {
173
- name: string; // Unique identifier
174
- entityType: string; // Classification (person, project, concept)
175
- observations: string[]; // Facts about the entity
176
- parentId?: string; // Parent entity for hierarchical nesting
177
- tags?: string[]; // Lowercase tags for categorization
178
- importance?: number; // 0-10 scale for prioritization
179
- createdAt?: string; // ISO 8601 timestamp
180
- lastModified?: string; // ISO 8601 timestamp
339
+ name: string; // Unique identifier
340
+ entityType: string; // Classification (person, project, concept)
341
+ observations: string[]; // Facts about the entity
342
+ parentId?: string; // Parent entity for hierarchical nesting
343
+ tags?: string[]; // Lowercase tags for categorization
344
+ importance?: number; // 0-10 scale for prioritization
345
+ createdAt?: string; // ISO 8601 timestamp
346
+ lastModified?: string; // ISO 8601 timestamp
347
+
348
+ // Freshness
349
+ ttl?: number; // Seconds until stale
350
+ confidence?: number; // [0, 1] belief strength
351
+
352
+ // Project scoping + supersession
353
+ projectId?: string; // Multi-project isolation
354
+ version?: number; // Supersession chain version (also drives η.5.5.c OCC)
355
+ parentEntityName?: string;
356
+ rootEntityName?: string;
357
+ isLatest?: boolean;
358
+ supersededBy?: string;
359
+
360
+ // Memory Engine dedup
361
+ contentHash?: string; // SHA-256 for O(1) Tier-1 dedup
362
+
363
+ // η.4.4 — Bitemporal validity (orthogonal to supersession)
364
+ validFrom?: string; // Entity valid from this instant
365
+ validUntil?: string; // Entity valid until this instant
366
+ observationMeta?: Array<{ // Per-observation validity windows
367
+ content: string;
368
+ validFrom?: string;
369
+ validUntil?: string;
370
+ recordedAt?: string; // Bitemporal axis
371
+ }>;
181
372
  }
182
373
  ```
183
374
 
@@ -202,17 +393,54 @@ Discrete facts about entities. Each observation should be atomic and independent
202
393
  Central access point for all managers with lazy initialization:
203
394
 
204
395
  ```typescript
205
- ctx.entityManager // Entity CRUD + hierarchy
206
- ctx.relationManager // Relation management
207
- ctx.searchManager // All search operations
208
- ctx.tagManager // Tag aliases and bulk operations
209
- ctx.ioManager // Import/export/backup
210
- ctx.graphTraversal // Graph algorithms
211
- ctx.archiveManager // Entity archival
212
- ctx.analyticsManager // Graph statistics and validation
213
- ctx.compressionManager // Duplicate detection, entity merging
214
- ctx.semanticSearch // Vector similarity search (lazy, optional)
215
- ctx.accessTracker // Memory access tracking (lazy)
396
+ // Core
397
+ ctx.entityManager // Entity CRUD + hierarchy + temporal validity + OCC
398
+ ctx.relationManager // Relation management + temporal invalidation
399
+ ctx.observationManager // Observation CRUD + bitemporal axis
400
+ ctx.hierarchyManager // Entity tree (parents, children, ancestors)
401
+ ctx.searchManager // All search operations (incl. searchByTime)
402
+ ctx.rankedSearch // TF-IDF / BM25 ranked search
403
+ ctx.graphTraversal // BFS / DFS / shortest path / centrality
404
+ ctx.tagManager // Tag aliases + bulk operations
405
+ ctx.refIndex // Stable name entity O(1) lookup
406
+
407
+ // Storage + I/O
408
+ ctx.ioManager // Import / export (incl. RDF/Turtle/JSON-LD) / backup / ingest
409
+ ctx.archiveManager // Entity archival
410
+ ctx.compressionManager // Duplicate detection, entity merging
411
+ ctx.analyticsManager // Graph statistics + validation
412
+ ctx.semanticForget // Two-tier deletion with audit
413
+ ctx.governanceManager // Transactions + policy enforcement (canCreate/Update/Delete)
414
+ ctx.freshnessManager // TTL/confidence freshness reports
415
+
416
+ // Search extensions
417
+ ctx.semanticSearch // Vector similarity (lazy; needs embedding provider)
418
+ ctx.temporalSearch // Natural language time-range search
419
+ ctx.activeRetrieval // 3B.5 — iterative query rewriting (no LLM)
420
+ ctx.llmQueryPlanner() // NL → StructuredQuery decomposition (optional LLM)
421
+ ctx.queryNaturalLanguage // Convenience wrapper around the planner
422
+
423
+ // Memory + agent
424
+ ctx.memoryEngine // Turn-aware conversation memory (4-tier dedup)
425
+ ctx.memoryBackend // Pluggable IMemoryBackend (in-memory / sqlite)
426
+ ctx.contextWindowManager // 4-layer wake-up stack + token budgeting
427
+ ctx.agentMemory() // Full Agent Memory System facade
428
+
429
+ // Memory intelligence
430
+ ctx.memoryValidator // Validate consistency / contradictions / temporal order
431
+ ctx.trajectoryCompressor // Distill / abstract / merge redundant trajectories
432
+ ctx.experienceExtractor // Cluster trajectories → reusable experience patterns
433
+ ctx.patternDetector // Trigger / sequence / outcome pattern mining
434
+
435
+ // Memory theory
436
+ ctx.procedureManager // 3B.4 — executable procedure memory + EWMA refinement
437
+ ctx.causalReasoner // 3B.6 — findCauses / findEffects / counterfactual
438
+ ctx.worldModelManager // 3B.7 — snapshot orchestrator + state-change diff
439
+
440
+ // Access control + audit
441
+ ctx.roleAssignmentStore // η.6.1 — role grants registry
442
+ ctx.rbacMiddleware // η.6.1 — RbacPolicy.checkPermission()
443
+ ctx.accessTracker // Per-entity access metrics
216
444
  ```
217
445
 
218
446
  ## Storage Options
@@ -271,11 +499,15 @@ When using JSONL, related files are automatically created:
271
499
 
272
500
  | Method | Description | Use Case |
273
501
  |--------|-------------|----------|
274
- | `search()` | Basic substring matching | Simple queries |
275
- | `searchRanked()` | TF-IDF relevance scoring | Finding most relevant results |
276
- | `booleanSearch()` | AND/OR/NOT operators | Complex filtering |
277
- | `fuzzySearch()` | Levenshtein distance | Typo tolerance |
278
- | `hybridSearch()` | Semantic + lexical + symbolic | Multi-signal ranking |
502
+ | `searchManager.search()` | Basic substring matching | Simple queries |
503
+ | `searchManager.searchRanked()` | TF-IDF relevance scoring | Finding most relevant results |
504
+ | `searchManager.booleanSearch()` | AND/OR/NOT operators with AST | Complex filtering |
505
+ | `searchManager.fuzzySearch()` | Levenshtein + N-gram pre-filter | Typo tolerance |
506
+ | `searchManager.hybridSearch()` | Semantic + lexical + symbolic | Multi-signal ranking |
507
+ | `searchManager.searchByTime()` | Natural-language time ranges | "last hour", "10 minutes ago" |
508
+ | `activeRetrieval.adaptiveRetrieve()` | Iterative rewrite + retrieve | Adaptive coverage refinement |
509
+ | `queryNaturalLanguage()` | LLM-planned decomposition | Free-text queries (optional LLM provider) |
510
+ | `causalReasoner.findEffects()` | Causal subgraph traversal | Inference over `causes`/`enables`/`prevents` edges |
279
511
 
280
512
  ### Basic Search
281
513
 
@@ -436,13 +668,27 @@ await agent.endSession(session.name);
436
668
  ### Memory Types
437
669
 
438
670
  ```typescript
439
- type MemoryType = 'working' | 'episodic' | 'semantic' | 'procedural';
671
+ type MemoryType =
672
+ | 'working' // Short-term, session-scoped memories that may be promoted
673
+ | 'episodic' // Timeline-based event memories with temporal ordering
674
+ | 'semantic' // Long-term factual knowledge
675
+ | 'procedural' // Learned behaviors and patterns (3B.4)
676
+ | 'prospective' // (Phase 1) Intentions-to-act at a future time / event / condition
677
+ | 'failure' // (Phase 2 Sprint 4) Pre-task failure lookup with applicability_hint
678
+ | 'plan' // (Phase 2 Sprint 5) Hierarchical goal trees with sub-tasks + acceptance criteria
679
+ | 'reflection'; // (Phase 2 Sprint 8) Additive derived insights with content-hash dedup
440
680
  ```
441
681
 
442
682
  - **Working Memory**: Short-term, session-scoped memories that may be promoted
443
683
  - **Episodic Memory**: Timeline-based event memories with temporal ordering
444
684
  - **Semantic Memory**: Long-term factual knowledge
445
- - **Procedural Memory**: Learned behaviors and patterns
685
+ - **Procedural Memory**: Learned behaviors and patterns (`ctx.procedureManager`)
686
+ - **Prospective Memory**: Forward-looking intentions with discriminated `ProspectiveLifecycle` (`pending` / `fired` / `cancelled` / `expired`); `ctx.prospectiveMemory`. Catalog Type 4
687
+ - **Failure Memory**: Structured `FailureRecord` with `applicability_hint` as the retrieval key; `markResolved` returns discriminated `MarkResolvedResult`; `ctx.failureManager`. Catalog Type 9
688
+ - **Plan Memory**: Recursive `GoalNode` tree with discriminated `PlanLifecycle` / `GoalNodeLifecycle`, branded `PlanId` / `GoalNodeId`, `validatePlanInvariants` after every mutation; `ctx.plan`. Catalog Type 6
689
+ - **Reflection Memory**: Additive (no supersession of evidence entities) with `ReflectionScope` discriminator (`session` / `project` / `global`); content-hash dedup at `create`; `ctx.reflectionManager`. Catalog Type 10. Produced by `ReflectionStage` pipeline stage
690
+
691
+ **Trust-hierarchy mixin** (Phase 2 Sprint 6, Catalog Type 12): every `MemorySource` may carry an optional categorical `trustLevel?: TrustLevel` (`'ground-truth' | 'verified' | 'inferred' | 'unverified'`) — backfilled from `method` + `reliability` via `inferTrustLevel(source)`. Powers the `'trust_level'` `ConflictStrategy` with recency tiebreak.
446
692
 
447
693
  ### Decay System
448
694
 
@@ -494,16 +740,15 @@ const results = await agent.searchCrossAgent('agent_2', 'query');
494
740
  |--------|-------------|
495
741
  | `createEntities(entities)` | Create multiple entities |
496
742
  | `deleteEntities(names)` | Delete entities by name |
497
- | `getEntityByName(name)` | Get single entity |
498
- | `addObservations(name, observations)` | Add observations to entity |
499
- | `deleteObservations(name, observations)` | Remove specific observations |
500
- | `addTags(name, tags)` | Add tags to entity |
501
- | `removeTags(name, tags)` | Remove tags from entity |
743
+ | `getEntity(name, options?)` | Get single entity (with optional access tracking) |
744
+ | `updateEntity(name, updates, { expectedVersion? })` | Partial update; OCC if `expectedVersion` provided (η.5.5.c) |
745
+ | `batchUpdate(updates[])` | Atomic multi-entity update |
746
+ | `addTags(name, tags)` / `removeTags(name, tags)` | Tag management |
502
747
  | `setImportance(name, score)` | Set importance (0-10) |
503
- | `setEntityParent(name, parentName)` | Set/remove parent |
504
- | `getChildren(name)` | Get immediate children |
505
- | `getAncestors(name)` | Get ancestor chain |
506
- | `getDescendants(name)` | Get all descendants |
748
+ | `getVersionChain(name)` / `getLatestVersion(name)` | supersession chains |
749
+ | `invalidateEntity(name, ended?)` | η.4.4 set `validUntil` |
750
+ | `entityAsOf(name, asOf)` | η.4.4 time-travel query |
751
+ | `entityTimeline(name)` | η.4.4 versions sorted by `validFrom` |
507
752
 
508
753
  ### RelationManager
509
754
 
@@ -512,6 +757,18 @@ const results = await agent.searchCrossAgent('agent_2', 'query');
512
757
  | `createRelations(relations)` | Create multiple relations |
513
758
  | `getRelations(entityName)` | Get incoming/outgoing relations |
514
759
  | `deleteRelations(relations)` | Delete specific relations |
760
+ | `invalidateRelation(from, type, to, ended?)` | set `validUntil` on a relation |
761
+ | `queryAsOf(entity, asOf, { direction? })` | relations valid at time T |
762
+ | `timeline(entity, { direction? })` | chronological history |
763
+
764
+ ### ObservationManager
765
+
766
+ | Method | Description |
767
+ |--------|-------------|
768
+ | `addObservations(adds, dedupOptions?)` | Add observations (with optional dedup) |
769
+ | `deleteObservations(deletions)` | Remove specific observations |
770
+ | `invalidateObservation(entity, content, ended?)` | η.4.4 — set per-observation `validUntil` |
771
+ | `observationsAsOf(entity, asOf)` | η.4.4 — observations valid at time T |
515
772
 
516
773
  ### SearchManager
517
774
 
@@ -528,31 +785,165 @@ const results = await agent.searchCrossAgent('agent_2', 'query');
528
785
 
529
786
  | Method | Description |
530
787
  |--------|-------------|
531
- | `exportGraph(format, options)` | Export to JSON/CSV/GraphML/GEXF/DOT/Markdown/Mermaid |
532
- | `importGraph(format, data, options)` | Import with merge strategies |
533
- | `createBackup(options)` | Create timestamped backup |
534
- | `restoreBackup(path)` | Restore from backup |
788
+ | `exportGraph(graph, format)` | Export to `json` / `csv` / `graphml` / `gexf` / `dot` / `markdown` / `mermaid` / `turtle` / `rdf-xml` / `json-ld` |
789
+ | `exportGraphWithCompression(graph, format, options?)` | Brotli-compressed export |
790
+ | `importGraph(format, data, options)` | Import with merge strategies (`replace` / `skip` / `merge` / `fail`) |
791
+ | `ingest({ messages }, options?)` | conversation ingestion pipeline |
792
+ | `splitSessions(content, options?)` | split multi-session transcripts |
793
+ | `visualizeGraph(options?)` | interactive HTML visualization |
794
+ | `createBackup(options)` / `restoreBackup(path)` | Backup management |
535
795
 
536
796
  ### GraphTraversal
537
797
 
538
798
  | Method | Description |
539
799
  |--------|-------------|
540
800
  | `findShortestPath(from, to)` | BFS shortest path |
541
- | `findAllPaths(from, to, options)` | All paths with max depth |
542
- | `getCentrality(options)` | Centrality metrics |
801
+ | `findAllPaths(from, to, maxDepth, options?)` | All paths with max depth |
802
+ | `getCentrality(options)` | Centrality metrics (degree / betweenness / pagerank) |
543
803
  | `getConnectedComponents()` | Find isolated subgraphs |
544
- | `bfs(start, visitor)` | Breadth-first traversal |
545
- | `dfs(start, visitor)` | Depth-first traversal |
804
+ | `bfs(start, options)` / `dfs(start, options)` | Traversal |
805
+
806
+ ### CausalReasoner
807
+
808
+ | Method | Description |
809
+ |--------|-------------|
810
+ | `findEffects(cause, candidates, maxDepth?)` | Forward causal inference; sorted by `Π causalStrength` |
811
+ | `findCauses(effect, candidates, maxDepth?)` | Backward inference (symmetric inverse) |
812
+ | `counterfactual({ seed, removeFrom, removeTo, predict })` | Chains surviving edge removal (pure; no graph mutation) |
813
+ | `detectCycles(seed, maxDepth?)` | Depth-bounded DFS over causal subgraph |
814
+
815
+ ### ProcedureManager
816
+
817
+ | Method | Description |
818
+ |--------|-------------|
819
+ | `addProcedure({ steps, ... })` | Persist a procedure; auto-generates id |
820
+ | `getProcedure(id)` / `getStep(id, order)` / `getNextStep(id, order)` | Access |
821
+ | `openSequencer(id)` | Stateful execution cursor with fallback support |
822
+ | `matchProcedure(context, candidates, threshold?)` | Token-overlap match |
823
+ | `refineProcedure(id, { succeeded, notes? })` | EWMA success-rate update |
824
+
825
+ ### WorldModelManager
826
+
827
+ | Method | Description |
828
+ |--------|-------------|
829
+ | `getCurrentState()` | `WorldStateSnapshot` from live graph (capped at `maxSnapshotSize`) |
830
+ | `validateFact(observation, entityName)` | Delegates to `MemoryValidator` if wired |
831
+ | `predictOutcome(action, candidates)` | Delegates to `CausalReasoner.findEffects` |
832
+ | `detectStateChange(before, after)` | Pure snapshot diff |
833
+
834
+ ### ActiveRetrievalController
835
+
836
+ | Method | Description |
837
+ |--------|-------------|
838
+ | `shouldRetrieve(context)` | Cost heuristic; rejects empty / over-budget |
839
+ | `adaptiveRetrieve(context)` | Iterative rewrite + retrieve until coverage threshold |
840
+
841
+ ### CollaborativeSynthesis
842
+
843
+ | Method | Description |
844
+ |--------|-------------|
845
+ | `synthesize(seedEntity, context?)` | BFS + salience scoring; surfaces multi-agent `conflicts[]` |
846
+ | `resolveConflicts(result, policy)` | Pick winners per `most_recent` / `highest_confidence` / `highest_score` / `trusted_agent` |
847
+
848
+ ### MemoryValidator
849
+
850
+ | Method | Description |
851
+ |--------|-------------|
852
+ | `validateConsistency(newObs, existing)` | Composite duplicate / semantic / low-confidence check |
853
+ | `detectContradictions(entity)` | Delegates to `ContradictionDetector` |
854
+ | `repairWithResolver(entity, competing, resolver, contradiction?, options?)` | Apply `ConflictResolver` strategies |
855
+ | `validateTemporalOrder(observations)` | Sync `[T=ISO]` ordering check |
856
+ | `calculateReliability(entity)` | Confidence × confirmation × age penalty |
857
+
858
+ ### RbacMiddleware
859
+
860
+ | Method | Description |
861
+ |--------|-------------|
862
+ | `checkPermission(agentId, action, resourceType, resourceName?, now?)` | Returns `true` / `false`; falls back to `defaultRole` (default `reader`) |
863
+ | `roleAssignmentStore.assign({ agentId, role, resourceType?, scope?, validFrom?, validUntil? })` | Grant a role |
864
+ | `roleAssignmentStore.revoke(agentId, role, resourceType?)` | Remove a grant |
865
+ | `roleAssignmentStore.listActive(agentId, now?)` | Active grants at a point in time |
866
+
867
+ ### PiiRedactor
868
+
869
+ | Method | Description |
870
+ |--------|-------------|
871
+ | `redact(text)` | Apply patterns; returns redacted string |
872
+ | `redactWithStats(text)` | Returns `{ text, stats: { totalRedactedBytes, countsByPattern } }` |
873
+ | `redactGraph(graph)` | Apply to every observation in a graph-shaped object |
874
+
875
+ ### ProspectiveMemoryManager (`ctx.prospectiveMemory`)
876
+
877
+ | Method | Description |
878
+ |--------|-------------|
879
+ | `schedule(intention, options?)` | Persist a `ProspectiveEntity`; trigger kind `time-based` / `time-window` / `event` / `conditional` |
880
+ | `fire(id, result?)` | Transition `pending → fired`; returns discriminated `MarkResolvedResult` |
881
+ | `cancel(id, reason?)` | Transition `pending → cancelled`; returns `CancelResult` |
882
+ | `expireDueIntentions()` | Bulk-expire past-due pending intentions; returns count |
883
+ | `getPending(filter?)` / `getFired(filter?)` | Query by `sessionId` / `agentId` |
884
+
885
+ ### FailureManager (`ctx.failureManager`)
886
+
887
+ | Method | Description |
888
+ |--------|-------------|
889
+ | `record(input, options?)` | Persist a structured `FailureRecord`; validates five required non-empty fields |
890
+ | `lookupForTask(taskContext, options?)` | Pre-task substring-match scoring (`applicability_hint` 3× / `context` 2× / `attempted` 1×) |
891
+ | `markResolved(id, reason?)` | Returns discriminated `MarkResolvedResult` (`resolved` / `already-resolved` / `not-found` / `vanished-mid-update`) |
892
+ | `getAll(options?)` | Filter by `status` and/or `sourceSessionId` |
893
+
894
+ ### PlanManager (`ctx.plan`)
895
+
896
+ | Method | Description |
897
+ |--------|-------------|
898
+ | `createPlan(rootDescription, options?)` | Create a single-node plan tree; mints branded `PlanId` |
899
+ | `pushSubGoal(planId, parentNodeId, description, options?)` | Append a child `GoalNode`; throws on `persistPlan` failure |
900
+ | `transitionNode(planId, nodeId, transition)` | Unified `GoalNodeLifecycle` state-machine entry point |
901
+ | `markPlanComplete(planId, note?)` / `abandonPlan(planId, reason?)` | Plan-level lifecycle; returns `MarkResolvedResult` |
902
+ | `findPlan` / `findNode` / `getCurrentPath` | `Readonly<>` reads (clone-free) |
903
+ | `getActivePlan(sessionId)` / `listPlans(options?)` | Session-scoped + filtered queries |
904
+
905
+ ### ReflectionManager (`ctx.reflectionManager`)
906
+
907
+ | Method | Description |
908
+ |--------|-------------|
909
+ | `create(input, options?)` | Persist a `ReflectionRecord`; content-hash dedup on `sha256(scope\|sorted(evidence))` |
910
+ | `list(options?)` | Filter by `scope` / `sourceSessionId` / `minConfidence` / `includeArchived` / `limit` |
911
+ | `getRelevantForSession(sessionId, options?)` | Reflections matching `sourceSessionId` OR overlapping evidence; confidence-sorted |
912
+ | `archive(id)` | Soft-delete; returns discriminated `ArchiveReflectionResult` |
913
+ | `ReflectionStage.runOnSessionEnd(sessionId)` | Pipeline stage helper — runs the reflection pass scoped to one session |
546
914
 
547
915
  ## Configuration
548
916
 
549
917
  ### Environment Variables
550
918
 
919
+ The full env-var reference lives in [CLAUDE.md](CLAUDE.md). Most-used:
920
+
551
921
  | Variable | Description | Default |
552
922
  |----------|-------------|---------|
553
923
  | `MEMORY_STORAGE_TYPE` | Storage backend: `jsonl` or `sqlite` | `jsonl` |
554
- | `MEMORY_EMBEDDING_PROVIDER` | Embedding provider: `openai`, `local`, or `none` | `none` |
924
+ | `MEMORY_FILE_PATH` | Override storage file path | (per `ManagerContext` ctor) |
925
+ | `MEMORY_BACKEND` | Pluggable Memory Engine backend: `sqlite` or `in-memory` | `sqlite` |
926
+ | `MEMORY_EMBEDDING_PROVIDER` | Embedding provider: `openai`, `local`, or `none` | `local` |
555
927
  | `MEMORY_OPENAI_API_KEY` | OpenAI API key (required if provider is `openai`) | - |
928
+ | `MEMORY_AUTO_INDEX_EMBEDDINGS` | Auto-build embedding index on entity create | `false` |
929
+ | `MEMORY_AUTO_DECAY` | Enable background memory decay | `false` |
930
+ | `MEMORY_DECAY_HALF_LIFE_HOURS` | Half-life for importance decay | `168` |
931
+ | `MEMORY_GOVERNANCE_ENABLED` | Enable `GovernanceManager` policy enforcement | `false` |
932
+ | `MEMORY_AUDIT_LOG_FILE` | Path for audit JSONL trail | - |
933
+ | `MEMORY_AGENT_ROLE` | Apply built-in role profile (`researcher`/`planner`/`executor`/`reviewer`/`coordinator`) | - |
934
+ | `MEMORY_VALIDATE_ON_STORE` | Run `MemoryValidator` before observation writes | `false` |
935
+ | `MEMORY_AUDIT_ATTRIBUTION_REQUIRED` | `CollaborationAuditEnforcer` strict mode | `false` |
936
+ | `MEMORY_RBAC_ENABLED` | Wire `RbacMiddleware` into `GovernancePolicy` | `false` |
937
+ | `MEMORY_DEFAULT_VISIBILITY` | Default `AgentEntity.visibility` | `private` |
938
+ | `MEMORY_USE_MMAP` | Use mmap (`FsReadMmapBackend`) for `GraphStorage.loadFromDisk` | `false` (strict `'true'` literal match) |
939
+ | `MEMORY_MMAP_THRESHOLD_BYTES` | Minimum file size to trigger mmap path; `0` means always-on | `104857600` (100 MB) |
940
+ | `MEMORY_STORAGE_SEGMENT_COUNT` | Number of FNV-routed JSONL shards in `FileSegmentStorage` (1–1024) | `1` (off) |
941
+ | `MEMORY_SQLITE_READ_POOL_SIZE` | Read-connection pool size for `SQLiteStorage` | `4` |
942
+ | `MEMORY_SQLITE_AUTO_INDEX` | Enable `PartialIndexAdvisor`-driven automatic partial-index DDL | `false` |
943
+ | `SKIP_BENCHMARKS` | Skip perf benchmark tests | `false` |
944
+ | `LOG_LEVEL` | `debug` / `info` / `warn` / `error` | (none) |
945
+
946
+ See [CLAUDE.md](CLAUDE.md#environment-variables) for the complete list (~60 variables across decay/salience/context-window/freshness/RBAC/PRD scoring/MemoryEngine/mmap/segment/SQLite-pool/PartialIndex knobs).
556
947
 
557
948
  ## Development
558
949
 
@@ -565,120 +956,159 @@ const results = await agent.searchCrossAgent('agent_2', 'query');
565
956
  ### Build Commands
566
957
 
567
958
  ```bash
568
- npm install # Install dependencies
569
- npm run build # Build TypeScript to dist/
570
- npm run build:watch # Watch mode compilation
571
- npm test # Run all tests
572
- npm run test:watch # Watch mode testing
573
- npm run test:coverage # Run with coverage report
574
- npm run typecheck # Type checking without emit
959
+ npm install # Install dependencies
960
+ npm run build # Build TypeScript to dist/ (tsup; ESM + CJS dual output)
961
+ npm run build:watch # Watch mode compilation
962
+ npm run build:tsc # Bare tsc build (does NOT include workers — use tsup)
963
+ npm test # Run all tests
964
+ npm run test:watch # Watch mode testing
965
+ npm run test:coverage # Run with coverage report
966
+ npm run typecheck # Type checking without emit
967
+ npm run benchmark # Standalone synthetic benchmarks
968
+ npm run bench # Vitest performance suite
969
+ SKIP_BENCHMARKS=true npm test # Skip perf tests in main suite
970
+ ```
971
+
972
+ ### Tooling
973
+
974
+ ```bash
975
+ npm run audit:plans # Detect plan-doc rot
976
+ node tools/create-dependency-graph/create-dependency-graph.ts # Refresh DEPENDENCY_GRAPH.md
977
+ node tools/chunking-for-files/chunking-for-files.ts split <file> # Split large files
978
+ node tools/chunking-for-files/chunking-for-files.ts merge <manifest> # Merge back
979
+ node tools/migrate-from-jsonl-to-sqlite/... # JSONL → SQLite migration
575
980
  ```
576
981
 
577
982
  ### Architecture
578
983
 
579
984
  ```
580
- ┌─────────────────────────────────────────────────────────────┐
581
- │ Layer 1: ManagerContext (Central Facade)
582
- │ ┌───────────────────────────────────────────────────────┐ │
583
- │ │ Lazy-initialized access to all managers │ │
584
- │ └───────────────────────────────────────────────────────┘ │
585
- └──────────────────────────┬──────────────────────────────────┘
985
+ ┌──────────────────────────────────────────────────────────────────┐
986
+ │ Layer 1: ManagerContext (Central Facade — lazy init)
987
+ └──────────────────────────┬───────────────────────────────────────┘
586
988
 
587
- ┌──────────────────────────┴──────────────────────────────────┐
588
- │ Layer 2: Specialized Managers
589
- EntityManager (CRUD + hierarchy + archive)
590
- RelationManager (relation CRUD)
591
- SearchManager (search + compression + analytics)
592
- IOManager (import + export + backup)
593
- TagManager (tag aliases)
594
- GraphTraversal (path finding, centrality)
595
- SemanticSearch (embeddings, similarity)
596
- └──────────────────────────┬──────────────────────────────────┘
989
+ ┌──────────────────────────┴───────────────────────────────────────┐
990
+ │ Layer 2: Domain managers (40+ lazy getters)
991
+ Core: Entity / Relation / Observation / Hierarchy / Search /
992
+ GraphTraversal / Tags / RefIndex
993
+ I/O: IOManager / Archive / Compression / Analytics / Audit /
994
+ Governance / Freshness / SemanticForget
995
+ Search: Ranked / Hybrid / Semantic / Temporal / LLMQueryPlanner
996
+ / ActiveRetrievalController
997
+ Memory: MemoryEngine / MemoryBackend / ContextWindowManager /
998
+ │ AgentMemory(facade) │
999
+ │ Intel: MemoryValidator / TrajectoryCompressor / │
1000
+ │ ExperienceExtractor / PatternDetector │
1001
+ │ Theory: ProcedureManager / CausalReasoner / WorldModelManager │
1002
+ │ Auth: RbacMiddleware / RoleAssignmentStore / AccessTracker │
1003
+ └──────────────────────────┬───────────────────────────────────────┘
597
1004
 
598
- ┌──────────────────────────┴──────────────────────────────────┐
599
- │ Layer 3: Storage Layer
600
- │ GraphStorage (JSONL) or SQLiteStorage (better-sqlite3)
601
- └─────────────────────────────────────────────────────────────┘
1005
+ ┌──────────────────────────┴───────────────────────────────────────┐
1006
+ │ Layer 3: Storage
1007
+ │ GraphStorage (JSONL) or SQLiteStorage (better-sqlite3, FTS5)
1008
+ │ ─ Pluggable IMemoryBackend: in-memory or sqlite-backed engine │
1009
+ └──────────────────────────────────────────────────────────────────┘
602
1010
  ```
603
1011
 
604
1012
  ### Project Structure
605
1013
 
606
1014
  ```
607
1015
  memoryjs/
608
- ├── src/ # Source (113 TypeScript files)
1016
+ ├── src/ # Source (183 TypeScript files, 62.7K LOC)
609
1017
  │ ├── index.ts # Entry point
610
- │ ├── agent/ # Agent Memory System (30 files)
1018
+ │ ├── agent/ # Agent Memory System (61 files)
611
1019
  │ │ ├── AgentMemoryManager.ts # Unified facade
612
1020
  │ │ ├── SessionManager.ts # Session lifecycle
613
- │ │ ├── WorkingMemoryManager.ts # Working memory
614
- │ │ ├── EpisodicMemoryManager.ts # Episodic memory
615
- │ │ ├── DecayEngine.ts # Memory decay (TTL-aware)
616
- │ │ ├── SalienceEngine.ts # Context scoring (freshnessWeight)
1021
+ │ │ ├── WorkingMemoryManager.ts # Working memory + promotion
1022
+ │ │ ├── EpisodicMemoryManager.ts # Timeline-based events
1023
+ │ │ ├── DecayEngine.ts # Decay (legacy + PRD scales)
1024
+ │ │ ├── SalienceEngine.ts # Context-aware scoring
617
1025
  │ │ ├── MultiAgentMemoryManager.ts # Multi-agent support
618
- │ │ ├── ConflictResolver.ts # Conflict resolution
619
- │ │ ├── ArtifactManager.ts # Artifact creation + stable refs
620
- │ │ ├── DistillationPolicy.ts # Post-retrieval distillation policies
621
- │ │ ├── DistillationPipeline.ts # Distillation pipeline executor
622
- │ │ ├── RoleProfiles.ts # Role profiles + salience weight presets
623
- │ │ ├── EntropyFilter.ts # Shannon entropy gate for consolidation
624
- │ │ ├── ConsolidationScheduler.ts # Background recursive dedup+merge
1026
+ │ │ ├── ConflictResolver.ts # Concurrent-update resolution
1027
+ │ │ ├── ArtifactManager.ts # Stable artifact entities
1028
+ │ │ ├── DistillationPipeline.ts # Post-retrieval policy filter
1029
+ │ │ ├── RoleProfiles.ts # 5 built-in roles + presets
1030
+ │ │ ├── EntropyFilter.ts # Shannon entropy gate
1031
+ │ │ ├── ConsolidationScheduler.ts # Background dedup+merge
625
1032
  │ │ ├── MemoryFormatter.ts # formatWithSalienceBudget()
626
- │ │ ├── CollaborativeSynthesis.ts # Graph-neighbourhood multi-agent merge
627
- │ │ ├── FailureDistillation.ts # Causal chain lesson extraction
628
- │ │ ├── CognitiveLoadAnalyzer.ts # Token density + redundancy + diversity
629
- │ │ ├── VisibilityResolver.ts # 5-level visibility + GroupMembership
1033
+ │ │ ├── CollaborativeSynthesis.ts # Multi-agent merge + ConflictView
1034
+ │ │ ├── FailureDistillation.ts # Causal-chain lesson extraction
1035
+ │ │ ├── CognitiveLoadAnalyzer.ts # Density + redundancy + diversity
1036
+ │ │ ├── VisibilityResolver.ts # 5-level + role + time-window
1037
+ │ │ ├── ContextWindowManager.ts # 4-layer wake-up stack
1038
+ │ │ ├── MemoryEngine.ts # Turn-aware + 4-tier dedup (v1.11)
1039
+ │ │ ├── MemoryBackend.ts # IMemoryBackend interface (v1.12)
1040
+ │ │ ├── InMemoryBackend.ts # Ephemeral adapter
1041
+ │ │ ├── SQLiteBackend.ts # SQLite-backed adapter
1042
+ │ │ ├── MemoryValidator.ts # Memory consistency / contradiction checks
1043
+ │ │ ├── TrajectoryCompressor.ts # Distill / merge trajectory data
1044
+ │ │ ├── ExperienceExtractor.ts # Pattern abstraction from contrastive pairs
1045
+ │ │ ├── PatternDetector.ts # Sequence + outcome mining
1046
+ │ │ ├── causal/ # 3B.6 — CausalReasoner
1047
+ │ │ ├── procedural/ # 3B.4 — ProcedureManager + Sequencer
1048
+ │ │ ├── retrieval/ # 3B.5 — ActiveRetrievalController
1049
+ │ │ ├── world/ # 3B.7 — WorldModelManager + Snapshot
1050
+ │ │ ├── rbac/ # η.6.1 — Role/Permission/Matrix/Middleware
1051
+ │ │ ├── collaboration/ # η.5.5.d — CollaborationAuditEnforcer
630
1052
  │ │ └── ...
631
- │ ├── core/ # Core managers (13 files)
632
- │ │ ├── ManagerContext.ts # Context holder (lazy init)
633
- │ │ ├── EntityManager.ts # Entity CRUD + hierarchy
634
- │ │ ├── RelationManager.ts # Relation CRUD
635
- │ │ ├── GraphStorage.ts # JSONL I/O + caching
636
- │ │ ├── SQLiteStorage.ts # SQLite with better-sqlite3
637
- │ │ ├── TransactionManager.ts # ACID transactions
638
- │ │ ├── RefIndex.ts # Named refs for O(1) entity lookup
1053
+ │ ├── core/ # Core managers (14 files)
1054
+ │ │ ├── ManagerContext.ts # Central facade (lazy)
1055
+ │ │ ├── EntityManager.ts # CRUD + hierarchy + OCC + temporal
1056
+ │ │ ├── RelationManager.ts # CRUD + temporal validity
1057
+ │ │ ├── ObservationManager.ts # CRUD + per-obs validity windows
1058
+ │ │ ├── HierarchyManager.ts # Tree traversal
1059
+ │ │ ├── GraphStorage.ts # JSONL I/O + atomic writes
1060
+ │ │ ├── SQLiteStorage.ts # SQLite + FTS5 + BM25
1061
+ │ │ ├── GraphTraversal.ts # BFS / DFS / paths / centrality
1062
+ │ │ ├── TransactionManager.ts # ACID batch operations
1063
+ │ │ ├── RefIndex.ts # O(1) name → entity sidecar
639
1064
  │ │ └── ...
640
- │ ├── search/ # Search implementations (34 files)
641
- │ │ ├── SearchManager.ts # Search orchestrator
642
- │ │ ├── BasicSearch.ts # Text matching
643
- │ │ ├── RankedSearch.ts # TF-IDF scoring
644
- │ │ ├── BooleanSearch.ts # AND/OR/NOT logic
645
- │ │ ├── FuzzySearch.ts # Typo tolerance (NGram pre-filtered)
1065
+ │ ├── search/ # Search (37 files)
1066
+ │ │ ├── SearchManager.ts # Orchestrator
1067
+ │ │ ├── RankedSearch.ts # TF-IDF
1068
+ │ │ ├── BM25Search.ts # Okapi BM25 with stopwords
1069
+ │ │ ├── BooleanSearch.ts # AND/OR/NOT AST
1070
+ │ │ ├── FuzzySearch.ts # Levenshtein + N-gram pre-filter
646
1071
  │ │ ├── SemanticSearch.ts # Embedding-based
647
- │ │ ├── HybridSearchManager.ts # Multi-layer search
648
- │ │ ├── NGramIndex.ts # Trigram index + Jaccard pre-filter
649
- │ │ ├── TemporalQueryParser.ts # Natural language time parsing
650
- │ │ ├── TemporalSearch.ts # Time-range search executor
651
- │ │ ├── LLMQueryPlanner.ts # NL → StructuredQuery decomposition
652
- │ │ ├── LLMSearchExecutor.ts # LLM-planned search execution
1072
+ │ │ ├── HybridSearchManager.ts # Multi-signal scoring
1073
+ │ │ ├── NGramIndex.ts # Trigram + Jaccard
1074
+ │ │ ├── TemporalSearch.ts # Time-range execution
1075
+ │ │ ├── LLMQueryPlanner.ts # NL StructuredQuery
653
1076
  │ │ └── ...
654
- │ ├── features/ # Advanced capabilities (12 files)
655
- │ │ ├── IOManager.ts # Import/export/backup
1077
+ │ ├── features/ # Advanced capabilities (17 files)
1078
+ │ │ ├── IOManager.ts # Import / export (incl. RDF/JSON-LD) / backup / ingest
656
1079
  │ │ ├── TagManager.ts # Tag aliases
657
1080
  │ │ ├── ArchiveManager.ts # Entity archival
658
1081
  │ │ ├── CompressionManager.ts # Duplicate detection
659
- │ │ ├── FreshnessManager.ts # TTL/confidence freshness reports
660
- │ │ ├── AuditLog.ts # JSONL immutable audit trail
661
- │ │ ├── GovernanceManager.ts # Transactions + policy enforcement
1082
+ │ │ ├── FreshnessManager.ts # TTL/confidence
1083
+ │ │ ├── AuditLog.ts # JSONL immutable trail
1084
+ │ │ ├── GovernanceManager.ts # Transactions + policy
1085
+ │ │ ├── ContradictionDetector.ts # Semantic-similarity supersession
1086
+ │ │ ├── SemanticForget.ts # Two-tier deletion
662
1087
  │ │ └── ...
663
- │ ├── cli/ # CLI interface (6 files)
664
- ├── index.ts # CLI entry point
665
- ├── commands/ # Command implementations
666
- ├── config.ts # Config file support
667
- │ │ ├── formatters.ts # Output formatting
668
- │ │ ├── interactive.ts # REPL mode
669
- │ │ └── options.ts # CLI option parsing
670
- │ ├── types/ # TypeScript definitions (4 files)
671
- │ ├── utils/ # Shared utilities (18 files)
1088
+ │ ├── cli/ # CLI binary (16 files)
1089
+ │ ├── security/ # PII redaction (2 files; η.6.3)
1090
+ │ ├── types/ # TypeScript definitions (7 files)
1091
+ │ ├── utils/ # Shared utilities (26 files)
672
1092
  │ └── workers/ # Worker pool (2 files)
673
- ├── tests/ # Test suite (4674 tests)
674
- │ ├── unit/ # Unit tests
675
- │ ├── integration/ # Integration tests
676
- └── performance/ # Benchmarks
1093
+ ├── tests/ # 6157 passing tests
1094
+ │ ├── unit/ # Per-module unit tests
1095
+ │ ├── integration/ # Cross-module workflows
1096
+ ├── edge-cases/ # Boundary conditions
1097
+ │ └── performance/ # Benchmarks (gated by SKIP_BENCHMARKS)
677
1098
  ├── docs/ # Documentation
678
- └── architecture/ # Architecture docs
679
- ├── tools/ # Development utilities
680
- │ ├── chunking-for-files/ # File splitting tool
681
- └── create-dependency-graph/ # Dependency analyzer
1099
+ ├── architecture/ # OVERVIEW, ARCHITECTURE, DEPENDENCY_GRAPH, etc.
1100
+ ├── development/ # ADRs (incl. ADR-011 wrap-and-extend)
1101
+ │ ├── guides/ # API reference, configuration, recipes
1102
+ ├── roadmap/ # ROADMAP.md
1103
+ │ └── superpowers/plans/ # Phase α–η implementation plans
1104
+ ├── tools/ # Dev utilities
1105
+ │ ├── chunking-for-files/ # File splitting / merging
1106
+ │ ├── compress-for-context/ # LLM-context compression
1107
+ │ ├── create-dependency-graph/ # Generates DEPENDENCY_GRAPH.md
1108
+ │ ├── migrate-from-jsonl-to-sqlite/ # Storage migration
1109
+ │ └── plan-doc-audit/ # Plan-doc rot detection (audit:plans)
1110
+ ├── CLAUDE.md # Full env-var + architecture reference
1111
+ ├── CHANGELOG.md # Version-by-version history
682
1112
  └── README.md # This file
683
1113
  ```
684
1114
 
@@ -691,10 +1121,22 @@ Comprehensive architecture documentation in `docs/architecture/`:
691
1121
  - [COMPONENTS.md](docs/architecture/COMPONENTS.md) - Component breakdown
692
1122
  - [DATAFLOW.md](docs/architecture/DATAFLOW.md) - Data flow patterns
693
1123
  - [API.md](docs/architecture/API.md) - Complete API documentation
694
- - [DEPENDENCY_GRAPH.md](docs/architecture/DEPENDENCY_GRAPH.md) - Module dependencies
1124
+ - [DEPENDENCY_GRAPH.md](docs/architecture/DEPENDENCY_GRAPH.md) - Module dependencies (auto-generated by `tools/create-dependency-graph`)
1125
+ - [unused-analysis.md](docs/architecture/unused-analysis.md) - Unused exports report
695
1126
  - [TEST_COVERAGE.md](docs/architecture/TEST_COVERAGE.md) - Test coverage analysis
696
1127
  - [AGENT_MEMORY.md](docs/architecture/AGENT_MEMORY.md) - Agent memory system design
697
1128
 
1129
+ ADRs and roadmap:
1130
+
1131
+ - [ARCHITECTURE_DECISIONS.md](docs/development/ARCHITECTURE_DECISIONS.md) - including ADR-011 (wrap-and-extend pattern for memory intelligence services)
1132
+ - [ROADMAP.md](docs/roadmap/ROADMAP.md) - Feature roadmap with implementation details
1133
+ - [docs/superpowers/plans/](docs/superpowers/plans/) - Phase α–η implementation plans
1134
+
1135
+ Project-internal:
1136
+
1137
+ - [CLAUDE.md](CLAUDE.md) - Full environment-variable reference + architecture map
1138
+ - [CHANGELOG.md](CHANGELOG.md) - Version-by-version history
1139
+
698
1140
  ## License
699
1141
 
700
1142
  **MIT License** - see [LICENSE](LICENSE)