@danielsimonjr/memoryjs 1.15.0 → 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,14 +1,14 @@
1
1
  # MemoryJS
2
2
 
3
- [![Version](https://img.shields.io/badge/version-1.14.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-6157%20passing-brightgreen.svg)](https://github.com/danielsimonjr/memoryjs)
7
+ [![Tests](https://img.shields.io/badge/tests-7127%20passing-brightgreen.svg)](https://github.com/danielsimonjr/memoryjs)
8
8
 
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**, 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**.
10
10
 
11
- > Core library powering [@danielsimonjr/memory-mcp](https://www.npmjs.com/package/@danielsimonjr/memory-mcp). **183 TypeScript files**, **62,889 lines of code**, **6157 passing tests**, dual storage backends (JSONL/SQLite + pluggable `IMemoryBackend`), comprehensive search (BM25, TF-IDF, fuzzy with N-gram pre-filter, semantic, hybrid, temporal, LLM-planned, active iterative retrieval), 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, and a world-model orchestrator.
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.
12
12
 
13
13
  ## Table of Contents
14
14
 
@@ -58,103 +58,121 @@ A **TypeScript knowledge graph library** for managing entities, relations, and o
58
58
 
59
59
  | Module | Files | Key Components |
60
60
  |--------|-------|----------------|
61
- | `agent/` | 61 | 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** |
62
- | `core/` | 14 | ManagerContext, EntityManager (with OCC), RelationManager (with temporal validity), ObservationManager (with bitemporal axis), HierarchyManager, GraphStorage, SQLiteStorage, GraphTraversal, TransactionManager, RefIndex |
63
- | `search/` | 37 | SearchManager, RankedSearch (TF-IDF), BM25Search, BooleanSearch, FuzzySearch, SemanticSearch, HybridSearchManager, NGramIndex, TemporalQueryParser, TemporalSearch, LLMQueryPlanner, LLMSearchExecutor, EmbeddingService, VectorStore |
64
- | `features/` | 17 | IOManager (with RDF/Turtle/JSON-LD export), ArchiveManager, CompressionManager, StreamingExporter, FreshnessManager, AuditLog, GovernanceManager, ContradictionDetector, SemanticForget, AutoLinker |
65
- | `utils/` | 26 | BatchProcessor, CompressedCache, WorkerPoolManager, MemoryMonitor, schemas (Zod) |
66
- | `types/` | 7 | Entity, Relation, AgentEntity, SessionEntity, ArtifactEntity, Procedure |
67
- | `security/` | 2 | **PiiRedactor** + bundled patterns (email/SSN/CC/phone/IP) |
68
- | `cli/` | 16 | `memory` / `memoryjs` binary commands (entity, relation, search, observation, tag, hierarchy, graph, io, maintenance) |
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` |
69
70
  | `workers/` | 2 | Levenshtein distance calculations |
70
71
 
71
- **Total:** 183 TypeScript files | 62,889 lines of code | 6157 passing tests
72
-
73
- ### Recent additions (Unreleased — built on top of v1.14.0)
74
-
75
- | Feature | Entry Point |
76
- |---------|-------------|
77
- | **η.4.4 Bitemporal Versioning** | `EntityManager.invalidateEntity()` / `entityAsOf()` / `entityTimeline()`; `ObservationManager.invalidateObservation()` / `observationsAsOf()`; `Entity.validFrom` / `validUntil` / `observationMeta[]` |
78
- | **η.5.4 Linked Data Export** | `ioManager.exportGraph(g, 'turtle' \| 'rdf-xml' \| 'json-ld')` W3C RDF 1.1; reification fallback for non-NCName predicates |
79
- | **η.5.5.a Multi-Agent Conflict View** | `SynthesisResult.conflicts[]` + `CollaborativeSynthesis.resolveConflicts(result, policy)` (most_recent / highest_confidence / highest_score / trusted_agent) |
80
- | **η.5.5.b Visibility Expansion** | `AgentEntity.visibleFrom` / `visibleUntil` / `allowedRoles[]`; `VisibilityResolver` adds time-window gate + role predicate |
81
- | **η.5.5.c Optimistic Concurrency** | `EntityManager.updateEntity(name, updates, { expectedVersion })` → throws `VersionConflictError` on mismatch |
82
- | **η.5.5.d Attribution Enforcer** | `CollaborationAuditEnforcer` strict-mode requires `agentId` on every mutation; appends to `AuditLog` |
83
- | **η.6.1 RBAC** | `ctx.rbacMiddleware.checkPermission(agentId, action, resourceType, resourceName?)`; `ctx.roleAssignmentStore` with optional JSONL persistence |
84
- | **η.6.3 PII Redactor** | `new PiiRedactor().redactGraph(graph)` pluggable regex bank with `redactWithStats()` for compliance audit trails |
85
- | **3B.4 Procedural Memory** | `ctx.procedureManager.addProcedure({ steps })` / `matchProcedure(context)` / `refineProcedure(id, feedback)` (EWMA success-rate) |
86
- | **3B.5 Active Retrieval** | `ctx.activeRetrieval.adaptiveRetrieve({ query })` iterative query rewriting with token-overlap expansion |
87
- | **3B.6 Causal Reasoning** | `ctx.causalReasoner.findCauses()` / `findEffects()` / `counterfactual()` / `detectCycles()` |
88
- | **3B.7 World Model** | `ctx.worldModelManager.getCurrentState()` / `validateFact()` / `predictOutcome()` / `detectStateChange()` |
89
-
90
- ### v1.13.0 Memory Intelligence Services (Phase δ)
91
-
92
- | Feature | Entry Point |
93
- |---------|-------------|
94
- | Memory Validator | `ctx.memoryValidator.validateConsistency()` / `detectContradictions()` / `repairWithResolver()` / `validateTemporalOrder()` / `calculateReliability()` |
95
- | Trajectory Compressor | `ctx.trajectoryCompressor.distill()` / `abstractAtLevel()` / `findRedundancies()` / `mergeRedundant()` |
96
- | Experience Extractor | `ctx.experienceExtractor.extractFromContrastivePairs()` / `clusterTrajectories()` / `synthesizeExperience()` |
97
-
98
- ### v1.12.0 — Pluggable Memory Backends (Phase β)
99
-
100
- | Feature | Entry Point |
101
- |---------|-------------|
102
- | `IMemoryBackend` interface | `MEMORY_BACKEND=in-memory \| sqlite` selects via `ctx.memoryBackend` |
103
- | `InMemoryBackend` | Ephemeral, dedup on `(sessionId, content)` |
104
- | `SQLiteBackend` | Wraps `MemoryEngine` + `DecayEngine.calculatePrdEffectiveImportance()` |
105
- | Audit-tooling guard | `npm run audit:plans` PostToolUse hook catches plan-doc rot |
106
-
107
- ### v1.11.0 Turn-Aware Memory Engine
108
-
109
- | Feature | Entry Point |
110
- |---------|-------------|
111
- | `MemoryEngine` | `ctx.memoryEngine.addTurn()` / `getSessionTurns()` — four-tier dedup (exact / prefix / Jaccard / optional semantic) |
112
- | `ImportanceScorer` | length × keyword × recent-turn-overlap → integer [0, 10] |
113
- | O(1) exact-equality dedup | `Entity.contentHash` (SHA-256) + SQLite `idx_entities_content_hash` |
114
-
115
- ### v1.9.0 Temporal Relations + Conversation Ingest
116
-
117
- | Feature | Entry Point |
118
- |---------|-------------|
119
- | Temporal Relations | `RelationManager.invalidateRelation()` / `queryAsOf(date)` / `timeline()` |
120
- | 4-Layer Wake-Up Stack | `ContextWindowManager.wakeUp({ compress })` — ~600-token context bootstrap |
121
- | Conversation Ingestion | `IOManager.ingest({ messages, ...options })` — format-agnostic pipeline |
122
- | Per-Agent Diary | `AgentMemoryManager.writeDiary()` / `readDiary()` |
123
- | Local Embeddings (default) | `MEMORY_EMBEDDING_PROVIDER=local` — zero-config semantic search |
124
-
125
- ### v1.8.0 — Memory Versioning + Project Scoping
126
-
127
- | Feature | Entry Point |
128
- |---------|-------------|
129
- | Contradiction-driven supersession | `Entity.version` / `parentEntityName` / `rootEntityName` / `supersededBy` |
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` |
130
120
  | Project scoping | `Entity.projectId` + `MEMORY_DEFAULT_PROJECT_ID` |
131
- | Two-tier deletion | `ctx.semanticForget` — exact match → 0.85 semantic fallback with audit logging |
132
-
133
- ### v1.7.0Multi-Agent Memory
134
-
135
- | Feature | Entry Point |
136
- |---------|-------------|
137
- | Role-Aware Customization | `RoleProfileManager.apply(role)` salience weights + budget splits |
138
- | Entropy-Aware Filtering | `EntropyFilter`Shannon entropy gate in `ConsolidationPipeline` |
139
- | Recursive Memory Consolidation | `ConsolidationScheduler` background dedup + merge to fixed point |
140
- | Salience Budget Allocation | `MemoryFormatter.formatWithSalienceBudget()` |
141
- | Collaborative Memory Synthesis | `CollaborativeSynthesis.synthesize(entity, hopDepth)` |
142
- | Failure-Driven Distillation | `FailureDistillation.distill(failureEntity)` |
143
- | Cognitive Load Metrics | `CognitiveLoadAnalyzer.analyze(memories)` → `CognitiveLoadReport` |
144
- | Shared Visibility Hierarchies | `VisibilityResolver.canAccess()` 5-level model |
145
-
146
- ### v1.6.0 Governance + Temporal
147
-
148
- | Feature | Entry Point |
149
- |---------|-------------|
150
- | Stable Index Dereferencing | `ctx.refIndex` `register` / `resolve` / `deregister` |
151
- | Artifact-Level Granularity | `ctx.agentMemory().artifactManager.createArtifact()` |
152
- | Temporal Range Queries | `ctx.searchManager.searchByTime()` / `ctx.temporalSearch` |
153
- | Memory Distillation Policy | `IDistillationPolicy` wired into `ContextWindowManager` |
154
- | Freshness Auditing | `ctx.freshnessManager` TTL, confidence, staleness report |
155
- | N-gram Pre-filtering | Automatic in `FuzzySearch` via `NGramIndex` |
156
- | LLM Query Planner | `ctx.queryNaturalLanguage(query, llmProvider?)` |
157
- | Dynamic Memory Governance | `ctx.governanceManager` — `withTransaction` / `GovernancePolicy` |
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 / exportJSON, CSV, GraphML, GEXF, DOT, Markdown, Mermaid | `ctx.ioManager.exportGraph(format)` |
129
+ | W3C Linked Data exportTurtle, 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).
158
176
 
159
177
  ## Installation
160
178
 
@@ -259,7 +277,7 @@ await enforcer.createEntities([{ name: 'X', entityType: 't', observations: ['fac
259
277
  'agent-alice'); // throws AttributionRequiredError if agentId is missing
260
278
  ```
261
279
 
262
- ### 6. Bitemporal versioning (η.4.4)
280
+ ### 6. Bitemporal versioning
263
281
 
264
282
  ```typescript
265
283
  // Mark an entity as no longer valid at a specific time
@@ -277,7 +295,7 @@ const obsAtTime = await ctx.observationManager.observationsAsOf(
277
295
  );
278
296
  ```
279
297
 
280
- ### 7. Causal reasoning + world model (3B.6 / 3B.7)
298
+ ### 7. Causal reasoning and world model
281
299
 
282
300
  ```typescript
283
301
  // Forward inference — "what does X cause?"
@@ -294,7 +312,7 @@ const after = await ctx.worldModelManager.getCurrentState();
294
312
  const change = ctx.worldModelManager.detectStateChange(before, after);
295
313
  ```
296
314
 
297
- ### 8. RBAC + PII redaction (η.6.1 / η.6.3)
315
+ ### 8. RBAC and PII redaction
298
316
 
299
317
  ```typescript
300
318
  // Grant a role
@@ -327,11 +345,11 @@ interface Entity {
327
345
  createdAt?: string; // ISO 8601 timestamp
328
346
  lastModified?: string; // ISO 8601 timestamp
329
347
 
330
- // v1.6.0 — Freshness
348
+ // Freshness
331
349
  ttl?: number; // Seconds until stale
332
350
  confidence?: number; // [0, 1] belief strength
333
351
 
334
- // v1.8.0 — Project scoping + supersession
352
+ // Project scoping + supersession
335
353
  projectId?: string; // Multi-project isolation
336
354
  version?: number; // Supersession chain version (also drives η.5.5.c OCC)
337
355
  parentEntityName?: string;
@@ -339,7 +357,7 @@ interface Entity {
339
357
  isLatest?: boolean;
340
358
  supersededBy?: string;
341
359
 
342
- // v1.11.0 — Memory Engine dedup
360
+ // Memory Engine dedup
343
361
  contentHash?: string; // SHA-256 for O(1) Tier-1 dedup
344
362
 
345
363
  // η.4.4 — Bitemporal validity (orthogonal to supersession)
@@ -408,13 +426,13 @@ ctx.memoryBackend // Pluggable IMemoryBackend (in-memory / sqlite)
408
426
  ctx.contextWindowManager // 4-layer wake-up stack + token budgeting
409
427
  ctx.agentMemory() // Full Agent Memory System facade
410
428
 
411
- // Memory intelligence (Phase δ)
429
+ // Memory intelligence
412
430
  ctx.memoryValidator // Validate consistency / contradictions / temporal order
413
431
  ctx.trajectoryCompressor // Distill / abstract / merge redundant trajectories
414
432
  ctx.experienceExtractor // Cluster trajectories → reusable experience patterns
415
433
  ctx.patternDetector // Trigger / sequence / outcome pattern mining
416
434
 
417
- // Memory theory (Phase 3B)
435
+ // Memory theory
418
436
  ctx.procedureManager // 3B.4 — executable procedure memory + EWMA refinement
419
437
  ctx.causalReasoner // 3B.6 — findCauses / findEffects / counterfactual
420
438
  ctx.worldModelManager // 3B.7 — snapshot orchestrator + state-change diff
@@ -650,13 +668,27 @@ await agent.endSession(session.name);
650
668
  ### Memory Types
651
669
 
652
670
  ```typescript
653
- 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
654
680
  ```
655
681
 
656
682
  - **Working Memory**: Short-term, session-scoped memories that may be promoted
657
683
  - **Episodic Memory**: Timeline-based event memories with temporal ordering
658
684
  - **Semantic Memory**: Long-term factual knowledge
659
- - **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.
660
692
 
661
693
  ### Decay System
662
694
 
@@ -713,7 +745,7 @@ const results = await agent.searchCrossAgent('agent_2', 'query');
713
745
  | `batchUpdate(updates[])` | Atomic multi-entity update |
714
746
  | `addTags(name, tags)` / `removeTags(name, tags)` | Tag management |
715
747
  | `setImportance(name, score)` | Set importance (0-10) |
716
- | `getVersionChain(name)` / `getLatestVersion(name)` | v1.8.0 supersession chains |
748
+ | `getVersionChain(name)` / `getLatestVersion(name)` | supersession chains |
717
749
  | `invalidateEntity(name, ended?)` | η.4.4 — set `validUntil` |
718
750
  | `entityAsOf(name, asOf)` | η.4.4 — time-travel query |
719
751
  | `entityTimeline(name)` | η.4.4 — versions sorted by `validFrom` |
@@ -725,9 +757,9 @@ const results = await agent.searchCrossAgent('agent_2', 'query');
725
757
  | `createRelations(relations)` | Create multiple relations |
726
758
  | `getRelations(entityName)` | Get incoming/outgoing relations |
727
759
  | `deleteRelations(relations)` | Delete specific relations |
728
- | `invalidateRelation(from, type, to, ended?)` | v1.9.0 — set `validUntil` on a relation |
729
- | `queryAsOf(entity, asOf, { direction? })` | v1.9.0 — relations valid at time T |
730
- | `timeline(entity, { direction? })` | v1.9.0 — chronological history |
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 |
731
763
 
732
764
  ### ObservationManager
733
765
 
@@ -756,9 +788,9 @@ const results = await agent.searchCrossAgent('agent_2', 'query');
756
788
  | `exportGraph(graph, format)` | Export to `json` / `csv` / `graphml` / `gexf` / `dot` / `markdown` / `mermaid` / `turtle` / `rdf-xml` / `json-ld` |
757
789
  | `exportGraphWithCompression(graph, format, options?)` | Brotli-compressed export |
758
790
  | `importGraph(format, data, options)` | Import with merge strategies (`replace` / `skip` / `merge` / `fail`) |
759
- | `ingest({ messages }, options?)` | v1.9.0 — conversation ingestion pipeline |
760
- | `splitSessions(content, options?)` | v1.9.0 — split multi-session transcripts |
761
- | `visualizeGraph(options?)` | v1.9.1 — interactive HTML visualization |
791
+ | `ingest({ messages }, options?)` | conversation ingestion pipeline |
792
+ | `splitSessions(content, options?)` | split multi-session transcripts |
793
+ | `visualizeGraph(options?)` | interactive HTML visualization |
762
794
  | `createBackup(options)` / `restoreBackup(path)` | Backup management |
763
795
 
764
796
  ### GraphTraversal
@@ -771,7 +803,7 @@ const results = await agent.searchCrossAgent('agent_2', 'query');
771
803
  | `getConnectedComponents()` | Find isolated subgraphs |
772
804
  | `bfs(start, options)` / `dfs(start, options)` | Traversal |
773
805
 
774
- ### CausalReasoner (3B.6)
806
+ ### CausalReasoner
775
807
 
776
808
  | Method | Description |
777
809
  |--------|-------------|
@@ -780,7 +812,7 @@ const results = await agent.searchCrossAgent('agent_2', 'query');
780
812
  | `counterfactual({ seed, removeFrom, removeTo, predict })` | Chains surviving edge removal (pure; no graph mutation) |
781
813
  | `detectCycles(seed, maxDepth?)` | Depth-bounded DFS over causal subgraph |
782
814
 
783
- ### ProcedureManager (3B.4)
815
+ ### ProcedureManager
784
816
 
785
817
  | Method | Description |
786
818
  |--------|-------------|
@@ -790,7 +822,7 @@ const results = await agent.searchCrossAgent('agent_2', 'query');
790
822
  | `matchProcedure(context, candidates, threshold?)` | Token-overlap match |
791
823
  | `refineProcedure(id, { succeeded, notes? })` | EWMA success-rate update |
792
824
 
793
- ### WorldModelManager (3B.7)
825
+ ### WorldModelManager
794
826
 
795
827
  | Method | Description |
796
828
  |--------|-------------|
@@ -799,21 +831,21 @@ const results = await agent.searchCrossAgent('agent_2', 'query');
799
831
  | `predictOutcome(action, candidates)` | Delegates to `CausalReasoner.findEffects` |
800
832
  | `detectStateChange(before, after)` | Pure snapshot diff |
801
833
 
802
- ### ActiveRetrievalController (3B.5)
834
+ ### ActiveRetrievalController
803
835
 
804
836
  | Method | Description |
805
837
  |--------|-------------|
806
838
  | `shouldRetrieve(context)` | Cost heuristic; rejects empty / over-budget |
807
839
  | `adaptiveRetrieve(context)` | Iterative rewrite + retrieve until coverage threshold |
808
840
 
809
- ### CollaborativeSynthesis (η.5.5.a)
841
+ ### CollaborativeSynthesis
810
842
 
811
843
  | Method | Description |
812
844
  |--------|-------------|
813
845
  | `synthesize(seedEntity, context?)` | BFS + salience scoring; surfaces multi-agent `conflicts[]` |
814
846
  | `resolveConflicts(result, policy)` | Pick winners per `most_recent` / `highest_confidence` / `highest_score` / `trusted_agent` |
815
847
 
816
- ### MemoryValidator (Phase δ)
848
+ ### MemoryValidator
817
849
 
818
850
  | Method | Description |
819
851
  |--------|-------------|
@@ -823,7 +855,7 @@ const results = await agent.searchCrossAgent('agent_2', 'query');
823
855
  | `validateTemporalOrder(observations)` | Sync `[T=ISO]` ordering check |
824
856
  | `calculateReliability(entity)` | Confidence × confirmation × age penalty |
825
857
 
826
- ### RbacMiddleware (η.6.1)
858
+ ### RbacMiddleware
827
859
 
828
860
  | Method | Description |
829
861
  |--------|-------------|
@@ -832,7 +864,7 @@ const results = await agent.searchCrossAgent('agent_2', 'query');
832
864
  | `roleAssignmentStore.revoke(agentId, role, resourceType?)` | Remove a grant |
833
865
  | `roleAssignmentStore.listActive(agentId, now?)` | Active grants at a point in time |
834
866
 
835
- ### PiiRedactor (η.6.3)
867
+ ### PiiRedactor
836
868
 
837
869
  | Method | Description |
838
870
  |--------|-------------|
@@ -840,6 +872,46 @@ const results = await agent.searchCrossAgent('agent_2', 'query');
840
872
  | `redactWithStats(text)` | Returns `{ text, stats: { totalRedactedBytes, countsByPattern } }` |
841
873
  | `redactGraph(graph)` | Apply to every observation in a graph-shaped object |
842
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 |
914
+
843
915
  ## Configuration
844
916
 
845
917
  ### Environment Variables
@@ -863,10 +935,15 @@ The full env-var reference lives in [CLAUDE.md](CLAUDE.md). Most-used:
863
935
  | `MEMORY_AUDIT_ATTRIBUTION_REQUIRED` | `CollaborationAuditEnforcer` strict mode | `false` |
864
936
  | `MEMORY_RBAC_ENABLED` | Wire `RbacMiddleware` into `GovernancePolicy` | `false` |
865
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` |
866
943
  | `SKIP_BENCHMARKS` | Skip perf benchmark tests | `false` |
867
944
  | `LOG_LEVEL` | `debug` / `info` / `warn` / `error` | (none) |
868
945
 
869
- See [CLAUDE.md](CLAUDE.md#environment-variables) for the complete list (~50 variables across decay/salience/context-window/freshness/RBAC/PRD scoring/MemoryEngine knobs).
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).
870
947
 
871
948
  ## Development
872
949
 
@@ -962,9 +1039,9 @@ memoryjs/
962
1039
  │ │ ├── MemoryBackend.ts # IMemoryBackend interface (v1.12)
963
1040
  │ │ ├── InMemoryBackend.ts # Ephemeral adapter
964
1041
  │ │ ├── SQLiteBackend.ts # SQLite-backed adapter
965
- │ │ ├── MemoryValidator.ts # Phase δ consistency checks
966
- │ │ ├── TrajectoryCompressor.ts # Phase δ distill / merge
967
- │ │ ├── ExperienceExtractor.ts # Phase δ pattern abstraction
1042
+ │ │ ├── MemoryValidator.ts # Memory consistency / contradiction checks
1043
+ │ │ ├── TrajectoryCompressor.ts # Distill / merge trajectory data
1044
+ │ │ ├── ExperienceExtractor.ts # Pattern abstraction from contrastive pairs
968
1045
  │ │ ├── PatternDetector.ts # Sequence + outcome mining
969
1046
  │ │ ├── causal/ # 3B.6 — CausalReasoner
970
1047
  │ │ ├── procedural/ # 3B.4 — ProcedureManager + Sequencer
@@ -1051,7 +1128,7 @@ Comprehensive architecture documentation in `docs/architecture/`:
1051
1128
 
1052
1129
  ADRs and roadmap:
1053
1130
 
1054
- - [ARCHITECTURE_DECISIONS.md](docs/development/ARCHITECTURE_DECISIONS.md) - including ADR-011 (Phase δ wrap-and-extend pattern)
1131
+ - [ARCHITECTURE_DECISIONS.md](docs/development/ARCHITECTURE_DECISIONS.md) - including ADR-011 (wrap-and-extend pattern for memory intelligence services)
1055
1132
  - [ROADMAP.md](docs/roadmap/ROADMAP.md) - Feature roadmap with implementation details
1056
1133
  - [docs/superpowers/plans/](docs/superpowers/plans/) - Phase α–η implementation plans
1057
1134