nexus-agents 2.77.12 → 2.78.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{child-mcp-config-MJMUF7TL.js → child-mcp-config-CTO2MBRM.js} +3 -4
- package/dist/{child-mcp-config-MJMUF7TL.js.map → child-mcp-config-CTO2MBRM.js.map} +1 -1
- package/dist/{chunk-YJ2IGAD2.js → chunk-2UYTFLMO.js} +2 -2
- package/dist/{chunk-6AY5DK4E.js → chunk-2YPG6PDG.js} +3 -3
- package/dist/{chunk-3VWMM6UF.js → chunk-3NIPH6UP.js} +2 -2
- package/dist/{chunk-L3TPDTP3.js → chunk-4N33QZLH.js} +13 -15
- package/dist/{chunk-L3TPDTP3.js.map → chunk-4N33QZLH.js.map} +1 -1
- package/dist/{chunk-JN6UWGHH.js → chunk-5O6XLBPP.js} +2 -2
- package/dist/{chunk-ERWXGXV2.js → chunk-6TFTVW77.js} +3 -3
- package/dist/{chunk-2IAWMNNB.js → chunk-6WBTNZAY.js} +183 -87
- package/dist/chunk-6WBTNZAY.js.map +1 -0
- package/dist/{chunk-GOT7OAL5.js → chunk-7BMOZJYS.js} +29 -5
- package/dist/chunk-7BMOZJYS.js.map +1 -0
- package/dist/{chunk-C2LLQ6TW.js → chunk-7XCUZI4G.js} +4 -4
- package/dist/chunk-7XCUZI4G.js.map +1 -0
- package/dist/{chunk-TDV5ALHY.js → chunk-D6TM2VHX.js} +3 -3
- package/dist/{chunk-PWTJGGKB.js → chunk-DLXT23AC.js} +2 -2
- package/dist/chunk-DNO2INX5.js +276 -0
- package/dist/chunk-DNO2INX5.js.map +1 -0
- package/dist/{chunk-G2CSKBY5.js → chunk-FJWWSVWB.js} +29 -6
- package/dist/chunk-FJWWSVWB.js.map +1 -0
- package/dist/{chunk-DSQ5XM4O.js → chunk-FVPYP5DD.js} +4 -4
- package/dist/{chunk-MGLWPN2I.js → chunk-GONMG4NM.js} +2 -2
- package/dist/{chunk-XYA3DPWJ.js → chunk-GTGDVBLW.js} +5 -5
- package/dist/{chunk-YQMQSJQK.js → chunk-HYU4GZY6.js} +2 -2
- package/dist/{chunk-3DH5SLFH.js → chunk-K2QILJG4.js} +6 -6
- package/dist/{chunk-5WHWKY32.js → chunk-KT5FIBWS.js} +2 -2
- package/dist/{chunk-DIB6V67T.js → chunk-L6SCKLGO.js} +3 -3
- package/dist/{chunk-IPWCD22D.js → chunk-PLX6FCFC.js} +2 -2
- package/dist/chunk-PQHVC4BD.js +639 -0
- package/dist/chunk-PQHVC4BD.js.map +1 -0
- package/dist/chunk-Q5CFPIJ5.js +5581 -0
- package/dist/chunk-Q5CFPIJ5.js.map +1 -0
- package/dist/{chunk-G6ZPVADX.js → chunk-SD76JZBG.js} +2 -2
- package/dist/{chunk-Y2CP4Z5B.js → chunk-SWFJU3W2.js} +220 -4580
- package/dist/chunk-SWFJU3W2.js.map +1 -0
- package/dist/{chunk-3MRM53T4.js → chunk-WDYCIJWN.js} +640 -470
- package/dist/chunk-WDYCIJWN.js.map +1 -0
- package/dist/{chunk-CM3TORGV.js → chunk-YXWGEIQR.js} +2 -2
- package/dist/{chunk-7NK7BTWP.js → chunk-ZVCED4Z4.js} +2 -2
- package/dist/cli-circuit-breaker-I74ZQ44Q.js +13 -0
- package/dist/cli.js +109 -58
- package/dist/cli.js.map +1 -1
- package/dist/{composite-router-S6E26BCI.js → composite-router-V3OC57IE.js} +3 -4
- package/dist/consensus-vote-ESFPGEJE.js +30 -0
- package/dist/context-retriever-MB3D7KS6.js +18 -0
- package/dist/dist-NIXVXYIH.js +42 -0
- package/dist/doctor-deep-KQ765XZA.js +12 -0
- package/dist/expert-bridge-JKLC57IC.js +10 -0
- package/dist/factory-BUUXNGIB.js +14 -0
- package/dist/{factory-X3VKIGKP.js → factory-LHHYDVZX.js} +5 -6
- package/dist/index.d.ts +72 -8
- package/dist/index.js +208 -316
- package/dist/index.js.map +1 -1
- package/dist/{init-opencode-CFE7M6XA.js → init-opencode-GXZN2W5S.js} +6 -7
- package/dist/{init-opencode-CFE7M6XA.js.map → init-opencode-GXZN2W5S.js.map} +1 -1
- package/dist/issue-triage-RMXPDZ2K.js +15 -0
- package/dist/{learning-persistence-N6ILD2HX.js → learning-persistence-Q3HTOGTU.js} +2 -3
- package/dist/outcome-store-adapter-QRFJJIKB.js +57 -0
- package/dist/outcome-store-adapter-QRFJJIKB.js.map +1 -0
- package/dist/{registry-command-RPPC7N2K.js → registry-command-6E4YKAMT.js} +3 -4
- package/dist/{registry-command-RPPC7N2K.js.map → registry-command-6E4YKAMT.js.map} +1 -1
- package/dist/{repo-security-plan-7ZCDVH5O.js → repo-security-plan-AGRU72DL.js} +4 -5
- package/dist/research-helpers-synthesize-K2UCJQQG.js +13 -0
- package/dist/{routing-memory-5VTX7LQX.js → routing-memory-3B6DDZ76.js} +3 -4
- package/dist/{session-memory-7XBV6BMY.js → session-memory-L7EQIY2O.js} +4 -5
- package/dist/{setup-command-3ZTEPKDA.js → setup-command-VYV4RFWW.js} +11 -12
- package/dist/setup-config-EQT24DD4.js +10 -0
- package/dist/{setup-custom-api-WM5W5AY5.js → setup-custom-api-IBDV654K.js} +5 -6
- package/dist/{setup-custom-api-WM5W5AY5.js.map → setup-custom-api-IBDV654K.js.map} +1 -1
- package/dist/tool-memory-6HCHQLAN.js +19 -0
- package/dist/{weather-report-YJMVKJGA.js → weather-report-ER3WUZ7S.js} +3 -4
- package/package.json +3 -2
- package/dist/adaptive-memory-EI564K4C.js +0 -16
- package/dist/chunk-2IAWMNNB.js.map +0 -1
- package/dist/chunk-3MRM53T4.js.map +0 -1
- package/dist/chunk-BJ2OMC7P.js +0 -944
- package/dist/chunk-BJ2OMC7P.js.map +0 -1
- package/dist/chunk-C2LLQ6TW.js.map +0 -1
- package/dist/chunk-G2CSKBY5.js.map +0 -1
- package/dist/chunk-GOT7OAL5.js.map +0 -1
- package/dist/chunk-I7ORMAO7.js +0 -32
- package/dist/chunk-I7ORMAO7.js.map +0 -1
- package/dist/chunk-Y2CP4Z5B.js.map +0 -1
- package/dist/cli-circuit-breaker-YX4BWZD5.js +0 -14
- package/dist/consensus-vote-MUQ4HPIF.js +0 -30
- package/dist/doctor-deep-BRU5ZUJI.js +0 -13
- package/dist/expert-bridge-ZPNVLJVN.js +0 -11
- package/dist/factory-A7DTCCUY.js +0 -15
- package/dist/issue-triage-6XD6CVPB.js +0 -16
- package/dist/mobimem-CG2MNS7V.js +0 -14
- package/dist/nexus-data-dir-77UO7N6J.js +0 -12
- package/dist/research-helpers-synthesize-36TUTUUA.js +0 -14
- package/dist/setup-config-EI5KROA3.js +0 -11
- /package/dist/{chunk-YJ2IGAD2.js.map → chunk-2UYTFLMO.js.map} +0 -0
- /package/dist/{chunk-6AY5DK4E.js.map → chunk-2YPG6PDG.js.map} +0 -0
- /package/dist/{chunk-3VWMM6UF.js.map → chunk-3NIPH6UP.js.map} +0 -0
- /package/dist/{chunk-JN6UWGHH.js.map → chunk-5O6XLBPP.js.map} +0 -0
- /package/dist/{chunk-ERWXGXV2.js.map → chunk-6TFTVW77.js.map} +0 -0
- /package/dist/{chunk-TDV5ALHY.js.map → chunk-D6TM2VHX.js.map} +0 -0
- /package/dist/{chunk-PWTJGGKB.js.map → chunk-DLXT23AC.js.map} +0 -0
- /package/dist/{chunk-DSQ5XM4O.js.map → chunk-FVPYP5DD.js.map} +0 -0
- /package/dist/{chunk-MGLWPN2I.js.map → chunk-GONMG4NM.js.map} +0 -0
- /package/dist/{chunk-XYA3DPWJ.js.map → chunk-GTGDVBLW.js.map} +0 -0
- /package/dist/{chunk-YQMQSJQK.js.map → chunk-HYU4GZY6.js.map} +0 -0
- /package/dist/{chunk-3DH5SLFH.js.map → chunk-K2QILJG4.js.map} +0 -0
- /package/dist/{chunk-5WHWKY32.js.map → chunk-KT5FIBWS.js.map} +0 -0
- /package/dist/{chunk-DIB6V67T.js.map → chunk-L6SCKLGO.js.map} +0 -0
- /package/dist/{chunk-IPWCD22D.js.map → chunk-PLX6FCFC.js.map} +0 -0
- /package/dist/{chunk-G6ZPVADX.js.map → chunk-SD76JZBG.js.map} +0 -0
- /package/dist/{chunk-CM3TORGV.js.map → chunk-YXWGEIQR.js.map} +0 -0
- /package/dist/{chunk-7NK7BTWP.js.map → chunk-ZVCED4Z4.js.map} +0 -0
- /package/dist/{adaptive-memory-EI564K4C.js.map → cli-circuit-breaker-I74ZQ44Q.js.map} +0 -0
- /package/dist/{cli-circuit-breaker-YX4BWZD5.js.map → composite-router-V3OC57IE.js.map} +0 -0
- /package/dist/{composite-router-S6E26BCI.js.map → consensus-vote-ESFPGEJE.js.map} +0 -0
- /package/dist/{consensus-vote-MUQ4HPIF.js.map → context-retriever-MB3D7KS6.js.map} +0 -0
- /package/dist/{doctor-deep-BRU5ZUJI.js.map → dist-NIXVXYIH.js.map} +0 -0
- /package/dist/{expert-bridge-ZPNVLJVN.js.map → doctor-deep-KQ765XZA.js.map} +0 -0
- /package/dist/{factory-A7DTCCUY.js.map → expert-bridge-JKLC57IC.js.map} +0 -0
- /package/dist/{factory-X3VKIGKP.js.map → factory-BUUXNGIB.js.map} +0 -0
- /package/dist/{issue-triage-6XD6CVPB.js.map → factory-LHHYDVZX.js.map} +0 -0
- /package/dist/{learning-persistence-N6ILD2HX.js.map → issue-triage-RMXPDZ2K.js.map} +0 -0
- /package/dist/{mobimem-CG2MNS7V.js.map → learning-persistence-Q3HTOGTU.js.map} +0 -0
- /package/dist/{nexus-data-dir-77UO7N6J.js.map → repo-security-plan-AGRU72DL.js.map} +0 -0
- /package/dist/{repo-security-plan-7ZCDVH5O.js.map → research-helpers-synthesize-K2UCJQQG.js.map} +0 -0
- /package/dist/{research-helpers-synthesize-36TUTUUA.js.map → routing-memory-3B6DDZ76.js.map} +0 -0
- /package/dist/{routing-memory-5VTX7LQX.js.map → session-memory-L7EQIY2O.js.map} +0 -0
- /package/dist/{session-memory-7XBV6BMY.js.map → setup-command-VYV4RFWW.js.map} +0 -0
- /package/dist/{setup-command-3ZTEPKDA.js.map → setup-config-EQT24DD4.js.map} +0 -0
- /package/dist/{setup-config-EI5KROA3.js.map → tool-memory-6HCHQLAN.js.map} +0 -0
- /package/dist/{weather-report-YJMVKJGA.js.map → weather-report-ER3WUZ7S.js.map} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/mcp/tools/tool-memory.ts","../src/context/memory-backend-types.ts","../src/context/belief-core-types.ts","../src/context/belief-update-types.ts","../src/context/belief-hindsight-types.ts","../src/context/belief-memory-interface.ts","../src/utils/id-utils.ts","../src/context/belief-memory-helpers.ts","../src/context/belief-memory-recall.ts","../src/context/belief-memory-audit.ts","../src/context/belief-memory-reflect.ts","../src/context/belief-memory.ts","../src/context/belief-cleanup.ts","../src/context/memory-backend.ts","../src/context/memory-markdown.ts","../src/context/memory-operations.ts","../src/context/graph-memory-types.ts","../src/utils/memory-db-utils.ts","../src/context/graph-memory-helpers.ts","../src/context/graph-memory.ts","../src/context/agentic-memory-types.ts","../src/context/agentic-memory-primitives.ts","../src/context/agentic-memory-extraction.ts","../src/context/agentic-memory-linking.ts","../src/context/agentic-memory-db-helpers.ts","../src/context/agentic-memory-operations.ts","../src/context/agentic-memory.ts","../src/context/adaptive-memory-types.ts","../src/utils/similarity-utils.ts","../src/context/adaptive-memory-helpers.ts","../src/context/adaptive-memory.ts","../src/context/belief-memory-persistence.ts","../src/context/belief-persistence-types.ts","../src/context/memory-types.ts","../src/context/memory-module-types.ts","../src/context/typed-memory-impl.ts","../src/context/typed-memory.ts","../src/mcp/tools/tool-memory-registry-adapters.ts","../src/mcp/tools/memory-promotion.ts","../src/mcp/tools/memory-decay.ts","../src/mcp/tools/tool-memory-query.ts"],"sourcesContent":["/* eslint-disable max-lines -- Cohesive memory facade composing 6 backends (governance: 400-600 lines OK if cohesive) */\n/**\n * nexus-agents/mcp - Tool Memory Integration\n *\n * Unified memory facade for MCP tools. Composes SessionMemory (episodic),\n * BeliefMemory (structured knowledge), and optionally AgenticMemory\n * (Zettelkasten-style), AdaptiveMemory (priority-scored), TypedMemory\n * (MIRIX-style typed access), and MobiMem (post-deployment learning)\n * when SQLite is available. Graceful degradation when backends are absent.\n *\n * @module mcp/tools/tool-memory\n * (Source: Issue #690, #714, #746 - Unified memory facade)\n */\n\nimport * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport { nexusDataPath } from '../../config/nexus-data-dir.js';\nimport type { ILogger } from '../../core/index.js';\nimport { getErrorMessage, createLogger, getTimeProvider } from '../../core/index.js';\n\nimport { SessionMemory } from '../../context/session-memory.js';\nimport type {\n SessionLearning,\n CompletedTask,\n ResolvedError,\n} from '../../context/session-memory-types.js';\nimport { HindsightBeliefMemory } from '../../context/belief-memory.js';\nimport { BeliefConfidence, BeliefSourceType } from '../../context/belief-core-types.js';\nimport type { Belief } from '../../context/belief-core-types.js';\nimport { runBeliefCleanup } from '../../context/belief-cleanup.js';\nimport { AgenticMemoryBackend } from '../../context/agentic-memory.js';\nimport { AdaptiveMemoryBackend } from '../../context/adaptive-memory.js';\nimport type { MemoryMetadata, MemoryImportance } from '../../context/memory-backend-types.js';\nimport { saveBeliefSnapshot, loadBeliefSnapshot } from '../../context/belief-memory-persistence.js';\nimport { HybridMemoryBackend } from '../../context/memory-backend.js';\nimport { createTypedMemory } from '../../context/typed-memory.js';\nimport type {\n ITypedMemory,\n TypedMemoryEntry,\n TypedMemoryStats,\n TypedMemoryPruneResult,\n MemoryType,\n} from '../../context/memory-types.js';\nimport type { AgentRole } from '../../core/types/agent.js';\nimport { getMemoryRegistry } from 'nexus-memory';\nimport {\n MobiMem,\n getSharedMobiMem,\n setSharedMobiMemDbPathResolver,\n} from '../../context/mobimem.js';\nimport { StatsOnlyAdapter } from './tool-memory-registry-adapters.js';\nimport type { MobiMemStats } from '../../context/mobimem-types.js';\nimport {\n MemoryPromoter,\n type PromotionStats,\n type MemoryPromotionConfig,\n} from './memory-promotion.js';\nimport {\n MemoryDecayManager,\n type DecayRunStats,\n type DecayAggregateStats,\n} from './memory-decay.js';\nimport type { UnifiedMemoryResult } from './tool-memory-types.js';\nimport {\n querySessionMemory as querySessionMemoryHelper,\n queryBeliefMemory as queryBeliefMemoryHelper,\n queryAgenticMemory as queryAgenticMemoryHelper,\n queryTypedMemory as queryTypedMemoryHelper,\n queryAdaptiveMemory as queryAdaptiveMemoryHelper,\n} from './tool-memory-query.js';\n\n// Re-export types tools may need\nexport type { SessionLearning, CompletedTask, ResolvedError, Belief };\n\n// UnifiedMemoryResult extracted to tool-memory-types.ts to avoid circular imports (#1671)\nexport type { UnifiedMemoryResult } from './tool-memory-types.js';\nexport type {\n TypedMemoryEntry,\n TypedMemoryStats,\n TypedMemoryPruneResult,\n MemoryType,\n} from '../../context/memory-types.js';\nexport type { AgentRole } from '../../core/types/agent.js';\nexport type { MobiMemStats } from '../../context/mobimem-types.js';\nexport type { PromotionStats, MemoryPromotionConfig } from './memory-promotion.js';\n\n/**\n * Status of memory backend availability (#754).\n */\nexport interface MemoryBackendStatus {\n session: boolean;\n belief: boolean;\n agentic: boolean;\n adaptive: boolean;\n typed: boolean;\n mobimem: boolean;\n decay: boolean;\n}\nexport type { DecayRunStats, DecayAggregateStats } from './memory-decay.js';\n\n// ============================================================================\n// Constants\n// ============================================================================\n\n/** Default memory directory under the resolved nexus data dir (#2302). */\nconst MEMORY_BASE = nexusDataPath('memory');\nconst DEFAULT_MEMORY_DIR = path.join(MEMORY_BASE, 'sessions');\nconst AGENTIC_DB_PATH = path.join(MEMORY_BASE, 'agentic.db');\nconst ADAPTIVE_DB_PATH = path.join(MEMORY_BASE, 'adaptive.db');\nconst TYPED_DB_PATH = path.join(MEMORY_BASE, 'typed.db');\nconst MOBIMEM_DB_PATH = path.join(MEMORY_BASE, 'mobimem.db');\nconst MARKDOWN_DIR = path.join(MEMORY_BASE, 'markdown');\n\n// ============================================================================\n// Shared Instance (Singleton per process)\n// ============================================================================\n\nlet sharedInstance: ToolMemoryManager | null = null;\n\n/**\n * Phase 5 of #2766. Attach a tool-memory backend to the unified registry\n * so `memory_stats` and future telemetry consumers can discover it\n * without the per-backend type-knowledge that `tool-memory.ts` carries\n * today. Safe to call multiple times — the registry rejects duplicate\n * domains, and that's silently caught so re-init doesn't break.\n */\nfunction attachToRegistry(\n domain: string,\n backend: {\n count(): unknown;\n search?(query: string, limit: number): Promise<readonly unknown[]>;\n }\n): void {\n try {\n getMemoryRegistry().attach(domain, new StatsOnlyAdapter(domain, backend));\n } catch {\n // Domain already registered — re-init of tool-memory should be a no-op.\n }\n}\n\n/**\n * Get or create the shared ToolMemoryManager singleton.\n * Automatically starts a session on first access.\n */\nexport function getToolMemory(logger?: ILogger): ToolMemoryManager {\n sharedInstance ??= new ToolMemoryManager(logger);\n return sharedInstance;\n}\n\n/**\n * Shut down the shared memory instance. Call during server cleanup.\n */\nexport function shutdownToolMemory(): void {\n if (sharedInstance !== null) {\n sharedInstance.endSession();\n sharedInstance = null;\n }\n}\n\n/**\n * Reinitialize SQLite-based memory backends that failed during startup.\n * Useful after installing better-sqlite3 to enable full memory functionality.\n * @returns Status of each backend after reinitialization\n */\nexport async function reinitializeMemoryBackends(): Promise<MemoryBackendStatus> {\n return getToolMemory().reinitializeSqliteBackends();\n}\n\n// ============================================================================\n// ToolMemoryManager\n// ============================================================================\n\n/**\n * Manages session memory for MCP tool execution.\n * Auto-initializes a session and provides safe recording methods\n * that silently degrade if memory is unavailable.\n */\nexport class ToolMemoryManager {\n private readonly memory: SessionMemory;\n private readonly beliefs: HindsightBeliefMemory;\n private readonly log: ILogger;\n private pastLearnings: readonly SessionLearning[] = [];\n private agentic: AgenticMemoryBackend | null = null;\n private adaptive: AdaptiveMemoryBackend | null = null;\n private typed: ITypedMemory | null = null;\n private typedBackend: HybridMemoryBackend | null = null;\n private mobimem: MobiMem | null = null;\n private decayManager: MemoryDecayManager | null = null;\n private initPromise: Promise<void> | null = null;\n\n constructor(logger?: ILogger) {\n this.log = logger ?? createLogger({ component: 'ToolMemory' });\n\n this.memory = new SessionMemory({\n memoryDir: DEFAULT_MEMORY_DIR,\n logger: this.log,\n });\n this.beliefs = new HindsightBeliefMemory(undefined, this.log);\n this.loadBeliefSnapshotFromDisk();\n const beliefs = this.beliefs;\n attachToRegistry('belief', {\n count: async () => {\n const stats = await beliefs.getStats();\n return stats.ok ? stats.value.totalBeliefs : 0;\n },\n // Phase 1 of #2792 — text search delegates to recallBySubject.\n search: async (query, limit) => {\n const res = await beliefs.recallBySubject(query, limit);\n return res.ok ? res.value : [];\n },\n });\n // Phase 9 of #2766: drop belief rows polluted by the pre-#2755\n // arXiv feed-fallback bug. Marker-file gated so subsequent runs\n // no-op. Best-effort — never block startup on cleanup errors.\n void this.runBeliefCleanupOnce(beliefs);\n\n // Auto-start session\n const sessionId = `mcp-${String(getTimeProvider().now())}`;\n const result = this.memory.startSession(sessionId);\n if (result.ok) {\n this.pastLearnings = result.value;\n this.log.info('Tool memory session started', {\n sessionId,\n pastLearnings: this.pastLearnings.length,\n });\n } else {\n this.log.warn('Tool memory session start failed', {\n error: result.error.message,\n });\n }\n\n // Phase 2: activate SQLite backends (best-effort, non-blocking)\n this.initPromise = this.initSqliteBackends();\n }\n\n /** Try to activate SQLite backends (best-effort, non-blocking). */\n private async initSqliteBackends(): Promise<void> {\n fs.mkdirSync(MARKDOWN_DIR, { recursive: true });\n await this.initAgenticMemory();\n await this.initAdaptiveMemory();\n await this.initTypedMemory();\n this.initMobiMem();\n this.initDecayManager();\n }\n\n /**\n * Phase 9 of #2766: idempotent one-shot cleanup of belief rows polluted\n * by the pre-#2755 arXiv feed-fallback bug. Marker-file gated. Best-effort\n * — failures don't block startup.\n */\n private async runBeliefCleanupOnce(beliefs: HindsightBeliefMemory): Promise<void> {\n try {\n const result = await runBeliefCleanup({\n loadBeliefs: async () => {\n const q = await beliefs.query({ includeSuperseded: true });\n return q.ok ? q.value : [];\n },\n deleteBelief: async (id: string) => {\n await beliefs.forget(id);\n },\n });\n if (!result.skipped && result.removed > 0) {\n this.log.info('Belief cleanup removed polluted rows', {\n scanned: result.scanned,\n removed: result.removed,\n samples: result.samples,\n });\n }\n } catch (error: unknown) {\n this.log.debug('Belief cleanup failed', { error: getErrorMessage(error) });\n }\n }\n\n /** Initialize AgenticMemory (Phase 2). */\n private async initAgenticMemory(): Promise<void> {\n try {\n const backend = new AgenticMemoryBackend({\n dbPath: AGENTIC_DB_PATH,\n markdownDir: MARKDOWN_DIR,\n });\n const result = await backend.initialize();\n if (result.ok) {\n this.agentic = backend;\n attachToRegistry('agentic', {\n count: async () => {\n const res = await backend.count();\n return res.ok ? res.value : 0;\n },\n // Phase 1 of #2792 — A-MEM text search returns attribute-rich entries.\n search: async (query, limit) => {\n const res = await backend.searchAgentic(query, limit);\n return res.ok ? res.value : [];\n },\n });\n this.log.info('AgenticMemory activated (Phase 2)');\n } else {\n this.log.info('AgenticMemory unavailable', { reason: result.error.message });\n }\n } catch (error: unknown) {\n this.log.debug('AgenticMemory init failed', {\n error: getErrorMessage(error),\n });\n }\n }\n\n /** Initialize AdaptiveMemory (Phase 2). */\n private async initAdaptiveMemory(): Promise<void> {\n try {\n const backend = new AdaptiveMemoryBackend({\n dbPath: ADAPTIVE_DB_PATH,\n markdownDir: MARKDOWN_DIR,\n });\n const result = await backend.initialize();\n if (result.ok) {\n this.adaptive = backend;\n attachToRegistry('adaptive', {\n count: async () => {\n const res = await backend.count();\n return res.ok ? res.value : 0;\n },\n // Phase 1 of #2792 — adaptive memory returns priority-scored entries.\n search: async (query, limit) => {\n const res = await backend.retrieveByPriority({ query, limit });\n return res.ok ? res.value : [];\n },\n });\n this.log.info('AdaptiveMemory activated (Phase 2)');\n } else {\n this.log.info('AdaptiveMemory unavailable', { reason: result.error.message });\n }\n } catch (error: unknown) {\n this.log.debug('AdaptiveMemory init failed', {\n error: getErrorMessage(error),\n });\n }\n }\n\n /** Initialize TypedMemory (Phase 1 #746 - MIRIX-style typed access). */\n private async initTypedMemory(): Promise<void> {\n try {\n const backend = new HybridMemoryBackend({\n dbPath: TYPED_DB_PATH,\n markdownDir: MARKDOWN_DIR,\n logger: this.log,\n });\n const result = await backend.initialize();\n if (result.ok) {\n this.typedBackend = backend;\n this.typed = createTypedMemory(backend);\n attachToRegistry('typed', {\n count: async () => {\n const res = await backend.count();\n return res.ok ? res.value : 0;\n },\n // Phase 1 of #2792 — typed search uses the underlying hybrid backend.\n search: async (query, limit) => {\n const res = await backend.search(query, limit);\n return res.ok ? res.value : [];\n },\n });\n this.log.info('TypedMemory activated (Phase 1 #746)');\n } else {\n this.log.info('TypedMemory unavailable', { reason: result.error.message });\n }\n } catch (error: unknown) {\n this.log.debug('TypedMemory init failed', {\n error: getErrorMessage(error),\n });\n }\n }\n\n /** Initialize MobiMem (Phase 2 #746 - post-deployment learning).\n * #2719: routes through the process-wide singleton so this tool-memory\n * instance, RoutingMemory, and any other caller share state. The\n * shared singleton uses the same MOBIMEM_DB_PATH this tool used to\n * pass directly. */\n private initMobiMem(): void {\n try {\n setSharedMobiMemDbPathResolver(() => MOBIMEM_DB_PATH);\n this.mobimem = getSharedMobiMem();\n const mobimem = this.mobimem;\n attachToRegistry('mobimem', {\n count: () => mobimem.profile.getEntryCount(),\n // Phase 1 of #2792 — MobiMem exposes patterns by task type. Text\n // query is interpreted as the task type (best-effort; consumers\n // can pre-normalize).\n search: (query, limit) => Promise.resolve(mobimem.experience.findPatterns(query, limit)),\n });\n this.log.info('MobiMem activated (Phase 2 #746)');\n } catch (error: unknown) {\n this.log.debug('MobiMem init failed', {\n error: getErrorMessage(error),\n });\n }\n }\n\n /** Initialize coordinated decay manager (Phase 5 #746). */\n private initDecayManager(): void {\n try {\n this.decayManager = new MemoryDecayManager({}, this.log);\n this.decayManager.initialize({\n beliefs: this.beliefs,\n agentic: this.agentic,\n adaptive: this.adaptive,\n mobimem: this.mobimem,\n });\n // Start auto-decay for long-running sessions\n this.decayManager.startAutoDecay();\n // Run decay once at startup — the setInterval timer may never fire\n // in short-lived MCP sessions, so this ensures at least one run (#1673).\n void this.decayManager.runDecay().catch((error: unknown) => {\n this.log.debug('Startup decay run failed', {\n error: getErrorMessage(error),\n });\n });\n this.log.info('MemoryDecayManager activated (Phase 5 #746)');\n } catch (error: unknown) {\n this.log.debug('MemoryDecayManager init failed', {\n error: getErrorMessage(error),\n });\n }\n }\n\n /**\n * Re-initialize SQLite backends that failed during startup.\n * Skips already-initialized backends. Useful after installing better-sqlite3.\n * @returns Status of each backend after reinitialization attempt\n */\n async reinitializeSqliteBackends(): Promise<MemoryBackendStatus> {\n this.log.info('Reinitializing SQLite backends');\n // Wait for any in-flight initialization to complete first (#794)\n if (this.initPromise !== null) {\n await this.initPromise;\n this.initPromise = null;\n }\n if (this.agentic === null) await this.initAgenticMemory();\n if (this.adaptive === null) await this.initAdaptiveMemory();\n if (this.typed === null) await this.initTypedMemory();\n if (this.mobimem === null) this.initMobiMem();\n if (this.decayManager === null) this.initDecayManager();\n return this.getBackendStatus();\n }\n\n /** Get current backend availability status. */\n getBackendStatus(): MemoryBackendStatus {\n return {\n session: true,\n belief: true,\n agentic: this.agentic !== null,\n adaptive: this.adaptive !== null,\n typed: this.typed !== null,\n mobimem: this.mobimem !== null,\n decay: this.decayManager !== null,\n };\n }\n\n /**\n * Get learnings from previous sessions.\n */\n getPastLearnings(): readonly SessionLearning[] {\n return this.pastLearnings;\n }\n\n /**\n * Record a completed task. Safe to call even if session inactive.\n */\n recordTask(task: CompletedTask): void {\n if (!this.memory.isSessionActive()) return;\n\n const result = this.memory.recordTask(task);\n if (!result.ok) {\n this.log.debug('Failed to record task', { error: result.error.message });\n }\n }\n\n /**\n * Record a learning. Safe to call even if session inactive.\n * High-confidence learnings are also stored as beliefs for structured retrieval.\n */\n recordLearning(learning: SessionLearning): void {\n if (!this.memory.isSessionActive()) return;\n\n const result = this.memory.recordLearning(learning);\n if (!result.ok) {\n this.log.debug('Failed to record learning', { error: result.error.message });\n }\n\n // Auto-create belief for high-confidence learnings (cross-backend sync)\n if (learning.confidence >= 0.8) {\n void this.retainBeliefFromLearning(learning);\n }\n }\n\n /**\n * Record a structured belief (subject-predicate-object triple).\n * Safe to call at any time; failures are logged but not thrown.\n */\n async recordBelief(\n subject: string,\n predicate: string,\n object: string,\n confidence: 'high' | 'medium' | 'low' = 'medium'\n ): Promise<void> {\n try {\n await this.beliefs.retain({\n subject,\n predicate,\n object,\n confidence,\n sourceType: BeliefSourceType.OBSERVATION,\n sourceRef: 'mcp-tool-execution',\n });\n } catch (error) {\n this.log.debug('Failed to record belief', { subject, error });\n }\n }\n\n /**\n * Query beliefs relevant to a subject. Returns formatted string or undefined.\n */\n async getRelevantBeliefs(subject: string, limit = 5): Promise<string | undefined> {\n try {\n const result = await this.beliefs.recallBySubject(subject, limit);\n if (!result.ok || result.value.length === 0) return undefined;\n const active = result.value.filter((b) => !b.superseded);\n if (active.length === 0) return undefined;\n return active\n .map((b) => `- [${b.confidence}] ${b.subject} ${b.predicate} ${b.object}`)\n .join('\\n');\n } catch (e: unknown) {\n this.log.debug('Belief recall failed', { error: String(e) });\n return undefined;\n }\n }\n\n /**\n * Record a resolved error. Safe to call even if session inactive.\n */\n recordError(error: ResolvedError): void {\n if (!this.memory.isSessionActive()) return;\n\n const result = this.memory.recordError(error);\n if (!result.ok) {\n this.log.debug('Failed to record error', { error: result.error.message });\n }\n }\n\n /**\n * Search past learnings for relevant patterns.\n */\n searchLearnings(query: string): readonly SessionLearning[] {\n return this.memory.searchLearnings(query);\n }\n\n /**\n * Get recent error solutions.\n */\n getRecentErrorSolutions(limit?: number): readonly ResolvedError[] {\n return this.memory.getRecentErrorSolutions(limit);\n }\n\n /**\n * Retrieve past learnings relevant to a task description.\n * Searches by keywords, falls back to highest-confidence learnings.\n * Returns formatted string or undefined if none found.\n */\n getRelevantLearnings(taskDescription: string, maxResults = 5): string | undefined {\n const past = this.pastLearnings;\n if (past.length === 0) return undefined;\n\n const keywords = taskDescription.split(/\\s+/).slice(0, 5).join(' ');\n const searched = this.searchLearnings(keywords).slice(0, maxResults);\n const learnings =\n searched.length > 0\n ? searched\n : [...past].sort((a, b) => b.confidence - a.confidence).slice(0, 3);\n\n if (learnings.length === 0) return undefined;\n return learnings\n .map((l) => `- [${String(l.confidence)}] ${l.pattern} (${l.context})`)\n .join('\\n');\n }\n\n /**\n * Retrieve past error solutions relevant to a given role or context.\n * Returns formatted string or undefined if none found.\n */\n getRelevantErrorHints(role: string, maxResults = 3): string | undefined {\n const errors = this.getRecentErrorSolutions(10);\n if (errors.length === 0) return undefined;\n\n const relevant = errors.filter(\n (e) => e.filePattern?.includes('execute-expert') === true || e.error.includes(role)\n );\n if (relevant.length === 0) return undefined;\n\n return relevant\n .slice(0, maxResults)\n .map((e) => `- Error: ${e.error.slice(0, 80)} → ${e.solution.slice(0, 80)}`)\n .join('\\n');\n }\n\n /** Whether SQLite-backed memory backends are available (Phase 2). */\n isAdvancedMemoryAvailable(): boolean {\n return this.agentic !== null || this.adaptive !== null;\n }\n\n /** Whether AgenticMemory backend is available. */\n isAgenticMemoryAvailable(): boolean {\n return this.agentic !== null;\n }\n\n /** Whether AdaptiveMemory backend is available. */\n isAdaptiveMemoryAvailable(): boolean {\n return this.adaptive !== null;\n }\n\n /** Store knowledge with auto-extracted attributes (AgenticMemory). Best-effort. */\n async recordKnowledge(key: string, value: unknown, metadata: MemoryMetadata): Promise<void> {\n if (this.agentic === null) return;\n try {\n const result = await this.agentic.storeWithAttributes(key, value, metadata);\n if (!result.ok) {\n this.log.debug('Failed to record knowledge', { key, error: result.error.message });\n }\n } catch (error: unknown) {\n this.log.debug('Knowledge recording failed', {\n key,\n error: getErrorMessage(error),\n });\n }\n }\n\n /** Store a value in AdaptiveMemory with importance scoring. Best-effort. */\n async storeAdaptive(key: string, value: unknown, importance: number): Promise<void> {\n if (this.adaptive === null) return;\n try {\n const level = importance >= 0.8 ? 'high' : importance >= 0.6 ? 'medium' : 'low';\n const result = await this.adaptive.store(key, value, {\n importance: level,\n tags: ['memory_write_tool'],\n });\n if (!result.ok) {\n this.log.debug('Failed to store adaptive memory', { key, error: result.error.message });\n }\n } catch (error: unknown) {\n this.log.debug('Adaptive memory store failed', {\n key,\n error: getErrorMessage(error),\n });\n }\n }\n\n /** Store a value in TypedMemory (via HybridMemoryBackend). Best-effort. */\n async storeTyped(key: string, value: unknown, importance: MemoryImportance): Promise<void> {\n if (this.typedBackend === null) return;\n try {\n const result = await this.typedBackend.store(`semantic ${key}`, value, {\n importance,\n tags: ['memory_write_tool', 'semantic'],\n });\n if (!result.ok) {\n this.log.debug('Failed to store typed memory', { key, error: result.error.message });\n }\n } catch (error: unknown) {\n this.log.debug('Typed memory store failed', {\n key,\n error: getErrorMessage(error),\n });\n }\n }\n\n /** Query knowledge with attribute-based search (AgenticMemory). Best-effort. */\n async queryKnowledge(query: string, limit = 5): Promise<string | undefined> {\n if (this.agentic === null) return undefined;\n try {\n const result = await this.agentic.searchAgentic(query, limit);\n if (!result.ok || result.value.length === 0) return undefined;\n return result.value.map((e) => `- [${e.attributes.keywords.join(',')}] ${e.key}`).join('\\n');\n } catch (e: unknown) {\n this.log.debug('Agentic knowledge query failed', { error: String(e) });\n return undefined;\n }\n }\n\n // ==========================================================================\n // TypedMemory (Phase 1 #746 - MIRIX-style typed memory access)\n // ==========================================================================\n\n /** Whether TypedMemory is available (requires SQLite). */\n isTypedMemoryAvailable(): boolean {\n return this.typed !== null;\n }\n\n /**\n * Query memories by type (core, episodic, semantic, procedural, resource, vault, belief).\n * Returns formatted results or undefined if TypedMemory unavailable.\n */\n async queryByMemoryType(\n type: MemoryType,\n query: string,\n limit = 10\n ): Promise<readonly TypedMemoryEntry[] | undefined> {\n if (this.typed === null) return undefined;\n try {\n const result = await this.typed.queryByType(type, query, limit);\n if (!result.ok) {\n this.log.debug('TypedMemory query failed', { type, error: result.error.message });\n return undefined;\n }\n return result.value;\n } catch (e: unknown) {\n this.log.debug('TypedMemory queryByType failed', { type, error: String(e) });\n return undefined;\n }\n }\n\n /**\n * Filter memories by relevance to an agent role.\n * Uses MIRIX role-memory type mappings (e.g., tech_lead gets core, episodic, vault, belief).\n * Returns filtered entries or undefined if TypedMemory unavailable.\n */\n async filterMemoriesForRole(\n role: AgentRole,\n limit = 50\n ): Promise<readonly TypedMemoryEntry[] | undefined> {\n if (this.typed === null) return undefined;\n try {\n const result = await this.typed.filterByRelevance(role, limit);\n if (!result.ok) {\n this.log.debug('TypedMemory filter failed', { role, error: result.error.message });\n return undefined;\n }\n return result.value;\n } catch (e: unknown) {\n this.log.debug('TypedMemory filterByRelevance failed', { role, error: String(e) });\n return undefined;\n }\n }\n\n /**\n * Get statistics across all typed memory categories.\n * Returns stats object with counts per type or undefined if unavailable.\n */\n async getTypedMemoryStats(): Promise<TypedMemoryStats | undefined> {\n if (this.typed === null) return undefined;\n try {\n const result = await this.typed.getStats();\n if (!result.ok) return undefined;\n return result.value;\n } catch (e: unknown) {\n this.log.debug('TypedMemory getStats failed', { error: String(e) });\n return undefined;\n }\n }\n\n /**\n * Prune expired entries from TypedMemory.\n * Returns prune result with counts per type or undefined if unavailable.\n */\n async pruneTypedMemory(): Promise<TypedMemoryPruneResult | undefined> {\n if (this.typed === null) return undefined;\n try {\n const result = await this.typed.pruneExpired();\n if (!result.ok) return undefined;\n return result.value;\n } catch (e: unknown) {\n this.log.debug('TypedMemory pruneExpired failed', { error: String(e) });\n return undefined;\n }\n }\n\n // ==========================================================================\n // MobiMem (Phase 2 #746 - Post-deployment learning)\n // ==========================================================================\n\n /** Whether MobiMem is available for post-deployment learning. */\n isMobiMemAvailable(): boolean {\n return this.mobimem !== null;\n }\n\n /**\n * Get the MobiMem instance for direct access to profile, experience, and action cache.\n * Returns null if MobiMem is unavailable.\n */\n getMobiMem(): MobiMem | null {\n return this.mobimem;\n }\n\n /**\n * Get MobiMem statistics across all three modules.\n * Returns stats object or undefined if unavailable.\n */\n getMobiMemStats(): MobiMemStats | undefined {\n if (this.mobimem === null) return undefined;\n return this.mobimem.getStats();\n }\n\n /** Returns the count of beliefs in the belief memory backend. */\n getBeliefCount(): number {\n const data = this.beliefs.exportData();\n return data.beliefs.size;\n }\n\n /**\n * Get the shared {@link HindsightBeliefMemory} singleton.\n *\n * Public accessor used by {@link getContextForTask} (Phase 2 of #2792)\n * so cross-cutting consumers can perform typed reads without\n * reconstructing a backend or routing through MCP tools.\n */\n getBeliefMemory(): HindsightBeliefMemory {\n return this.beliefs;\n }\n\n /**\n * Get the shared {@link AgenticMemoryBackend} singleton, or `null` if\n * SQLite init failed and the backend is unavailable. Public accessor\n * used by {@link getContextForTask} (Phase 2 of #2792).\n */\n getAgenticMemoryBackend(): AgenticMemoryBackend | null {\n return this.agentic;\n }\n\n /**\n * Get the shared {@link AdaptiveMemoryBackend} singleton, or `null` if\n * SQLite init failed and the backend is unavailable. Public accessor\n * used by {@link getContextForTask} (Phase 2 of #2792).\n */\n getAdaptiveMemoryBackend(): AdaptiveMemoryBackend | null {\n return this.adaptive;\n }\n\n /**\n * Run MobiMem maintenance (eviction and cleanup).\n * Safe to call even if MobiMem is unavailable.\n */\n runMobiMemMaintenance(): void {\n if (this.mobimem === null) return;\n this.mobimem.runMaintenance();\n }\n\n // ==========================================================================\n // Cross-Memory Query (Phase 3 #746 - Unified search across all backends)\n // ==========================================================================\n\n /**\n * Unified search across all active memory systems.\n * Returns results from SessionMemory, BeliefMemory, AgenticMemory, and TypedMemory\n * with source attribution and relevance scoring.\n */\n async queryAll(query: string, limit = 10): Promise<readonly UnifiedMemoryResult[]> {\n // Wait for SQLite backends to finish initializing before querying (#794 pattern)\n if (this.initPromise !== null) {\n await this.initPromise;\n this.initPromise = null;\n }\n const keywords = query\n .toLowerCase()\n .split(/\\s+/)\n .filter((k) => k.length > 2);\n const sourceCount = 4 + (this.adaptive !== null ? 1 : 0);\n const perSource = Math.ceil(limit / sourceCount);\n const results = [\n ...this.querySessionMemory(query, keywords, perSource),\n ...(await this.queryBeliefMemory(query, keywords, perSource)),\n ...(await this.queryAgenticMemory(query, keywords, perSource)),\n ...(await this.queryTypedMemory(query, keywords, Math.ceil(perSource / 2))),\n ...(await this.queryAdaptiveMemory(query, keywords, perSource)),\n ];\n return results.sort((a, b) => b.relevance - a.relevance).slice(0, limit);\n }\n\n /**\n * Query a specific memory backend directly, bypassing cross-backend limit dilution.\n * When source is 'all', delegates to queryAll(). Otherwise dispatches to the\n * single-backend method so the full limit is applied to that backend only.\n */\n async queryBySource(\n source: 'session' | 'belief' | 'agentic' | 'typed' | 'adaptive' | 'all',\n query: string,\n limit = 10\n ): Promise<readonly UnifiedMemoryResult[]> {\n if (source === 'all') {\n return this.queryAll(query, limit);\n }\n // Wait for SQLite backends to finish initializing\n if (this.initPromise !== null) {\n await this.initPromise;\n this.initPromise = null;\n }\n const keywords = query\n .toLowerCase()\n .split(/\\s+/)\n .filter((k) => k.length > 2);\n let results: UnifiedMemoryResult[];\n switch (source) {\n case 'session':\n results = this.querySessionMemory(query, keywords, limit);\n break;\n case 'belief':\n results = await this.queryBeliefMemory(query, keywords, limit);\n break;\n case 'agentic':\n results = await this.queryAgenticMemory(query, keywords, limit);\n break;\n case 'typed':\n results = await this.queryTypedMemory(query, keywords, limit);\n break;\n case 'adaptive':\n results = await this.queryAdaptiveMemory(query, keywords, limit);\n break;\n }\n return results.sort((a, b) => b.relevance - a.relevance).slice(0, limit);\n }\n\n /** Query SessionMemory for learnings. */\n // Per-backend query helpers delegated to tool-memory-query.ts (#1671).\n\n private querySessionMemory(\n query: string,\n keywords: readonly string[],\n limit: number\n ): UnifiedMemoryResult[] {\n return querySessionMemoryHelper(this.searchLearnings(query), keywords, limit);\n }\n\n private async queryBeliefMemory(\n query: string,\n keywords: readonly string[],\n limit: number\n ): Promise<UnifiedMemoryResult[]> {\n return queryBeliefMemoryHelper(this.beliefs, query, keywords, limit, this.log);\n }\n\n private async queryAgenticMemory(\n query: string,\n keywords: readonly string[],\n limit: number\n ): Promise<UnifiedMemoryResult[]> {\n if (this.agentic === null) return [];\n\n return queryAgenticMemoryHelper(this.agentic, query, keywords, limit, this.log);\n }\n\n private async queryTypedMemory(\n query: string,\n keywords: readonly string[],\n limitPerType: number\n ): Promise<UnifiedMemoryResult[]> {\n if (this.typed === null) return [];\n\n return queryTypedMemoryHelper(this.typed, query, keywords, limitPerType, this.log);\n }\n\n private async queryAdaptiveMemory(\n query: string,\n keywords: readonly string[],\n limit: number\n ): Promise<UnifiedMemoryResult[]> {\n if (this.adaptive === null) return [];\n\n return queryAdaptiveMemoryHelper(this.adaptive, query, keywords, limit, this.log);\n }\n\n // ==========================================================================\n // Memory Promotion Pipeline (Phase 4 #746)\n // ==========================================================================\n\n /**\n * Run the memory promotion pipeline.\n * Promotes high-confidence learnings to beliefs, and stable beliefs to AgenticMemory.\n * Returns statistics about the promotion run.\n */\n async runPromotionPipeline(config?: Partial<MemoryPromotionConfig>): Promise<PromotionStats> {\n const promoter = new MemoryPromoter(this.beliefs, this.agentic, config, this.log);\n\n // Get current learnings and beliefs for promotion evaluation\n const learnings = this.pastLearnings;\n const beliefData = this.beliefs.exportData();\n const beliefs = Array.from(beliefData.beliefs.values());\n\n const stats = await promoter.runPromotionPipeline(learnings, beliefs);\n\n this.log.info('Promotion pipeline completed', {\n learningsPromoted: stats.learningsPromotedToBelief,\n beliefsPromoted: stats.beliefsPromotedToAgentic,\n });\n\n return stats;\n }\n\n // ==========================================================================\n // Coordinated Decay (Phase 5 #746)\n // ==========================================================================\n\n /** Whether coordinated decay is available. */\n isDecayManagerAvailable(): boolean {\n return this.decayManager !== null;\n }\n\n /**\n * Run coordinated decay across all memory systems.\n * Implements FADE (Forgetting with Adaptive Decay) principles.\n * Returns statistics about the decay run.\n */\n async runDecay(): Promise<DecayRunStats | undefined> {\n if (this.decayManager === null) return undefined;\n return this.decayManager.runDecay();\n }\n\n /**\n * Get aggregate statistics across all decay runs.\n */\n getDecayStats(): DecayAggregateStats | undefined {\n if (this.decayManager === null) return undefined;\n return this.decayManager.getAggregateStats();\n }\n\n /**\n * Get the last N decay run results.\n */\n getRecentDecayRuns(limit = 10): readonly DecayRunStats[] {\n if (this.decayManager === null) return [];\n return this.decayManager.getRecentRuns(limit);\n }\n\n /**\n * Register a cross-reference between memory systems.\n * Used to prevent orphaned references during decay.\n */\n registerCrossReference(\n sourceMemory: 'session' | 'belief' | 'agentic' | 'adaptive' | 'mobimem',\n sourceKey: string,\n targetMemory: 'session' | 'belief' | 'agentic' | 'adaptive' | 'mobimem',\n targetKey: string\n ): void {\n if (this.decayManager === null) return;\n this.decayManager.registerCrossReference(sourceMemory, sourceKey, targetMemory, targetKey);\n }\n\n /** End the current session and persist to disk. Closes SQLite backends. */\n endSession(): void {\n // Persist belief memory to disk (Phase 3, Issue #714)\n this.saveBeliefSnapshotToDisk();\n\n if (this.memory.isSessionActive()) {\n const result = this.memory.endSession('MCP session ended');\n if (result.ok) {\n this.log.info('Tool memory session saved', {\n learnings: result.value.learnings.length,\n tasks: result.value.tasksCompleted.length,\n errors: result.value.errorsResolved.length,\n });\n }\n }\n if (this.agentic !== null) {\n this.agentic.close();\n this.agentic = null;\n }\n if (this.adaptive !== null) {\n this.adaptive.close();\n this.adaptive = null;\n }\n // TypedMemory uses HybridMemoryBackend which needs explicit close\n if (this.typedBackend !== null) {\n this.typedBackend.close();\n this.typedBackend = null;\n }\n this.typed = null;\n // MobiMem has its own close method\n if (this.mobimem !== null) {\n this.mobimem.close();\n this.mobimem = null;\n }\n // Shutdown decay manager (Phase 5 #746)\n if (this.decayManager !== null) {\n this.decayManager.shutdown();\n this.decayManager = null;\n }\n }\n\n /** Convert a high-confidence learning into a structured belief. */\n private async retainBeliefFromLearning(learning: SessionLearning): Promise<void> {\n try {\n const confidence =\n learning.confidence >= 0.9 ? BeliefConfidence.HIGH : BeliefConfidence.MEDIUM;\n await this.beliefs.retain({\n subject: learning.context,\n predicate: 'learned-pattern',\n object: learning.pattern,\n confidence,\n sourceType: BeliefSourceType.OBSERVATION,\n sourceRef: `session-learning`,\n });\n } catch (e: unknown) {\n this.log.debug('Belief creation from learning failed', { error: String(e) });\n }\n }\n\n /** Load belief snapshot from disk on startup (Phase 3, Issue #714). */\n private loadBeliefSnapshotFromDisk(): void {\n try {\n const result = loadBeliefSnapshot(this.log);\n if (!result.ok) {\n this.log.warn('Failed to load belief snapshot', { error: result.error.message });\n return;\n }\n if (result.value === null) return;\n this.beliefs.hydrate(result.value);\n } catch (error: unknown) {\n this.log.debug('Belief snapshot load failed', {\n error: getErrorMessage(error),\n });\n }\n }\n\n /** Save belief snapshot to disk on shutdown (Phase 3, Issue #714). */\n private saveBeliefSnapshotToDisk(): void {\n try {\n const data = this.beliefs.exportData();\n if (data.beliefs.size === 0) {\n this.log.debug('No beliefs to persist, skipping snapshot');\n return;\n }\n const result = saveBeliefSnapshot(data, this.log);\n if (!result.ok) {\n this.log.warn('Failed to save belief snapshot', { error: result.error.message });\n }\n } catch (error: unknown) {\n this.log.debug('Belief snapshot save failed', {\n error: getErrorMessage(error),\n });\n }\n }\n}\n","/**\n * nexus-agents/context - Hybrid Memory Backend Types\n *\n * Type definitions, interfaces, and schemas for the hybrid memory backend.\n *\n * @module context/memory-backend-types\n */\n\nimport { z } from 'zod';\nimport type { Result } from '../core/result.js';\nimport { NexusError, ErrorCode } from '../core/errors.js';\nimport type { ILogger } from '../core/logger.js';\nimport type { ISQLiteDatabase, ISQLiteStatement } from '../core/types/index.js';\n\n// Re-export for backward compatibility\nexport type { ISQLiteDatabase, ISQLiteStatement };\n\n// ============================================================================\n// Types and Interfaces\n// ============================================================================\n\n/**\n * Importance levels for memory entries.\n */\nexport const MemoryImportance = {\n LOW: 'low',\n MEDIUM: 'medium',\n HIGH: 'high',\n} as const;\n\nexport type MemoryImportance = (typeof MemoryImportance)[keyof typeof MemoryImportance];\n\n/**\n * Zod schema for MemoryImportance validation.\n */\nexport const MemoryImportanceSchema = z.enum(['low', 'medium', 'high']);\n\n/**\n * Metadata associated with a memory entry.\n */\nexport interface MemoryMetadata {\n /** Importance level determining storage strategy */\n importance: MemoryImportance;\n /** Optional tags for categorization */\n tags?: string[];\n /** Time-to-live in milliseconds (optional) */\n ttl?: number;\n}\n\n/**\n * Zod schema for MemoryMetadata validation.\n */\nexport const MemoryMetadataSchema = z.object({\n importance: MemoryImportanceSchema,\n tags: z.array(z.string()).optional(),\n ttl: z.number().positive().optional(),\n});\n\n/**\n * A complete memory entry with all fields.\n */\nexport interface MemoryEntry {\n /** Unique key for the memory */\n key: string;\n /** The stored value (JSON-serializable) */\n value: unknown;\n /** Associated metadata */\n metadata: MemoryMetadata;\n /** When the entry was created */\n createdAt: Date;\n /** When the entry was last accessed */\n accessedAt: Date;\n}\n\n/**\n * Zod schema for MemoryEntry validation.\n */\nexport const MemoryEntrySchema = z.object({\n key: z.string().min(1),\n value: z.unknown(),\n metadata: MemoryMetadataSchema,\n createdAt: z.date(),\n accessedAt: z.date(),\n});\n\n/**\n * Error class for memory operations.\n */\nexport class MemoryError extends NexusError {\n constructor(\n message: string,\n options?: Partial<\n Omit<{ code: ErrorCode; cause?: Error; context?: Record<string, unknown> }, 'code'>\n >\n ) {\n super(message, { code: ErrorCode.INTERNAL_ERROR, ...options });\n this.name = 'MemoryError';\n }\n}\n\n/**\n * Interface for memory backend implementations.\n */\nexport interface IMemoryBackend {\n /**\n * Store a value with associated metadata.\n * @param key - Unique key for the memory\n * @param value - The value to store (must be JSON-serializable)\n * @param metadata - Associated metadata\n */\n store(key: string, value: unknown, metadata: MemoryMetadata): Promise<Result<void, MemoryError>>;\n\n /**\n * Retrieve a value by key.\n * @param key - The key to look up\n * @returns The value or null if not found\n */\n retrieve(key: string): Promise<Result<unknown, MemoryError>>;\n\n /**\n * Search memories using full-text search.\n * @param query - Search query string\n * @param limit - Maximum number of results\n */\n search(query: string, limit: number): Promise<Result<MemoryEntry[], MemoryError>>;\n\n /**\n * Remove memories older than the specified date.\n * @param olderThan - Cutoff date for pruning\n * @returns Number of entries pruned\n */\n prune(olderThan: Date): Promise<Result<number, MemoryError>>;\n}\n\n// ============================================================================\n// Configuration\n// ============================================================================\n\n/**\n * Configuration for HybridMemoryBackend.\n */\nexport interface HybridMemoryConfig {\n /** Path to SQLite database file */\n dbPath: string;\n /** Directory for Markdown exports */\n markdownDir: string;\n /** Optional logger instance */\n logger?: ILogger;\n /** Whether to auto-expire TTL entries on access (default: true) */\n autoExpire?: boolean;\n}\n\n/**\n * Zod schema for HybridMemoryConfig validation.\n */\nexport const HybridMemoryConfigSchema = z.object({\n dbPath: z.string().min(1),\n markdownDir: z.string().min(1),\n autoExpire: z.boolean().optional(),\n});\n\n// ============================================================================\n// SQLite Types (for better-sqlite3)\n// ============================================================================\n\n/**\n * Row structure in the memories table.\n */\nexport interface MemoryRow {\n key: string;\n value: string;\n metadata: string;\n created_at: number;\n accessed_at: number;\n expires_at: number | null;\n}\n\n// ISQLiteDatabase and ISQLiteStatement imported from core/types/database-types.ts\n// and re-exported above for backward compatibility\n","/**\n * nexus-agents/context - Belief Core Types\n *\n * Core type definitions for belief states including confidence levels,\n * source types, and the fundamental Belief interface.\n *\n * @module context/belief-core-types\n * @see belief-types for re-exports\n * (Source: Issue #336, arXiv:2512.12818 - Hindsight Belief Memory)\n */\n\nimport { z } from 'zod';\n\n// ============================================================================\n// Belief Confidence Levels\n// ============================================================================\n\n/**\n * Confidence level for belief states.\n * Based on evidence quality and reasoning chain length.\n */\nexport const BeliefConfidence = {\n /** Strong evidence, short reasoning chain */\n HIGH: 'high',\n /** Moderate evidence or indirect inference */\n MEDIUM: 'medium',\n /** Weak evidence or long inference chain */\n LOW: 'low',\n /** Speculative or hypothetical */\n SPECULATIVE: 'speculative',\n} as const;\n\nexport type BeliefConfidence = (typeof BeliefConfidence)[keyof typeof BeliefConfidence];\n\nexport const BeliefConfidenceSchema = z.enum(['high', 'medium', 'low', 'speculative']);\n\n// ============================================================================\n// Belief Source Types\n// ============================================================================\n\n/**\n * Source type for belief origin tracking.\n */\nexport const BeliefSourceType = {\n /** Direct observation from environment */\n OBSERVATION: 'observation',\n /** Inference from other beliefs */\n INFERENCE: 'inference',\n /** External knowledge or provided fact */\n EXTERNAL: 'external',\n /** User-provided information */\n USER_INPUT: 'user_input',\n /** Hindsight correction from outcome */\n HINDSIGHT: 'hindsight',\n /** Default or prior belief */\n PRIOR: 'prior',\n} as const;\n\nexport type BeliefSourceType = (typeof BeliefSourceType)[keyof typeof BeliefSourceType];\n\nexport const BeliefSourceTypeSchema = z.enum([\n 'observation',\n 'inference',\n 'external',\n 'user_input',\n 'hindsight',\n 'prior',\n]);\n\n// ============================================================================\n// Belief State\n// ============================================================================\n\n/**\n * A belief represents an agent's held proposition about the world.\n * Beliefs are versioned and traceable to their sources.\n */\nexport interface Belief {\n /** Unique identifier for this belief */\n readonly beliefId: string;\n /** The entity this belief is about */\n readonly subject: string;\n /** The property or relation being described */\n readonly predicate: string;\n /** The value or target of the relation */\n readonly object: string;\n /** Confidence level in this belief */\n readonly confidence: BeliefConfidence;\n /** Source type for this belief */\n readonly sourceType: BeliefSourceType;\n /** Reference to source evidence or reasoning */\n readonly sourceRef?: string;\n /** Parent belief IDs if derived through inference */\n readonly derivedFrom?: readonly string[];\n /** Version number for tracking updates */\n readonly version: number;\n /** When this belief was formed */\n readonly createdAt: Date;\n /** When this belief was last updated */\n readonly updatedAt: Date;\n /** Whether this belief has been superseded */\n readonly superseded: boolean;\n /** ID of belief that superseded this one */\n readonly supersededBy?: string;\n /** Domain or context for this belief */\n readonly domain?: string;\n /** Additional metadata */\n readonly metadata?: Record<string, unknown>;\n}\n\nexport const BeliefSchema = z.object({\n beliefId: z.string().min(1),\n subject: z.string().min(1),\n predicate: z.string().min(1),\n object: z.string(),\n confidence: BeliefConfidenceSchema,\n sourceType: BeliefSourceTypeSchema,\n sourceRef: z.string().optional(),\n derivedFrom: z.array(z.string()).optional(),\n version: z.number().int().min(1),\n createdAt: z.date(),\n updatedAt: z.date(),\n superseded: z.boolean(),\n supersededBy: z.string().optional(),\n domain: z.string().optional(),\n metadata: z.record(z.string(), z.unknown()).optional(),\n});\n","/**\n * nexus-agents/context - Belief Update Types\n *\n * Type definitions for belief update operations, queries, and audit records.\n *\n * @module context/belief-update-types\n * @see belief-types for re-exports\n * (Source: Issue #336, arXiv:2512.12818 - Hindsight Belief Memory)\n */\n\nimport { z } from 'zod';\nimport type { Belief } from './belief-core-types.js';\nimport { BeliefConfidenceSchema, BeliefSourceTypeSchema } from './belief-core-types.js';\nimport type { BeliefConfidence, BeliefSourceType } from './belief-core-types.js';\n\n// ============================================================================\n// Belief Update Operations\n// ============================================================================\n\n/**\n * Types of belief update operations.\n */\nexport const BeliefUpdateType = {\n /** Add a new belief (retain) */\n RETAIN: 'retain',\n /** Update confidence or metadata */\n REVISE: 'revise',\n /** Mark belief as superseded */\n SUPERSEDE: 'supersede',\n /** Hindsight correction based on outcome */\n CORRECT: 'correct',\n /** Strengthen belief based on corroboration */\n REINFORCE: 'reinforce',\n /** Weaken belief based on contradicting evidence */\n WEAKEN: 'weaken',\n} as const;\n\nexport type BeliefUpdateType = (typeof BeliefUpdateType)[keyof typeof BeliefUpdateType];\n\nexport const BeliefUpdateTypeSchema = z.enum([\n 'retain',\n 'revise',\n 'supersede',\n 'correct',\n 'reinforce',\n 'weaken',\n]);\n\n/**\n * Record of a belief update for audit trail.\n */\nexport interface BeliefUpdate {\n /** Unique identifier for this update */\n readonly updateId: string;\n /** ID of the belief being updated */\n readonly beliefId: string;\n /** Type of update operation */\n readonly updateType: BeliefUpdateType;\n /** Previous state (for revisions) */\n readonly previousState?: Partial<Belief>;\n /** New state after update */\n readonly newState: Partial<Belief>;\n /** Reason for the update */\n readonly reason: string;\n /** Evidence supporting this update */\n readonly evidence?: string;\n /** When this update occurred */\n readonly timestamp: Date;\n /** Agent or process that made the update */\n readonly updatedBy?: string;\n}\n\nexport const BeliefUpdateSchema = z.object({\n updateId: z.string().min(1),\n beliefId: z.string().min(1),\n updateType: BeliefUpdateTypeSchema,\n previousState: z.record(z.string(), z.unknown()).optional(),\n newState: z.record(z.string(), z.unknown()),\n reason: z.string().min(1),\n evidence: z.string().optional(),\n timestamp: z.date(),\n updatedBy: z.string().optional(),\n});\n\n// ============================================================================\n// Belief Query Types\n// ============================================================================\n\n/**\n * Query options for retrieving beliefs.\n */\nexport interface BeliefQuery {\n /** Filter by subject entity */\n readonly subject?: string;\n /** Filter by predicate */\n readonly predicate?: string;\n /** Filter by domain */\n readonly domain?: string;\n /** Minimum confidence level */\n readonly minConfidence?: BeliefConfidence;\n /** Include superseded beliefs */\n readonly includeSuperseded?: boolean;\n /** Filter by source type */\n readonly sourceType?: BeliefSourceType;\n /** Maximum number of results */\n readonly limit?: number;\n /** Order by field */\n readonly orderBy?: 'createdAt' | 'updatedAt' | 'confidence';\n /** Order direction */\n readonly orderDirection?: 'asc' | 'desc';\n}\n\nexport const BeliefQuerySchema = z.object({\n subject: z.string().optional(),\n predicate: z.string().optional(),\n domain: z.string().optional(),\n minConfidence: BeliefConfidenceSchema.optional(),\n includeSuperseded: z.boolean().optional(),\n sourceType: BeliefSourceTypeSchema.optional(),\n limit: z.number().int().positive().max(1000).optional(),\n orderBy: z.enum(['createdAt', 'updatedAt', 'confidence']).optional(),\n orderDirection: z.enum(['asc', 'desc']).optional(),\n});\n","/**\n * nexus-agents/context - Belief Hindsight Types\n *\n * Type definitions for counterfactual reasoning and hindsight learning.\n *\n * @module context/belief-hindsight-types\n * @see belief-types for re-exports\n * (Source: Issue #336, arXiv:2512.12818 - Hindsight Belief Memory)\n */\n\nimport { z } from 'zod';\n\n// ============================================================================\n// Counterfactual Reasoning\n// ============================================================================\n\n/**\n * A counterfactual represents an alternative scenario for reasoning.\n */\nexport interface Counterfactual {\n /** Unique identifier */\n readonly counterfactualId: string;\n /** The hypothetical change to consider */\n readonly hypothesis: string;\n /** Beliefs that would change under this hypothesis */\n readonly affectedBeliefs: readonly string[];\n /** Predicted outcomes under this scenario */\n readonly predictedOutcomes: readonly string[];\n /** Actual outcomes if hypothesis was tested */\n readonly actualOutcomes?: readonly string[];\n /** Whether the counterfactual was validated */\n readonly validated: boolean;\n /** When this counterfactual was created */\n readonly createdAt: Date;\n /** Task or context that prompted this counterfactual */\n readonly taskContext?: string;\n}\n\nexport const CounterfactualSchema = z.object({\n counterfactualId: z.string().min(1),\n hypothesis: z.string().min(1),\n affectedBeliefs: z.array(z.string()),\n predictedOutcomes: z.array(z.string()),\n actualOutcomes: z.array(z.string()).optional(),\n validated: z.boolean(),\n createdAt: z.date(),\n taskContext: z.string().optional(),\n});\n\n// ============================================================================\n// Hindsight Learning\n// ============================================================================\n\n/**\n * Hindsight record captures learning from outcomes.\n */\nexport interface HindsightRecord {\n /** Unique identifier */\n readonly hindsightId: string;\n /** Task that produced this hindsight */\n readonly taskId: string;\n /** Beliefs held before the task */\n readonly priorBeliefs: readonly string[];\n /** Expected outcome based on prior beliefs */\n readonly expectedOutcome: string;\n /** Actual outcome observed */\n readonly actualOutcome: string;\n /** Whether expectation matched reality */\n readonly outcomeMatched: boolean;\n /** Beliefs that were corrected */\n readonly correctedBeliefs: readonly string[];\n /** New beliefs formed from this experience */\n readonly newBeliefs: readonly string[];\n /** Lessons learned */\n readonly lessons: readonly string[];\n /** When this record was created */\n readonly createdAt: Date;\n}\n\nexport const HindsightRecordSchema = z.object({\n hindsightId: z.string().min(1),\n taskId: z.string().min(1),\n priorBeliefs: z.array(z.string()),\n expectedOutcome: z.string(),\n actualOutcome: z.string(),\n outcomeMatched: z.boolean(),\n correctedBeliefs: z.array(z.string()),\n newBeliefs: z.array(z.string()),\n lessons: z.array(z.string()),\n createdAt: z.date(),\n});\n","/**\n * nexus-agents/context - Belief Memory Interface\n *\n * Interface definition for Hindsight Belief Memory operations,\n * statistics types, and configuration options.\n *\n * @module context/belief-memory-interface\n * @see belief-types for re-exports\n * (Source: Issue #336, arXiv:2512.12818 - Hindsight Belief Memory)\n */\n\nimport { z } from 'zod';\nimport type { Result } from '../core/result.js';\nimport type { MemoryError } from './memory-backend-types.js';\nimport type { Belief, BeliefConfidence, BeliefSourceType } from './belief-core-types.js';\nimport { BeliefConfidenceSchema, BeliefSourceTypeSchema } from './belief-core-types.js';\nimport { BeliefConfidence as BeliefConfidenceConst } from './belief-core-types.js';\nimport type { BeliefUpdate, BeliefQuery } from './belief-update-types.js';\nimport type { Counterfactual, HindsightRecord } from './belief-hindsight-types.js';\n\n// ============================================================================\n// Belief Memory Interface\n// ============================================================================\n\n/**\n * Interface for Hindsight Belief Memory operations.\n * Implements the three core operations: retain, recall, and reflect.\n */\nexport interface IHindsightBeliefMemory {\n // === Retain Operations (Adding Information) ===\n\n /**\n * Store a new belief.\n * @param belief - The belief to store (without beliefId, version, timestamps)\n */\n retain(\n belief: Omit<Belief, 'beliefId' | 'version' | 'createdAt' | 'updatedAt' | 'superseded'>\n ): Promise<Result<Belief, MemoryError>>;\n\n /**\n * Store multiple beliefs atomically.\n */\n retainBatch(\n beliefs: readonly Omit<\n Belief,\n 'beliefId' | 'version' | 'createdAt' | 'updatedAt' | 'superseded'\n >[]\n ): Promise<Result<readonly Belief[], MemoryError>>;\n\n // === Recall Operations (Accessing Information) ===\n\n /**\n * Retrieve a belief by ID.\n */\n recall(beliefId: string): Promise<Result<Belief | null, MemoryError>>;\n\n /**\n * Query beliefs with filters.\n */\n query(query: BeliefQuery): Promise<Result<readonly Belief[], MemoryError>>;\n\n /**\n * Get all beliefs about a subject.\n */\n recallBySubject(subject: string, limit?: number): Promise<Result<readonly Belief[], MemoryError>>;\n\n /**\n * Get current belief for a subject-predicate pair.\n */\n recallCurrent(subject: string, predicate: string): Promise<Result<Belief | null, MemoryError>>;\n\n /**\n * Get belief history for a subject-predicate pair.\n */\n recallHistory(\n subject: string,\n predicate: string,\n limit?: number\n ): Promise<Result<readonly Belief[], MemoryError>>;\n\n // === Reflect Operations (Updating Information) ===\n\n /**\n * Update a belief with a new version.\n */\n revise(\n beliefId: string,\n updates: Partial<Pick<Belief, 'object' | 'confidence' | 'metadata'>>,\n reason: string\n ): Promise<Result<Belief, MemoryError>>;\n\n /**\n * Supersede a belief with a new one.\n */\n supersede(\n beliefId: string,\n newBelief: Omit<Belief, 'beliefId' | 'version' | 'createdAt' | 'updatedAt' | 'superseded'>,\n reason: string\n ): Promise<Result<Belief, MemoryError>>;\n\n /**\n * Apply hindsight correction to beliefs.\n */\n applyHindsight(record: HindsightRecord): Promise<Result<readonly Belief[], MemoryError>>;\n\n /**\n * Reinforce a belief based on corroborating evidence.\n */\n reinforce(beliefId: string, evidence: string): Promise<Result<Belief, MemoryError>>;\n\n /**\n * Weaken a belief based on contradicting evidence.\n */\n weaken(beliefId: string, evidence: string): Promise<Result<Belief, MemoryError>>;\n\n // === Counterfactual Reasoning ===\n\n /**\n * Create a counterfactual scenario.\n */\n createCounterfactual(\n hypothesis: string,\n taskContext?: string\n ): Promise<Result<Counterfactual, MemoryError>>;\n\n /**\n * Validate a counterfactual with actual outcomes.\n */\n validateCounterfactual(\n counterfactualId: string,\n actualOutcomes: readonly string[]\n ): Promise<Result<Counterfactual, MemoryError>>;\n\n /**\n * Get counterfactuals for a task context.\n */\n getCounterfactuals(taskContext: string): Promise<Result<readonly Counterfactual[], MemoryError>>;\n\n // === Audit and History ===\n\n /**\n * Get update history for a belief.\n */\n getUpdateHistory(beliefId: string): Promise<Result<readonly BeliefUpdate[], MemoryError>>;\n\n /**\n * Get hindsight records for a task.\n */\n getHindsightRecords(taskId: string): Promise<Result<readonly HindsightRecord[], MemoryError>>;\n\n // === Statistics ===\n\n /**\n * Get belief memory statistics.\n */\n getStats(): Promise<Result<BeliefMemoryStats, MemoryError>>;\n\n /**\n * Prune old superseded beliefs.\n */\n pruneSuperseded(olderThan: Date): Promise<Result<number, MemoryError>>;\n}\n\n// ============================================================================\n// Statistics\n// ============================================================================\n\n/**\n * Statistics for belief memory.\n */\nexport interface BeliefMemoryStats {\n readonly totalBeliefs: number;\n readonly activeBeliefs: number;\n readonly supersededBeliefs: number;\n readonly beliefsByConfidence: Record<BeliefConfidence, number>;\n readonly beliefsBySource: Record<BeliefSourceType, number>;\n readonly totalUpdates: number;\n readonly totalCounterfactuals: number;\n readonly totalHindsightRecords: number;\n readonly oldestBelief?: Date;\n readonly newestBelief?: Date;\n}\n\nexport const BeliefMemoryStatsSchema = z.object({\n totalBeliefs: z.number().int().min(0),\n activeBeliefs: z.number().int().min(0),\n supersededBeliefs: z.number().int().min(0),\n beliefsByConfidence: z.record(BeliefConfidenceSchema, z.number().int().min(0)),\n beliefsBySource: z.record(BeliefSourceTypeSchema, z.number().int().min(0)),\n totalUpdates: z.number().int().min(0),\n totalCounterfactuals: z.number().int().min(0),\n totalHindsightRecords: z.number().int().min(0),\n oldestBelief: z.date().optional(),\n newestBelief: z.date().optional(),\n});\n\n// ============================================================================\n// Configuration\n// ============================================================================\n\n/**\n * Configuration for HindsightBeliefMemory.\n */\nexport interface BeliefMemoryConfig {\n /** Maximum beliefs to retain per subject */\n readonly maxBeliefsPerSubject?: number;\n /** Maximum total beliefs across all subjects (prevents unbounded growth) */\n readonly maxTotalBeliefs?: number;\n /** Auto-prune superseded beliefs older than this (ms) */\n readonly autoPruneAge?: number;\n /** Enable belief inference from observations */\n readonly enableInference?: boolean;\n /** Default confidence for new beliefs without explicit confidence */\n readonly defaultConfidence?: BeliefConfidence;\n /** Maximum depth for derived belief chains */\n readonly maxInferenceDepth?: number;\n}\n\nexport const BeliefMemoryConfigSchema = z.object({\n maxBeliefsPerSubject: z.number().int().positive().optional(),\n maxTotalBeliefs: z.number().int().positive().optional(),\n autoPruneAge: z.number().positive().optional(),\n enableInference: z.boolean().optional(),\n defaultConfidence: BeliefConfidenceSchema.optional(),\n maxInferenceDepth: z.number().int().positive().max(10).optional(),\n});\n\n/**\n * Default configuration values.\n */\nexport const DEFAULT_BELIEF_CONFIG: Required<BeliefMemoryConfig> = {\n maxBeliefsPerSubject: 100,\n maxTotalBeliefs: 10_000,\n autoPruneAge: 30 * 24 * 60 * 60 * 1000, // 30 days\n enableInference: true,\n defaultConfidence: BeliefConfidenceConst.MEDIUM,\n maxInferenceDepth: 5,\n};\n","/**\n * nexus-agents/utils - ID Generation Utilities\n *\n * Shared utility functions for generating unique identifiers.\n * Consolidates duplicate generateId implementations per ADR-0013.\n *\n * Uses getTimeProvider and getRandomProvider for deterministic testing.\n *\n * @module utils/id-utils\n * @see docs/adr/0013-memory-helpers-consolidation.md\n */\n\nimport { randomUUID } from 'node:crypto';\nimport { getTimeProvider, getRandomProvider } from '../core/index.js';\n\n/**\n * Generate a unique ID with prefix using timestamp and random suffix.\n *\n * Format: `${prefix}_${timestamp}_${random}` (underscore-separated)\n *\n * Uses getTimeProvider() and getRandomProvider() for deterministic testing.\n *\n * @param prefix - ID prefix (e.g., 'belief', 'update', 'exec')\n * @param randomLength - Length of random suffix (default: 8)\n * @returns Unique ID string\n *\n * @example\n * ```typescript\n * const beliefId = generateId('belief'); // 'belief_1p5k3x2_a1b2c3d4'\n * const execId = generateId('exec', 6); // 'exec_1p5k3x2_a1b2c3'\n * ```\n */\nexport function generateId(prefix: string, randomLength = 8): string {\n const timestamp = getTimeProvider().now().toString(36);\n const random = getRandomProvider()\n .random()\n .toString(36)\n .substring(2, 2 + randomLength);\n return `${prefix}_${timestamp}_${random}`;\n}\n\n/**\n * Generate a unique ID with hyphen separators.\n *\n * Format: `${prefix}-${timestamp}-${random}` (hyphen-separated)\n *\n * @param prefix - ID prefix\n * @param randomLength - Length of random suffix (default: 6)\n * @returns Unique ID string\n *\n * @example\n * ```typescript\n * const id = generateHyphenId('workflow'); // 'workflow-1769876392192-a1b2c3'\n * ```\n */\nexport function generateHyphenId(prefix: string, randomLength = 6): string {\n const timestamp = String(getTimeProvider().now());\n const random = getRandomProvider()\n .random()\n .toString(36)\n .slice(2, 2 + randomLength);\n return `${prefix}-${timestamp}-${random}`;\n}\n\n/**\n * Generate a short unique ID using randomUUID.\n *\n * Format: `${prefix}-${shortUuid}` where shortUuid is first 8 chars of UUID.\n *\n * @param prefix - ID prefix\n * @returns Short unique ID string\n *\n * @example\n * ```typescript\n * const id = generateShortUuid('workflow'); // 'workflow-a1b2c3d4'\n * ```\n */\nexport function generateShortUuid(prefix: string): string {\n // Use random provider for determinism, generate UUID-like pattern\n const rand1 = getRandomProvider().random().toString(16).substring(2, 6);\n const rand2 = getRandomProvider().random().toString(16).substring(2, 6);\n return `${prefix}-${rand1}${rand2}`;\n}\n\n// ============================================================================\n// UUID Generation (node:crypto)\n// ============================================================================\n\n/**\n * Generates a UUID v4 using node:crypto.randomUUID().\n * This is the canonical UUID generator - use instead of `uuid` package.\n *\n * Note: This uses node:crypto directly for performance. For deterministic\n * testing scenarios, use generateId() or generateShortUuid() instead.\n *\n * @returns A UUID v4 string\n *\n * @example\n * ```typescript\n * const id = generateUUID(); // 'f47ac10b-58cc-4372-a567-0e02b2c3d479'\n * ```\n */\nexport function generateUUID(): string {\n return randomUUID();\n}\n\n/**\n * Generates a short UUID (first 8 characters).\n * Useful for display purposes or step IDs.\n *\n * @param prefix - Optional prefix for the ID\n * @returns A short UUID string, optionally prefixed\n *\n * @example\n * ```typescript\n * const id = generateShortUUIDv4(); // 'f47ac10b'\n * const stepId = generateShortUUIDv4('step'); // 'step-f47ac10b'\n * ```\n */\nexport function generateShortUUIDv4(prefix?: string): string {\n const shortId = randomUUID().slice(0, 8);\n return prefix !== undefined ? `${prefix}-${shortId}` : shortId;\n}\n\n/**\n * Generates a step ID using UUID.\n * Replacement for `step-${uuidv4().slice(0, 8)}` pattern.\n *\n * @param prefix - Prefix for the step ID (default: 'step')\n * @returns A prefixed short UUID\n */\nexport function generateStepId(prefix = 'step'): string {\n return generateShortUUIDv4(prefix);\n}\n","/**\n * nexus-agents/context - Hindsight Belief Memory Helpers\n *\n * Helper functions for the Hindsight Belief Memory implementation.\n *\n * @module context/belief-memory-helpers\n * (Source: Issue #336, arXiv:2512.12818 - Hindsight Belief Memory)\n */\n\nimport { getTimeProvider } from '../core/index.js';\nimport type {\n Belief,\n BeliefConfidence,\n BeliefMemoryStats,\n BeliefQuery,\n BeliefSourceType,\n} from './belief-types.js';\nimport { BeliefConfidence as BeliefConfidenceEnum } from './belief-types.js';\n// Shared utilities per ADR-0013\nimport { generateId as sharedGenerateId } from '../utils/id-utils.js';\n\n// ============================================================================\n// Confidence Level Operations\n// ============================================================================\n\n/** Compare confidence levels for ordering */\nexport function compareConfidence(a: BeliefConfidence, b: BeliefConfidence): number {\n const order: Record<BeliefConfidence, number> = {\n high: 4,\n medium: 3,\n low: 2,\n speculative: 1,\n };\n return order[a] - order[b];\n}\n\n/** Get next confidence level up */\nexport function strengthenConfidence(current: BeliefConfidence): BeliefConfidence {\n const progression: Record<BeliefConfidence, BeliefConfidence> = {\n speculative: BeliefConfidenceEnum.LOW,\n low: BeliefConfidenceEnum.MEDIUM,\n medium: BeliefConfidenceEnum.HIGH,\n high: BeliefConfidenceEnum.HIGH,\n };\n return progression[current];\n}\n\n/** Get next confidence level down */\nexport function weakenConfidence(current: BeliefConfidence): BeliefConfidence {\n const regression: Record<BeliefConfidence, BeliefConfidence> = {\n high: BeliefConfidenceEnum.MEDIUM,\n medium: BeliefConfidenceEnum.LOW,\n low: BeliefConfidenceEnum.SPECULATIVE,\n speculative: BeliefConfidenceEnum.SPECULATIVE,\n };\n return regression[current];\n}\n\n// ============================================================================\n// Belief Sorting\n// ============================================================================\n\n/** Sort beliefs by query options */\nexport function sortBeliefs(\n beliefs: readonly Belief[],\n orderBy?: 'createdAt' | 'updatedAt' | 'confidence',\n direction?: 'asc' | 'desc'\n): Belief[] {\n const sorted = [...beliefs];\n const multiplier = direction === 'asc' ? 1 : -1;\n\n sorted.sort((a, b) => {\n switch (orderBy) {\n case 'createdAt':\n return (a.createdAt.getTime() - b.createdAt.getTime()) * multiplier;\n case 'updatedAt':\n return (a.updatedAt.getTime() - b.updatedAt.getTime()) * multiplier;\n case 'confidence':\n return compareConfidence(a.confidence, b.confidence) * multiplier;\n default:\n return (b.updatedAt.getTime() - a.updatedAt.getTime()) * multiplier;\n }\n });\n\n return sorted;\n}\n\n// ============================================================================\n// Query Filtering\n// ============================================================================\n\n/** Check if belief matches query filters */\nexport function matchesQueryFilters(belief: Belief, query: BeliefQuery): boolean {\n if (query.includeSuperseded !== true && belief.superseded) {\n return false;\n }\n if (query.minConfidence !== undefined) {\n if (compareConfidence(belief.confidence, query.minConfidence) < 0) {\n return false;\n }\n }\n if (query.sourceType !== undefined && belief.sourceType !== query.sourceType) {\n return false;\n }\n return true;\n}\n\n/** Intersect two sets */\nexport function intersectSets<T>(a: Set<T>, b: Set<T>): Set<T> {\n const result = new Set<T>();\n for (const item of a) {\n if (b.has(item)) {\n result.add(item);\n }\n }\n return result;\n}\n\n// ============================================================================\n// Statistics Computation\n// ============================================================================\n\n/** Initialize empty stats counters */\nexport function initializeStatsCounters(): {\n beliefsByConfidence: Record<BeliefConfidence, number>;\n beliefsBySource: Record<BeliefSourceType, number>;\n} {\n return {\n beliefsByConfidence: {\n high: 0,\n medium: 0,\n low: 0,\n speculative: 0,\n },\n beliefsBySource: {\n observation: 0,\n inference: 0,\n external: 0,\n user_input: 0,\n hindsight: 0,\n prior: 0,\n },\n };\n}\n\n/** Build final stats object with optional date fields */\nexport function buildStatsResult(\n baseStats: Omit<BeliefMemoryStats, 'oldestBelief' | 'newestBelief'>,\n oldestBelief: Date | undefined,\n newestBelief: Date | undefined\n): BeliefMemoryStats {\n if (oldestBelief !== undefined && newestBelief !== undefined) {\n return { ...baseStats, oldestBelief, newestBelief };\n } else if (oldestBelief !== undefined) {\n return { ...baseStats, oldestBelief };\n } else if (newestBelief !== undefined) {\n return { ...baseStats, newestBelief };\n }\n return baseStats;\n}\n\n// ============================================================================\n// Update Record Creation\n// ============================================================================\n\nimport type { BeliefUpdate, BeliefUpdateType } from './belief-types.js';\n\n/** Options for creating an update record */\nexport interface UpdateRecordOptions {\n readonly beliefId: string;\n readonly updateType: BeliefUpdateType;\n readonly previousState: Record<string, unknown>;\n readonly newState: Record<string, unknown>;\n readonly reason: string;\n readonly evidence?: string;\n}\n\n/** Create a new update record */\nexport function createUpdateRecord(options: UpdateRecordOptions): BeliefUpdate {\n return {\n updateId: sharedGenerateId('update', 8),\n beliefId: options.beliefId,\n updateType: options.updateType,\n previousState: options.previousState,\n newState: options.newState,\n reason: options.reason,\n ...(options.evidence !== undefined ? { evidence: options.evidence } : {}),\n timestamp: new Date(getTimeProvider().now()),\n };\n}\n","/**\n * nexus-agents/context - Belief Memory Recall Operations\n *\n * Query and retrieval operations for Hindsight Belief Memory.\n * Extracted from belief-memory.ts to comply with 400-line limit.\n *\n * @module context/belief-memory-recall\n * (Source: Issue #336, arXiv:2512.12818 - Hindsight Belief Memory)\n */\n\nimport type { Result } from '../core/result.js';\nimport { ok, err } from '../core/result.js';\nimport { MemoryError } from './memory-backend-types.js';\nimport type { Belief, BeliefQuery } from './belief-types.js';\nimport { BeliefQuerySchema } from './belief-types.js';\nimport { sortBeliefs, matchesQueryFilters, intersectSets } from './belief-memory-helpers.js';\n\n// ============================================================================\n// Types for Recall Data Stores\n// ============================================================================\n\n/**\n * Data stores required for recall operations.\n */\nexport interface RecallDataStores {\n readonly beliefs: Map<string, Belief>;\n readonly subjectIndex: Map<string, Set<string>>;\n readonly predicateIndex: Map<string, Set<string>>;\n readonly domainIndex: Map<string, Set<string>>;\n}\n\n// ============================================================================\n// Recall Operations\n// ============================================================================\n\n/**\n * Recall a single belief by ID.\n */\nexport function recallInternal(\n stores: Pick<RecallDataStores, 'beliefs'>,\n beliefId: string\n): Promise<Result<Belief | null, MemoryError>> {\n try {\n return Promise.resolve(ok(stores.beliefs.get(beliefId) ?? null));\n } catch (error) {\n return Promise.resolve(\n err(\n new MemoryError('Failed to recall belief', {\n cause: error instanceof Error ? error : new Error(String(error)),\n })\n )\n );\n }\n}\n\n/**\n * Get candidate belief IDs based on indexed fields.\n */\nfunction getCandidateIds(stores: RecallDataStores, query: BeliefQuery): Set<string> | null {\n let ids: Set<string> | null = null;\n\n if (query.subject !== undefined) {\n ids = new Set(stores.subjectIndex.get(query.subject) ?? []);\n }\n\n if (query.predicate !== undefined) {\n const pIds = stores.predicateIndex.get(query.predicate) ?? new Set();\n ids = ids ? intersectSets(ids, pIds) : new Set(pIds);\n }\n\n if (query.domain !== undefined) {\n const dIds = stores.domainIndex.get(query.domain) ?? new Set();\n ids = ids ? intersectSets(ids, dIds) : new Set(dIds);\n }\n\n return ids;\n}\n\n/**\n * Filter candidates by query criteria.\n */\nfunction filterCandidates(\n stores: Pick<RecallDataStores, 'beliefs'>,\n candidateIds: Set<string> | null,\n query: BeliefQuery\n): Belief[] {\n const allIds = candidateIds ?? new Set(stores.beliefs.keys());\n const filtered: Belief[] = [];\n\n for (const id of allIds) {\n const b = stores.beliefs.get(id);\n if (b !== undefined && matchesQueryFilters(b, query)) {\n filtered.push(b);\n }\n }\n\n return filtered;\n}\n\n/**\n * Query beliefs with filters, sorting, and pagination.\n */\nexport function queryInternal(\n stores: RecallDataStores,\n query: BeliefQuery\n): Promise<Result<readonly Belief[], MemoryError>> {\n try {\n const validation = BeliefQuerySchema.safeParse(query);\n if (!validation.success) {\n return Promise.resolve(\n err(new MemoryError('Invalid query', { context: { errors: validation.error.issues } }))\n );\n }\n\n const candidateIds = getCandidateIds(stores, query);\n const filtered = filterCandidates(stores, candidateIds, query);\n const sorted = sortBeliefs(filtered, query.orderBy, query.orderDirection);\n const limited = query.limit !== undefined ? sorted.slice(0, query.limit) : sorted;\n\n return Promise.resolve(ok(limited));\n } catch (error) {\n return Promise.resolve(\n err(\n new MemoryError('Failed to query beliefs', {\n cause: error instanceof Error ? error : new Error(String(error)),\n })\n )\n );\n }\n}\n\n/**\n * Recall beliefs by subject.\n */\nexport function recallBySubjectInternal(\n stores: RecallDataStores,\n subject: string,\n limit?: number\n): Promise<Result<readonly Belief[], MemoryError>> {\n const q: BeliefQuery = { subject, includeSuperseded: false };\n return limit !== undefined ? queryInternal(stores, { ...q, limit }) : queryInternal(stores, q);\n}\n\n/**\n * Recall current (most recent, non-superseded) belief for subject-predicate.\n */\nexport async function recallCurrentInternal(\n stores: RecallDataStores,\n subject: string,\n predicate: string\n): Promise<Result<Belief | null, MemoryError>> {\n const result = await queryInternal(stores, {\n subject,\n predicate,\n includeSuperseded: false,\n orderBy: 'updatedAt',\n orderDirection: 'desc',\n limit: 1,\n });\n\n if (!result.ok) return result;\n return ok(result.value[0] ?? null);\n}\n\n/**\n * Recall belief history for subject-predicate (including superseded).\n */\nexport function recallHistoryInternal(\n stores: RecallDataStores,\n subject: string,\n predicate: string,\n limit?: number\n): Promise<Result<readonly Belief[], MemoryError>> {\n const q: BeliefQuery = {\n subject,\n predicate,\n includeSuperseded: true,\n orderBy: 'updatedAt',\n orderDirection: 'desc',\n };\n return limit !== undefined ? queryInternal(stores, { ...q, limit }) : queryInternal(stores, q);\n}\n","/**\n * nexus-agents/context - Hindsight Belief Memory Audit\n *\n * Counterfactual reasoning, audit, and statistics methods.\n *\n * @module context/belief-memory-audit\n * (Source: Issue #336, arXiv:2512.12818 - Hindsight Belief Memory)\n */\n\nimport type { Result } from '../core/result.js';\nimport { ok, err } from '../core/result.js';\nimport { getTimeProvider } from '../core/index.js';\nimport type { ILogger } from '../core/logger.js';\nimport { MemoryError } from './memory-backend-types.js';\nimport type {\n Belief,\n BeliefMemoryStats,\n BeliefUpdate,\n Counterfactual,\n HindsightRecord,\n} from './belief-types.js';\nimport { initializeStatsCounters, buildStatsResult } from './belief-memory-helpers.js';\n// Shared utilities per ADR-0013\nimport { generateId } from '../utils/id-utils.js';\n\n/** Data stores required for audit operations */\nexport interface AuditDataStores {\n readonly beliefs: Map<string, Belief>;\n readonly updates: Map<string, BeliefUpdate[]>;\n readonly counterfactuals: Map<string, Counterfactual>;\n readonly hindsightRecords: Map<string, HindsightRecord[]>;\n readonly logger: ILogger;\n}\n\n/** Create a counterfactual scenario */\nexport function createCounterfactualInternal(\n stores: AuditDataStores,\n hypothesis: string,\n taskContext?: string\n): Promise<Result<Counterfactual, MemoryError>> {\n try {\n const affectedBeliefs = findAffectedBeliefs(stores.beliefs, hypothesis);\n const baseCounterfactual = {\n counterfactualId: generateId('cf'),\n hypothesis,\n affectedBeliefs: affectedBeliefs.map((b) => b.beliefId),\n predictedOutcomes: predictOutcomes(hypothesis, affectedBeliefs),\n validated: false as const,\n createdAt: new Date(getTimeProvider().now()),\n };\n const counterfactual: Counterfactual =\n taskContext !== undefined ? { ...baseCounterfactual, taskContext } : baseCounterfactual;\n stores.counterfactuals.set(counterfactual.counterfactualId, counterfactual);\n stores.logger.debug('Counterfactual created', {\n counterfactualId: counterfactual.counterfactualId,\n });\n return Promise.resolve(ok(counterfactual));\n } catch (error) {\n const causeError = error instanceof Error ? error : new Error(String(error));\n return Promise.resolve(\n err(new MemoryError('Failed to create counterfactual', { cause: causeError }))\n );\n }\n}\n\n/** Validate a counterfactual with actual outcomes */\nexport function validateCounterfactualInternal(\n stores: AuditDataStores,\n counterfactualId: string,\n actualOutcomes: readonly string[]\n): Promise<Result<Counterfactual, MemoryError>> {\n try {\n const existing = stores.counterfactuals.get(counterfactualId);\n if (existing === undefined) {\n return Promise.resolve(\n err(new MemoryError('Counterfactual not found', { context: { counterfactualId } }))\n );\n }\n const validated: Counterfactual = { ...existing, actualOutcomes, validated: true };\n stores.counterfactuals.set(counterfactualId, validated);\n stores.logger.debug('Counterfactual validated', { counterfactualId });\n return Promise.resolve(ok(validated));\n } catch (error) {\n const causeError = error instanceof Error ? error : new Error(String(error));\n return Promise.resolve(\n err(new MemoryError('Failed to validate counterfactual', { cause: causeError }))\n );\n }\n}\n\n/** Get counterfactuals for a task context */\nexport function getCounterfactualsInternal(\n stores: AuditDataStores,\n taskContext: string\n): Promise<Result<readonly Counterfactual[], MemoryError>> {\n try {\n const results: Counterfactual[] = [];\n for (const cf of stores.counterfactuals.values()) {\n if (cf.taskContext === taskContext) results.push(cf);\n }\n return Promise.resolve(ok(results));\n } catch (error) {\n const causeError = error instanceof Error ? error : new Error(String(error));\n return Promise.resolve(\n err(new MemoryError('Failed to get counterfactuals', { cause: causeError }))\n );\n }\n}\n\n/** Get update history for a belief */\nexport function getUpdateHistoryInternal(\n stores: AuditDataStores,\n beliefId: string\n): Promise<Result<readonly BeliefUpdate[], MemoryError>> {\n try {\n return Promise.resolve(ok(stores.updates.get(beliefId) ?? []));\n } catch (error) {\n const causeError = error instanceof Error ? error : new Error(String(error));\n return Promise.resolve(\n err(new MemoryError('Failed to get update history', { cause: causeError }))\n );\n }\n}\n\n/** Get hindsight records for a task */\nexport function getHindsightRecordsInternal(\n stores: AuditDataStores,\n taskId: string\n): Promise<Result<readonly HindsightRecord[], MemoryError>> {\n try {\n return Promise.resolve(ok(stores.hindsightRecords.get(taskId) ?? []));\n } catch (error) {\n const causeError = error instanceof Error ? error : new Error(String(error));\n return Promise.resolve(\n err(new MemoryError('Failed to get hindsight records', { cause: causeError }))\n );\n }\n}\n\n/** Compute belief memory statistics */\nexport function computeStatsInternal(stores: AuditDataStores): BeliefMemoryStats {\n const { beliefsByConfidence, beliefsBySource } = initializeStatsCounters();\n let activeBeliefs = 0,\n supersededBeliefs = 0;\n let oldestBelief: Date | undefined, newestBelief: Date | undefined;\n\n for (const belief of stores.beliefs.values()) {\n beliefsByConfidence[belief.confidence]++;\n beliefsBySource[belief.sourceType]++;\n if (belief.superseded) {\n supersededBeliefs++;\n } else {\n activeBeliefs++;\n }\n if (oldestBelief === undefined || belief.createdAt < oldestBelief)\n oldestBelief = belief.createdAt;\n if (newestBelief === undefined || belief.createdAt > newestBelief)\n newestBelief = belief.createdAt;\n }\n\n let totalUpdates = 0,\n totalHindsightRecords = 0;\n for (const history of stores.updates.values()) totalUpdates += history.length;\n for (const records of stores.hindsightRecords.values()) totalHindsightRecords += records.length;\n\n return buildStatsResult(\n {\n totalBeliefs: stores.beliefs.size,\n activeBeliefs,\n supersededBeliefs,\n beliefsByConfidence,\n beliefsBySource,\n totalUpdates,\n totalCounterfactuals: stores.counterfactuals.size,\n totalHindsightRecords,\n },\n oldestBelief,\n newestBelief\n );\n}\n\n/** Find beliefs affected by a hypothesis */\nfunction findAffectedBeliefs(beliefs: Map<string, Belief>, hypothesis: string): Belief[] {\n const keywords = hypothesis.toLowerCase().split(/\\s+/);\n const affected: Belief[] = [];\n for (const belief of beliefs.values()) {\n if (belief.superseded) continue;\n const beliefText = `${belief.subject} ${belief.predicate} ${belief.object}`.toLowerCase();\n if (keywords.some((k) => beliefText.includes(k))) affected.push(belief);\n }\n return affected;\n}\n\n/** Predict outcomes for a hypothesis */\nfunction predictOutcomes(hypothesis: string, affectedBeliefs: Belief[]): string[] {\n return affectedBeliefs.map(\n (b) => `If \"${hypothesis}\", then ${b.subject} ${b.predicate} may change`\n );\n}\n","/**\n * nexus-agents/context - Belief Memory Reflect Operations\n *\n * Extracted reflect operations for HindsightBeliefMemory to comply with 400-line limit.\n *\n * @module context/belief-memory-reflect\n */\n\nimport type { Result } from '../core/result.js';\nimport { ok, err } from '../core/result.js';\nimport { getTimeProvider } from '../core/index.js';\nimport type { ILogger } from '../core/logger.js';\nimport { MemoryError } from './memory-backend-types.js';\nimport type { Belief, BeliefUpdate, HindsightRecord } from './belief-types.js';\nimport {\n BeliefSourceType as BeliefSourceTypeEnum,\n BeliefUpdateType as BeliefUpdateTypeEnum,\n} from './belief-types.js';\nimport { strengthenConfidence, weakenConfidence } from './belief-memory-helpers.js';\n\n/**\n * Options for revising a belief.\n */\nexport interface ReviseOptions {\n readonly beliefId: string;\n readonly updates: Partial<Pick<Belief, 'object' | 'confidence' | 'metadata'>>;\n readonly reason: string;\n}\n\n/**\n * Options for superseding a belief.\n */\nexport interface SupersedeOptions {\n readonly beliefId: string;\n readonly newBelief: Omit<\n Belief,\n 'beliefId' | 'version' | 'createdAt' | 'updatedAt' | 'superseded'\n >;\n readonly reason: string;\n}\n\n/**\n * Internal stores used by reflect operations.\n */\nexport interface ReflectDataStores {\n readonly beliefs: Map<string, Belief>;\n readonly updates: Map<string, BeliefUpdate[]>;\n readonly hindsightRecords: Map<string, HindsightRecord[]>;\n readonly logger: ILogger;\n readonly recordUpdate: (opts: RecordUpdateOptions) => void;\n}\n\n/**\n * Options for recording an update.\n */\nexport interface RecordUpdateOptions {\n readonly beliefId: string;\n readonly updateType: BeliefUpdate['updateType'];\n readonly previousState: Record<string, unknown>;\n readonly newState: Record<string, unknown>;\n readonly reason: string;\n readonly evidence?: string;\n}\n\n/**\n * Revise an existing belief with updates.\n */\nexport function reviseBeliefInternal(\n stores: ReflectDataStores,\n opts: ReviseOptions\n): Promise<Result<Belief, MemoryError>> {\n const { beliefId, updates, reason } = opts;\n try {\n const existing = stores.beliefs.get(beliefId);\n if (existing === undefined) {\n return Promise.resolve(err(new MemoryError('Belief not found', { context: { beliefId } })));\n }\n if (existing.superseded) {\n return Promise.resolve(\n err(new MemoryError('Cannot revise superseded belief', { context: { beliefId } }))\n );\n }\n const now = new Date(getTimeProvider().now());\n const revised: Belief = {\n ...existing,\n ...updates,\n version: existing.version + 1,\n updatedAt: now,\n };\n stores.beliefs.set(beliefId, revised);\n stores.recordUpdate({\n beliefId,\n updateType: BeliefUpdateTypeEnum.REVISE,\n previousState: { object: existing.object, confidence: existing.confidence },\n newState: updates,\n reason,\n });\n stores.logger.debug('Belief revised', { beliefId, reason });\n return Promise.resolve(ok(revised));\n } catch (error) {\n return Promise.resolve(\n err(\n new MemoryError('Failed to revise belief', {\n cause: error instanceof Error ? error : new Error(String(error)),\n })\n )\n );\n }\n}\n\n/**\n * Apply hindsight correction to beliefs.\n */\nexport function applyHindsightInternal(\n stores: ReflectDataStores,\n record: HindsightRecord\n): Promise<Result<readonly Belief[], MemoryError>> {\n try {\n const correctedBeliefs: Belief[] = [];\n const now = new Date(getTimeProvider().now());\n\n // Store the hindsight record\n const taskRecords = stores.hindsightRecords.get(record.taskId) ?? [];\n taskRecords.push(record);\n stores.hindsightRecords.set(record.taskId, taskRecords);\n\n // Apply corrections to all affected beliefs\n for (const beliefId of record.correctedBeliefs) {\n const belief = stores.beliefs.get(beliefId);\n if (belief === undefined || belief.superseded) continue;\n\n const corrected: Belief = {\n ...belief,\n confidence: weakenConfidence(belief.confidence),\n sourceType: BeliefSourceTypeEnum.HINDSIGHT,\n version: belief.version + 1,\n updatedAt: now,\n };\n stores.beliefs.set(beliefId, corrected);\n correctedBeliefs.push(corrected);\n\n stores.recordUpdate({\n beliefId,\n updateType: BeliefUpdateTypeEnum.CORRECT,\n previousState: { confidence: belief.confidence },\n newState: { confidence: corrected.confidence },\n reason: `Hindsight correction: expected \"${record.expectedOutcome}\", got \"${record.actualOutcome}\"`,\n evidence: record.hindsightId,\n });\n }\n\n stores.logger.info('Hindsight applied', {\n hindsightId: record.hindsightId,\n correctedCount: correctedBeliefs.length,\n });\n return Promise.resolve(ok(correctedBeliefs));\n } catch (error) {\n return Promise.resolve(\n err(\n new MemoryError('Failed to apply hindsight', {\n cause: error instanceof Error ? error : new Error(String(error)),\n })\n )\n );\n }\n}\n\n/**\n * Adjust confidence of a belief (reinforce or weaken).\n */\nexport function adjustConfidenceInternal(\n stores: ReflectDataStores,\n beliefId: string,\n evidence: string,\n direction: 'reinforce' | 'weaken'\n): Promise<Result<Belief, MemoryError>> {\n try {\n const existing = stores.beliefs.get(beliefId);\n if (existing === undefined) {\n return Promise.resolve(err(new MemoryError('Belief not found', { context: { beliefId } })));\n }\n if (existing.superseded) {\n return Promise.resolve(\n err(new MemoryError(`Cannot ${direction} superseded belief`, { context: { beliefId } }))\n );\n }\n\n const now = new Date(getTimeProvider().now());\n const newConfidence =\n direction === 'reinforce'\n ? strengthenConfidence(existing.confidence)\n : weakenConfidence(existing.confidence);\n\n const updated: Belief = {\n ...existing,\n confidence: newConfidence,\n version: existing.version + 1,\n updatedAt: now,\n };\n stores.beliefs.set(beliefId, updated);\n\n const updateType =\n direction === 'reinforce' ? BeliefUpdateTypeEnum.REINFORCE : BeliefUpdateTypeEnum.WEAKEN;\n stores.recordUpdate({\n beliefId,\n updateType,\n previousState: { confidence: existing.confidence },\n newState: { confidence: newConfidence },\n reason: direction === 'reinforce' ? 'Corroborating evidence' : 'Contradicting evidence',\n evidence,\n });\n\n stores.logger.debug(`Belief ${direction}d`, { beliefId, newConfidence });\n return Promise.resolve(ok(updated));\n } catch (error) {\n return Promise.resolve(\n err(\n new MemoryError(`Failed to ${direction} belief`, {\n cause: error instanceof Error ? error : new Error(String(error)),\n })\n )\n );\n }\n}\n\n/**\n * Prune superseded beliefs older than the given date.\n */\nexport function pruneSupersededInternal(\n stores: ReflectDataStores & {\n readonly subjectIndex: Map<string, Set<string>>;\n readonly predicateIndex: Map<string, Set<string>>;\n readonly domainIndex: Map<string, Set<string>>;\n },\n olderThan: Date\n): Promise<Result<number, MemoryError>> {\n try {\n let pruned = 0;\n const cutoff = olderThan.getTime();\n\n for (const [id, belief] of stores.beliefs.entries()) {\n if (belief.superseded && belief.updatedAt.getTime() < cutoff) {\n stores.beliefs.delete(id);\n // Remove from indices\n stores.subjectIndex.get(belief.subject)?.delete(belief.beliefId);\n stores.predicateIndex.get(belief.predicate)?.delete(belief.beliefId);\n if (belief.domain !== undefined) {\n stores.domainIndex.get(belief.domain)?.delete(belief.beliefId);\n }\n stores.updates.delete(id);\n pruned++;\n }\n }\n\n stores.logger.info('Pruned superseded beliefs', { pruned, olderThan: olderThan.toISOString() });\n return Promise.resolve(ok(pruned));\n } catch (error) {\n return Promise.resolve(\n err(\n new MemoryError('Failed to prune superseded beliefs', {\n cause: error instanceof Error ? error : new Error(String(error)),\n })\n )\n );\n }\n}\n","/* eslint-disable max-lines */\n/**\n * nexus-agents/context - Hindsight Belief Memory\n *\n * Implements the Hindsight Belief Memory layer for reasoning agents.\n * Core operations: retain, recall, and reflect.\n *\n * @module context/belief-memory\n * (Source: Issue #336, arXiv:2512.12818 - Hindsight Belief Memory)\n */\n\nimport type { Result } from '../core/result.js';\nimport { ok, err } from '../core/result.js';\nimport { getTimeProvider, formatZodError } from '../core/index.js';\nimport type { ILogger } from '../core/logger.js';\nimport { createLogger } from '../core/logger.js';\nimport { MemoryError } from './memory-backend-types.js';\nimport type {\n Belief,\n BeliefMemoryConfig,\n BeliefMemoryStats,\n BeliefQuery,\n BeliefUpdate,\n Counterfactual,\n HindsightRecord,\n IHindsightBeliefMemory,\n} from './belief-types.js';\nimport {\n BeliefMemoryConfigSchema,\n BeliefSchema,\n BeliefUpdateType as BeliefUpdateTypeEnum,\n DEFAULT_BELIEF_CONFIG,\n} from './belief-types.js';\nimport { createUpdateRecord } from './belief-memory-helpers.js';\n// Shared utilities per ADR-0013\nimport { generateId } from '../utils/id-utils.js';\nimport {\n recallInternal,\n queryInternal,\n recallBySubjectInternal,\n recallCurrentInternal,\n recallHistoryInternal,\n type RecallDataStores,\n} from './belief-memory-recall.js';\nimport {\n createCounterfactualInternal,\n validateCounterfactualInternal,\n getCounterfactualsInternal,\n getUpdateHistoryInternal,\n getHindsightRecordsInternal,\n computeStatsInternal,\n type AuditDataStores,\n} from './belief-memory-audit.js';\nimport {\n reviseBeliefInternal,\n applyHindsightInternal,\n adjustConfidenceInternal,\n pruneSupersededInternal,\n type ReflectDataStores,\n} from './belief-memory-reflect.js';\nimport type { BeliefMemoryData, HydratedBeliefData } from './belief-memory-persistence.js';\n\n/**\n * In-memory implementation of Hindsight Belief Memory.\n */\nexport class HindsightBeliefMemory implements IHindsightBeliefMemory {\n private readonly beliefs: Map<string, Belief> = new Map();\n private readonly updates: Map<string, BeliefUpdate[]> = new Map();\n private readonly counterfactuals: Map<string, Counterfactual> = new Map();\n private readonly hindsightRecords: Map<string, HindsightRecord[]> = new Map();\n private readonly subjectIndex: Map<string, Set<string>> = new Map();\n private readonly predicateIndex: Map<string, Set<string>> = new Map();\n private readonly domainIndex: Map<string, Set<string>> = new Map();\n private readonly config: Required<BeliefMemoryConfig>;\n private readonly logger: ILogger;\n\n constructor(config?: BeliefMemoryConfig, logger?: ILogger) {\n const validation = BeliefMemoryConfigSchema.safeParse(config ?? {});\n if (!validation.success) {\n throw new MemoryError(`Invalid BeliefMemoryConfig: ${formatZodError(validation.error)}`);\n }\n this.config = { ...DEFAULT_BELIEF_CONFIG, ...config };\n this.logger = logger ?? createLogger({ component: 'HindsightBeliefMemory' });\n this.logger.info('HindsightBeliefMemory initialized', { config: this.config });\n }\n\n private get auditStores(): AuditDataStores {\n return {\n beliefs: this.beliefs,\n updates: this.updates,\n counterfactuals: this.counterfactuals,\n hindsightRecords: this.hindsightRecords,\n logger: this.logger,\n };\n }\n\n private get reflectStores(): ReflectDataStores {\n return {\n beliefs: this.beliefs,\n updates: this.updates,\n hindsightRecords: this.hindsightRecords,\n logger: this.logger,\n recordUpdate: (opts) => {\n this.recordUpdate(opts);\n },\n };\n }\n\n private get recallStores(): RecallDataStores {\n return {\n beliefs: this.beliefs,\n subjectIndex: this.subjectIndex,\n predicateIndex: this.predicateIndex,\n domainIndex: this.domainIndex,\n };\n }\n\n // =========================================================================\n // Retain Operations\n // =========================================================================\n\n retain(\n belief: Omit<Belief, 'beliefId' | 'version' | 'createdAt' | 'updatedAt' | 'superseded'>\n ): Promise<Result<Belief, MemoryError>> {\n return this.retainInternal(belief, false);\n }\n\n private retainInternal(\n belief: Omit<Belief, 'beliefId' | 'version' | 'createdAt' | 'updatedAt' | 'superseded'>,\n skipDedup: boolean\n ): Promise<Result<Belief, MemoryError>> {\n try {\n const validationError = this.validateBeliefInput(belief);\n if (validationError !== undefined) return Promise.resolve(err(validationError));\n\n const existingBelief = skipDedup\n ? undefined\n : this.findActiveBySubjectPredicate(belief.subject, belief.predicate);\n\n // Content-hash dedup: skip write if identical content already exists (#1455)\n const dedupResult = this.checkDedupMatch(existingBelief, belief);\n if (dedupResult !== undefined) {\n return Promise.resolve(ok(dedupResult));\n }\n\n const version = existingBelief !== undefined ? existingBelief.version + 1 : 1;\n const now = new Date(getTimeProvider().now());\n const newBelief: Belief = {\n ...belief,\n beliefId: generateId('belief'),\n version,\n createdAt: now,\n updatedAt: now,\n superseded: false,\n };\n this.beliefs.set(newBelief.beliefId, newBelief);\n this.indexBelief(newBelief);\n if (existingBelief !== undefined) {\n this.markSuperseded(existingBelief, newBelief.beliefId, now);\n }\n this.recordRetainUpdate(newBelief, existingBelief !== undefined);\n this.evictIfOverCapacity();\n return Promise.resolve(ok(newBelief));\n } catch (error) {\n const causeError = error instanceof Error ? error : new Error(String(error));\n return Promise.resolve(\n err(new MemoryError('Failed to retain belief', { cause: causeError }))\n );\n }\n }\n\n async retainBatch(\n beliefs: readonly Omit<\n Belief,\n 'beliefId' | 'version' | 'createdAt' | 'updatedAt' | 'superseded'\n >[]\n ): Promise<Result<readonly Belief[], MemoryError>> {\n const results: Belief[] = [];\n for (const belief of beliefs) {\n const result = await this.retainInternal(belief, false);\n if (!result.ok) return result;\n results.push(result.value);\n }\n return ok(results);\n }\n\n // =========================================================================\n // Recall Operations (delegated to belief-memory-recall.ts)\n // =========================================================================\n\n recall(beliefId: string): Promise<Result<Belief | null, MemoryError>> {\n return recallInternal(this.recallStores, beliefId);\n }\n\n query(query: BeliefQuery): Promise<Result<readonly Belief[], MemoryError>> {\n return queryInternal(this.recallStores, query);\n }\n\n recallBySubject(\n subject: string,\n limit?: number\n ): Promise<Result<readonly Belief[], MemoryError>> {\n return recallBySubjectInternal(this.recallStores, subject, limit);\n }\n\n recallCurrent(subject: string, predicate: string): Promise<Result<Belief | null, MemoryError>> {\n return recallCurrentInternal(this.recallStores, subject, predicate);\n }\n\n recallHistory(\n subject: string,\n predicate: string,\n limit?: number\n ): Promise<Result<readonly Belief[], MemoryError>> {\n return recallHistoryInternal(this.recallStores, subject, predicate, limit);\n }\n\n // =========================================================================\n // Reflect Operations (delegated to belief-memory-reflect.ts)\n // =========================================================================\n\n revise(\n beliefId: string,\n updates: Partial<Pick<Belief, 'object' | 'confidence' | 'metadata'>>,\n reason: string\n ): Promise<Result<Belief, MemoryError>> {\n return reviseBeliefInternal(this.reflectStores, { beliefId, updates, reason });\n }\n\n async supersede(\n beliefId: string,\n newBelief: Omit<Belief, 'beliefId' | 'version' | 'createdAt' | 'updatedAt' | 'superseded'>,\n reason: string\n ): Promise<Result<Belief, MemoryError>> {\n try {\n const existing = this.beliefs.get(beliefId);\n if (existing === undefined)\n return err(new MemoryError('Belief not found', { context: { beliefId } }));\n const retainResult = await this.retainInternal(newBelief, true);\n if (!retainResult.ok) return retainResult;\n const now = new Date(getTimeProvider().now());\n const superseded: Belief = {\n ...existing,\n superseded: true,\n supersededBy: retainResult.value.beliefId,\n updatedAt: now,\n };\n this.beliefs.set(beliefId, superseded);\n this.recordUpdate({\n beliefId,\n updateType: BeliefUpdateTypeEnum.SUPERSEDE,\n previousState: { superseded: false },\n newState: { superseded: true, supersededBy: retainResult.value.beliefId },\n reason,\n });\n this.logger.debug('Belief superseded', {\n oldBeliefId: beliefId,\n newBeliefId: retainResult.value.beliefId,\n });\n return ok(retainResult.value);\n } catch (error) {\n return err(\n new MemoryError('Failed to supersede belief', {\n cause: error instanceof Error ? error : new Error(String(error)),\n })\n );\n }\n }\n\n applyHindsight(record: HindsightRecord): Promise<Result<readonly Belief[], MemoryError>> {\n return applyHindsightInternal(this.reflectStores, record);\n }\n\n reinforce(beliefId: string, evidence: string): Promise<Result<Belief, MemoryError>> {\n return adjustConfidenceInternal(this.reflectStores, beliefId, evidence, 'reinforce');\n }\n\n weaken(beliefId: string, evidence: string): Promise<Result<Belief, MemoryError>> {\n return adjustConfidenceInternal(this.reflectStores, beliefId, evidence, 'weaken');\n }\n\n // =========================================================================\n // Counterfactual, Audit, and Stats (delegated to belief-memory-audit.ts)\n // =========================================================================\n\n createCounterfactual(\n hypothesis: string,\n taskContext?: string\n ): Promise<Result<Counterfactual, MemoryError>> {\n return createCounterfactualInternal(this.auditStores, hypothesis, taskContext);\n }\n\n validateCounterfactual(\n counterfactualId: string,\n actualOutcomes: readonly string[]\n ): Promise<Result<Counterfactual, MemoryError>> {\n return validateCounterfactualInternal(this.auditStores, counterfactualId, actualOutcomes);\n }\n\n getCounterfactuals(taskContext: string): Promise<Result<readonly Counterfactual[], MemoryError>> {\n return getCounterfactualsInternal(this.auditStores, taskContext);\n }\n\n getUpdateHistory(beliefId: string): Promise<Result<readonly BeliefUpdate[], MemoryError>> {\n return getUpdateHistoryInternal(this.auditStores, beliefId);\n }\n\n getHindsightRecords(taskId: string): Promise<Result<readonly HindsightRecord[], MemoryError>> {\n return getHindsightRecordsInternal(this.auditStores, taskId);\n }\n\n getStats(): Promise<Result<BeliefMemoryStats, MemoryError>> {\n try {\n return Promise.resolve(ok(computeStatsInternal(this.auditStores)));\n } catch (e) {\n return Promise.resolve(\n err(\n new MemoryError('Failed to get stats', {\n cause: e instanceof Error ? e : new Error(String(e)),\n })\n )\n );\n }\n }\n\n pruneSuperseded(olderThan: Date): Promise<Result<number, MemoryError>> {\n return pruneSupersededInternal(\n {\n ...this.reflectStores,\n subjectIndex: this.subjectIndex,\n predicateIndex: this.predicateIndex,\n domainIndex: this.domainIndex,\n },\n olderThan\n );\n }\n\n /**\n * Forget a belief by ID. Removes the row and all index entries.\n * Returns `ok(true)` if the row existed and was removed; `ok(false)`\n * if it was never present. Used by the Phase 9 cleanup driver to\n * remove rows polluted by the pre-#2755 arXiv feed-fallback bug.\n */\n forget(beliefId: string): Promise<Result<boolean, MemoryError>> {\n try {\n const had = this.beliefs.has(beliefId);\n this.removeBelief(beliefId);\n return Promise.resolve(ok(had));\n } catch (error) {\n const causeError = error instanceof Error ? error : new Error(String(error));\n return Promise.resolve(\n err(new MemoryError('Failed to forget belief', { cause: causeError }))\n );\n }\n }\n\n // =========================================================================\n // Persistence (Issue #714 Phase 3)\n // =========================================================================\n\n /** Export all internal data for disk serialization. */\n exportData(): BeliefMemoryData {\n return {\n beliefs: this.beliefs,\n updates: this.updates,\n counterfactuals: this.counterfactuals,\n hindsightRecords: this.hindsightRecords,\n };\n }\n\n /** Hydrate from a previously loaded snapshot. Rebuilds indexes. */\n hydrate(data: HydratedBeliefData): void {\n this.beliefs.clear();\n this.updates.clear();\n this.counterfactuals.clear();\n this.hindsightRecords.clear();\n this.subjectIndex.clear();\n this.predicateIndex.clear();\n this.domainIndex.clear();\n\n for (const [id, belief] of data.beliefs) {\n this.beliefs.set(id, belief);\n this.indexBelief(belief);\n }\n for (const [id, records] of data.updates) {\n this.updates.set(id, records);\n }\n for (const [id, cf] of data.counterfactuals) {\n this.counterfactuals.set(id, cf);\n }\n for (const [id, records] of data.hindsightRecords) {\n this.hindsightRecords.set(id, records);\n }\n this.logger.info('BeliefMemory hydrated from snapshot', {\n beliefs: this.beliefs.size,\n updates: this.updates.size,\n counterfactuals: this.counterfactuals.size,\n hindsightRecords: this.hindsightRecords.size,\n });\n }\n\n // =========================================================================\n // Private Helpers\n // =========================================================================\n\n /** Validate belief input against schema; returns MemoryError if invalid. */\n private validateBeliefInput(\n belief: Omit<Belief, 'beliefId' | 'version' | 'createdAt' | 'updatedAt' | 'superseded'>\n ): MemoryError | undefined {\n const validation = BeliefSchema.omit({\n beliefId: true,\n version: true,\n createdAt: true,\n updatedAt: true,\n superseded: true,\n }).safeParse(belief);\n if (!validation.success) {\n return new MemoryError('Invalid belief data', {\n context: { errors: validation.error.issues },\n });\n }\n return undefined;\n }\n\n /** Return existing belief if content-identical, otherwise undefined (#1455). */\n private checkDedupMatch(\n existing: Belief | undefined,\n incoming: Omit<Belief, 'beliefId' | 'version' | 'createdAt' | 'updatedAt' | 'superseded'>\n ): Belief | undefined {\n if (existing === undefined || !this.isIdenticalBelief(existing, incoming)) {\n return undefined;\n }\n this.logger.debug('Skipping duplicate belief retain', {\n beliefId: existing.beliefId,\n subject: incoming.subject,\n predicate: incoming.predicate,\n });\n return existing;\n }\n\n /** Check if an existing belief has identical content to a new belief (#1455). */\n private isIdenticalBelief(\n existing: Belief,\n incoming: Omit<Belief, 'beliefId' | 'version' | 'createdAt' | 'updatedAt' | 'superseded'>\n ): boolean {\n return (\n existing.object === incoming.object &&\n existing.confidence === incoming.confidence &&\n existing.sourceType === incoming.sourceType\n );\n }\n\n /** Find a non-superseded belief matching the given (subject, predicate). */\n private findActiveBySubjectPredicate(subject: string, predicate: string): Belief | undefined {\n const subjectIds = this.subjectIndex.get(subject);\n if (subjectIds === undefined) return undefined;\n for (const id of subjectIds) {\n const belief = this.beliefs.get(id);\n if (belief?.predicate === predicate && !belief.superseded) {\n return belief;\n }\n }\n return undefined;\n }\n\n /** Mark an existing belief as superseded by a newer one. */\n private markSuperseded(existing: Belief, newBeliefId: string, now: Date): void {\n const superseded: Belief = {\n ...existing,\n superseded: true,\n supersededBy: newBeliefId,\n updatedAt: now,\n };\n this.beliefs.set(existing.beliefId, superseded);\n this.recordUpdate({\n beliefId: existing.beliefId,\n updateType: BeliefUpdateTypeEnum.SUPERSEDE,\n previousState: { superseded: false },\n newState: { superseded: true, supersededBy: newBeliefId },\n reason: 'Auto-superseded by retain with same subject+predicate',\n });\n }\n\n /** Record the RETAIN update event for a newly created belief. */\n private recordRetainUpdate(newBelief: Belief, wasSuperseding: boolean): void {\n this.recordUpdate({\n beliefId: newBelief.beliefId,\n updateType: BeliefUpdateTypeEnum.RETAIN,\n previousState: {},\n newState: Object.fromEntries(Object.entries(newBelief)),\n reason: wasSuperseding ? 'Belief creation (superseding existing)' : 'Initial belief creation',\n });\n this.logger.debug('Belief retained', {\n beliefId: newBelief.beliefId,\n subject: newBelief.subject,\n supersededExisting: wasSuperseding,\n });\n }\n\n /** Evicts oldest superseded beliefs when total beliefs exceed maxTotalBeliefs. */\n private evictIfOverCapacity(): void {\n const max = this.config.maxTotalBeliefs;\n if (this.beliefs.size <= max) return;\n\n // Collect superseded beliefs sorted by updatedAt (oldest first)\n const superseded: Belief[] = [];\n for (const belief of this.beliefs.values()) {\n if (belief.superseded) superseded.push(belief);\n }\n superseded.sort((a, b) => a.updatedAt.getTime() - b.updatedAt.getTime());\n\n const toEvict = this.beliefs.size - max;\n const evicted = Math.min(toEvict, superseded.length);\n for (let i = 0; i < evicted; i++) {\n const belief = superseded[i];\n if (belief !== undefined) this.removeBelief(belief.beliefId);\n }\n if (evicted > 0) {\n this.logger.debug('Evicted superseded beliefs for capacity', {\n evicted,\n remaining: this.beliefs.size,\n maxTotalBeliefs: max,\n });\n }\n }\n\n /** Removes a belief and cleans up all indexes. */\n private removeBelief(beliefId: string): void {\n const belief = this.beliefs.get(beliefId);\n if (belief === undefined) return;\n this.beliefs.delete(beliefId);\n this.removeFromIndex(this.subjectIndex, belief.subject, beliefId);\n this.removeFromIndex(this.predicateIndex, belief.predicate, beliefId);\n if (belief.domain !== undefined) {\n this.removeFromIndex(this.domainIndex, belief.domain, beliefId);\n }\n }\n\n private removeFromIndex(index: Map<string, Set<string>>, key: string, id: string): void {\n const set = index.get(key);\n if (set === undefined) return;\n set.delete(id);\n if (set.size === 0) index.delete(key);\n }\n\n private indexBelief(belief: Belief): void {\n const subjectSet = this.subjectIndex.get(belief.subject) ?? new Set();\n subjectSet.add(belief.beliefId);\n this.subjectIndex.set(belief.subject, subjectSet);\n const predicateSet = this.predicateIndex.get(belief.predicate) ?? new Set();\n predicateSet.add(belief.beliefId);\n this.predicateIndex.set(belief.predicate, predicateSet);\n if (belief.domain !== undefined) {\n const domainSet = this.domainIndex.get(belief.domain) ?? new Set();\n domainSet.add(belief.beliefId);\n this.domainIndex.set(belief.domain, domainSet);\n }\n }\n\n private recordUpdate(opts: {\n beliefId: string;\n updateType: BeliefUpdate['updateType'];\n previousState: Record<string, unknown>;\n newState: Record<string, unknown>;\n reason: string;\n evidence?: string;\n }): void {\n const history = this.updates.get(opts.beliefId) ?? [];\n history.push(createUpdateRecord(opts));\n this.updates.set(opts.beliefId, history);\n }\n}\n\n// Re-export types and schemas\nexport type {\n Belief,\n BeliefConfidence,\n BeliefMemoryConfig,\n BeliefMemoryStats,\n BeliefQuery,\n BeliefSourceType,\n BeliefUpdate,\n BeliefUpdateType,\n Counterfactual,\n HindsightRecord,\n IHindsightBeliefMemory,\n} from './belief-types.js';\nexport {\n BeliefConfidence as BeliefConfidenceEnum,\n BeliefMemoryConfigSchema,\n BeliefQuerySchema,\n BeliefSchema,\n BeliefSourceType as BeliefSourceTypeEnum,\n BeliefUpdateType as BeliefUpdateTypeEnum,\n DEFAULT_BELIEF_CONFIG,\n} from './belief-types.js';\n","/**\n * Phase 9 of #2766 — one-shot cleanup script for belief-backend rows\n * polluted by the #2719-era arXiv feed-fallback bug.\n *\n * Pre-#2755 the `extractEntryXml` helper fell back to the feed-level\n * `<title>` when an arXiv query returned no entries. The feed title for\n * a no-results query is literally `arXiv Query: search_query=...`, which\n * then got persisted as a \"belief\" with the bogus title as the subject.\n * The feed-fallback bug was fixed in #2755, but pre-fix rows still live\n * in users' belief stores. This module flags + removes them.\n *\n * Idempotent: a marker file under `<nexusDataDir>/memory/` records\n * completion; re-running after a successful pass is a no-op.\n *\n * @module context/belief-cleanup\n */\n\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';\nimport { dirname, join } from 'node:path';\nimport type { Belief } from './belief-core-types.js';\nimport { nexusDataPath } from '../config/nexus-data-dir.js';\n\n/** Regex patterns that identify a polluted belief row. */\nconst POLLUTED_PATTERNS: readonly RegExp[] = [\n /arXiv Query:\\s*search_query=/i,\n // `id_list=...max_results=` — the no-results feed-fallback URL format.\n // Allow `&` separators between params; `[\\s\\S]` keeps it permissive but\n // capped to 200 chars so it won't false-positive on long unrelated text.\n /id_list=[\\s\\S]{0,200}?max_results=/i,\n];\n\n/** Marker file name used to skip re-runs of a successful cleanup. */\nexport const BELIEF_CLEANUP_MARKER = '.belief-cleanup-done';\n\n/** Decision for a single belief: keep or drop. */\nexport interface BeliefCleanupDecision {\n readonly belief: Belief;\n readonly polluted: boolean;\n readonly matchedPattern?: string;\n}\n\n/** Summary returned by `runBeliefCleanup`. */\nexport interface BeliefCleanupResult {\n readonly scanned: number;\n readonly removed: number;\n readonly kept: number;\n readonly samples: readonly string[];\n readonly skipped: boolean;\n readonly markerPath: string;\n}\n\n/** Inspect a single belief; return a decision. */\nexport function classifyBelief(belief: Belief): BeliefCleanupDecision {\n const haystacks = [belief.subject, belief.predicate, belief.object].filter(\n (s): s is string => typeof s === 'string' && s.length > 0\n );\n for (const pattern of POLLUTED_PATTERNS) {\n for (const text of haystacks) {\n if (pattern.test(text)) {\n return { belief, polluted: true, matchedPattern: pattern.source };\n }\n }\n }\n return { belief, polluted: false };\n}\n\n/**\n * Run cleanup against a provided beliefs array. Returns the decisions\n * (caller is responsible for actually removing the polluted rows from\n * the underlying store). This separation keeps the function pure and\n * testable; the storage-aware wrapper is below.\n */\nexport function classifyBeliefs(beliefs: readonly Belief[]): readonly BeliefCleanupDecision[] {\n return beliefs.map(classifyBelief);\n}\n\n/**\n * Storage-aware cleanup driver. Reads beliefs via the provided\n * `loadBeliefs` callback, identifies polluted rows, removes them via\n * `deleteBelief`, and writes a marker file so subsequent runs no-op.\n *\n * Tests inject the callbacks with in-memory stores; production wires\n * them to `HindsightBeliefMemory.query()` + `.forget()` (or the persisted\n * snapshot at `<nexusDataDir>/memory/belief-snapshot.json`).\n *\n * Callbacks are async-only: every real implementation is async (the\n * belief store returns `Promise<Result<...>>`), and tests can wrap\n * sync data with `Promise.resolve`.\n */\nexport interface RunBeliefCleanupOptions {\n readonly loadBeliefs: () => Promise<readonly Belief[]>;\n readonly deleteBelief: (id: string) => Promise<void>;\n /** Directory to place the `.belief-cleanup-done` marker. */\n readonly markerDir?: string;\n /** Skip the marker check (force re-run). Tests only. */\n readonly force?: boolean;\n}\n\nexport async function runBeliefCleanup(\n options: RunBeliefCleanupOptions\n): Promise<BeliefCleanupResult> {\n const markerDir = options.markerDir ?? nexusDataPath('memory');\n const markerPath = join(markerDir, BELIEF_CLEANUP_MARKER);\n\n if (options.force !== true && existsSync(markerPath)) {\n return {\n scanned: 0,\n removed: 0,\n kept: 0,\n samples: [],\n skipped: true,\n markerPath,\n };\n }\n\n const beliefs = await options.loadBeliefs();\n const decisions = classifyBeliefs(beliefs);\n const polluted = decisions.filter((d) => d.polluted);\n const samples = polluted.slice(0, 3).map((d) => d.belief.subject);\n\n for (const d of polluted) {\n await options.deleteBelief(d.belief.beliefId);\n }\n\n mkdirSync(dirname(markerPath), { recursive: true });\n writeFileSync(\n markerPath,\n JSON.stringify(\n {\n completedAt: new Date().toISOString(),\n scanned: beliefs.length,\n removed: polluted.length,\n samples,\n },\n null,\n 2\n ),\n 'utf-8'\n );\n\n return {\n scanned: beliefs.length,\n removed: polluted.length,\n kept: beliefs.length - polluted.length,\n samples,\n skipped: false,\n markerPath,\n };\n}\n\n/** Read an existing marker file, if any. Useful for status displays. */\nexport function readBeliefCleanupMarker(markerDir: string = nexusDataPath('memory')): unknown {\n const path = join(markerDir, BELIEF_CLEANUP_MARKER);\n if (!existsSync(path)) return null;\n try {\n return JSON.parse(readFileSync(path, 'utf-8')) as unknown;\n } catch {\n return null;\n }\n}\n","/**\n * nexus-agents/context - Hybrid Memory Backend\n *\n * Implements hybrid memory storage using SQLite for fast retrieval\n * and full-text search, with Markdown export for human-readable\n * high-importance memories.\n *\n * @module context/memory-backend\n */\n\nimport { z } from 'zod';\nimport type { Result } from '../core/result.js';\nimport { ok, err } from '../core/result.js';\nimport { getTimeProvider, formatZodError } from '../core/index.js';\nimport { ValidationError } from '../core/errors.js';\nimport type { ILogger } from '../core/logger.js';\nimport { createLogger } from '../core/logger.js';\nimport {\n type HybridMemoryConfig,\n type IMemoryBackend,\n type ISQLiteDatabase,\n type MemoryEntry,\n type MemoryMetadata,\n type MemoryRow,\n HybridMemoryConfigSchema,\n MemoryError,\n MemoryImportance,\n MemoryMetadataSchema,\n} from './memory-backend-types.js';\nimport { MemoryMarkdownHelper } from './memory-markdown.js';\nimport {\n sanitizeFtsQuery,\n cleanupExpiredEntries,\n countMemories,\n expireAllEntries,\n pruneOldEntries,\n} from './memory-operations.js';\n\n// Re-export types for convenience\nexport {\n type HybridMemoryConfig,\n type IMemoryBackend,\n type ISQLiteDatabase,\n type ISQLiteStatement,\n type MemoryEntry,\n type MemoryMetadata,\n type MemoryRow,\n HybridMemoryConfigSchema,\n MemoryEntrySchema,\n MemoryError,\n MemoryImportance,\n MemoryImportanceSchema,\n MemoryMetadataSchema,\n} from './memory-backend-types.js';\n\n/**\n * Hybrid memory backend using SQLite for storage and Markdown for export.\n */\nexport class HybridMemoryBackend implements IMemoryBackend {\n private readonly dbPath: string;\n private readonly logger: ILogger;\n private readonly autoExpire: boolean;\n private readonly markdown: MemoryMarkdownHelper;\n private db: ISQLiteDatabase | null = null;\n private initialized = false;\n private initPromise: Promise<Result<void, MemoryError>> | undefined;\n\n constructor(config: HybridMemoryConfig) {\n const validation = HybridMemoryConfigSchema.safeParse(config);\n if (!validation.success) {\n throw new ValidationError(\n `Invalid HybridMemoryBackend config: ${formatZodError(validation.error)}`,\n {\n context: { config, validationErrors: validation.error.issues },\n }\n );\n }\n\n this.dbPath = config.dbPath;\n this.logger = config.logger ?? createLogger({ component: 'HybridMemoryBackend' });\n this.autoExpire = config.autoExpire ?? true;\n this.markdown = new MemoryMarkdownHelper(config.markdownDir, this.logger);\n }\n\n initializeWithDatabase(database: ISQLiteDatabase): void {\n this.db = database;\n this.createTables();\n this.markdown.ensureDir();\n this.initialized = true;\n this.logger.info('HybridMemoryBackend initialized', { dbPath: this.dbPath });\n }\n\n async initialize(): Promise<Result<void, MemoryError>> {\n if (this.initialized) return ok(undefined);\n this.initPromise ??= this.doInitialize().finally(() => {\n this.initPromise = undefined;\n });\n return this.initPromise;\n }\n\n private async doInitialize(): Promise<Result<void, MemoryError>> {\n try {\n const betterSqlite3Module = await import('better-sqlite3').catch((cause: unknown) => {\n this.logger.debug('better-sqlite3 import failed', { error: String(cause) });\n return null;\n });\n if (betterSqlite3Module === null) {\n return err(\n new MemoryError('better-sqlite3 not installed. Install: npm install better-sqlite3', {\n context: { dbPath: this.dbPath },\n })\n );\n }\n\n const Database = betterSqlite3Module.default;\n this.db = new Database(this.dbPath);\n this.createTables();\n this.markdown.ensureDir();\n this.initialized = true;\n this.logger.info('HybridMemoryBackend initialized', { dbPath: this.dbPath });\n return ok(undefined);\n } catch (error) {\n const causeError = error instanceof Error ? error : new Error(String(error));\n this.logger.error('Failed to initialize HybridMemoryBackend', causeError);\n return err(\n new MemoryError('Failed to initialize memory backend', {\n cause: causeError,\n context: { dbPath: this.dbPath },\n })\n );\n }\n }\n\n private createTables(): void {\n const database = this.getDatabase();\n database.exec(`\n CREATE TABLE IF NOT EXISTS memories (\n key TEXT PRIMARY KEY, value TEXT NOT NULL, metadata TEXT NOT NULL,\n created_at INTEGER NOT NULL, accessed_at INTEGER NOT NULL, expires_at INTEGER\n )\n `);\n database.exec(`\n CREATE VIRTUAL TABLE IF NOT EXISTS memories_fts USING fts5(\n key, value, tags, content='memories', content_rowid='rowid'\n )\n `);\n database.exec(`\n CREATE TRIGGER IF NOT EXISTS memories_ai AFTER INSERT ON memories BEGIN\n INSERT INTO memories_fts(rowid, key, value, tags)\n SELECT rowid, NEW.key, NEW.value, json_extract(NEW.metadata, '$.tags') FROM memories WHERE key = NEW.key;\n END\n `);\n database.exec(`\n CREATE TRIGGER IF NOT EXISTS memories_ad AFTER DELETE ON memories BEGIN\n INSERT INTO memories_fts(memories_fts, rowid, key, value, tags)\n VALUES('delete', OLD.rowid, OLD.key, OLD.value, json_extract(OLD.metadata, '$.tags'));\n END\n `);\n database.exec(`\n CREATE TRIGGER IF NOT EXISTS memories_au AFTER UPDATE ON memories BEGIN\n INSERT INTO memories_fts(memories_fts, rowid, key, value, tags)\n VALUES('delete', OLD.rowid, OLD.key, OLD.value, json_extract(OLD.metadata, '$.tags'));\n INSERT INTO memories_fts(rowid, key, value, tags)\n SELECT rowid, NEW.key, NEW.value, json_extract(NEW.metadata, '$.tags') FROM memories WHERE key = NEW.key;\n END\n `);\n database.exec(\n `CREATE INDEX IF NOT EXISTS idx_memories_expires_at ON memories(expires_at) WHERE expires_at IS NOT NULL`\n );\n database.exec(`CREATE INDEX IF NOT EXISTS idx_memories_created_at ON memories(created_at)`);\n this.logger.debug('Database tables created');\n }\n\n private getDatabase(): ISQLiteDatabase {\n if (this.db === null) throw new MemoryError('Database not initialized');\n return this.db;\n }\n\n private ensureInitialized(): void {\n if (!this.initialized || this.db === null) {\n throw new MemoryError('HybridMemoryBackend not initialized. Call initialize() first.');\n }\n }\n\n async store(\n key: string,\n value: unknown,\n metadata: MemoryMetadata\n ): Promise<Result<void, MemoryError>> {\n try {\n this.ensureInitialized();\n const keyValidation = z.string().min(1).safeParse(key);\n if (!keyValidation.success)\n return err(new MemoryError('Invalid key: must be non-empty string', { context: { key } }));\n\n const metadataValidation = MemoryMetadataSchema.safeParse(metadata);\n if (!metadataValidation.success)\n return err(\n new MemoryError('Invalid metadata', {\n context: { metadata, errors: metadataValidation.error.issues },\n })\n );\n\n const now = getTimeProvider().now();\n const expiresAt = metadata.ttl !== undefined ? now + metadata.ttl : null;\n const database = this.getDatabase();\n\n const stmt = database.prepare<MemoryRow>(\n `INSERT OR REPLACE INTO memories (key, value, metadata, created_at, accessed_at, expires_at) VALUES (?, ?, ?, ?, ?, ?)`\n );\n stmt.run(key, JSON.stringify(value), JSON.stringify(metadata), now, now, expiresAt);\n\n this.logger.debug('Stored memory', { key, importance: metadata.importance });\n if (metadata.importance === MemoryImportance.HIGH)\n await this.markdown.write(key, value, metadata, new Date(now));\n\n return ok(undefined);\n } catch (error) {\n const causeError = error instanceof Error ? error : new Error(String(error));\n this.logger.error('Failed to store memory', causeError, { key });\n return err(\n new MemoryError('Failed to store memory', { cause: causeError, context: { key } })\n );\n }\n }\n\n retrieve(key: string): Promise<Result<unknown, MemoryError>> {\n try {\n this.ensureInitialized();\n const database = this.getDatabase();\n const stmt = database.prepare<MemoryRow>(\n `SELECT key, value, metadata, created_at, accessed_at, expires_at FROM memories WHERE key = ?`\n );\n const row = stmt.get(key);\n\n if (row === undefined) return Promise.resolve(ok(null));\n if (this.autoExpire && row.expires_at !== null && row.expires_at < getTimeProvider().now()) {\n database.prepare('DELETE FROM memories WHERE key = ?').run(key);\n this.logger.debug('Auto-expired memory', { key });\n return Promise.resolve(ok(null));\n }\n database\n .prepare('UPDATE memories SET accessed_at = ? WHERE key = ?')\n .run(getTimeProvider().now(), key);\n return Promise.resolve(ok(JSON.parse(row.value) as unknown));\n } catch (error) {\n const causeError = error instanceof Error ? error : new Error(String(error));\n this.logger.error('Failed to retrieve memory', causeError, { key });\n return Promise.resolve(\n err(new MemoryError('Failed to retrieve memory', { cause: causeError, context: { key } }))\n );\n }\n }\n\n search(query: string, limit: number): Promise<Result<MemoryEntry[], MemoryError>> {\n try {\n this.ensureInitialized();\n if (limit <= 0 || limit > 1000)\n return Promise.resolve(\n err(new MemoryError('Invalid limit: must be between 1 and 1000', { context: { limit } }))\n );\n\n const sanitizedQuery = sanitizeFtsQuery(query);\n if (sanitizedQuery.length === 0) return Promise.resolve(ok([]));\n\n const database = this.getDatabase();\n const stmt = database.prepare<MemoryRow>(`\n SELECT m.key, m.value, m.metadata, m.created_at, m.accessed_at, m.expires_at\n FROM memories m INNER JOIN memories_fts fts ON m.rowid = fts.rowid\n WHERE memories_fts MATCH ? ORDER BY rank LIMIT ?\n `);\n const rows = stmt.all(sanitizedQuery, limit);\n const { entries } = cleanupExpiredEntries(rows, database, this.autoExpire, this.logger);\n return Promise.resolve(ok(entries));\n } catch (error) {\n const causeError = error instanceof Error ? error : new Error(String(error));\n this.logger.error('Failed to search memories', causeError, { query });\n return Promise.resolve(\n err(\n new MemoryError('Failed to search memories', {\n cause: causeError,\n context: { query, limit },\n })\n )\n );\n }\n }\n\n prune(olderThan: Date): Promise<Result<number, MemoryError>> {\n this.ensureInitialized();\n return Promise.resolve(pruneOldEntries(this.getDatabase(), olderThan, this.logger));\n }\n\n expireAll(): Promise<Result<number, MemoryError>> {\n this.ensureInitialized();\n return Promise.resolve(expireAllEntries(this.getDatabase(), this.logger));\n }\n\n delete(key: string): Promise<Result<boolean, MemoryError>> {\n try {\n this.ensureInitialized();\n const result = this.getDatabase().prepare('DELETE FROM memories WHERE key = ?').run(key);\n if (result.changes > 0) {\n this.markdown.delete(key);\n this.logger.debug('Deleted memory', { key });\n return Promise.resolve(ok(true));\n }\n return Promise.resolve(ok(false));\n } catch (error) {\n const causeError = error instanceof Error ? error : new Error(String(error));\n this.logger.error('Failed to delete memory', causeError, { key });\n return Promise.resolve(\n err(new MemoryError('Failed to delete memory', { cause: causeError, context: { key } }))\n );\n }\n }\n\n getAll(limit = 100): Promise<Result<MemoryEntry[], MemoryError>> {\n try {\n this.ensureInitialized();\n const database = this.getDatabase();\n const rows = database\n .prepare<MemoryRow>(\n `SELECT key, value, metadata, created_at, accessed_at, expires_at FROM memories ORDER BY accessed_at DESC LIMIT ?`\n )\n .all(limit);\n const { entries } = cleanupExpiredEntries(rows, database, this.autoExpire, this.logger);\n return Promise.resolve(ok(entries));\n } catch (error) {\n const causeError = error instanceof Error ? error : new Error(String(error));\n this.logger.error('Failed to get all memories', causeError);\n return Promise.resolve(\n err(new MemoryError('Failed to get all memories', { cause: causeError }))\n );\n }\n }\n\n count(): Promise<Result<number, MemoryError>> {\n this.ensureInitialized();\n return Promise.resolve(countMemories(this.getDatabase()));\n }\n\n close(): void {\n if (this.db !== null) {\n this.db.close();\n this.db = null;\n this.initialized = false;\n this.logger.info('HybridMemoryBackend closed');\n }\n }\n}\n","/**\n * nexus-agents/context - Memory Markdown Helper\n *\n * Handles Markdown file export for high-importance memories.\n *\n * @module context/memory-markdown\n */\n\nimport * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport type { ILogger } from '../core/logger.js';\nimport type { MemoryMetadata } from './memory-backend-types.js';\n\n/**\n * Helper class for Markdown memory file operations.\n */\nexport class MemoryMarkdownHelper {\n constructor(\n private readonly markdownDir: string,\n private readonly logger: ILogger\n ) {}\n\n /**\n * Ensure the Markdown export directory exists.\n */\n ensureDir(): void {\n if (!fs.existsSync(this.markdownDir)) {\n fs.mkdirSync(this.markdownDir, { recursive: true });\n this.logger.debug('Created Markdown directory', { path: this.markdownDir });\n }\n }\n\n /**\n * Write a memory entry to Markdown file.\n */\n async write(\n key: string,\n value: unknown,\n metadata: MemoryMetadata,\n createdAt: Date\n ): Promise<void> {\n const filename = this.keyToFilename(key);\n const filepath = path.join(this.markdownDir, filename);\n\n const content = this.format(key, value, metadata, createdAt);\n\n try {\n await fs.promises.writeFile(filepath, content, 'utf-8');\n this.logger.debug('Wrote Markdown file', { key, filepath });\n } catch (error) {\n this.logger.warn('Failed to write Markdown file', { key, filepath, error });\n // Don't throw - Markdown export is secondary to SQLite storage\n }\n }\n\n /**\n * Delete a Markdown file for a memory.\n */\n delete(key: string): void {\n const filename = this.keyToFilename(key);\n const filepath = path.join(this.markdownDir, filename);\n\n try {\n if (fs.existsSync(filepath)) {\n fs.unlinkSync(filepath);\n this.logger.debug('Deleted Markdown file', { key, filepath });\n }\n } catch (error) {\n this.logger.warn('Failed to delete Markdown file', { key, filepath, error });\n }\n }\n\n /**\n * Convert a memory key to a safe filename.\n */\n private keyToFilename(key: string): string {\n // Replace unsafe characters with underscores\n const safeKey = key\n .replace(/[^a-zA-Z0-9-_]/g, '_')\n .replace(/_+/g, '_')\n .substring(0, 200); // Limit filename length\n\n return `${safeKey}.md`;\n }\n\n /**\n * Format a memory entry as Markdown.\n */\n private format(key: string, value: unknown, metadata: MemoryMetadata, createdAt: Date): string {\n const lines: string[] = [\n `# Memory: ${key}`,\n '',\n '## Metadata',\n '',\n `- **Importance:** ${metadata.importance}`,\n `- **Created:** ${createdAt.toISOString()}`,\n ];\n\n if (metadata.tags !== undefined && metadata.tags.length > 0) {\n lines.push(`- **Tags:** ${metadata.tags.join(', ')}`);\n }\n\n if (metadata.ttl !== undefined) {\n const expiresAt = new Date(createdAt.getTime() + metadata.ttl);\n lines.push(`- **Expires:** ${expiresAt.toISOString()}`);\n }\n\n lines.push('', '## Value', '');\n\n // Format value based on type\n if (typeof value === 'string') {\n lines.push(value);\n } else if (value === null) {\n lines.push('`null`');\n } else if (typeof value === 'object') {\n lines.push('```json', JSON.stringify(value, null, 2), '```');\n } else {\n // For primitives (number, boolean, etc.), convert to string representation\n const stringValue =\n typeof value === 'number' || typeof value === 'boolean'\n ? String(value)\n : JSON.stringify(value);\n lines.push(`\\`${stringValue}\\``);\n }\n\n lines.push('');\n\n return lines.join('\\n');\n }\n}\n","/**\n * nexus-agents/context - Memory Operations\n *\n * Query and mutation operations for the hybrid memory backend.\n *\n * @module context/memory-operations\n */\n\nimport type { Result } from '../core/result.js';\nimport { ok, err } from '../core/result.js';\nimport { getTimeProvider } from '../core/index.js';\nimport type { ILogger } from '../core/logger.js';\nimport type {\n ISQLiteDatabase,\n MemoryEntry,\n MemoryMetadata,\n MemoryRow,\n} from './memory-backend-types.js';\nimport { MemoryError } from './memory-backend-types.js';\n\n/** Safely parse JSON from a DB column, returning null on corrupt data. */\nfunction safeParseJson(raw: string): unknown {\n try {\n return JSON.parse(raw) as unknown;\n } catch {\n return null;\n }\n}\n\n/** Parse metadata JSON or return safe defaults for corrupt rows. */\nfunction parseMetadataOrDefault(raw: string): MemoryMetadata {\n const parsed = safeParseJson(raw);\n if (parsed !== null && typeof parsed === 'object') return parsed as MemoryMetadata;\n return { importance: 'medium' };\n}\n\n/**\n * Converts a database row to a MemoryEntry.\n * Gracefully handles corrupt JSON in DB rows (#1680 quality scan).\n */\nexport function rowToEntry(row: MemoryRow): MemoryEntry {\n return {\n key: row.key,\n value: safeParseJson(row.value),\n metadata: parseMetadataOrDefault(row.metadata),\n createdAt: new Date(row.created_at),\n accessedAt: new Date(row.accessed_at),\n };\n}\n\n/**\n * Sanitizes a query string for FTS5.\n * Removes special FTS5 operators to prevent injection.\n */\nexport function sanitizeFtsQuery(query: string): string {\n return query\n .replace(/[*:^\"(){}[\\]]/g, ' ')\n .replace(/\\bAND\\b/gi, ' ')\n .replace(/\\bOR\\b/gi, ' ')\n .replace(/\\bNOT\\b/gi, ' ')\n .replace(/\\bNEAR\\b/gi, ' ')\n .replace(/\\s+/g, ' ')\n .trim();\n}\n\n/**\n * Cleans up expired entries from the results.\n */\nexport function cleanupExpiredEntries(\n rows: MemoryRow[],\n database: ISQLiteDatabase,\n autoExpire: boolean,\n logger: ILogger\n): { entries: MemoryEntry[]; expiredCount: number } {\n const now = getTimeProvider().now();\n const entries: MemoryEntry[] = [];\n const expiredKeys: string[] = [];\n\n for (const row of rows) {\n if (autoExpire && row.expires_at !== null && row.expires_at < now) {\n expiredKeys.push(row.key);\n continue;\n }\n entries.push(rowToEntry(row));\n }\n\n if (expiredKeys.length > 0) {\n const deleteStmt = database.prepare(\n `DELETE FROM memories WHERE key IN (${expiredKeys.map(() => '?').join(',')})`\n );\n deleteStmt.run(...expiredKeys);\n logger.debug('Auto-expired memories', { count: expiredKeys.length });\n }\n\n return { entries, expiredCount: expiredKeys.length };\n}\n\n/**\n * Executes a search query against FTS5.\n */\nexport function executeSearch(\n database: ISQLiteDatabase,\n sanitizedQuery: string,\n limit: number,\n autoExpire: boolean,\n logger: ILogger\n): Result<MemoryEntry[], MemoryError> {\n try {\n const stmt = database.prepare<MemoryRow>(`\n SELECT m.key, m.value, m.metadata, m.created_at, m.accessed_at, m.expires_at\n FROM memories m\n INNER JOIN memories_fts fts ON m.rowid = fts.rowid\n WHERE memories_fts MATCH ?\n ORDER BY rank\n LIMIT ?\n `);\n\n const rows = stmt.all(sanitizedQuery, limit);\n const { entries } = cleanupExpiredEntries(rows, database, autoExpire, logger);\n\n return ok(entries);\n } catch (error) {\n const causeError = error instanceof Error ? error : new Error(String(error));\n return err(new MemoryError('Failed to execute search', { cause: causeError }));\n }\n}\n\n/**\n * Retrieves all memories with pagination.\n */\nexport function getAllMemories(\n database: ISQLiteDatabase,\n limit: number,\n autoExpire: boolean,\n logger: ILogger\n): Result<MemoryEntry[], MemoryError> {\n try {\n const stmt = database.prepare<MemoryRow>(`\n SELECT key, value, metadata, created_at, accessed_at, expires_at\n FROM memories ORDER BY accessed_at DESC LIMIT ?\n `);\n\n const rows = stmt.all(limit);\n const { entries } = cleanupExpiredEntries(rows, database, autoExpire, logger);\n\n return ok(entries);\n } catch (error) {\n const causeError = error instanceof Error ? error : new Error(String(error));\n return err(new MemoryError('Failed to get all memories', { cause: causeError }));\n }\n}\n\n/**\n * Counts total memories in the database.\n */\nexport function countMemories(database: ISQLiteDatabase): Result<number, MemoryError> {\n try {\n const stmt = database.prepare<{ count: number }>('SELECT COUNT(*) as count FROM memories');\n const row = stmt.get();\n return ok(row?.count ?? 0);\n } catch (error) {\n const causeError = error instanceof Error ? error : new Error(String(error));\n return err(new MemoryError('Failed to count memories', { cause: causeError }));\n }\n}\n\n/**\n * Expires all entries that have passed their TTL.\n */\nexport function expireAllEntries(\n database: ISQLiteDatabase,\n logger: ILogger\n): Result<number, MemoryError> {\n try {\n const stmt = database.prepare(\n 'DELETE FROM memories WHERE expires_at IS NOT NULL AND expires_at < ?'\n );\n const result = stmt.run(getTimeProvider().now());\n logger.info('Expired memories', { count: result.changes });\n return ok(result.changes);\n } catch (error) {\n const causeError = error instanceof Error ? error : new Error(String(error));\n return err(new MemoryError('Failed to expire memories', { cause: causeError }));\n }\n}\n\n/**\n * Prunes entries older than the specified date.\n */\nexport function pruneOldEntries(\n database: ISQLiteDatabase,\n olderThan: Date,\n logger: ILogger\n): Result<number, MemoryError> {\n try {\n const stmt = database.prepare('DELETE FROM memories WHERE created_at < ?');\n const result = stmt.run(olderThan.getTime());\n logger.info('Pruned old memories', {\n olderThan: olderThan.toISOString(),\n count: result.changes,\n });\n return ok(result.changes);\n } catch (error) {\n const causeError = error instanceof Error ? error : new Error(String(error));\n return err(\n new MemoryError('Failed to prune memories', {\n cause: causeError,\n context: { olderThan: olderThan.toISOString() },\n })\n );\n }\n}\n","/**\n * Graph-Based Memory Types\n *\n * Type definitions for graph-structured memory with entity relationships.\n * Implements concepts from arXiv:2308.09687 (MiRIX) for knowledge graphs.\n *\n * @module context/graph-memory-types\n * (Source: Issue #142, arXiv:2308.09687)\n */\n\nimport { z } from 'zod';\nimport type { Result } from '../core/result.js';\nimport type {\n MemoryEntry,\n MemoryMetadata,\n MemoryError,\n IMemoryBackend,\n} from './memory-backend-types.js';\n\n// ============================================================================\n// Relationship Types\n// ============================================================================\n\n/**\n * Types of relationships between memory nodes.\n */\nexport const RelationType = {\n /** General association between memories */\n RELATED_TO: 'related_to',\n /** One memory derived from another */\n DERIVED_FROM: 'derived_from',\n /** Memories that contradict each other */\n CONTRADICTS: 'contradicts',\n /** One memory supersedes another */\n SUPERSEDES: 'supersedes',\n /** Parent-child hierarchy */\n PARENT_OF: 'parent_of',\n /** Memories about the same entity */\n SAME_ENTITY: 'same_entity',\n /** Temporal sequence */\n PRECEDES: 'precedes',\n /** Causal relationship */\n CAUSES: 'causes',\n} as const;\n\nexport type RelationType = (typeof RelationType)[keyof typeof RelationType];\n\n/** Zod schema for RelationType validation. */\nexport const RelationTypeSchema = z.enum([\n 'related_to',\n 'derived_from',\n 'contradicts',\n 'supersedes',\n 'parent_of',\n 'same_entity',\n 'precedes',\n 'causes',\n]);\n\n// ============================================================================\n// Graph Structures\n// ============================================================================\n\n/**\n * A relationship edge between two memory nodes.\n */\nexport interface GraphEdge {\n /** Source node key */\n readonly from: string;\n /** Target node key */\n readonly to: string;\n /** Type of relationship */\n readonly type: RelationType;\n /** Relationship strength/weight (0-1) */\n readonly weight: number;\n /** When the relationship was created */\n readonly createdAt: Date;\n /** Optional metadata about the relationship */\n readonly metadata?: Record<string, unknown>;\n}\n\n/** Zod schema for GraphEdge validation. */\nexport const GraphEdgeSchema = z.object({\n from: z.string().min(1),\n to: z.string().min(1),\n type: RelationTypeSchema,\n weight: z.number().min(0).max(1),\n createdAt: z.date(),\n metadata: z.record(z.string(), z.unknown()).optional(),\n});\n\n/**\n * A memory node with its relationships.\n */\nexport interface GraphNode extends MemoryEntry {\n /** Outgoing edges from this node */\n readonly outEdges: readonly GraphEdge[];\n /** Incoming edges to this node */\n readonly inEdges: readonly GraphEdge[];\n}\n\n/**\n * Options for graph traversal operations.\n */\nexport interface TraversalOptions {\n /** Maximum depth to traverse (default: 2) */\n readonly maxDepth?: number;\n /** Filter by relationship types */\n readonly relationTypes?: readonly RelationType[];\n /** Minimum edge weight to follow (default: 0) */\n readonly minWeight?: number;\n /** Maximum number of results */\n readonly limit?: number;\n /** Whether to include the starting node */\n readonly includeStart?: boolean;\n /** Direction: outgoing, incoming, or both */\n readonly direction?: 'outgoing' | 'incoming' | 'both';\n}\n\n/** Zod schema for TraversalOptions validation. */\nexport const TraversalOptionsSchema = z.object({\n maxDepth: z.number().int().positive().optional(),\n relationTypes: z.array(RelationTypeSchema).optional(),\n minWeight: z.number().min(0).max(1).optional(),\n limit: z.number().int().positive().optional(),\n includeStart: z.boolean().optional(),\n direction: z.enum(['outgoing', 'incoming', 'both']).optional(),\n});\n\n/**\n * Result of a graph traversal with path information.\n */\nexport interface TraversalResult {\n /** The memory entry found */\n readonly entry: MemoryEntry;\n /** Distance from the starting node */\n readonly depth: number;\n /** Path of keys from start to this node */\n readonly path: readonly string[];\n /** Edge that led to this node (if not start) */\n readonly edge?: GraphEdge;\n}\n\n/**\n * Options for adding a relationship.\n */\nexport interface AddRelationshipOptions {\n /** Relationship strength (default: 1.0) */\n readonly weight?: number;\n /** Optional metadata about the relationship */\n readonly metadata?: Record<string, unknown>;\n}\n\n// ============================================================================\n// Graph Memory Interface\n// ============================================================================\n\n/**\n * Extended memory backend with graph-based relationship operations.\n */\nexport interface IGraphMemory extends IMemoryBackend {\n /**\n * Add a relationship between two memory entries.\n * @param from - Source memory key\n * @param to - Target memory key\n * @param type - Type of relationship\n * @param opts - Additional options\n */\n addRelationship(\n from: string,\n to: string,\n type: RelationType,\n opts?: AddRelationshipOptions\n ): Promise<Result<void, MemoryError>>;\n\n /**\n * Remove a relationship between two memory entries.\n * @param from - Source memory key\n * @param to - Target memory key\n * @param type - Optional: specific type to remove (removes all if not specified)\n */\n removeRelationship(\n from: string,\n to: string,\n type?: RelationType\n ): Promise<Result<void, MemoryError>>;\n\n /**\n * Get all relationships for a memory entry.\n * @param key - Memory key\n * @param direction - Which edges to retrieve\n */\n getRelationships(\n key: string,\n direction?: 'outgoing' | 'incoming' | 'both'\n ): Promise<Result<GraphEdge[], MemoryError>>;\n\n /**\n * Traverse the graph from a starting node.\n * @param startKey - Starting memory key\n * @param opts - Traversal options\n */\n traverse(\n startKey: string,\n opts?: TraversalOptions\n ): Promise<Result<TraversalResult[], MemoryError>>;\n\n /**\n * Find the shortest path between two memories.\n * @param from - Source memory key\n * @param to - Target memory key\n * @param opts - Traversal constraints\n */\n findPath(\n from: string,\n to: string,\n opts?: Pick<TraversalOptions, 'relationTypes' | 'minWeight'>\n ): Promise<Result<string[] | null, MemoryError>>;\n\n /**\n * Get all memories connected to a key within a certain depth.\n * @param key - Central memory key\n * @param depth - Maximum hops (default: 1)\n */\n getNeighbors(key: string, depth?: number): Promise<Result<MemoryEntry[], MemoryError>>;\n\n /**\n * Store a memory with automatic relationship inference.\n * @param key - Memory key\n * @param value - Memory value\n * @param metadata - Memory metadata\n * @param relatedTo - Keys of related memories\n */\n storeWithRelations(\n key: string,\n value: unknown,\n metadata: MemoryMetadata,\n relatedTo?: readonly string[]\n ): Promise<Result<void, MemoryError>>;\n}\n\n// ============================================================================\n// SQLite Row Types\n// ============================================================================\n\n/**\n * Row structure for the graph_edges table.\n */\nexport interface GraphEdgeRow {\n from_key: string;\n to_key: string;\n relation_type: string;\n weight: number;\n created_at: number;\n metadata: string | null;\n}\n\n// ============================================================================\n// Configuration\n// ============================================================================\n\n/**\n * Configuration for GraphMemoryBackend.\n */\nexport interface GraphMemoryConfig {\n /** Path to SQLite database file */\n readonly dbPath: string;\n /** Directory for Markdown exports */\n readonly markdownDir: string;\n /** Default traversal depth (default: 2) */\n readonly defaultTraversalDepth?: number;\n /** Maximum allowed traversal depth (default: 5) */\n readonly maxTraversalDepth?: number;\n /** Whether to auto-expire TTL entries (default: true) */\n readonly autoExpire?: boolean;\n}\n\n/** Zod schema for GraphMemoryConfig validation. */\nexport const GraphMemoryConfigSchema = z.object({\n dbPath: z.string().min(1),\n markdownDir: z.string().min(1),\n defaultTraversalDepth: z.number().int().positive().optional(),\n maxTraversalDepth: z.number().int().positive().optional(),\n autoExpire: z.boolean().optional(),\n});\n\n// ============================================================================\n// Default Configuration\n// ============================================================================\n\n/** Default configuration values. */\nexport const DEFAULT_GRAPH_MEMORY_CONFIG = {\n defaultTraversalDepth: 2,\n maxTraversalDepth: 5,\n autoExpire: true,\n} as const;\n","/**\n * nexus-agents/utils - Memory Database Utilities\n *\n * Shared utility functions for memory database operations.\n * Consolidates duplicate code from multiple memory systems per ADR-0013.\n *\n * Used by:\n * - context/adaptive-memory-helpers.ts\n * - context/graph-memory-helpers.ts\n *\n * @module utils/memory-db-utils\n * @see docs/adr/0013-memory-helpers-consolidation.md\n */\n\nimport {\n type MemoryEntry,\n type MemoryRow,\n type ISQLiteDatabase,\n MemoryImportance,\n} from '../context/memory-backend-types.js';\nimport { createLogger } from '../core/index.js';\n\nconst logger = createLogger({ component: 'MemoryDbUtils' });\n\n// ============================================================================\n// Row Conversion\n// ============================================================================\n\n/**\n * Safely parse JSON, returning fallback on corrupt data instead of throwing.\n */\nfunction safeJsonParse<T>(json: string, fallback: T, context: string): T {\n try {\n return JSON.parse(json) as T;\n } catch {\n logger.warn('Corrupt JSON in memory database row', { context });\n return fallback;\n }\n}\n\n/**\n * Convert a database MemoryRow to a MemoryEntry.\n *\n * Parses JSON fields (value, metadata) and converts timestamps to Date objects.\n * Handles corrupt JSON gracefully by returning safe defaults.\n *\n * @param row - Database row from memories table\n * @returns Parsed MemoryEntry object\n */\nexport function memoryRowToEntry(row: MemoryRow): MemoryEntry {\n return {\n key: row.key,\n value: safeJsonParse<unknown>(row.value, row.value, `value for key=\"${row.key}\"`),\n metadata: safeJsonParse<MemoryEntry['metadata']>(\n row.metadata,\n { importance: MemoryImportance.MEDIUM },\n `metadata for key=\"${row.key}\"`\n ),\n createdAt: new Date(row.created_at),\n accessedAt: new Date(row.accessed_at),\n };\n}\n\n// ============================================================================\n// Existence Check\n// ============================================================================\n\n/**\n * Check if a memory key exists in the database.\n *\n * @param db - SQLite database instance\n * @param key - Memory key to check\n * @returns true if key exists, false otherwise\n */\nexport function memoryExists(db: ISQLiteDatabase, key: string): boolean {\n const stmt = db.prepare<{ count: number }>(\n 'SELECT COUNT(*) as count FROM memories WHERE key = ?'\n );\n const result = stmt.get(key);\n return result !== undefined && result.count > 0;\n}\n\n// ============================================================================\n// Memory Retrieval\n// ============================================================================\n\n/**\n * Get a memory entry by key.\n *\n * @param db - SQLite database instance\n * @param key - Memory key to retrieve\n * @returns MemoryEntry if found, undefined otherwise\n */\nexport function getMemoryEntry(db: ISQLiteDatabase, key: string): MemoryEntry | undefined {\n const stmt = db.prepare<MemoryRow>('SELECT * FROM memories WHERE key = ?');\n const row = stmt.get(key);\n return row !== undefined ? memoryRowToEntry(row) : undefined;\n}\n\n/**\n * Get a single memory row by key.\n *\n * @param db - SQLite database instance\n * @param key - Memory key to retrieve\n * @returns MemoryRow if found, undefined otherwise\n */\nexport function getMemoryRow(db: ISQLiteDatabase, key: string): MemoryRow | undefined {\n const stmt = db.prepare<MemoryRow>('SELECT * FROM memories WHERE key = ?');\n return stmt.get(key);\n}\n\n/**\n * Get all memory rows from the database with limit.\n *\n * @param db - SQLite database instance\n * @param limit - Maximum number of rows to return\n * @returns Array of MemoryRow objects\n */\nexport function getAllMemoryRows(db: ISQLiteDatabase, limit: number): MemoryRow[] {\n const stmt = db.prepare<MemoryRow>('SELECT * FROM memories ORDER BY accessed_at DESC LIMIT ?');\n return stmt.all(limit);\n}\n","/**\n * Graph Memory Helpers\n *\n * Helper functions for graph memory operations including SQL queries\n * and traversal algorithms.\n *\n * @module context/graph-memory-helpers\n * (Source: Issue #142, arXiv:2308.09687)\n */\n\nimport type {\n GraphEdge,\n GraphEdgeRow,\n TraversalOptions,\n TraversalResult,\n RelationType,\n} from './graph-memory-types.js';\nimport { DEFAULT_GRAPH_MEMORY_CONFIG } from './graph-memory-types.js';\nimport type { MemoryEntry, ISQLiteDatabase } from './memory-backend-types.js';\n// Shared utilities per ADR-0013\nimport { getMemoryEntry as sharedGetMemoryEntry } from '../utils/memory-db-utils.js';\n\n// ============================================================================\n// SQL Schema\n// ============================================================================\n\n/** SQL to create the graph_edges table. */\nexport const CREATE_EDGES_TABLE_SQL = `\n CREATE TABLE IF NOT EXISTS graph_edges (\n from_key TEXT NOT NULL,\n to_key TEXT NOT NULL,\n relation_type TEXT NOT NULL,\n weight REAL NOT NULL DEFAULT 1.0,\n created_at INTEGER NOT NULL,\n metadata TEXT,\n PRIMARY KEY (from_key, to_key, relation_type),\n FOREIGN KEY (from_key) REFERENCES memories(key) ON DELETE CASCADE,\n FOREIGN KEY (to_key) REFERENCES memories(key) ON DELETE CASCADE\n )\n`;\n\n/** SQL to create index on from_key. */\nexport const CREATE_FROM_INDEX_SQL = `\n CREATE INDEX IF NOT EXISTS idx_edges_from ON graph_edges(from_key)\n`;\n\n/** SQL to create index on to_key. */\nexport const CREATE_TO_INDEX_SQL = `\n CREATE INDEX IF NOT EXISTS idx_edges_to ON graph_edges(to_key)\n`;\n\n// ============================================================================\n// Row Conversion\n// ============================================================================\n\n/** Convert a database row to a GraphEdge. */\nexport function rowToEdge(row: GraphEdgeRow): GraphEdge {\n const base = {\n from: row.from_key,\n to: row.to_key,\n type: row.relation_type as RelationType,\n weight: row.weight,\n createdAt: new Date(row.created_at),\n };\n if (row.metadata !== null) {\n try {\n return { ...base, metadata: JSON.parse(row.metadata) as Record<string, unknown> };\n } catch {\n return { ...base, metadata: {} };\n }\n }\n return base;\n}\n\n// ============================================================================\n// Traversal Options\n// ============================================================================\n\n/** Resolved traversal options with defaults applied. */\nexport interface ResolvedTraversalOptions {\n readonly maxDepth: number;\n readonly relationTypes: readonly RelationType[] | undefined;\n readonly minWeight: number;\n readonly limit: number;\n readonly includeStart: boolean;\n readonly direction: 'outgoing' | 'incoming' | 'both';\n}\n\n/** Default values for traversal options. */\nconst TRAVERSAL_DEFAULTS: Omit<ResolvedTraversalOptions, 'relationTypes'> = {\n maxDepth: DEFAULT_GRAPH_MEMORY_CONFIG.defaultTraversalDepth,\n minWeight: 0,\n limit: 100,\n includeStart: false,\n direction: 'both',\n};\n\n/** Resolve traversal options with defaults. */\nexport function resolveTraversalOptions(opts?: TraversalOptions): ResolvedTraversalOptions {\n if (opts === undefined) return { ...TRAVERSAL_DEFAULTS, relationTypes: undefined };\n return {\n maxDepth: opts.maxDepth ?? TRAVERSAL_DEFAULTS.maxDepth,\n relationTypes: opts.relationTypes,\n minWeight: opts.minWeight ?? TRAVERSAL_DEFAULTS.minWeight,\n limit: opts.limit ?? TRAVERSAL_DEFAULTS.limit,\n includeStart: opts.includeStart ?? TRAVERSAL_DEFAULTS.includeStart,\n direction: opts.direction ?? TRAVERSAL_DEFAULTS.direction,\n };\n}\n\n// ============================================================================\n// Edge Queries\n// ============================================================================\n\n/** Query configuration for edge retrieval. */\nexport interface EdgeQueryConfig {\n readonly db: ISQLiteDatabase;\n readonly key: string;\n readonly direction: 'outgoing' | 'incoming' | 'both';\n}\n\n/** Get edges for a key based on direction. */\nexport function getEdgesForKey(config: EdgeQueryConfig): GraphEdge[] {\n const { db, key, direction } = config;\n const edges: GraphEdge[] = [];\n\n if (direction === 'outgoing' || direction === 'both') {\n const stmt = db.prepare<GraphEdgeRow>('SELECT * FROM graph_edges WHERE from_key = ?');\n const rows = stmt.all(key);\n edges.push(...rows.map(rowToEdge));\n }\n\n if (direction === 'incoming' || direction === 'both') {\n const stmt = db.prepare<GraphEdgeRow>('SELECT * FROM graph_edges WHERE to_key = ?');\n const rows = stmt.all(key);\n edges.push(...rows.map(rowToEdge));\n }\n\n return edges;\n}\n\n// ============================================================================\n// BFS Traversal\n// ============================================================================\n\n/** State for BFS traversal. */\ninterface BFSState {\n readonly visited: Set<string>;\n readonly queue: Array<{ key: string; depth: number; path: string[]; edge?: GraphEdge }>;\n readonly results: TraversalResult[];\n}\n\n/** Configuration for BFS traversal. */\nexport interface BFSConfig {\n readonly db: ISQLiteDatabase;\n readonly startKey: string;\n readonly opts: ResolvedTraversalOptions;\n}\n\n/** Check if an edge passes the filter criteria. */\nexport function edgePassesFilter(edge: GraphEdge, opts: ResolvedTraversalOptions): boolean {\n if (edge.weight < opts.minWeight) return false;\n if (opts.relationTypes !== undefined && !opts.relationTypes.includes(edge.type)) return false;\n return true;\n}\n\n/** Get next keys to visit from current edges. */\nexport function getNextKeys(\n currentKey: string,\n edges: GraphEdge[],\n opts: ResolvedTraversalOptions\n): Array<{ key: string; edge: GraphEdge }> {\n const next: Array<{ key: string; edge: GraphEdge }> = [];\n\n for (const edge of edges) {\n if (!edgePassesFilter(edge, opts)) continue;\n\n if (opts.direction !== 'incoming' && edge.from === currentKey) {\n next.push({ key: edge.to, edge });\n }\n if (opts.direction !== 'outgoing' && edge.to === currentKey) {\n next.push({ key: edge.from, edge });\n }\n }\n\n return next;\n}\n\n/** Build a TraversalResult, conditionally including the edge if present. */\nfunction buildTraversalResult(\n entry: MemoryEntry,\n depth: number,\n path: readonly string[],\n edge: GraphEdge | undefined\n): TraversalResult {\n if (edge !== undefined) {\n return { entry, depth, path, edge };\n }\n return { entry, depth, path };\n}\n\n/** Perform BFS traversal. */\nexport function bfsTraverse(config: BFSConfig): TraversalResult[] {\n const { db, startKey, opts } = config;\n\n const state: BFSState = {\n visited: new Set([startKey]),\n queue: [{ key: startKey, depth: 0, path: [startKey] }],\n results: [],\n };\n\n while (state.queue.length > 0 && state.results.length < opts.limit) {\n const current = state.queue.shift();\n if (current === undefined) break;\n\n if (current.depth > 0 || opts.includeStart) {\n const entry = sharedGetMemoryEntry(db, current.key);\n if (entry !== undefined) {\n state.results.push(buildTraversalResult(entry, current.depth, current.path, current.edge));\n }\n }\n\n if (current.depth >= opts.maxDepth) continue;\n\n const edges = getEdgesForKey({ db, key: current.key, direction: opts.direction });\n const nextKeys = getNextKeys(current.key, edges, opts);\n\n for (const { key: nextKey, edge } of nextKeys) {\n if (!state.visited.has(nextKey)) {\n state.visited.add(nextKey);\n state.queue.push({\n key: nextKey,\n depth: current.depth + 1,\n path: [...current.path, nextKey],\n edge,\n });\n }\n }\n }\n\n return state.results;\n}\n\n// ============================================================================\n// Path Finding (BFS-based shortest path)\n// ============================================================================\n\n/** Find shortest path between two keys. */\nexport function findShortestPath(\n db: ISQLiteDatabase,\n from: string,\n to: string,\n opts: Pick<ResolvedTraversalOptions, 'relationTypes' | 'minWeight'>\n): string[] | null {\n const visited = new Set<string>([from]);\n const queue: Array<{ key: string; path: string[] }> = [{ key: from, path: [from] }];\n const resolvedOpts = { ...resolveTraversalOptions(), ...opts, maxDepth: 10 };\n\n while (queue.length > 0) {\n const current = queue.shift();\n if (current === undefined) break;\n\n if (current.key === to) return current.path;\n\n const edges = getEdgesForKey({ db, key: current.key, direction: 'both' });\n const nextKeys = getNextKeys(current.key, edges, resolvedOpts);\n\n for (const { key: nextKey } of nextKeys) {\n if (!visited.has(nextKey)) {\n visited.add(nextKey);\n queue.push({ key: nextKey, path: [...current.path, nextKey] });\n }\n }\n }\n\n return null;\n}\n","/**\n * Graph-Based Memory Backend\n *\n * Implements graph-structured memory with entity relationships.\n * Extends HybridMemoryBackend with graph operations for traversal\n * and relationship management.\n *\n * @module context/graph-memory\n * (Source: Issue #142, arXiv:2308.09687)\n */\n\nimport type { Result } from '../core/result.js';\nimport { ok, err } from '../core/result.js';\nimport { getTimeProvider } from '../core/index.js';\nimport type { ILogger } from '../core/logger.js';\nimport { createLogger } from '../core/logger.js';\nimport type { MemoryEntry, MemoryMetadata, ISQLiteDatabase } from './memory-backend-types.js';\nimport { MemoryError } from './memory-backend-types.js';\nimport { HybridMemoryBackend } from './memory-backend.js';\nimport type {\n IGraphMemory,\n GraphEdge,\n GraphMemoryConfig,\n TraversalOptions,\n TraversalResult,\n RelationType,\n AddRelationshipOptions,\n} from './graph-memory-types.js';\nimport {\n GraphMemoryConfigSchema,\n DEFAULT_GRAPH_MEMORY_CONFIG,\n RelationType as RelationTypes,\n} from './graph-memory-types.js';\nimport {\n CREATE_EDGES_TABLE_SQL,\n CREATE_FROM_INDEX_SQL,\n CREATE_TO_INDEX_SQL,\n resolveTraversalOptions,\n getEdgesForKey,\n bfsTraverse,\n findShortestPath,\n} from './graph-memory-helpers.js';\n// Shared utilities per ADR-0013\nimport { memoryExists } from '../utils/memory-db-utils.js';\n\n// Re-export types\nexport type {\n IGraphMemory,\n GraphEdge,\n GraphMemoryConfig,\n TraversalOptions,\n TraversalResult,\n RelationType,\n AddRelationshipOptions,\n} from './graph-memory-types.js';\nexport { RelationType as RelationTypes } from './graph-memory-types.js';\n\nconst logger = createLogger({ component: 'GraphMemoryBackend' });\n\n/**\n * Graph-based memory backend with relationship traversal.\n */\nexport class GraphMemoryBackend implements IGraphMemory {\n private readonly config: GraphMemoryConfig;\n private readonly log: ILogger;\n private readonly base: HybridMemoryBackend;\n private db: ISQLiteDatabase | null = null;\n private initialized = false;\n private initPromise: Promise<Result<void, MemoryError>> | undefined;\n\n constructor(config: GraphMemoryConfig) {\n const validation = GraphMemoryConfigSchema.safeParse(config);\n if (!validation.success) {\n const msg = validation.error.issues\n .map((i) => `${i.path.join('.')}: ${i.message}`)\n .join('; ');\n throw new MemoryError(`Invalid GraphMemoryBackend config: ${msg}`);\n }\n this.config = { ...DEFAULT_GRAPH_MEMORY_CONFIG, ...config };\n this.log = logger;\n this.base = new HybridMemoryBackend({ dbPath: config.dbPath, markdownDir: config.markdownDir });\n }\n\n async initialize(): Promise<Result<void, MemoryError>> {\n if (this.initialized) return ok(undefined);\n this.initPromise ??= this.doInitialize().finally(() => {\n this.initPromise = undefined;\n });\n return this.initPromise;\n }\n\n private async doInitialize(): Promise<Result<void, MemoryError>> {\n const baseInit = await this.base.initialize();\n if (!baseInit.ok) return baseInit;\n\n try {\n const mod = await import('better-sqlite3').catch((cause: unknown) => {\n logger.debug('better-sqlite3 import failed', { error: String(cause) });\n return null;\n });\n if (mod === null)\n return err(\n new MemoryError('better-sqlite3 not installed. Install: npm install better-sqlite3')\n );\n const Database = mod.default;\n this.db = new Database(this.config.dbPath);\n this.createGraphTables();\n this.initialized = true;\n this.log.info('GraphMemoryBackend initialized');\n return ok(undefined);\n } catch (error) {\n const cause = error instanceof Error ? error : new Error(String(error));\n return err(new MemoryError('Failed to initialize graph backend', { cause }));\n }\n }\n\n initializeWithDatabase(database: ISQLiteDatabase): void {\n this.base.initializeWithDatabase(database);\n this.db = database;\n this.createGraphTables();\n this.initialized = true;\n this.log.info('GraphMemoryBackend initialized with database');\n }\n\n private createGraphTables(): void {\n const db = this.getDb();\n db.exec(CREATE_EDGES_TABLE_SQL);\n db.exec(CREATE_FROM_INDEX_SQL);\n db.exec(CREATE_TO_INDEX_SQL);\n this.log.debug('Graph tables created');\n }\n\n private getDb(): ISQLiteDatabase {\n if (this.db === null) throw new MemoryError('Database not initialized');\n return this.db;\n }\n\n private ensureInit(): void {\n if (!this.initialized) throw new MemoryError('GraphMemoryBackend not initialized');\n }\n\n // =========================================================================\n // IMemoryBackend Methods (delegated to base)\n // =========================================================================\n\n store(key: string, value: unknown, metadata: MemoryMetadata): Promise<Result<void, MemoryError>> {\n return this.base.store(key, value, metadata);\n }\n\n retrieve(key: string): Promise<Result<unknown, MemoryError>> {\n return this.base.retrieve(key);\n }\n\n search(query: string, limit: number): Promise<Result<MemoryEntry[], MemoryError>> {\n return this.base.search(query, limit);\n }\n\n prune(olderThan: Date): Promise<Result<number, MemoryError>> {\n return this.base.prune(olderThan);\n }\n\n // =========================================================================\n // Graph Relationship Methods\n // =========================================================================\n\n addRelationship(\n from: string,\n to: string,\n type: RelationType,\n opts?: AddRelationshipOptions\n ): Promise<Result<void, MemoryError>> {\n try {\n this.ensureInit();\n const db = this.getDb();\n if (!memoryExists(db, from))\n return Promise.resolve(err(new MemoryError(`Source key not found: ${from}`)));\n if (!memoryExists(db, to))\n return Promise.resolve(err(new MemoryError(`Target key not found: ${to}`)));\n\n const weight = opts?.weight ?? 1.0;\n const metadata = opts?.metadata !== undefined ? JSON.stringify(opts.metadata) : null;\n const stmt = db.prepare(`INSERT OR REPLACE INTO graph_edges VALUES (?, ?, ?, ?, ?, ?)`);\n stmt.run(from, to, type, weight, getTimeProvider().now(), metadata);\n this.log.debug('Added relationship', { from, to, type, weight });\n return Promise.resolve(ok(undefined));\n } catch (error) {\n const cause = error instanceof Error ? error : new Error(String(error));\n return Promise.resolve(err(new MemoryError('Failed to add relationship', { cause })));\n }\n }\n\n removeRelationship(\n from: string,\n to: string,\n type?: RelationType\n ): Promise<Result<void, MemoryError>> {\n try {\n this.ensureInit();\n const db = this.getDb();\n const sql =\n type !== undefined\n ? 'DELETE FROM graph_edges WHERE from_key = ? AND to_key = ? AND relation_type = ?'\n : 'DELETE FROM graph_edges WHERE from_key = ? AND to_key = ?';\n const args = type !== undefined ? [from, to, type] : [from, to];\n db.prepare(sql).run(...args);\n this.log.debug('Removed relationship', { from, to, type });\n return Promise.resolve(ok(undefined));\n } catch (error) {\n const cause = error instanceof Error ? error : new Error(String(error));\n return Promise.resolve(err(new MemoryError('Failed to remove relationship', { cause })));\n }\n }\n\n getRelationships(\n key: string,\n direction: 'outgoing' | 'incoming' | 'both' = 'both'\n ): Promise<Result<GraphEdge[], MemoryError>> {\n try {\n this.ensureInit();\n const edges = getEdgesForKey({ db: this.getDb(), key, direction });\n return Promise.resolve(ok(edges));\n } catch (error) {\n const cause = error instanceof Error ? error : new Error(String(error));\n return Promise.resolve(err(new MemoryError('Failed to get relationships', { cause })));\n }\n }\n\n // =========================================================================\n // Graph Traversal Methods\n // =========================================================================\n\n traverse(\n startKey: string,\n opts?: TraversalOptions\n ): Promise<Result<TraversalResult[], MemoryError>> {\n try {\n this.ensureInit();\n const db = this.getDb();\n if (!memoryExists(db, startKey))\n return Promise.resolve(err(new MemoryError(`Key not found: ${startKey}`)));\n\n const maxDepth =\n this.config.maxTraversalDepth ?? DEFAULT_GRAPH_MEMORY_CONFIG.maxTraversalDepth;\n const resolved = resolveTraversalOptions(opts);\n if (resolved.maxDepth > maxDepth) {\n const msg = `Max depth exceeded: ${String(resolved.maxDepth)} > ${String(maxDepth)}`;\n return Promise.resolve(err(new MemoryError(msg)));\n }\n\n const results = bfsTraverse({ db, startKey, opts: resolved });\n return Promise.resolve(ok(results));\n } catch (error) {\n const cause = error instanceof Error ? error : new Error(String(error));\n return Promise.resolve(err(new MemoryError('Traversal failed', { cause })));\n }\n }\n\n findPath(\n from: string,\n to: string,\n opts?: Pick<TraversalOptions, 'relationTypes' | 'minWeight'>\n ): Promise<Result<string[] | null, MemoryError>> {\n try {\n this.ensureInit();\n const db = this.getDb();\n if (!memoryExists(db, from))\n return Promise.resolve(err(new MemoryError(`From key not found: ${from}`)));\n if (!memoryExists(db, to))\n return Promise.resolve(err(new MemoryError(`To key not found: ${to}`)));\n\n const resolved = resolveTraversalOptions(opts);\n const path = findShortestPath(db, from, to, resolved);\n return Promise.resolve(ok(path));\n } catch (error) {\n const cause = error instanceof Error ? error : new Error(String(error));\n return Promise.resolve(err(new MemoryError('Path finding failed', { cause })));\n }\n }\n\n async getNeighbors(key: string, depth = 1): Promise<Result<MemoryEntry[], MemoryError>> {\n const result = await this.traverse(key, { maxDepth: depth, includeStart: false });\n if (!result.ok) return result;\n return ok(result.value.map((r) => r.entry));\n }\n\n // =========================================================================\n // Store with Relations\n // =========================================================================\n\n async storeWithRelations(\n key: string,\n value: unknown,\n metadata: MemoryMetadata,\n relatedTo?: readonly string[]\n ): Promise<Result<void, MemoryError>> {\n const storeResult = await this.store(key, value, metadata);\n if (!storeResult.ok) return storeResult;\n\n if (relatedTo !== undefined && relatedTo.length > 0) {\n for (const relKey of relatedTo) {\n const addResult = await this.addRelationship(key, relKey, RelationTypes.RELATED_TO);\n if (!addResult.ok) this.log.warn('Failed to add relation', { from: key, to: relKey });\n }\n }\n return ok(undefined);\n }\n\n // =========================================================================\n // Lifecycle\n // =========================================================================\n\n close(): void {\n this.base.close();\n if (this.db !== null) {\n this.db.close();\n this.db = null;\n }\n this.initialized = false;\n this.log.info('GraphMemoryBackend closed');\n }\n}\n\n/** Create a GraphMemoryBackend instance. */\nexport function createGraphMemory(config: GraphMemoryConfig): GraphMemoryBackend {\n return new GraphMemoryBackend(config);\n}\n","/**\n * Agentic Memory Types\n *\n * Type definitions for A-MEM agentic memory with Zettelkasten-style\n * dynamic linking, attribute extraction, and memory evolution.\n *\n * @module context/agentic-memory-types\n * (Source: Issue #122, arXiv:2502.12110)\n */\n\nimport { z } from 'zod';\nimport type { Result } from '../core/result.js';\nimport type { MemoryEntry, MemoryError, IMemoryBackend } from './memory-backend-types.js';\nimport type { RelationType } from './graph-memory-types.js';\nimport { RelationTypeSchema } from './graph-memory-types.js';\n\n// Re-export primitives for backward compatibility\nexport {\n EntityType,\n EntityTypeSchema,\n type EntityReference,\n EntityReferenceSchema,\n EvolutionType,\n EvolutionTypeSchema,\n type EvolutionResult,\n EvolutionResultSchema,\n type LinkSuggestion,\n LinkSuggestionSchema,\n} from './agentic-memory-primitives.js';\n\n// Import primitives for use in this file\nimport type {\n EntityReference,\n EvolutionResult,\n LinkSuggestion,\n} from './agentic-memory-primitives.js';\nimport { EntityReferenceSchema } from './agentic-memory-primitives.js';\n\n// ============================================================================\n// Memory Attributes (Zettelkasten-style)\n// ============================================================================\n\n/**\n * A-MEM attributes for a memory entry.\n * These are automatically extracted when storing memories.\n */\nexport interface MemoryAttributes {\n /** Auto-extracted keywords from content */\n readonly keywords: readonly string[];\n /** Semantic tags (broader categories) */\n readonly semanticTags: readonly string[];\n /** Contextual description (brief summary) */\n readonly contextDescription: string;\n /** Entity references extracted from content */\n readonly entities: readonly EntityReference[];\n /** When attributes were last updated */\n readonly attributesUpdatedAt: Date;\n}\n\n/** Zod schema for MemoryAttributes validation. */\nexport const MemoryAttributesSchema = z.object({\n keywords: z.array(z.string().max(100)).max(50),\n semanticTags: z.array(z.string().max(50)).max(20),\n contextDescription: z.string().max(500),\n entities: z.array(EntityReferenceSchema).max(30),\n attributesUpdatedAt: z.date(),\n});\n\n// ============================================================================\n// Agentic Memory Entry\n// ============================================================================\n\n/**\n * Memory entry with A-MEM attributes attached.\n */\nexport interface AgenticMemoryEntry extends MemoryEntry {\n /** Auto-extracted attributes */\n readonly attributes: MemoryAttributes;\n}\n\n// ============================================================================\n// Store Result\n// ============================================================================\n\n/**\n * Result of an agentic store operation.\n */\nexport interface AgenticStoreResult {\n /** The stored entry with extracted attributes */\n readonly entry: AgenticMemoryEntry;\n /** Suggested links to other memories */\n readonly linkSuggestions: readonly LinkSuggestion[];\n /** Detected evolution relationships */\n readonly evolution: readonly EvolutionResult[];\n}\n\n// ============================================================================\n// Configuration\n// ============================================================================\n\n/**\n * Configuration for attribute extraction.\n */\nexport interface ExtractionConfig {\n /** Maximum keywords to extract (default: 10) */\n readonly maxKeywords: number;\n /** Maximum semantic tags (default: 5) */\n readonly maxSemanticTags: number;\n /** Maximum context description length in chars (default: 200) */\n readonly maxContextLength: number;\n /** Maximum entities to extract (default: 10) */\n readonly maxEntities: number;\n}\n\n/** Zod schema for ExtractionConfig validation. */\nexport const ExtractionConfigSchema = z.object({\n maxKeywords: z.number().int().positive().max(50),\n maxSemanticTags: z.number().int().positive().max(20),\n maxContextLength: z.number().int().positive().max(500),\n maxEntities: z.number().int().positive().max(30),\n});\n\n/**\n * Configuration for automatic linking behavior.\n */\nexport interface LinkingConfig {\n /** Minimum confidence to suggest links (default: 0.5) */\n readonly suggestionThreshold: number;\n /** Maximum link suggestions per memory (default: 5) */\n readonly maxSuggestions: number;\n /** Relationship types to consider for linking */\n readonly allowedTypes: readonly RelationType[];\n}\n\n/** Zod schema for LinkingConfig validation. */\nexport const LinkingConfigSchema = z.object({\n suggestionThreshold: z.number().min(0).max(1),\n maxSuggestions: z.number().int().positive().max(20),\n allowedTypes: z.array(RelationTypeSchema),\n});\n\n/**\n * Options for linking related memories.\n */\nexport interface LinkingOptions {\n /** Minimum confidence threshold for applying links (default: 0.7) */\n readonly threshold?: number;\n /** Maximum links to apply (default: config.maxSuggestions) */\n readonly maxLinks?: number;\n /** Whether to create bidirectional links (default: true) */\n readonly bidirectional?: boolean;\n}\n\n/** Zod schema for LinkingOptions validation. */\nexport const LinkingOptionsSchema = z.object({\n threshold: z.number().min(0).max(1).optional(),\n maxLinks: z.number().int().positive().optional(),\n bidirectional: z.boolean().optional(),\n});\n\n// ============================================================================\n// Agentic Memory Interface\n// ============================================================================\n\n/**\n * Agentic memory interface implementing A-MEM Zettelkasten-style organization.\n * Extends IMemoryBackend with automatic attribute extraction, dynamic linking,\n * and memory evolution detection.\n *\n * (Source: Issue #122, arXiv:2502.12110)\n */\nexport interface IAgenticMemory extends IMemoryBackend {\n /**\n * Store a memory with automatic attribute extraction.\n * Extracts keywords, tags, entities, and context from the value.\n * Does NOT auto-link; call linkRelatedMemories() separately.\n * @param key - Memory key\n * @param value - Memory value (text content for extraction)\n * @param metadata - Memory metadata (importance, tags, ttl)\n * @returns Store result with extracted attributes and suggestions\n */\n storeWithAttributes(\n key: string,\n value: unknown,\n metadata: import('./memory-backend-types.js').MemoryMetadata\n ): Promise<Result<AgenticStoreResult, MemoryError>>;\n\n /**\n * Retrieve a memory with its A-MEM attributes.\n * @param key - Memory key\n * @returns Entry with attributes or null if not found\n */\n retrieveWithAttributes(key: string): Promise<Result<AgenticMemoryEntry | null, MemoryError>>;\n\n /**\n * Search with A-MEM enhanced retrieval.\n * Uses keywords and semantic tags for better relevance scoring.\n * @param query - Search query\n * @param limit - Max results (default: 10)\n * @returns Entries sorted by relevance\n */\n searchAgentic(query: string, limit?: number): Promise<Result<AgenticMemoryEntry[], MemoryError>>;\n\n /**\n * Get link suggestions for a memory entry.\n * Analyzes keyword overlap and entity co-occurrence.\n * Does NOT modify state.\n * @param key - Memory key to analyze\n * @param limit - Max suggestions (default: config.maxSuggestions)\n * @returns Suggested links ranked by confidence\n */\n suggestLinks(key: string, limit?: number): Promise<Result<LinkSuggestion[], MemoryError>>;\n\n /**\n * Link related memories based on suggestions.\n * Creates graph relationships for suggestions meeting threshold.\n * @param key - Memory key to link from\n * @param opts - Linking options (threshold, maxLinks, bidirectional)\n * @returns Number of links created\n */\n linkRelatedMemories(key: string, opts?: LinkingOptions): Promise<Result<number, MemoryError>>;\n\n /**\n * Detect evolution relationships with existing memories.\n * Identifies refinements, contradictions, extensions, supersessions.\n * @param key - Memory key to analyze\n * @returns Detected evolution relationships\n */\n detectEvolution(key: string): Promise<Result<EvolutionResult[], MemoryError>>;\n\n /**\n * Refresh attributes for a memory (re-extract).\n * Updates keywords, tags, entities, and context from current value.\n * @param key - Memory key\n * @returns Updated attributes\n */\n refreshAttributes(key: string): Promise<Result<MemoryAttributes, MemoryError>>;\n\n /**\n * Find memories that share attributes with the given key.\n * @param key - Memory key\n * @param attributeType - Type of attribute to match\n * @param limit - Max results (default: 10)\n * @returns Entries sharing attributes\n */\n findBySharedAttributes(\n key: string,\n attributeType: 'keywords' | 'semanticTags' | 'entities',\n limit?: number\n ): Promise<Result<AgenticMemoryEntry[], MemoryError>>;\n\n /** Get extraction config. */\n getExtractionConfig(): ExtractionConfig;\n\n /** Update extraction config. */\n updateExtractionConfig(config: Partial<ExtractionConfig>): void;\n\n /** Get linking config. */\n getLinkingConfig(): LinkingConfig;\n\n /** Update linking config. */\n updateLinkingConfig(config: Partial<LinkingConfig>): void;\n}\n\n// ============================================================================\n// Backend Configuration\n// ============================================================================\n\n/**\n * Configuration for AgenticMemoryBackend.\n */\nexport interface AgenticMemoryConfig {\n /** Path to SQLite database file */\n readonly dbPath: string;\n /** Directory for Markdown exports */\n readonly markdownDir: string;\n /** Attribute extraction config (uses defaults if not provided) */\n readonly extraction?: Partial<ExtractionConfig>;\n /** Linking config (uses defaults if not provided) */\n readonly linking?: Partial<LinkingConfig>;\n /** Whether to auto-expire TTL entries (default: true) */\n readonly autoExpire?: boolean;\n}\n\n/** Zod schema for AgenticMemoryConfig validation. */\nexport const AgenticMemoryConfigSchema = z.object({\n dbPath: z.string().min(1),\n markdownDir: z.string().min(1),\n extraction: ExtractionConfigSchema.partial().optional(),\n linking: LinkingConfigSchema.partial().optional(),\n autoExpire: z.boolean().optional(),\n});\n\n// ============================================================================\n// Default Configuration\n// ============================================================================\n\n/** Default extraction configuration. */\nexport const DEFAULT_EXTRACTION_CONFIG: ExtractionConfig = {\n maxKeywords: 10,\n maxSemanticTags: 5,\n maxContextLength: 200,\n maxEntities: 10,\n};\n\n/** Default linking configuration. */\nexport const DEFAULT_LINKING_CONFIG: LinkingConfig = {\n suggestionThreshold: 0.5,\n maxSuggestions: 5,\n allowedTypes: ['related_to', 'derived_from', 'same_entity'],\n};\n\n/** Default agentic memory configuration. */\nexport const DEFAULT_AGENTIC_MEMORY_CONFIG = {\n extraction: DEFAULT_EXTRACTION_CONFIG,\n linking: DEFAULT_LINKING_CONFIG,\n autoExpire: true,\n} as const;\n","/**\n * Agentic Memory Primitives\n *\n * Core primitive types for A-MEM agentic memory including entity types,\n * evolution types, and link suggestions. Extracted from agentic-memory-types.ts\n * for module size compliance.\n *\n * @module context/agentic-memory-primitives\n * (Source: Issue #122, arXiv:2502.12110)\n */\n\nimport { z } from 'zod';\nimport type { RelationType } from './graph-memory-types.js';\nimport { RelationTypeSchema } from './graph-memory-types.js';\n\n// ============================================================================\n// Entity Types\n// ============================================================================\n\n/**\n * Types of entities that can be extracted from memory content.\n */\nexport const EntityType = {\n PERSON: 'person',\n ORGANIZATION: 'organization',\n CONCEPT: 'concept',\n CODE: 'code',\n FILE: 'file',\n UNKNOWN: 'unknown',\n} as const;\n\nexport type EntityType = (typeof EntityType)[keyof typeof EntityType];\n\n/** Zod schema for EntityType validation. */\nexport const EntityTypeSchema = z.enum([\n 'person',\n 'organization',\n 'concept',\n 'code',\n 'file',\n 'unknown',\n]);\n\n/**\n * An entity reference extracted from memory content.\n */\nexport interface EntityReference {\n /** Name or identifier of the entity */\n readonly name: string;\n /** Type of entity */\n readonly type: EntityType;\n}\n\n/** Zod schema for EntityReference validation. */\nexport const EntityReferenceSchema = z.object({\n name: z.string().min(1).max(200),\n type: EntityTypeSchema,\n});\n\n// ============================================================================\n// Evolution Types\n// ============================================================================\n\n/**\n * Types of memory evolution.\n */\nexport const EvolutionType = {\n /** New memory refines/improves existing knowledge */\n REFINEMENT: 'refinement',\n /** New memory contradicts existing knowledge */\n CONTRADICTION: 'contradiction',\n /** New memory extends existing knowledge */\n EXTENSION: 'extension',\n /** New memory supersedes (replaces) existing knowledge */\n SUPERSESSION: 'supersession',\n} as const;\n\nexport type EvolutionType = (typeof EvolutionType)[keyof typeof EvolutionType];\n\n/** Zod schema for EvolutionType validation. */\nexport const EvolutionTypeSchema = z.enum([\n 'refinement',\n 'contradiction',\n 'extension',\n 'supersession',\n]);\n\n/**\n * Result of memory evolution analysis.\n */\nexport interface EvolutionResult {\n /** Type of evolution detected */\n readonly type: EvolutionType;\n /** Key of the affected existing memory */\n readonly affectedKey: string;\n /** Confidence score (0-1) */\n readonly confidence: number;\n /** Description of what changed */\n readonly description: string;\n}\n\n/** Zod schema for EvolutionResult validation. */\nexport const EvolutionResultSchema = z.object({\n type: EvolutionTypeSchema,\n affectedKey: z.string().min(1),\n confidence: z.number().min(0).max(1),\n description: z.string().max(500),\n});\n\n// ============================================================================\n// Link Suggestions\n// ============================================================================\n\n/**\n * A suggested link between memories.\n */\nexport interface LinkSuggestion {\n /** Source memory key */\n readonly from: string;\n /** Target memory key */\n readonly to: string;\n /** Suggested relationship type */\n readonly relationType: RelationType;\n /** Reason for the suggestion */\n readonly reason: string;\n /** Confidence score (0-1) */\n readonly confidence: number;\n}\n\n/** Zod schema for LinkSuggestion validation. */\nexport const LinkSuggestionSchema = z.object({\n from: z.string().min(1),\n to: z.string().min(1),\n relationType: RelationTypeSchema,\n reason: z.string().max(200),\n confidence: z.number().min(0).max(1),\n});\n","/**\n * Agentic Memory Extraction Helpers\n *\n * Rule-based attribute extraction for A-MEM agentic memory.\n *\n * @module context/agentic-memory-extraction\n * (Source: Issue #122, arXiv:2502.12110)\n */\n\nimport { getTimeProvider } from '../core/index.js';\nimport type {\n MemoryAttributes,\n EntityReference,\n EntityType,\n ExtractionConfig,\n} from './agentic-memory-types.js';\nimport { DEFAULT_EXTRACTION_CONFIG } from './agentic-memory-types.js';\n// Shared utilities per ADR-0013\nimport {\n tokenizeFiltered as sharedTokenizeFiltered,\n stringifyValue as sharedStringifyValue,\n} from '../utils/text-utils.js';\n\n// ============================================================================\n// Keyword Extraction (Rule-based)\n// ============================================================================\n\n/**\n * Extract keywords from text using TF-IDF-like frequency analysis.\n * Returns the most frequent significant words.\n */\nexport function extractKeywords(text: string, maxKeywords: number): string[] {\n const tokens = sharedTokenizeFiltered(text, 2);\n if (tokens.length === 0) return [];\n\n // Count frequencies\n const freq = new Map<string, number>();\n for (const token of tokens) {\n freq.set(token, (freq.get(token) ?? 0) + 1);\n }\n\n // Sort by frequency descending and take top\n return [...freq.entries()]\n .sort((a, b) => b[1] - a[1])\n .slice(0, maxKeywords)\n .map(([word]) => word);\n}\n\n// ============================================================================\n// Semantic Tag Extraction\n// ============================================================================\n\nconst TAG_PATTERNS: Array<{ pattern: RegExp; tag: string }> = [\n {\n pattern: /\\b(function|class|method|interface|type|const|let|var|import|export)\\b/i,\n tag: 'code',\n },\n { pattern: /\\b(test|spec|expect|describe|it|assert|mock)\\b/i, tag: 'testing' },\n { pattern: /\\b(error|exception|bug|fix|issue|problem)\\b/i, tag: 'debugging' },\n { pattern: /\\b(api|endpoint|request|response|http|rest|graphql)\\b/i, tag: 'api' },\n { pattern: /\\b(database|sql|query|table|schema|migration)\\b/i, tag: 'database' },\n { pattern: /\\b(config|setting|option|parameter|environment)\\b/i, tag: 'configuration' },\n { pattern: /\\b(security|auth|token|permission|access|credential)\\b/i, tag: 'security' },\n { pattern: /\\b(performance|latency|throughput|optimize|cache)\\b/i, tag: 'performance' },\n { pattern: /\\b(deploy|release|pipeline|ci|cd|build)\\b/i, tag: 'devops' },\n { pattern: /\\b(documentation|readme|guide|tutorial|example)\\b/i, tag: 'documentation' },\n { pattern: /\\b(agent|workflow|task|orchestrate|delegate)\\b/i, tag: 'agents' },\n { pattern: /\\b(memory|context|recall|retrieve|store)\\b/i, tag: 'memory' },\n];\n\n/**\n * Extract semantic tags by matching content against patterns.\n */\nexport function extractSemanticTags(text: string, maxTags: number): string[] {\n const matched: string[] = [];\n for (const { pattern, tag } of TAG_PATTERNS) {\n if (pattern.test(text)) {\n matched.push(tag);\n if (matched.length >= maxTags) break;\n }\n }\n return matched;\n}\n\n// ============================================================================\n// Entity Extraction\n// ============================================================================\n\nconst ENTITY_PATTERNS: Array<{ pattern: RegExp; type: EntityType }> = [\n { pattern: /(?:^|[\\s'\"(])((?:\\.\\/|\\.\\.\\/|\\/)[\\w\\-./]+\\.\\w+)/g, type: 'file' },\n { pattern: /(?:^|[\\s'\"(])([\\w-]+\\.(ts|js|tsx|jsx|py|go|rs|md|json|yaml|yml))/g, type: 'file' },\n { pattern: /\\b([A-Z][a-z]+(?:[A-Z][a-z]+)+)\\b/g, type: 'code' },\n { pattern: /\\b([a-z]+_[a-z_]+)\\b/g, type: 'code' },\n { pattern: /\\b([A-Z][a-z]+(?: [A-Z][a-z]+)+)\\b/g, type: 'concept' },\n];\n\n/**\n * Check if a string looks like PII (SSN, phone, email, etc.)\n */\nfunction isPotentialPII(text: string): boolean {\n if (/^\\d{3}-\\d{2}-\\d{4}$/.test(text)) return true; // SSN\n if (/^\\d{3}[-.\\s]?\\d{3}[-.\\s]?\\d{4}$/.test(text)) return true; // Phone\n if (/^\\+?\\d{10,15}$/.test(text)) return true; // Intl phone\n if (/^[\\w.-]+@[\\w.-]+\\.\\w+$/.test(text)) return true; // Email\n if (/^\\d{4}[-\\s]?\\d{4}[-\\s]?\\d{4}[-\\s]?\\d{4}$/.test(text)) return true; // CC\n return false;\n}\n\n/**\n * Extract entities from text using pattern matching.\n * PII filtering: excludes patterns that look like SSN, phone, email.\n */\nexport function extractEntities(text: string, maxEntities: number): EntityReference[] {\n const entities: EntityReference[] = [];\n const seen = new Set<string>();\n\n for (const { pattern, type } of ENTITY_PATTERNS) {\n pattern.lastIndex = 0;\n let match: RegExpExecArray | null;\n while ((match = pattern.exec(text)) !== null) {\n const name = match[1];\n if (name === undefined) continue;\n if (seen.has(name.toLowerCase()) || name.length < 3) continue;\n if (isPotentialPII(name)) continue;\n\n seen.add(name.toLowerCase());\n entities.push({ name, type });\n if (entities.length >= maxEntities) break;\n }\n if (entities.length >= maxEntities) break;\n }\n return entities;\n}\n\n// ============================================================================\n// Context Description Generation\n// ============================================================================\n\n/**\n * Generate a brief context description from text.\n */\nexport function generateContextDescription(text: string, maxLength: number): string {\n const firstSentence = text.match(/^[^.!?]+[.!?]/);\n if (firstSentence !== null && firstSentence[0].length <= maxLength) {\n return firstSentence[0].trim();\n }\n if (text.length <= maxLength) return text.trim();\n\n const truncated = text.slice(0, maxLength);\n const lastSpace = truncated.lastIndexOf(' ');\n if (lastSpace > maxLength * 0.7) {\n return truncated.slice(0, lastSpace).trim() + '...';\n }\n return truncated.trim() + '...';\n}\n\n// ============================================================================\n// Attribute Extraction Pipeline\n// ============================================================================\n\n/**\n * Extract all A-MEM attributes from a value.\n */\nexport function extractAttributes(value: unknown, config: ExtractionConfig): MemoryAttributes {\n const text = sharedStringifyValue(value);\n return {\n keywords: extractKeywords(text, config.maxKeywords),\n semanticTags: extractSemanticTags(text, config.maxSemanticTags),\n contextDescription: generateContextDescription(text, config.maxContextLength),\n entities: extractEntities(text, config.maxEntities),\n attributesUpdatedAt: new Date(getTimeProvider().now()),\n };\n}\n\n/**\n * Merge partial extraction config with defaults.\n * Canonical location per ADR-0013.\n */\nexport function mergeExtractionConfig(partial?: Partial<ExtractionConfig>): ExtractionConfig {\n if (partial === undefined) return DEFAULT_EXTRACTION_CONFIG;\n return {\n maxKeywords: partial.maxKeywords ?? DEFAULT_EXTRACTION_CONFIG.maxKeywords,\n maxSemanticTags: partial.maxSemanticTags ?? DEFAULT_EXTRACTION_CONFIG.maxSemanticTags,\n maxContextLength: partial.maxContextLength ?? DEFAULT_EXTRACTION_CONFIG.maxContextLength,\n maxEntities: partial.maxEntities ?? DEFAULT_EXTRACTION_CONFIG.maxEntities,\n };\n}\n","/**\n * Agentic Memory Linking\n *\n * Similarity calculation, link suggestion, and evolution detection\n * for A-MEM agentic memory system.\n *\n * @module context/agentic-memory-linking\n * (Source: Issue #122, arXiv:2502.12110)\n */\n\nimport { RelationType } from './graph-memory-types.js';\nimport type {\n MemoryAttributes,\n LinkingConfig,\n LinkSuggestion,\n EvolutionResult,\n EvolutionType,\n} from './agentic-memory-types.js';\nimport { DEFAULT_LINKING_CONFIG } from './agentic-memory-types.js';\n\n// ============================================================================\n// Similarity Calculation (FTS-based)\n// ============================================================================\n\n/**\n * Calculate keyword overlap similarity between two memory entries.\n * Uses Jaccard-like coefficient: |intersection| / |union|\n */\nexport function calculateKeywordSimilarity(\n attrs1: MemoryAttributes,\n attrs2: MemoryAttributes\n): number {\n const set1 = new Set(attrs1.keywords);\n const set2 = new Set(attrs2.keywords);\n\n if (set1.size === 0 && set2.size === 0) return 0;\n\n let intersection = 0;\n for (const k of set1) {\n if (set2.has(k)) intersection++;\n }\n\n const union = set1.size + set2.size - intersection;\n return union > 0 ? intersection / union : 0;\n}\n\n/**\n * Calculate entity overlap similarity.\n * Returns the fraction of shared entities.\n */\nexport function calculateEntitySimilarity(\n attrs1: MemoryAttributes,\n attrs2: MemoryAttributes\n): number {\n const names1 = new Set(attrs1.entities.map((e) => e.name.toLowerCase()));\n const names2 = new Set(attrs2.entities.map((e) => e.name.toLowerCase()));\n\n if (names1.size === 0 && names2.size === 0) return 0;\n\n let intersection = 0;\n for (const name of names1) {\n if (names2.has(name)) intersection++;\n }\n\n const union = names1.size + names2.size - intersection;\n return union > 0 ? intersection / union : 0;\n}\n\n/**\n * Calculate overall similarity between two memories.\n * Combines keyword similarity (60%) and entity similarity (40%).\n */\nexport function calculateOverallSimilarity(\n attrs1: MemoryAttributes,\n attrs2: MemoryAttributes\n): number {\n const keywordSim = calculateKeywordSimilarity(attrs1, attrs2);\n const entitySim = calculateEntitySimilarity(attrs1, attrs2);\n\n return keywordSim * 0.6 + entitySim * 0.4;\n}\n\n// ============================================================================\n// Link Suggestion Generation\n// ============================================================================\n\n/**\n * Infer relationship type based on similarity and content.\n */\nexport function inferRelationType(\n fromAttrs: MemoryAttributes,\n toAttrs: MemoryAttributes,\n fromCreatedAt: Date,\n toCreatedAt: Date\n): RelationType {\n // Check for shared entities (same_entity)\n const fromNames = new Set(fromAttrs.entities.map((e) => e.name.toLowerCase()));\n const toNames = new Set(toAttrs.entities.map((e) => e.name.toLowerCase()));\n let sharedEntities = 0;\n for (const name of fromNames) {\n if (toNames.has(name)) sharedEntities++;\n }\n if (sharedEntities > 0) return RelationType.SAME_ENTITY;\n\n // Check temporal relationship (precedes)\n if (fromCreatedAt < toCreatedAt) return RelationType.PRECEDES;\n\n // Default to related_to\n return RelationType.RELATED_TO;\n}\n\n/**\n * Generate a human-readable reason for a link suggestion.\n */\nfunction generateLinkReason(\n fromAttrs: MemoryAttributes,\n toAttrs: MemoryAttributes,\n similarity: number\n): string {\n // Find shared keywords\n const sharedKeywords = fromAttrs.keywords.filter((k) => toAttrs.keywords.includes(k));\n\n if (sharedKeywords.length > 0) {\n const sample = sharedKeywords.slice(0, 3).join(', ');\n return `Shared keywords: ${sample}`;\n }\n\n // Find shared entities\n const fromNames = fromAttrs.entities.map((e) => e.name);\n const sharedEntities = fromNames.filter((n) =>\n toAttrs.entities.some((e) => e.name.toLowerCase() === n.toLowerCase())\n );\n\n const firstSharedEntity = sharedEntities[0];\n if (firstSharedEntity !== undefined) {\n return `Shared entity: ${firstSharedEntity}`;\n }\n\n return `Similarity: ${(similarity * 100).toFixed(0)}%`;\n}\n\n/**\n * Generate link suggestions for a memory.\n */\nexport function generateLinkSuggestions(\n key: string,\n attrs: MemoryAttributes,\n createdAt: Date,\n candidates: Array<{ key: string; attrs: MemoryAttributes; createdAt: Date }>,\n config: LinkingConfig\n): LinkSuggestion[] {\n const suggestions: LinkSuggestion[] = [];\n\n for (const candidate of candidates) {\n // Skip self\n if (candidate.key === key) continue;\n\n // Calculate similarity\n const similarity = calculateOverallSimilarity(attrs, candidate.attrs);\n\n // Skip if below threshold\n if (similarity < config.suggestionThreshold) continue;\n\n // Infer relationship type\n const relationType = inferRelationType(attrs, candidate.attrs, createdAt, candidate.createdAt);\n\n // Skip if type not allowed\n if (!config.allowedTypes.includes(relationType)) continue;\n\n // Generate reason\n const reason = generateLinkReason(attrs, candidate.attrs, similarity);\n\n suggestions.push({\n from: key,\n to: candidate.key,\n relationType,\n reason,\n confidence: similarity,\n });\n\n if (suggestions.length >= config.maxSuggestions) break;\n }\n\n // Sort by confidence descending\n suggestions.sort((a, b) => b.confidence - a.confidence);\n\n return suggestions.slice(0, config.maxSuggestions);\n}\n\n// ============================================================================\n// Evolution Detection\n// ============================================================================\n\n/**\n * Detect evolution relationship between two memories.\n * Returns null if no evolution detected.\n */\nexport function detectEvolutionPair(\n newAttrs: MemoryAttributes,\n newCreatedAt: Date,\n existingKey: string,\n existingAttrs: MemoryAttributes,\n existingCreatedAt: Date\n): EvolutionResult | null {\n // Calculate similarity\n const similarity = calculateOverallSimilarity(newAttrs, existingAttrs);\n\n // Only consider if sufficiently similar\n if (similarity < 0.5) return null;\n\n // Determine evolution type\n let type: EvolutionType;\n let description: string;\n\n // Check if new memory is newer\n if (newCreatedAt > existingCreatedAt) {\n // Check for contradictions (high similarity but different content keywords)\n const newOnlyKeywords = newAttrs.keywords.filter((k) => !existingAttrs.keywords.includes(k));\n const existingOnlyKeywords = existingAttrs.keywords.filter(\n (k) => !newAttrs.keywords.includes(k)\n );\n\n if (newOnlyKeywords.length > existingOnlyKeywords.length + 2) {\n type = 'extension';\n description = `Extends with new concepts: ${newOnlyKeywords.slice(0, 3).join(', ')}`;\n } else if (similarity > 0.8) {\n type = 'supersession';\n description = 'Highly similar newer memory, may supersede';\n } else {\n type = 'refinement';\n description = `Refines existing memory (${(similarity * 100).toFixed(0)}% similar)`;\n }\n } else {\n // New memory is older (shouldn't happen in typical flow)\n type = 'refinement';\n description = 'Related historical memory';\n }\n\n return {\n type,\n affectedKey: existingKey,\n confidence: similarity,\n description,\n };\n}\n\n/**\n * Detect all evolution relationships for a new memory.\n */\nexport function detectEvolution(\n newKey: string,\n newAttrs: MemoryAttributes,\n newCreatedAt: Date,\n existingMemories: Array<{ key: string; attrs: MemoryAttributes; createdAt: Date }>\n): EvolutionResult[] {\n const results: EvolutionResult[] = [];\n\n for (const existing of existingMemories) {\n if (existing.key === newKey) continue;\n\n const evolution = detectEvolutionPair(\n newAttrs,\n newCreatedAt,\n existing.key,\n existing.attrs,\n existing.createdAt\n );\n\n if (evolution !== null) {\n results.push(evolution);\n }\n }\n\n // Sort by confidence descending\n results.sort((a, b) => b.confidence - a.confidence);\n\n return results;\n}\n\n// ============================================================================\n// Configuration Merging\n// ============================================================================\n\n/**\n * Merge partial linking config with defaults.\n * Canonical location per ADR-0013.\n */\nexport function mergeLinkingConfig(partial?: Partial<LinkingConfig>): LinkingConfig {\n if (partial === undefined) return DEFAULT_LINKING_CONFIG;\n return {\n suggestionThreshold: partial.suggestionThreshold ?? DEFAULT_LINKING_CONFIG.suggestionThreshold,\n maxSuggestions: partial.maxSuggestions ?? DEFAULT_LINKING_CONFIG.maxSuggestions,\n allowedTypes: partial.allowedTypes ?? DEFAULT_LINKING_CONFIG.allowedTypes,\n };\n}\n","/**\n * Agentic Memory Database Helpers\n *\n * Database-related helper functions for A-MEM attribute storage and retrieval.\n *\n * @module context/agentic-memory-db-helpers\n * (Source: Issue #122, arXiv:2502.12110)\n */\n\nimport type { MemoryRow, ISQLiteDatabase } from './memory-backend-types.js';\nimport type {\n MemoryAttributes,\n ExtractionConfig,\n AgenticMemoryEntry,\n} from './agentic-memory-types.js';\n// Shared utilities per ADR-0013\nimport { memoryRowToEntry } from '../utils/memory-db-utils.js';\nimport { extractAttributes } from './agentic-memory-extraction.js';\nimport { createLogger } from '../core/index.js';\n\nconst logger = createLogger({ component: 'AgenticMemoryDbHelpers' });\n\n// ============================================================================\n// Database Helpers\n// ============================================================================\n\n/**\n * Safely extract MemoryAttributes from a raw amem record using type guards.\n * Returns null if the record shape is invalid.\n */\nfunction safeExtractAttributes(amem: Record<string, unknown>): MemoryAttributes | null {\n if (!Array.isArray(amem.keywords) || amem.attributesUpdatedAt === undefined) return null;\n\n const updatedAt = amem.attributesUpdatedAt;\n if (typeof updatedAt !== 'number' && typeof updatedAt !== 'string') return null;\n\n return {\n keywords: amem.keywords.filter((k): k is string => typeof k === 'string'),\n semanticTags: Array.isArray(amem.semanticTags)\n ? amem.semanticTags.filter((t): t is string => typeof t === 'string')\n : [],\n contextDescription: typeof amem.contextDescription === 'string' ? amem.contextDescription : '',\n entities: Array.isArray(amem.entities) ? (amem.entities as MemoryAttributes['entities']) : [],\n attributesUpdatedAt: new Date(updatedAt),\n };\n}\n\n/**\n * Parse A-MEM attributes from memory metadata JSON.\n */\nexport function parseAmemAttributes(metadata: unknown): MemoryAttributes | null {\n if (typeof metadata !== 'object' || metadata === null) return null;\n\n const meta = metadata as Record<string, unknown>;\n if (meta.amem === undefined || typeof meta.amem !== 'object' || meta.amem === null) return null;\n\n return safeExtractAttributes(meta.amem as Record<string, unknown>);\n}\n\n/**\n * Convert MemoryRow to AgenticMemoryEntry.\n */\nexport function memoryRowToAgenticEntry(\n row: MemoryRow,\n extractionConfig: ExtractionConfig\n): AgenticMemoryEntry {\n const baseEntry = memoryRowToEntry(row);\n\n let parsedMeta: Record<string, unknown> = {};\n try {\n parsedMeta = JSON.parse(row.metadata) as Record<string, unknown>;\n } catch {\n logger.warn('Corrupt metadata JSON in memory row, using fallback extraction', {\n key: row.key,\n });\n }\n\n const attributes =\n parseAmemAttributes(parsedMeta) ?? extractAttributes(baseEntry.value, extractionConfig);\n\n return { ...baseEntry, attributes };\n}\n\n/**\n * Search for memories with FTS and return with A-MEM attributes.\n */\nexport function searchWithAttributes(\n db: ISQLiteDatabase,\n query: string,\n limit: number,\n extractionConfig: ExtractionConfig\n): AgenticMemoryEntry[] {\n const sanitized = query\n .replace(/[*()\":^]/g, '')\n .replace(/\\s+/g, ' ')\n .trim();\n if (sanitized.length === 0) return [];\n\n const stmt = db.prepare<MemoryRow>(`\n SELECT m.key, m.value, m.metadata, m.created_at, m.accessed_at, m.expires_at\n FROM memories m INNER JOIN memories_fts fts ON m.rowid = fts.rowid\n WHERE memories_fts MATCH ? ORDER BY rank LIMIT ?\n `);\n\n const rows = stmt.all(sanitized, limit);\n return rows.map((row) => memoryRowToAgenticEntry(row, extractionConfig));\n}\n\n/**\n * Get a set of attribute values for comparison.\n */\nexport function getAttributeSet(\n attrs: MemoryAttributes,\n type: 'keywords' | 'semanticTags' | 'entities'\n): Set<string> {\n switch (type) {\n case 'keywords':\n return new Set(attrs.keywords);\n case 'semanticTags':\n return new Set(attrs.semanticTags);\n case 'entities':\n return new Set(attrs.entities.map((e) => e.name.toLowerCase()));\n }\n}\n\n/**\n * Extract attributes from a memory row's metadata or value.\n */\nexport function getAttributesFromRow(\n row: MemoryRow,\n extractionConfig: ExtractionConfig\n): MemoryAttributes {\n let meta: Record<string, unknown> = {};\n try {\n meta = JSON.parse(row.metadata) as Record<string, unknown>;\n } catch {\n logger.warn('Corrupt metadata JSON in getAttributesFromRow, using value extraction', {\n key: row.key,\n });\n }\n\n if (meta.amem !== undefined && typeof meta.amem === 'object' && meta.amem !== null) {\n const parsed = safeExtractAttributes(meta.amem as Record<string, unknown>);\n if (parsed !== null) return parsed;\n }\n\n let parsedValue: unknown = row.value;\n try {\n parsedValue = JSON.parse(row.value);\n } catch {\n logger.warn('Corrupt value JSON in getAttributesFromRow, using raw string', {\n key: row.key,\n });\n }\n\n return extractAttributes(parsedValue, extractionConfig);\n}\n\n/**\n * Find memories with overlapping attributes.\n */\nexport function findMatchingMemories(\n rows: MemoryRow[],\n sourceSet: Set<string>,\n attributeType: 'keywords' | 'semanticTags' | 'entities',\n extractionConfig: ExtractionConfig\n): Array<{ entry: AgenticMemoryEntry; overlap: number }> {\n const matches: Array<{ entry: AgenticMemoryEntry; overlap: number }> = [];\n for (const row of rows) {\n const attrs = getAttributesFromRow(row, extractionConfig);\n const targetSet = getAttributeSet(attrs, attributeType);\n let overlap = 0;\n for (const item of sourceSet) if (targetSet.has(item)) overlap++;\n if (overlap > 0)\n matches.push({ entry: memoryRowToAgenticEntry(row, extractionConfig), overlap });\n }\n matches.sort((a, b) => b.overlap - a.overlap);\n return matches;\n}\n","/**\n * Agentic Memory Database Operations\n *\n * Pure database operation helpers for AgenticMemoryBackend.\n * These functions take database instances as parameters to avoid\n * class state dependencies.\n *\n * @module context/agentic-memory-operations\n * (Source: Issue #122, arXiv:2502.12110)\n */\n\nimport { getTimeProvider } from '../core/index.js';\nimport type { ISQLiteDatabase, MemoryRow, MemoryMetadata } from './memory-backend-types.js';\nimport type {\n MemoryAttributes,\n ExtractionConfig,\n AgenticMemoryEntry,\n LinkSuggestion,\n} from './agentic-memory-types.js';\nimport { getAttributesFromRow, memoryRowToAgenticEntry } from './agentic-memory-db-helpers.js';\nimport { GraphMemoryBackend } from './graph-memory.js';\n\n// ============================================================================\n// Database Query Operations\n// ============================================================================\n\n/**\n * Query existing memories for analysis, excluding a specific key.\n * Returns memories with their attributes for linking and evolution detection.\n */\nexport function queryMemoriesForAnalysis(\n db: ISQLiteDatabase,\n excludeKey: string,\n extractionConfig: ExtractionConfig,\n limit = 100\n): Array<{ key: string; attrs: MemoryAttributes; createdAt: Date }> {\n const rows = db\n .prepare<MemoryRow>('SELECT * FROM memories WHERE key != ? ORDER BY accessed_at DESC LIMIT ?')\n .all(excludeKey, limit);\n return rows.map((row) => ({\n key: row.key,\n attrs: getAttributesFromRow(row, extractionConfig),\n createdAt: new Date(row.created_at),\n }));\n}\n\n/**\n * Query a single memory by key.\n */\nexport function queryMemoryByKey(db: ISQLiteDatabase, key: string): MemoryRow | undefined {\n return db.prepare<MemoryRow>('SELECT * FROM memories WHERE key = ?').get(key);\n}\n\n/**\n * Query candidate memories for link suggestions.\n */\nexport function queryCandidateMemories(\n db: ISQLiteDatabase,\n excludeKey: string,\n extractionConfig: ExtractionConfig,\n limit = 100\n): Array<{ key: string; attrs: MemoryAttributes; createdAt: Date }> {\n const rows = db\n .prepare<MemoryRow>('SELECT * FROM memories WHERE key != ? ORDER BY accessed_at DESC LIMIT ?')\n .all(excludeKey, limit);\n return rows.map((row) => ({\n key: row.key,\n attrs: getAttributesFromRow(row, extractionConfig),\n createdAt: new Date(row.created_at),\n }));\n}\n\n/**\n * Query memories for evolution detection.\n */\nexport function queryMemoriesForEvolution(\n db: ISQLiteDatabase,\n excludeKey: string,\n extractionConfig: ExtractionConfig,\n limit = 50\n): Array<{ key: string; attrs: MemoryAttributes; createdAt: Date }> {\n const rows = db\n .prepare<MemoryRow>('SELECT * FROM memories WHERE key != ? ORDER BY created_at DESC LIMIT ?')\n .all(excludeKey, limit);\n return rows.map((row) => ({\n key: row.key,\n attrs: getAttributesFromRow(row, extractionConfig),\n createdAt: new Date(row.created_at),\n }));\n}\n\n/**\n * Query all memories except one for attribute matching.\n */\nexport function queryAllMemoriesExcept(\n db: ISQLiteDatabase,\n excludeKey: string,\n limit = 200\n): MemoryRow[] {\n return db\n .prepare<MemoryRow>('SELECT * FROM memories WHERE key != ? ORDER BY accessed_at DESC LIMIT ?')\n .all(excludeKey, limit);\n}\n\n/**\n * Update memory metadata with refreshed attributes.\n */\nexport function updateMemoryMetadata(\n db: ISQLiteDatabase,\n key: string,\n metadata: Record<string, unknown>\n): void {\n db.prepare('UPDATE memories SET metadata = ? WHERE key = ?').run(JSON.stringify(metadata), key);\n}\n\n// ============================================================================\n// Graph Relationship Operations\n// ============================================================================\n\n/**\n * Apply link suggestions to the graph backend.\n * Returns the number of links successfully created.\n */\nexport async function applyLinkSuggestions(\n graph: GraphMemoryBackend,\n suggestions: LinkSuggestion[],\n bidirectional: boolean\n): Promise<number> {\n let count = 0;\n for (const s of suggestions) {\n const result = await graph.addRelationship(s.from, s.to, s.relationType, {\n weight: s.confidence,\n metadata: { reason: s.reason },\n });\n if (!result.ok) continue;\n count++;\n if (bidirectional) {\n await graph.addRelationship(s.to, s.from, s.relationType, {\n weight: s.confidence,\n metadata: { reason: s.reason },\n });\n }\n }\n return count;\n}\n\n// ============================================================================\n// Attribute Refresh Operations\n// ============================================================================\n\n/**\n * Prepare updated metadata with refreshed attributes.\n */\nexport function prepareRefreshedMetadata(\n currentMeta: Record<string, unknown>,\n attributes: MemoryAttributes\n): Record<string, unknown> {\n return {\n ...currentMeta,\n amem: { ...attributes, attributesUpdatedAt: getTimeProvider().now() },\n };\n}\n\n// ============================================================================\n// Entry Conversion Operations\n// ============================================================================\n\n/**\n * Convert memory row to agentic entry with attributes.\n * Re-exported for convenience.\n */\nexport { memoryRowToAgenticEntry, getAttributesFromRow };\n\n/**\n * Build agentic memory entry from components.\n */\nexport function buildAgenticEntry(\n key: string,\n value: unknown,\n metadata: MemoryMetadata,\n attributes: MemoryAttributes,\n createdAt: Date\n): AgenticMemoryEntry {\n return {\n key,\n value,\n metadata,\n createdAt,\n accessedAt: createdAt,\n attributes,\n };\n}\n","/**\n * Agentic Memory Backend\n *\n * Implements A-MEM Zettelkasten-style agentic memory with:\n * - Automatic attribute extraction (keywords, tags, entities)\n * - Dynamic linking between related memories\n * - Memory evolution detection\n *\n * Composes with HybridMemoryBackend for storage and GraphMemoryBackend\n * for relationship management.\n *\n * @module context/agentic-memory\n * (Source: Issue #122, arXiv:2502.12110)\n */\n\nimport type { Result } from '../core/result.js';\nimport { ok, err } from '../core/result.js';\nimport { getTimeProvider } from '../core/index.js';\nimport type { ILogger } from '../core/logger.js';\nimport { createLogger } from '../core/logger.js';\nimport type { MemoryEntry, MemoryMetadata, ISQLiteDatabase } from './memory-backend-types.js';\nimport { MemoryError } from './memory-backend-types.js';\nimport { HybridMemoryBackend } from './memory-backend.js';\nimport { GraphMemoryBackend } from './graph-memory.js';\nimport type {\n IAgenticMemory,\n AgenticMemoryConfig,\n AgenticMemoryEntry,\n AgenticStoreResult,\n MemoryAttributes,\n ExtractionConfig,\n LinkingConfig,\n LinkingOptions,\n LinkSuggestion,\n EvolutionResult,\n} from './agentic-memory-types.js';\nimport { AgenticMemoryConfigSchema } from './agentic-memory-types.js';\nimport { extractAttributes, mergeExtractionConfig } from './agentic-memory-extraction.js';\nimport {\n generateLinkSuggestions,\n detectEvolution,\n mergeLinkingConfig,\n} from './agentic-memory-linking.js';\nimport {\n searchWithAttributes,\n getAttributeSet,\n findMatchingMemories,\n} from './agentic-memory-db-helpers.js';\nimport {\n queryMemoriesForAnalysis,\n queryMemoryByKey,\n queryCandidateMemories,\n queryMemoriesForEvolution,\n queryAllMemoriesExcept,\n updateMemoryMetadata,\n applyLinkSuggestions,\n prepareRefreshedMetadata,\n buildAgenticEntry,\n memoryRowToAgenticEntry,\n getAttributesFromRow,\n} from './agentic-memory-operations.js';\n\n// Re-export types (type-only exports)\nexport type {\n IAgenticMemory,\n AgenticMemoryConfig,\n AgenticMemoryEntry,\n AgenticStoreResult,\n MemoryAttributes,\n ExtractionConfig,\n LinkingConfig,\n LinkingOptions,\n LinkSuggestion,\n EvolutionResult,\n EntityReference,\n} from './agentic-memory-types.js';\n\n// Re-export values (EntityType and EvolutionType are both const values and types)\nexport {\n EntityType,\n EvolutionType,\n DEFAULT_EXTRACTION_CONFIG,\n DEFAULT_LINKING_CONFIG,\n DEFAULT_AGENTIC_MEMORY_CONFIG,\n} from './agentic-memory-types.js';\n\nconst logger = createLogger({ component: 'AgenticMemoryBackend' });\n\n/**\n * Agentic memory backend with A-MEM Zettelkasten-style organization.\n *\n * Provides automatic attribute extraction, dynamic linking suggestions,\n * and memory evolution detection on top of the hybrid storage backend.\n */\nexport class AgenticMemoryBackend implements IAgenticMemory {\n private readonly config: AgenticMemoryConfig;\n private readonly log: ILogger;\n private readonly base: HybridMemoryBackend;\n private readonly graph: GraphMemoryBackend;\n private extractionConfig: ExtractionConfig;\n private linkingConfig: LinkingConfig;\n private db: ISQLiteDatabase | null = null;\n private initialized = false;\n private initPromise: Promise<Result<void, MemoryError>> | undefined;\n\n constructor(config: AgenticMemoryConfig) {\n const validation = AgenticMemoryConfigSchema.safeParse(config);\n if (!validation.success) {\n const msg = validation.error.issues\n .map((i) => `${i.path.join('.')}: ${i.message}`)\n .join('; ');\n throw new MemoryError(`Invalid AgenticMemoryBackend config: ${msg}`);\n }\n this.config = config;\n this.log = logger;\n this.extractionConfig = mergeExtractionConfig(config.extraction);\n this.linkingConfig = mergeLinkingConfig(config.linking);\n this.base = new HybridMemoryBackend({\n dbPath: config.dbPath,\n markdownDir: config.markdownDir,\n autoExpire: config.autoExpire ?? true,\n });\n this.graph = new GraphMemoryBackend({\n dbPath: config.dbPath,\n markdownDir: config.markdownDir,\n autoExpire: config.autoExpire ?? true,\n });\n }\n\n async initialize(): Promise<Result<void, MemoryError>> {\n if (this.initialized) return ok(undefined);\n this.initPromise ??= this.doInitialize().finally(() => {\n this.initPromise = undefined;\n });\n return this.initPromise;\n }\n\n private async doInitialize(): Promise<Result<void, MemoryError>> {\n const baseInit = await this.base.initialize();\n if (!baseInit.ok) return baseInit;\n\n const graphInit = await this.graph.initialize();\n if (!graphInit.ok) return graphInit;\n\n try {\n const mod = await import('better-sqlite3').catch((cause: unknown) => {\n this.log.debug('better-sqlite3 import failed', { error: String(cause) });\n return null;\n });\n if (mod === null)\n return err(\n new MemoryError('better-sqlite3 not installed. Install: npm install better-sqlite3')\n );\n const Database = mod.default;\n this.db = new Database(this.config.dbPath);\n this.initialized = true;\n this.log.info('AgenticMemoryBackend initialized');\n return ok(undefined);\n } catch (error) {\n const cause = error instanceof Error ? error : new Error(String(error));\n return err(new MemoryError('Failed to initialize agentic backend', { cause }));\n }\n }\n\n initializeWithDatabase(database: ISQLiteDatabase): void {\n this.base.initializeWithDatabase(database);\n this.graph.initializeWithDatabase(database);\n this.db = database;\n this.initialized = true;\n this.log.info('AgenticMemoryBackend initialized with database');\n }\n\n private getDb(): ISQLiteDatabase {\n if (this.db === null) throw new MemoryError('Database not initialized');\n return this.db;\n }\n\n private ensureInit(): void {\n if (!this.initialized) throw new MemoryError('AgenticMemoryBackend not initialized');\n }\n\n // IMemoryBackend Methods (delegated to base)\n store(key: string, value: unknown, metadata: MemoryMetadata): Promise<Result<void, MemoryError>> {\n return this.base.store(key, value, metadata);\n }\n retrieve(key: string): Promise<Result<unknown, MemoryError>> {\n return this.base.retrieve(key);\n }\n search(query: string, limit: number): Promise<Result<MemoryEntry[], MemoryError>> {\n return this.base.search(query, limit);\n }\n prune(olderThan: Date): Promise<Result<number, MemoryError>> {\n return this.base.prune(olderThan);\n }\n count(): Promise<Result<number, MemoryError>> {\n return this.base.count();\n }\n\n // IAgenticMemory Methods\n async storeWithAttributes(\n key: string,\n value: unknown,\n metadata: MemoryMetadata\n ): Promise<Result<AgenticStoreResult, MemoryError>> {\n try {\n this.ensureInit();\n const attributes = extractAttributes(value, this.extractionConfig);\n const extendedMetadata = { ...metadata, amem: { ...attributes } };\n\n const storeResult = await this.base.store(key, value, extendedMetadata);\n if (!storeResult.ok) return storeResult;\n\n const existingMemories = queryMemoriesForAnalysis(this.getDb(), key, this.extractionConfig);\n const now = new Date(getTimeProvider().now());\n const linkSuggestions = generateLinkSuggestions(\n key,\n attributes,\n now,\n existingMemories,\n this.linkingConfig\n );\n const evolution = detectEvolution(key, attributes, now, existingMemories);\n const entry = buildAgenticEntry(key, value, extendedMetadata, attributes, now);\n\n this.log.debug('Stored with attributes', { key, keywords: attributes.keywords.length });\n return ok({ entry, linkSuggestions, evolution });\n } catch (error) {\n const cause = error instanceof Error ? error : new Error(String(error));\n return err(new MemoryError('Failed to store with attributes', { cause }));\n }\n }\n\n retrieveWithAttributes(key: string): Promise<Result<AgenticMemoryEntry | null, MemoryError>> {\n try {\n this.ensureInit();\n const row = queryMemoryByKey(this.getDb(), key);\n if (row === undefined) return Promise.resolve(ok(null));\n const entry = memoryRowToAgenticEntry(row, this.extractionConfig);\n return Promise.resolve(ok(entry));\n } catch (error) {\n const cause = error instanceof Error ? error : new Error(String(error));\n return Promise.resolve(err(new MemoryError('Failed to retrieve with attributes', { cause })));\n }\n }\n\n searchAgentic(query: string, limit = 10): Promise<Result<AgenticMemoryEntry[], MemoryError>> {\n try {\n this.ensureInit();\n const entries = searchWithAttributes(this.getDb(), query, limit, this.extractionConfig);\n return Promise.resolve(ok(entries));\n } catch (error) {\n const cause = error instanceof Error ? error : new Error(String(error));\n return Promise.resolve(err(new MemoryError('Failed to search agentic', { cause })));\n }\n }\n\n suggestLinks(key: string, limit?: number): Promise<Result<LinkSuggestion[], MemoryError>> {\n try {\n this.ensureInit();\n const sourceRow = queryMemoryByKey(this.getDb(), key);\n if (sourceRow === undefined)\n return Promise.resolve(err(new MemoryError(`Memory not found: ${key}`)));\n\n const sourceAttrs = getAttributesFromRow(sourceRow, this.extractionConfig);\n const candidates = queryCandidateMemories(this.getDb(), key, this.extractionConfig);\n const maxSuggestions = limit ?? this.linkingConfig.maxSuggestions;\n const suggestions = generateLinkSuggestions(\n key,\n sourceAttrs,\n new Date(sourceRow.created_at),\n candidates,\n { ...this.linkingConfig, maxSuggestions }\n );\n return Promise.resolve(ok(suggestions));\n } catch (error) {\n const cause = error instanceof Error ? error : new Error(String(error));\n return Promise.resolve(err(new MemoryError('Failed to suggest links', { cause })));\n }\n }\n\n async linkRelatedMemories(\n key: string,\n opts?: LinkingOptions\n ): Promise<Result<number, MemoryError>> {\n try {\n this.ensureInit();\n const { threshold = 0.7, maxLinks, bidirectional = true } = opts ?? {};\n const limit = maxLinks ?? this.linkingConfig.maxSuggestions;\n\n const suggestionsResult = await this.suggestLinks(key, limit);\n if (!suggestionsResult.ok) return suggestionsResult;\n\n const filtered = suggestionsResult.value.filter((s) => s.confidence >= threshold);\n const linksCreated = await applyLinkSuggestions(this.graph, filtered, bidirectional);\n\n this.log.debug('Linked related memories', { key, linksCreated, threshold });\n return ok(linksCreated);\n } catch (error) {\n const cause = error instanceof Error ? error : new Error(String(error));\n return err(new MemoryError('Failed to link related memories', { cause }));\n }\n }\n\n detectEvolution(key: string): Promise<Result<EvolutionResult[], MemoryError>> {\n try {\n this.ensureInit();\n const sourceRow = queryMemoryByKey(this.getDb(), key);\n if (sourceRow === undefined)\n return Promise.resolve(err(new MemoryError(`Memory not found: ${key}`)));\n\n const sourceAttrs = getAttributesFromRow(sourceRow, this.extractionConfig);\n const existingMemories = queryMemoriesForEvolution(this.getDb(), key, this.extractionConfig);\n const evolution = detectEvolution(\n key,\n sourceAttrs,\n new Date(sourceRow.created_at),\n existingMemories\n );\n return Promise.resolve(ok(evolution));\n } catch (error) {\n const cause = error instanceof Error ? error : new Error(String(error));\n return Promise.resolve(err(new MemoryError('Failed to detect evolution', { cause })));\n }\n }\n\n refreshAttributes(key: string): Promise<Result<MemoryAttributes, MemoryError>> {\n try {\n this.ensureInit();\n const row = queryMemoryByKey(this.getDb(), key);\n if (row === undefined)\n return Promise.resolve(err(new MemoryError(`Memory not found: ${key}`)));\n\n const value = JSON.parse(row.value) as unknown;\n const attributes = extractAttributes(value, this.extractionConfig);\n const currentMeta = JSON.parse(row.metadata) as Record<string, unknown>;\n const updatedMeta = prepareRefreshedMetadata(currentMeta, attributes);\n updateMemoryMetadata(this.getDb(), key, updatedMeta);\n\n this.log.debug('Refreshed attributes', { key, keywords: attributes.keywords.length });\n return Promise.resolve(ok(attributes));\n } catch (error) {\n const cause = error instanceof Error ? error : new Error(String(error));\n return Promise.resolve(err(new MemoryError('Failed to refresh attributes', { cause })));\n }\n }\n\n findBySharedAttributes(\n key: string,\n attributeType: 'keywords' | 'semanticTags' | 'entities',\n limit = 10\n ): Promise<Result<AgenticMemoryEntry[], MemoryError>> {\n try {\n this.ensureInit();\n const sourceRow = queryMemoryByKey(this.getDb(), key);\n if (sourceRow === undefined)\n return Promise.resolve(err(new MemoryError(`Memory not found: ${key}`)));\n\n const sourceAttrs = getAttributesFromRow(sourceRow, this.extractionConfig);\n const sourceSet = getAttributeSet(sourceAttrs, attributeType);\n if (sourceSet.size === 0) return Promise.resolve(ok([]));\n\n const allRows = queryAllMemoriesExcept(this.getDb(), key);\n const matches = findMatchingMemories(\n allRows,\n sourceSet,\n attributeType,\n this.extractionConfig\n );\n return Promise.resolve(ok(matches.slice(0, limit).map((m) => m.entry)));\n } catch (error) {\n const cause = error instanceof Error ? error : new Error(String(error));\n return Promise.resolve(\n err(new MemoryError('Failed to find by shared attributes', { cause }))\n );\n }\n }\n\n // Configuration getters and setters\n getExtractionConfig(): ExtractionConfig {\n return this.extractionConfig;\n }\n updateExtractionConfig(config: Partial<ExtractionConfig>): void {\n this.extractionConfig = mergeExtractionConfig({ ...this.extractionConfig, ...config });\n this.log.info('Updated extraction config');\n }\n getLinkingConfig(): LinkingConfig {\n return this.linkingConfig;\n }\n updateLinkingConfig(config: Partial<LinkingConfig>): void {\n this.linkingConfig = mergeLinkingConfig({ ...this.linkingConfig, ...config });\n this.log.info('Updated linking config');\n }\n\n close(): void {\n this.base.close();\n this.graph.close();\n if (this.db !== null) {\n this.db.close();\n this.db = null;\n }\n this.initialized = false;\n this.log.info('AgenticMemoryBackend closed');\n }\n}\n\n/** Create an AgenticMemoryBackend instance. */\nexport function createAgenticMemory(config: AgenticMemoryConfig): AgenticMemoryBackend {\n return new AgenticMemoryBackend(config);\n}\n","/**\n * Adaptive Memory Types\n *\n * Type definitions for adaptive memory with priority-based retrieval\n * combining recency decay, importance weighting, and context relevance.\n *\n * @module context/adaptive-memory-types\n * (Source: Issue #143, arXiv:2310.08560)\n */\n\nimport { z } from 'zod';\nimport type { Result } from '../core/result.js';\nimport type { MemoryEntry, MemoryError, IMemoryBackend } from './memory-backend-types.js';\n\n// ============================================================================\n// Scoring Configuration\n// ============================================================================\n\n/**\n * Weights for combining priority score components.\n * All weights should sum to 1.0 for normalized scoring.\n */\nexport interface ScoringWeights {\n /** Weight for recency score (0-1) */\n readonly recency: number;\n /** Weight for importance score (0-1) */\n readonly importance: number;\n /** Weight for relevance score (0-1) */\n readonly relevance: number;\n}\n\n/** Base Zod schema for ScoringWeights (without sum validation). */\nconst ScoringWeightsBaseSchema = z.object({\n recency: z.number().min(0).max(1),\n importance: z.number().min(0).max(1),\n relevance: z.number().min(0).max(1),\n});\n\n/** Zod schema for ScoringWeights validation (with sum check). */\nexport const ScoringWeightsSchema = ScoringWeightsBaseSchema.refine(\n (w) => Math.abs(w.recency + w.importance + w.relevance - 1.0) < 0.001,\n { message: 'Weights must sum to 1.0' }\n);\n\n/** Partial ScoringWeights schema for overrides. */\nexport const PartialScoringWeightsSchema = ScoringWeightsBaseSchema.partial();\n\n/**\n * Configuration for importance level weights.\n */\nexport interface ImportanceWeights {\n /** Score for LOW importance (0-1) */\n readonly low: number;\n /** Score for MEDIUM importance (0-1) */\n readonly medium: number;\n /** Score for HIGH importance (0-1) */\n readonly high: number;\n}\n\n/** Zod schema for ImportanceWeights validation. */\nexport const ImportanceWeightsSchema = z.object({\n low: z.number().min(0).max(1),\n medium: z.number().min(0).max(1),\n high: z.number().min(0).max(1),\n});\n\n/**\n * Configuration for recency decay.\n */\nexport interface DecayConfig {\n /** Half-life in milliseconds (time for score to decay by 50%) */\n readonly halfLifeMs: number;\n /** Minimum recency score (floor, prevents zero scores) */\n readonly minScore: number;\n}\n\n/** Zod schema for DecayConfig validation. */\nexport const DecayConfigSchema = z.object({\n halfLifeMs: z.number().positive(),\n minScore: z.number().min(0).max(1),\n});\n\n// ============================================================================\n// Priority Score\n// ============================================================================\n\n/**\n * Components of a priority score.\n */\nexport interface PriorityScoreComponents {\n /** Recency score (0-1) based on time since last access */\n readonly recency: number;\n /** Importance score (0-1) based on importance level */\n readonly importance: number;\n /** Relevance score (0-1) based on query similarity */\n readonly relevance: number;\n}\n\n/**\n * Complete priority score with components.\n */\nexport interface PriorityScore {\n /** Final combined score */\n readonly score: number;\n /** Individual score components */\n readonly components: PriorityScoreComponents;\n}\n\n/** Zod schema for PriorityScore validation. */\nexport const PriorityScoreSchema = z.object({\n score: z.number().min(0),\n components: z.object({\n recency: z.number().min(0).max(1),\n importance: z.number().min(0).max(1),\n relevance: z.number().min(0).max(1),\n }),\n});\n\n// ============================================================================\n// Scored Memory Entry\n// ============================================================================\n\n/**\n * A memory entry with its priority score.\n */\nexport interface ScoredMemoryEntry {\n /** The memory entry */\n readonly entry: MemoryEntry;\n /** The priority score */\n readonly priority: PriorityScore;\n}\n\n/** Zod schema for ScoredMemoryEntry validation. */\nexport const ScoredMemoryEntrySchema = z.object({\n entry: z.object({\n key: z.string(),\n value: z.unknown(),\n metadata: z.object({\n importance: z.enum(['low', 'medium', 'high']),\n tags: z.array(z.string()).optional(),\n ttl: z.number().optional(),\n }),\n createdAt: z.date(),\n accessedAt: z.date(),\n }),\n priority: PriorityScoreSchema,\n});\n\n// ============================================================================\n// Retrieval Options\n// ============================================================================\n\n/**\n * Options for priority-based retrieval.\n */\nexport interface PriorityRetrievalOptions {\n /** Query string for relevance scoring (optional) */\n readonly query?: string;\n /** Maximum number of results */\n readonly limit?: number;\n /** Minimum priority score threshold */\n readonly minScore?: number;\n /** Override scoring weights for this query */\n readonly weights?: Partial<ScoringWeights>;\n /** Filter by importance levels */\n readonly importanceFilter?: readonly ('low' | 'medium' | 'high')[];\n /** Filter by tags (entries must have at least one matching tag) */\n readonly tagFilter?: readonly string[];\n}\n\n/** Zod schema for PriorityRetrievalOptions validation. */\nexport const PriorityRetrievalOptionsSchema = z.object({\n query: z.string().optional(),\n limit: z.number().int().positive().optional(),\n minScore: z.number().min(0).optional(),\n weights: PartialScoringWeightsSchema.optional(),\n importanceFilter: z.array(z.enum(['low', 'medium', 'high'])).optional(),\n tagFilter: z.array(z.string()).optional(),\n});\n\n// ============================================================================\n// Adaptive Memory Interface\n// ============================================================================\n\n/**\n * Extended memory backend with adaptive priority-based retrieval.\n */\nexport interface IAdaptiveMemory extends IMemoryBackend {\n /**\n * Retrieve memories sorted by priority score.\n * @param opts - Retrieval options\n */\n retrieveByPriority(\n opts?: PriorityRetrievalOptions\n ): Promise<Result<ScoredMemoryEntry[], MemoryError>>;\n\n /**\n * Get the priority score for a specific memory entry.\n * @param key - Memory key\n * @param query - Optional query for relevance scoring\n */\n getPriorityScore(key: string, query?: string): Promise<Result<PriorityScore, MemoryError>>;\n\n /**\n * Boost the priority of a memory entry by updating its access time.\n * @param key - Memory key\n */\n touch(key: string): Promise<Result<void, MemoryError>>;\n\n /**\n * Get the current scoring configuration.\n */\n getScoringConfig(): ScoringConfig;\n\n /**\n * Update the scoring configuration.\n * @param config - Partial configuration to update\n */\n updateScoringConfig(config: Partial<ScoringConfig>): void;\n}\n\n// ============================================================================\n// Configuration\n// ============================================================================\n\n/**\n * Complete scoring configuration.\n */\nexport interface ScoringConfig {\n /** Weights for combining score components */\n readonly weights: ScoringWeights;\n /** Importance level score mappings */\n readonly importanceWeights: ImportanceWeights;\n /** Recency decay configuration */\n readonly decay: DecayConfig;\n}\n\n/** Zod schema for ScoringConfig validation. */\nexport const ScoringConfigSchema = z.object({\n weights: ScoringWeightsSchema,\n importanceWeights: ImportanceWeightsSchema,\n decay: DecayConfigSchema,\n});\n\n/**\n * Configuration for AdaptiveMemoryBackend.\n */\nexport interface AdaptiveMemoryConfig {\n /** Path to SQLite database file */\n readonly dbPath: string;\n /** Directory for Markdown exports */\n readonly markdownDir: string;\n /** Scoring configuration (optional, uses defaults if not provided) */\n readonly scoring?: Partial<ScoringConfig>;\n /** Whether to auto-expire TTL entries (default: true) */\n readonly autoExpire?: boolean;\n}\n\n/** Zod schema for AdaptiveMemoryConfig validation. */\nexport const AdaptiveMemoryConfigSchema = z.object({\n dbPath: z.string().min(1),\n markdownDir: z.string().min(1),\n scoring: ScoringConfigSchema.partial().optional(),\n autoExpire: z.boolean().optional(),\n});\n\n// ============================================================================\n// Default Configuration\n// ============================================================================\n\n/** Default scoring weights (balanced). */\nexport const DEFAULT_SCORING_WEIGHTS: ScoringWeights = {\n recency: 0.4,\n importance: 0.3,\n relevance: 0.3,\n};\n\n/** Default importance weights. */\nexport const DEFAULT_IMPORTANCE_WEIGHTS: ImportanceWeights = {\n low: 0.25,\n medium: 0.5,\n high: 1.0,\n};\n\n/** Default decay configuration (24-hour half-life). */\nexport const DEFAULT_DECAY_CONFIG: DecayConfig = {\n halfLifeMs: 24 * 60 * 60 * 1000, // 24 hours\n minScore: 0.1,\n};\n\n/** Default scoring configuration. */\nexport const DEFAULT_SCORING_CONFIG: ScoringConfig = {\n weights: DEFAULT_SCORING_WEIGHTS,\n importanceWeights: DEFAULT_IMPORTANCE_WEIGHTS,\n decay: DEFAULT_DECAY_CONFIG,\n};\n","/**\n * nexus-agents/utils - Similarity Utilities\n *\n * Shared utility functions for text similarity calculations.\n * Consolidates duplicate similarity code from multiple modules per ADR-0013.\n *\n * Used by:\n * - context/adaptive-memory-helpers.ts (relevance scoring)\n * - agents/orchestration/policy-feature-extraction.ts (stuck detection)\n *\n * @module utils/similarity-utils\n * @see docs/adr/0013-memory-helpers-consolidation.md\n */\n\n// ============================================================================\n// Token-Based Similarity\n// ============================================================================\n\n/**\n * Calculate token overlap score (query coverage).\n *\n * Measures what fraction of query tokens appear in the target.\n * Score = |query ∩ target| / |query|\n *\n * @param queryTokens - Tokens to find matches for\n * @param targetTokens - Tokens to search in\n * @returns Score between 0 (no overlap) and 1 (full coverage)\n *\n * @example\n * ```ts\n * calculateTokenOverlap(['foo', 'bar'], ['bar', 'baz'])\n * // Returns 0.5 (1 match / 2 query tokens)\n * ```\n */\nexport function calculateTokenOverlap(queryTokens: string[], targetTokens: string[]): number {\n if (queryTokens.length === 0) return 0;\n if (targetTokens.length === 0) return 0;\n\n const targetSet = new Set(targetTokens);\n let matches = 0;\n\n for (const token of queryTokens) {\n if (targetSet.has(token)) matches++;\n }\n\n return matches / queryTokens.length;\n}\n\n/**\n * Calculate set overlap count.\n *\n * Returns the number of elements that appear in both sets.\n * |A ∩ B|\n *\n * @param sourceSet - First set\n * @param targetSet - Second set\n * @returns Number of overlapping elements\n */\nexport function calculateSetOverlapCount<T>(sourceSet: Set<T>, targetSet: Set<T>): number {\n let count = 0;\n for (const item of sourceSet) {\n if (targetSet.has(item)) count++;\n }\n return count;\n}\n\n// ============================================================================\n// Jaccard Similarity\n// ============================================================================\n\n/**\n * Calculate Jaccard similarity between two sets.\n *\n * Jaccard = |A ∩ B| / |A ∪ B|\n *\n * @param set1 - First set\n * @param set2 - Second set\n * @returns Score between 0 (no overlap) and 1 (identical sets)\n *\n * @example\n * ```ts\n * calculateJaccardSimilarity(new Set(['a', 'b']), new Set(['b', 'c']))\n * // Returns 0.333 (1 intersection / 3 union)\n * ```\n */\nexport function calculateJaccardSimilarity<T>(set1: Set<T>, set2: Set<T>): number {\n if (set1.size === 0 && set2.size === 0) return 1;\n if (set1.size === 0 || set2.size === 0) return 0;\n\n const intersection = calculateSetOverlapCount(set1, set2);\n const union = set1.size + set2.size - intersection;\n\n return union > 0 ? intersection / union : 0;\n}\n\n/**\n * Calculate Jaccard similarity between two strings using word tokenization.\n *\n * @param text1 - First text\n * @param text2 - Second text\n * @returns Score between 0 (no overlap) and 1 (identical word sets)\n */\nexport function calculateTextJaccardSimilarity(text1: string, text2: string): number {\n const words1 = new Set(\n text1\n .toLowerCase()\n .split(/\\s+/)\n .filter((w) => w.length > 0)\n );\n const words2 = new Set(\n text2\n .toLowerCase()\n .split(/\\s+/)\n .filter((w) => w.length > 0)\n );\n\n return calculateJaccardSimilarity(words1, words2);\n}\n\n// ============================================================================\n// Similarity Comparison Helpers\n// ============================================================================\n\n/**\n * Check if two texts are highly similar (above threshold).\n *\n * Useful for stuck/loop detection in orchestration.\n *\n * @param text1 - First text\n * @param text2 - Second text\n * @param threshold - Similarity threshold (default: 0.8)\n * @returns True if Jaccard similarity >= threshold\n */\nexport function areTextsSimilar(text1: string, text2: string, threshold = 0.8): boolean {\n return calculateTextJaccardSimilarity(text1, text2) >= threshold;\n}\n\n/**\n * Find the maximum pairwise similarity among a list of texts.\n *\n * @param texts - List of texts to compare\n * @returns Maximum similarity score between any two adjacent texts\n */\nexport function calculateMaxPairwiseSimilarity(texts: string[]): number {\n if (texts.length < 2) return 0;\n\n let maxSimilarity = 0;\n\n for (let i = 1; i < texts.length; i++) {\n const prev = texts[i - 1];\n const curr = texts[i];\n if (prev !== undefined && curr !== undefined) {\n const similarity = calculateTextJaccardSimilarity(prev, curr);\n if (similarity > maxSimilarity) {\n maxSimilarity = similarity;\n }\n }\n }\n\n return maxSimilarity;\n}\n","/**\n * Adaptive Memory Helpers\n *\n * Helper functions for adaptive memory scoring including recency decay,\n * importance weighting, and relevance calculation.\n *\n * @module context/adaptive-memory-helpers\n * (Source: Issue #143, arXiv:2310.08560)\n */\n\nimport { getTimeProvider } from '../core/index.js';\nimport type { MemoryEntry, MemoryRow, ISQLiteDatabase } from './memory-backend-types.js';\nimport { MemoryImportance } from './memory-backend-types.js';\nimport type {\n ScoringConfig,\n PriorityScore,\n PriorityScoreComponents,\n ScoredMemoryEntry,\n PriorityRetrievalOptions,\n ScoringWeights,\n} from './adaptive-memory-types.js';\nimport { DEFAULT_SCORING_CONFIG } from './adaptive-memory-types.js';\n// Shared utilities per ADR-0013\nimport {\n tokenize as sharedTokenize,\n stringifyValue as sharedStringifyValue,\n} from '../utils/text-utils.js';\nimport { calculateTokenOverlap } from '../utils/similarity-utils.js';\nimport { memoryRowToEntry as sharedMemoryRowToEntry } from '../utils/memory-db-utils.js';\n\n// ============================================================================\n// Recency Scoring\n// ============================================================================\n\n/**\n * Calculate recency score using exponential decay.\n * Score = max(minScore, e^(-λt)) where λ = ln(2) / halfLife\n *\n * @param accessedAt - Last access time\n * @param now - Current time\n * @param halfLifeMs - Half-life in milliseconds\n * @param minScore - Minimum score floor\n */\nexport function calculateRecencyScore(\n accessedAt: Date,\n now: Date,\n halfLifeMs: number,\n minScore: number\n): number {\n const elapsedMs = now.getTime() - accessedAt.getTime();\n if (elapsedMs <= 0) return 1.0;\n\n // λ = ln(2) / halfLife\n const lambda = Math.LN2 / halfLifeMs;\n const decayedScore = Math.exp(-lambda * elapsedMs);\n\n return Math.max(minScore, decayedScore);\n}\n\n// ============================================================================\n// Importance Scoring\n// ============================================================================\n\n/**\n * Calculate importance score based on importance level.\n *\n * @param importance - Memory importance level\n * @param config - Scoring configuration\n */\nexport function calculateImportanceScore(importance: string, config: ScoringConfig): number {\n switch (importance) {\n case MemoryImportance.HIGH:\n return config.importanceWeights.high;\n case MemoryImportance.MEDIUM:\n return config.importanceWeights.medium;\n case MemoryImportance.LOW:\n return config.importanceWeights.low;\n default:\n return config.importanceWeights.medium;\n }\n}\n\n// ============================================================================\n// Relevance Scoring\n// ============================================================================\n\n/**\n * Calculate relevance score between query and memory value.\n * Uses token overlap scoring via shared similarity-utils (ADR-0013).\n *\n * @param query - Search query\n * @param value - Memory value (stringified)\n */\nexport function calculateRelevanceScore(query: string | undefined, value: string): number {\n if (query === undefined || query.trim() === '') return 1.0;\n\n const queryTokens = tokenize(query);\n const valueTokens = tokenize(value);\n\n if (queryTokens.length === 0 || valueTokens.length === 0) return 0.5;\n\n // Use shared utility for overlap calculation (ADR-0013)\n return calculateTokenOverlap(queryTokens, valueTokens);\n}\n\n/**\n * Tokenize a string into lowercase words.\n * Uses shared utility from utils/text-utils.ts per ADR-0013.\n */\nfunction tokenize(text: string): string[] {\n return sharedTokenize(text, 1); // Use minLength=1 to match original filter(t.length > 0)\n}\n\n// ============================================================================\n// Combined Priority Scoring\n// ============================================================================\n\n/**\n * Configuration for priority calculation.\n */\nexport interface PriorityCalculationConfig {\n readonly entry: MemoryEntry;\n readonly query?: string;\n readonly now: Date;\n readonly config: ScoringConfig;\n readonly weightOverrides?: Partial<ScoringWeights>;\n}\n\n/**\n * Calculate combined priority score for a memory entry.\n */\nexport function calculatePriorityScore(input: PriorityCalculationConfig): PriorityScore {\n const { entry, query, now, config, weightOverrides } = input;\n\n // Calculate individual components\n const recency = calculateRecencyScore(\n entry.accessedAt,\n now,\n config.decay.halfLifeMs,\n config.decay.minScore\n );\n const importance = calculateImportanceScore(entry.metadata.importance, config);\n const relevance = calculateRelevanceScore(query, stringifyValue(entry.value));\n\n const components: PriorityScoreComponents = { recency, importance, relevance };\n\n // Apply weights\n const weights = resolveWeights(config.weights, weightOverrides);\n const score =\n recency * weights.recency + importance * weights.importance + relevance * weights.relevance;\n\n return { score, components };\n}\n\n/**\n * Stringify a value for relevance scoring.\n * Uses shared utility from utils/text-utils.ts per ADR-0013.\n */\nfunction stringifyValue(value: unknown): string {\n return sharedStringifyValue(value);\n}\n\n/**\n * Resolve weights with optional overrides.\n */\nfunction resolveWeights(base: ScoringWeights, overrides?: Partial<ScoringWeights>): ScoringWeights {\n if (overrides === undefined) return base;\n\n const merged = {\n recency: overrides.recency ?? base.recency,\n importance: overrides.importance ?? base.importance,\n relevance: overrides.relevance ?? base.relevance,\n };\n\n // Normalize if overrides don't sum to 1\n const sum = merged.recency + merged.importance + merged.relevance;\n if (sum === 0) return base;\n if (Math.abs(sum - 1.0) > 0.001) {\n return {\n recency: merged.recency / sum,\n importance: merged.importance / sum,\n relevance: merged.relevance / sum,\n };\n }\n\n return merged;\n}\n\n// ============================================================================\n// Filtering\n// ============================================================================\n\n/**\n * Configuration for filtering scored entries.\n */\nexport interface FilterConfig {\n readonly minScore?: number;\n readonly importanceFilter?: readonly string[];\n readonly tagFilter?: readonly string[];\n}\n\n/**\n * Filter scored entries based on options.\n */\nexport function filterScoredEntries(\n entries: ScoredMemoryEntry[],\n config: FilterConfig\n): ScoredMemoryEntry[] {\n return entries.filter((e) => {\n // Score threshold\n if (config.minScore !== undefined && e.priority.score < config.minScore) {\n return false;\n }\n\n // Importance filter\n if (config.importanceFilter !== undefined && config.importanceFilter.length > 0) {\n if (!config.importanceFilter.includes(e.entry.metadata.importance)) {\n return false;\n }\n }\n\n // Tag filter (at least one matching tag)\n if (config.tagFilter !== undefined && config.tagFilter.length > 0) {\n const entryTags = e.entry.metadata.tags ?? [];\n const hasMatch = config.tagFilter.some((t) => entryTags.includes(t));\n if (!hasMatch) return false;\n }\n\n return true;\n });\n}\n\n// ============================================================================\n// Database Queries\n// ============================================================================\n\n/**\n * Update the accessed_at timestamp for a memory.\n */\nexport function touchMemory(db: ISQLiteDatabase, key: string): boolean {\n const stmt = db.prepare('UPDATE memories SET accessed_at = ? WHERE key = ?');\n const result = stmt.run(getTimeProvider().now(), key);\n return result.changes > 0;\n}\n\n// ============================================================================\n// Scoring Pipeline\n// ============================================================================\n\n/**\n * Score all entries and return sorted by priority.\n */\nexport function scoreAndSortEntries(\n rows: MemoryRow[],\n opts: PriorityRetrievalOptions | undefined,\n config: ScoringConfig\n): ScoredMemoryEntry[] {\n const now = new Date(getTimeProvider().now());\n\n // Convert and score\n const scored: ScoredMemoryEntry[] = rows.map((row) => {\n const entry = sharedMemoryRowToEntry(row);\n const priority = calculatePriorityScore({\n entry,\n now,\n config,\n ...(opts?.query !== undefined && { query: opts.query }),\n ...(opts?.weights !== undefined && { weightOverrides: opts.weights }),\n });\n return { entry, priority };\n });\n\n // Filter - build config with only defined properties\n const filterConfig: FilterConfig = {\n ...(opts?.minScore !== undefined && { minScore: opts.minScore }),\n ...(opts?.importanceFilter !== undefined && { importanceFilter: opts.importanceFilter }),\n ...(opts?.tagFilter !== undefined && { tagFilter: opts.tagFilter }),\n };\n const filtered = filterScoredEntries(scored, filterConfig);\n\n // Sort by score descending\n filtered.sort((a, b) => b.priority.score - a.priority.score);\n\n // Apply limit\n const limit = opts?.limit ?? 100;\n return filtered.slice(0, limit);\n}\n\n// ============================================================================\n// Configuration Merging\n// ============================================================================\n\n/**\n * Merge partial scoring config with defaults.\n */\nexport function mergeScoringConfig(partial?: Partial<ScoringConfig>): ScoringConfig {\n if (partial === undefined) return DEFAULT_SCORING_CONFIG;\n\n return {\n weights: partial.weights ?? DEFAULT_SCORING_CONFIG.weights,\n importanceWeights: partial.importanceWeights ?? DEFAULT_SCORING_CONFIG.importanceWeights,\n decay: partial.decay ?? DEFAULT_SCORING_CONFIG.decay,\n };\n}\n","/**\n * Adaptive Memory Backend\n *\n * Implements adaptive memory with priority-based retrieval combining\n * recency decay, importance weighting, and context relevance.\n *\n * @module context/adaptive-memory\n * (Source: Issue #143, arXiv:2310.08560)\n */\n\nimport type { Result } from '../core/result.js';\nimport { ok, err } from '../core/result.js';\nimport { getTimeProvider } from '../core/index.js';\nimport type { ILogger } from '../core/logger.js';\nimport { createLogger } from '../core/logger.js';\nimport type { MemoryEntry, MemoryMetadata, ISQLiteDatabase } from './memory-backend-types.js';\nimport { MemoryError } from './memory-backend-types.js';\nimport { HybridMemoryBackend } from './memory-backend.js';\nimport type {\n IAdaptiveMemory,\n AdaptiveMemoryConfig,\n ScoringConfig,\n PriorityScore,\n ScoredMemoryEntry,\n PriorityRetrievalOptions,\n} from './adaptive-memory-types.js';\nimport { AdaptiveMemoryConfigSchema } from './adaptive-memory-types.js';\nimport {\n mergeScoringConfig,\n scoreAndSortEntries,\n touchMemory,\n calculatePriorityScore,\n} from './adaptive-memory-helpers.js';\n// Shared utilities per ADR-0013\nimport {\n getAllMemoryRows,\n getMemoryRow,\n memoryExists,\n memoryRowToEntry,\n} from '../utils/memory-db-utils.js';\n\n// Re-export types\nexport type {\n IAdaptiveMemory,\n AdaptiveMemoryConfig,\n ScoringConfig,\n PriorityScore,\n ScoredMemoryEntry,\n PriorityRetrievalOptions,\n ScoringWeights,\n ImportanceWeights,\n DecayConfig,\n PriorityScoreComponents,\n} from './adaptive-memory-types.js';\nexport { DEFAULT_SCORING_CONFIG } from './adaptive-memory-types.js';\n\nconst logger = createLogger({ component: 'AdaptiveMemoryBackend' });\n\n/**\n * Adaptive memory backend with priority-based retrieval.\n */\nexport class AdaptiveMemoryBackend implements IAdaptiveMemory {\n private readonly config: AdaptiveMemoryConfig;\n private readonly log: ILogger;\n private readonly base: HybridMemoryBackend;\n private scoringConfig: ScoringConfig;\n private db: ISQLiteDatabase | null = null;\n private initialized = false;\n private initPromise: Promise<Result<void, MemoryError>> | undefined;\n\n constructor(config: AdaptiveMemoryConfig) {\n const validation = AdaptiveMemoryConfigSchema.safeParse(config);\n if (!validation.success) {\n const msg = validation.error.issues\n .map((i) => `${i.path.join('.')}: ${i.message}`)\n .join('; ');\n throw new MemoryError(`Invalid AdaptiveMemoryBackend config: ${msg}`);\n }\n this.config = config;\n this.log = logger;\n this.scoringConfig = mergeScoringConfig(config.scoring);\n this.base = new HybridMemoryBackend({ dbPath: config.dbPath, markdownDir: config.markdownDir });\n }\n\n async initialize(): Promise<Result<void, MemoryError>> {\n if (this.initialized) return ok(undefined);\n this.initPromise ??= this.doInitialize().finally(() => {\n this.initPromise = undefined;\n });\n return this.initPromise;\n }\n\n private async doInitialize(): Promise<Result<void, MemoryError>> {\n const baseInit = await this.base.initialize();\n if (!baseInit.ok) return baseInit;\n\n try {\n const mod = await import('better-sqlite3').catch((cause: unknown) => {\n this.log.debug('better-sqlite3 import failed', { error: String(cause) });\n return null;\n });\n if (mod === null)\n return err(\n new MemoryError('better-sqlite3 not installed. Install: npm install better-sqlite3')\n );\n const Database = mod.default;\n this.db = new Database(this.config.dbPath);\n this.initialized = true;\n this.log.info('AdaptiveMemoryBackend initialized');\n return ok(undefined);\n } catch (error) {\n const cause = error instanceof Error ? error : new Error(String(error));\n return err(new MemoryError('Failed to initialize adaptive backend', { cause }));\n }\n }\n\n initializeWithDatabase(database: ISQLiteDatabase): void {\n this.base.initializeWithDatabase(database);\n this.db = database;\n this.initialized = true;\n this.log.info('AdaptiveMemoryBackend initialized with database');\n }\n\n private getDb(): ISQLiteDatabase {\n if (this.db === null) throw new MemoryError('Database not initialized');\n return this.db;\n }\n\n private ensureInit(): void {\n if (!this.initialized) throw new MemoryError('AdaptiveMemoryBackend not initialized');\n }\n\n // =========================================================================\n // IMemoryBackend Methods (delegated to base)\n // =========================================================================\n\n store(key: string, value: unknown, metadata: MemoryMetadata): Promise<Result<void, MemoryError>> {\n return this.base.store(key, value, metadata);\n }\n\n retrieve(key: string): Promise<Result<unknown, MemoryError>> {\n return this.base.retrieve(key);\n }\n\n search(query: string, limit: number): Promise<Result<MemoryEntry[], MemoryError>> {\n return this.base.search(query, limit);\n }\n\n prune(olderThan: Date): Promise<Result<number, MemoryError>> {\n return this.base.prune(olderThan);\n }\n\n count(): Promise<Result<number, MemoryError>> {\n return this.base.count();\n }\n\n // =========================================================================\n // IAdaptiveMemory Methods\n // =========================================================================\n\n retrieveByPriority(\n opts?: PriorityRetrievalOptions\n ): Promise<Result<ScoredMemoryEntry[], MemoryError>> {\n try {\n this.ensureInit();\n const db = this.getDb();\n\n // Get all rows (with a reasonable limit for initial fetch)\n const maxFetch = (opts?.limit ?? 100) * 2;\n const rows = getAllMemoryRows(db, maxFetch);\n\n // Score, filter, and sort\n const scored = scoreAndSortEntries(rows, opts, this.scoringConfig);\n\n this.log.debug('Retrieved by priority', { count: scored.length, query: opts?.query });\n return Promise.resolve(ok(scored));\n } catch (error) {\n const cause = error instanceof Error ? error : new Error(String(error));\n return Promise.resolve(err(new MemoryError('Failed to retrieve by priority', { cause })));\n }\n }\n\n getPriorityScore(key: string, query?: string): Promise<Result<PriorityScore, MemoryError>> {\n try {\n this.ensureInit();\n const db = this.getDb();\n\n if (!memoryExists(db, key)) {\n return Promise.resolve(err(new MemoryError(`Key not found: ${key}`)));\n }\n\n const row = getMemoryRow(db, key);\n if (row === undefined) {\n return Promise.resolve(err(new MemoryError(`Key not found: ${key}`)));\n }\n\n const entry = memoryRowToEntry(row);\n const priority = calculatePriorityScore({\n entry,\n now: new Date(getTimeProvider().now()),\n config: this.scoringConfig,\n ...(query !== undefined && { query }),\n });\n\n return Promise.resolve(ok(priority));\n } catch (error) {\n const cause = error instanceof Error ? error : new Error(String(error));\n return Promise.resolve(err(new MemoryError('Failed to get priority score', { cause })));\n }\n }\n\n touch(key: string): Promise<Result<void, MemoryError>> {\n try {\n this.ensureInit();\n const db = this.getDb();\n\n if (!memoryExists(db, key)) {\n return Promise.resolve(err(new MemoryError(`Key not found: ${key}`)));\n }\n\n const updated = touchMemory(db, key);\n if (!updated) {\n return Promise.resolve(err(new MemoryError(`Failed to touch: ${key}`)));\n }\n\n this.log.debug('Touched memory', { key });\n return Promise.resolve(ok(undefined));\n } catch (error) {\n const cause = error instanceof Error ? error : new Error(String(error));\n return Promise.resolve(err(new MemoryError('Failed to touch memory', { cause })));\n }\n }\n\n getScoringConfig(): ScoringConfig {\n return this.scoringConfig;\n }\n\n updateScoringConfig(config: Partial<ScoringConfig>): void {\n this.scoringConfig = mergeScoringConfig({ ...this.scoringConfig, ...config });\n this.log.info('Updated scoring config', { config: this.scoringConfig });\n }\n\n // =========================================================================\n // Lifecycle\n // =========================================================================\n\n close(): void {\n this.base.close();\n if (this.db !== null) {\n this.db.close();\n this.db = null;\n }\n this.initialized = false;\n this.log.info('AdaptiveMemoryBackend closed');\n }\n}\n\n/** Create an AdaptiveMemoryBackend instance. */\nexport function createAdaptiveMemory(config: AdaptiveMemoryConfig): AdaptiveMemoryBackend {\n return new AdaptiveMemoryBackend(config);\n}\n","/**\n * nexus-agents/context - Belief Memory Persistence\n *\n * Handles disk serialization/deserialization for HindsightBeliefMemory.\n * Converts in-memory Maps to JSON snapshots and back. Date fields are\n * serialized as ISO strings and restored on load.\n *\n * @module context/belief-memory-persistence\n * (Source: Issue #714 Phase 3 - Unified memory persistence)\n */\n\nimport * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport { nexusDataPath } from '../config/nexus-data-dir.js';\nimport type { Result } from '../core/result.js';\nimport { ok, err } from '../core/result.js';\nimport type { ILogger } from '../core/logger.js';\nimport type { Belief } from './belief-core-types.js';\nimport type { BeliefUpdate } from './belief-update-types.js';\nimport type { Counterfactual, HindsightRecord } from './belief-hindsight-types.js';\nimport {\n BeliefSnapshotSchema,\n type BeliefSnapshot,\n type BeliefMemoryData,\n type HydratedBeliefData,\n type SerializedBelief,\n type SerializedBeliefUpdate,\n type SerializedCounterfactual,\n} from './belief-persistence-types.js';\nimport { getErrorMessage } from '../core/index.js';\n\n// Re-export types for consumers\nexport type {\n BeliefSnapshot,\n BeliefMemoryData,\n HydratedBeliefData,\n} from './belief-persistence-types.js';\n\n// ============================================================================\n// Constants\n// ============================================================================\n\n/** Directory for belief memory snapshots. Resolved at call time via getBeliefsDir(). */\nfunction getBeliefsDir(): string {\n return nexusDataPath('memory', 'beliefs');\n}\nconst MAX_SNAPSHOT_FILES = 10;\nconst SNAPSHOT_VERSION = 1;\n\n// ============================================================================\n// Helpers\n// ============================================================================\n\n/** Conditionally add an optional property to an object. */\nfunction optProp<K extends string, V>(\n key: K,\n value: V | undefined\n): { [P in K]: V } | Record<string, never> {\n if (value === undefined) return {};\n return { [key]: value } as { [P in K]: V };\n}\n\n// ============================================================================\n// Serialization\n// ============================================================================\n\n/** Convert a Belief to its serialized form (Date → ISO string). */\nfunction serializeBelief(b: Belief): SerializedBelief {\n return {\n beliefId: b.beliefId,\n subject: b.subject,\n predicate: b.predicate,\n object: b.object,\n confidence: b.confidence,\n sourceType: b.sourceType,\n version: b.version,\n superseded: b.superseded,\n createdAt: b.createdAt.toISOString(),\n updatedAt: b.updatedAt.toISOString(),\n ...optProp('sourceRef', b.sourceRef),\n ...optProp('derivedFrom', b.derivedFrom),\n ...optProp('supersededBy', b.supersededBy),\n ...optProp('domain', b.domain),\n ...optProp('metadata', b.metadata),\n };\n}\n\n/** Safely extract a string from an unknown value. */\nfunction str(val: unknown, fallback = ''): string {\n return typeof val === 'string' ? val : fallback;\n}\n\n/** Convert a SerializedBelief back to Belief (ISO string → Date). */\nfunction deserializeBelief(s: { [k: string]: unknown }): Belief {\n return {\n beliefId: str(s.beliefId),\n subject: str(s.subject),\n predicate: str(s.predicate),\n object: str(s.object),\n confidence: str(s.confidence, 'medium') as Belief['confidence'],\n sourceType: str(s.sourceType, 'inference') as Belief['sourceType'],\n version: typeof s.version === 'number' ? s.version : 0,\n superseded: s.superseded === true,\n createdAt: new Date(str(s.createdAt)),\n updatedAt: new Date(str(s.updatedAt)),\n ...optProp('sourceRef', typeof s.sourceRef === 'string' ? s.sourceRef : undefined),\n ...optProp(\n 'derivedFrom',\n Array.isArray(s.derivedFrom) ? (s.derivedFrom as readonly string[]) : undefined\n ),\n ...optProp('supersededBy', typeof s.supersededBy === 'string' ? s.supersededBy : undefined),\n ...optProp('domain', typeof s.domain === 'string' ? s.domain : undefined),\n ...optProp(\n 'metadata',\n typeof s.metadata === 'object' && s.metadata !== null\n ? (s.metadata as Record<string, unknown>)\n : undefined\n ),\n };\n}\n\n/** Serialize a Counterfactual to JSON-safe form. */\nfunction serializeCounterfactual(c: Counterfactual): SerializedCounterfactual {\n return {\n counterfactualId: c.counterfactualId,\n hypothesis: c.hypothesis,\n affectedBeliefs: c.affectedBeliefs,\n predictedOutcomes: c.predictedOutcomes,\n validated: c.validated,\n createdAt: c.createdAt.toISOString(),\n ...optProp('actualOutcomes', c.actualOutcomes),\n ...optProp('taskContext', c.taskContext),\n };\n}\n\n/** Create a snapshot from in-memory belief data. */\nexport function createSnapshot(data: BeliefMemoryData): BeliefSnapshot {\n return {\n version: SNAPSHOT_VERSION,\n exportedAt: new Date().toISOString(),\n beliefs: Array.from(data.beliefs.values()).map(serializeBelief),\n updates: Array.from(data.updates.entries()).map(([beliefId, records]) => ({\n beliefId,\n records: records.map(\n (u): SerializedBeliefUpdate => ({\n updateId: u.updateId,\n beliefId: u.beliefId,\n updateType: u.updateType,\n newState: u.newState,\n reason: u.reason,\n timestamp: u.timestamp.toISOString(),\n ...optProp('previousState', u.previousState as Record<string, unknown> | undefined),\n ...optProp('evidence', u.evidence),\n ...optProp('updatedBy', u.updatedBy),\n })\n ),\n })),\n counterfactuals: Array.from(data.counterfactuals.values()).map(serializeCounterfactual),\n hindsightRecords: Array.from(data.hindsightRecords.entries()).map(([taskId, records]) => ({\n taskId,\n records: records.map((r) => ({\n hindsightId: r.hindsightId,\n taskId: r.taskId,\n priorBeliefs: r.priorBeliefs,\n expectedOutcome: r.expectedOutcome,\n actualOutcome: r.actualOutcome,\n outcomeMatched: r.outcomeMatched,\n correctedBeliefs: r.correctedBeliefs,\n newBeliefs: r.newBeliefs,\n lessons: r.lessons,\n createdAt: r.createdAt.toISOString(),\n })),\n })),\n };\n}\n\n// ============================================================================\n// Hydration\n// ============================================================================\n\n/** Hydrate update records from serialized form. */\nfunction hydrateUpdates(entries: BeliefSnapshot['updates']): Map<string, BeliefUpdate[]> {\n const updates = new Map<string, BeliefUpdate[]>();\n for (const entry of entries) {\n updates.set(\n entry.beliefId,\n entry.records.map(\n (u): BeliefUpdate => ({\n updateId: u.updateId,\n beliefId: u.beliefId,\n updateType: u.updateType as BeliefUpdate['updateType'],\n newState: u.newState,\n reason: u.reason,\n timestamp: new Date(u.timestamp),\n ...optProp('previousState', u.previousState as Partial<Belief> | undefined),\n ...optProp('evidence', u.evidence),\n ...optProp('updatedBy', u.updatedBy),\n })\n )\n );\n }\n return updates;\n}\n\n/** Hydrate counterfactuals from serialized form. */\nfunction hydrateCounterfactuals(\n items: BeliefSnapshot['counterfactuals']\n): Map<string, Counterfactual> {\n const map = new Map<string, Counterfactual>();\n for (const c of items) {\n map.set(c.counterfactualId, {\n counterfactualId: c.counterfactualId,\n hypothesis: c.hypothesis,\n affectedBeliefs: [...c.affectedBeliefs],\n predictedOutcomes: [...c.predictedOutcomes],\n validated: c.validated,\n createdAt: new Date(c.createdAt),\n ...optProp('actualOutcomes', c.actualOutcomes ? [...c.actualOutcomes] : undefined),\n ...optProp('taskContext', c.taskContext),\n });\n }\n return map;\n}\n\n/** Hydrate hindsight records from serialized form. */\nfunction hydrateHindsight(\n entries: BeliefSnapshot['hindsightRecords']\n): Map<string, HindsightRecord[]> {\n const map = new Map<string, HindsightRecord[]>();\n for (const entry of entries) {\n map.set(\n entry.taskId,\n entry.records.map((r) => ({\n hindsightId: r.hindsightId,\n taskId: r.taskId,\n priorBeliefs: [...r.priorBeliefs],\n expectedOutcome: r.expectedOutcome,\n actualOutcome: r.actualOutcome,\n outcomeMatched: r.outcomeMatched,\n correctedBeliefs: [...r.correctedBeliefs],\n newBeliefs: [...r.newBeliefs],\n lessons: [...r.lessons],\n createdAt: new Date(r.createdAt),\n }))\n );\n }\n return map;\n}\n\n/** Hydrate a validated snapshot back into Map structures. */\nexport function hydrateSnapshot(snapshot: BeliefSnapshot): HydratedBeliefData {\n const beliefs = new Map<string, Belief>();\n for (const s of snapshot.beliefs) {\n const belief = deserializeBelief(s as unknown as Record<string, unknown>);\n beliefs.set(belief.beliefId, belief);\n }\n return {\n beliefs,\n updates: hydrateUpdates(snapshot.updates),\n counterfactuals: hydrateCounterfactuals(snapshot.counterfactuals),\n hindsightRecords: hydrateHindsight(snapshot.hindsightRecords),\n };\n}\n\n// ============================================================================\n// Disk I/O\n// ============================================================================\n\nfunction ensureBeliefsDir(): void {\n if (!fs.existsSync(getBeliefsDir())) fs.mkdirSync(getBeliefsDir(), { recursive: true });\n}\n\nfunction getSnapshotFiles(): readonly string[] {\n try {\n return fs\n .readdirSync(getBeliefsDir())\n .filter((f) => f.startsWith('beliefs-') && f.endsWith('.json'))\n .sort()\n .reverse();\n } catch {\n return [];\n }\n}\n\nfunction enforceRetention(logger: ILogger): void {\n try {\n const files = getSnapshotFiles();\n if (files.length <= MAX_SNAPSHOT_FILES) return;\n const toDelete = files.slice(MAX_SNAPSHOT_FILES);\n for (const file of toDelete) fs.unlinkSync(path.join(getBeliefsDir(), file));\n logger.debug('Belief snapshot retention enforced', {\n kept: MAX_SNAPSHOT_FILES,\n deleted: toDelete.length,\n });\n } catch (error: unknown) {\n logger.debug('Belief snapshot retention cleanup failed', {\n error: getErrorMessage(error),\n });\n }\n}\n\n/** Save belief memory data to disk as a JSON snapshot. */\nexport function saveBeliefSnapshot(data: BeliefMemoryData, logger: ILogger): Result<string, Error> {\n try {\n ensureBeliefsDir();\n const snapshot = createSnapshot(data);\n const timestamp = new Date().toISOString().replace(/[:.]/g, '-');\n const filename = `beliefs-${timestamp}.json`;\n const filepath = path.join(getBeliefsDir(), filename);\n fs.writeFileSync(filepath, JSON.stringify(snapshot, null, 2), 'utf-8');\n logger.info('Belief memory snapshot saved', { filename, beliefs: snapshot.beliefs.length });\n enforceRetention(logger);\n return ok(filepath);\n } catch (error) {\n const message = getErrorMessage(error);\n return err(new Error(`Failed to save belief snapshot: ${message}`));\n }\n}\n\n/** Load the most recent belief memory snapshot from disk. */\nexport function loadBeliefSnapshot(logger: ILogger): Result<HydratedBeliefData | null, Error> {\n try {\n ensureBeliefsDir();\n const files = getSnapshotFiles();\n if (files.length === 0) {\n logger.debug('No belief snapshots found');\n return ok(null);\n }\n for (const file of files.slice(0, 3)) {\n try {\n const filepath = path.join(getBeliefsDir(), file);\n const raw = JSON.parse(fs.readFileSync(filepath, 'utf-8')) as unknown;\n const validation = BeliefSnapshotSchema.safeParse(raw);\n if (!validation.success) {\n logger.warn('Invalid belief snapshot file', { file, errors: validation.error.issues });\n continue;\n }\n // Cast required due to exactOptionalPropertyTypes — Zod validated the data\n const hydrated = hydrateSnapshot(validation.data);\n logger.info('Belief memory snapshot loaded', { file, beliefs: hydrated.beliefs.size });\n return ok(hydrated);\n } catch (error: unknown) {\n logger.warn('Failed to load belief snapshot file', {\n file,\n error: getErrorMessage(error),\n });\n }\n }\n logger.warn('All recent belief snapshots are invalid');\n return ok(null);\n } catch (error) {\n const message = getErrorMessage(error);\n return err(new Error(`Failed to load belief snapshot: ${message}`));\n }\n}\n","/**\n * nexus-agents/context - Belief Persistence Types & Schema\n *\n * Type definitions, Zod validation schema, and data interfaces\n * for belief memory disk persistence.\n *\n * @module context/belief-persistence-types\n * (Source: Issue #714 Phase 3 - Unified memory persistence)\n */\n\nimport { z } from 'zod';\nimport type { Belief } from './belief-core-types.js';\nimport { BeliefConfidenceSchema, BeliefSourceTypeSchema } from './belief-core-types.js';\nimport type { BeliefUpdate } from './belief-update-types.js';\nimport { BeliefUpdateTypeSchema } from './belief-update-types.js';\nimport type { Counterfactual, HindsightRecord } from './belief-hindsight-types.js';\n\n// ============================================================================\n// Serialized Types (Date → string for JSON)\n// ============================================================================\n\n/** Belief with Date fields as ISO strings. */\nexport interface SerializedBelief {\n readonly beliefId: string;\n readonly subject: string;\n readonly predicate: string;\n readonly object: string;\n readonly confidence: string;\n readonly sourceType: string;\n readonly sourceRef?: string | undefined;\n readonly derivedFrom?: readonly string[] | undefined;\n readonly version: number;\n readonly createdAt: string;\n readonly updatedAt: string;\n readonly superseded: boolean;\n readonly supersededBy?: string | undefined;\n readonly domain?: string | undefined;\n readonly metadata?: Record<string, unknown> | undefined;\n}\n\n/** BeliefUpdate with Date fields as ISO strings. */\nexport interface SerializedBeliefUpdate {\n readonly updateId: string;\n readonly beliefId: string;\n readonly updateType: string;\n readonly previousState?: Record<string, unknown> | undefined;\n readonly newState: Record<string, unknown>;\n readonly reason: string;\n readonly evidence?: string | undefined;\n readonly timestamp: string;\n readonly updatedBy?: string | undefined;\n}\n\n/** Counterfactual with Date fields as ISO strings. */\nexport interface SerializedCounterfactual {\n readonly counterfactualId: string;\n readonly hypothesis: string;\n readonly affectedBeliefs: readonly string[];\n readonly predictedOutcomes: readonly string[];\n readonly actualOutcomes?: readonly string[] | undefined;\n readonly validated: boolean;\n readonly createdAt: string;\n readonly taskContext?: string | undefined;\n}\n\n/** HindsightRecord with Date fields as ISO strings. */\nexport interface SerializedHindsightRecord {\n readonly hindsightId: string;\n readonly taskId: string;\n readonly priorBeliefs: readonly string[];\n readonly expectedOutcome: string;\n readonly actualOutcome: string;\n readonly outcomeMatched: boolean;\n readonly correctedBeliefs: readonly string[];\n readonly newBeliefs: readonly string[];\n readonly lessons: readonly string[];\n readonly createdAt: string;\n}\n\n// ============================================================================\n// Snapshot Type\n// ============================================================================\n\n/** Full snapshot of belief memory state for disk persistence. */\nexport interface BeliefSnapshot {\n readonly version: number;\n readonly exportedAt: string;\n readonly beliefs: readonly SerializedBelief[];\n readonly updates: ReadonlyArray<{\n beliefId: string;\n records: readonly SerializedBeliefUpdate[];\n }>;\n readonly counterfactuals: readonly SerializedCounterfactual[];\n readonly hindsightRecords: ReadonlyArray<{\n taskId: string;\n records: readonly SerializedHindsightRecord[];\n }>;\n}\n\n// ============================================================================\n// Data Interfaces\n// ============================================================================\n\n/** Raw data extracted from HindsightBeliefMemory for serialization. */\nexport interface BeliefMemoryData {\n readonly beliefs: ReadonlyMap<string, Belief>;\n readonly updates: ReadonlyMap<string, readonly BeliefUpdate[]>;\n readonly counterfactuals: ReadonlyMap<string, Counterfactual>;\n readonly hindsightRecords: ReadonlyMap<string, readonly HindsightRecord[]>;\n}\n\n/** Deserialized data ready to hydrate into HindsightBeliefMemory. */\nexport interface HydratedBeliefData {\n readonly beliefs: Map<string, Belief>;\n readonly updates: Map<string, BeliefUpdate[]>;\n readonly counterfactuals: Map<string, Counterfactual>;\n readonly hindsightRecords: Map<string, HindsightRecord[]>;\n}\n\n// ============================================================================\n// Zod Schema for Validation\n// ============================================================================\n\n/** Zod schema for snapshot validation on load. */\nexport const BeliefSnapshotSchema = z.object({\n version: z.number().int().min(1),\n exportedAt: z.string(),\n beliefs: z.array(\n z.object({\n beliefId: z.string(),\n subject: z.string(),\n predicate: z.string(),\n object: z.string(),\n confidence: BeliefConfidenceSchema,\n sourceType: BeliefSourceTypeSchema,\n sourceRef: z.string().optional(),\n derivedFrom: z.array(z.string()).optional(),\n version: z.number(),\n createdAt: z.string(),\n updatedAt: z.string(),\n superseded: z.boolean(),\n supersededBy: z.string().optional(),\n domain: z.string().optional(),\n metadata: z.record(z.string(), z.unknown()).optional(),\n })\n ),\n updates: z.array(\n z.object({\n beliefId: z.string(),\n records: z.array(\n z.object({\n updateId: z.string(),\n beliefId: z.string(),\n updateType: BeliefUpdateTypeSchema,\n previousState: z.record(z.string(), z.unknown()).optional(),\n newState: z.record(z.string(), z.unknown()),\n reason: z.string().max(10_000),\n evidence: z.string().max(10_000).optional(),\n timestamp: z.string(),\n updatedBy: z.string().optional(),\n })\n ),\n })\n ),\n counterfactuals: z.array(\n z.object({\n counterfactualId: z.string(),\n hypothesis: z.string().max(10_000),\n affectedBeliefs: z.array(z.string()),\n predictedOutcomes: z.array(z.string()),\n actualOutcomes: z.array(z.string()).optional(),\n validated: z.boolean(),\n createdAt: z.string(),\n taskContext: z.string().optional(),\n })\n ),\n hindsightRecords: z.array(\n z.object({\n taskId: z.string(),\n records: z.array(\n z.object({\n hindsightId: z.string(),\n taskId: z.string(),\n priorBeliefs: z.array(z.string()),\n expectedOutcome: z.string().max(10_000),\n actualOutcome: z.string().max(10_000),\n outcomeMatched: z.boolean(),\n correctedBeliefs: z.array(z.string()),\n newBeliefs: z.array(z.string()),\n lessons: z.array(z.string()),\n createdAt: z.string(),\n })\n ),\n })\n ),\n});\n","/**\n * nexus-agents/context - Typed Memory Architecture\n *\n * Implements MIRIX-style typed memory system with six distinct memory types\n * for improved agent coordination and context management.\n *\n * @module context/memory-types\n * (Source: Issue #101, arXiv:2507.07957 - MIRIX Architecture)\n */\n\nimport { z } from 'zod';\nimport type { Result } from '../core/result.js';\nimport type { AgentRole } from '../core/types/agent.js';\nimport type { MemoryError, MemoryMetadata } from './memory-backend-types.js';\n\n// Re-export all memory module types for backward compatibility\nexport type {\n CoreMemoryData,\n ICoreMemory,\n EpisodeData,\n IEpisodicMemory,\n SemanticFact,\n ISemanticMemory,\n ProcedureStep,\n Procedure,\n IProceduralMemory,\n ResourceReference,\n IResourceMemory,\n VaultEntry,\n IKnowledgeVault,\n} from './memory-module-types.js';\n\nexport {\n CoreMemoryDataSchema,\n EpisodeDataSchema,\n SemanticFactSchema,\n ProcedureStepSchema,\n ProcedureSchema,\n ResourceReferenceSchema,\n VaultEntrySchema,\n} from './memory-module-types.js';\n\n// Re-export Hindsight Belief Memory types (arXiv:2512.12818)\nexport type {\n Belief,\n BeliefConfidence,\n BeliefMemoryConfig,\n BeliefMemoryStats,\n BeliefQuery,\n BeliefSourceType,\n BeliefUpdate,\n BeliefUpdateType,\n Counterfactual,\n HindsightRecord,\n IHindsightBeliefMemory,\n} from './belief-types.js';\n\nexport {\n BeliefConfidence as BeliefConfidenceEnum,\n BeliefConfidenceSchema,\n BeliefMemoryConfigSchema,\n BeliefMemoryStatsSchema,\n BeliefQuerySchema,\n BeliefSchema,\n BeliefSourceType as BeliefSourceTypeEnum,\n BeliefSourceTypeSchema,\n BeliefUpdateSchema,\n BeliefUpdateType as BeliefUpdateTypeEnum,\n BeliefUpdateTypeSchema,\n CounterfactualSchema,\n DEFAULT_BELIEF_CONFIG,\n HindsightRecordSchema,\n} from './belief-types.js';\n\n// Import interfaces for use in ITypedMemory\nimport type {\n ICoreMemory,\n IEpisodicMemory,\n ISemanticMemory,\n IProceduralMemory,\n IResourceMemory,\n IKnowledgeVault,\n} from './memory-module-types.js';\n\n// Import belief memory interface for extended typed memory\nimport type { IHindsightBeliefMemory } from './belief-types.js';\n\n// ============================================================================\n// Memory Type Enum\n// ============================================================================\n\n/**\n * Seven distinct memory types: six from MIRIX architecture plus Belief Memory.\n * (Source: arXiv:2507.07957 - MIRIX, arXiv:2512.12818 - Hindsight Belief Memory)\n */\nexport const MemoryType = {\n CORE: 'core',\n EPISODIC: 'episodic',\n SEMANTIC: 'semantic',\n PROCEDURAL: 'procedural',\n RESOURCE: 'resource',\n VAULT: 'vault',\n /** Hindsight Belief Memory for reasoning agents (arXiv:2512.12818) */\n BELIEF: 'belief',\n} as const;\n\nexport type MemoryType = (typeof MemoryType)[keyof typeof MemoryType];\n\nexport const MemoryTypeSchema = z.enum([\n 'core',\n 'episodic',\n 'semantic',\n 'procedural',\n 'resource',\n 'vault',\n 'belief',\n]);\n\n// ============================================================================\n// Typed Memory Entry\n// ============================================================================\n\n/**\n * Base typed memory entry with type discrimination.\n */\nexport interface TypedMemoryEntry<T extends MemoryType = MemoryType> {\n readonly id: string;\n readonly type: T;\n readonly key: string;\n readonly value: unknown;\n readonly metadata: MemoryMetadata;\n readonly createdAt: Date;\n readonly accessedAt: Date;\n readonly agentId?: string;\n readonly relevanceScore?: number;\n}\n\n// ============================================================================\n// Typed Memory Interface\n// ============================================================================\n\n/**\n * Unified typed memory interface providing access to all seven memory types.\n * (Source: Issue #101, arXiv:2507.07957 - MIRIX, arXiv:2512.12818 - Hindsight)\n */\nexport interface ITypedMemory {\n readonly core: ICoreMemory;\n readonly episodic: IEpisodicMemory;\n readonly semantic: ISemanticMemory;\n readonly procedural: IProceduralMemory;\n readonly resource: IResourceMemory;\n readonly vault: IKnowledgeVault;\n /** Hindsight Belief Memory for reasoning agents (arXiv:2512.12818) */\n readonly belief: IHindsightBeliefMemory;\n\n /** Query entries by memory type */\n queryByType(\n type: MemoryType,\n query: string,\n limit?: number\n ): Promise<Result<readonly TypedMemoryEntry[], MemoryError>>;\n\n /** Filter memories by relevance to an agent role */\n filterByRelevance(\n agentRole: AgentRole,\n limit?: number\n ): Promise<Result<readonly TypedMemoryEntry[], MemoryError>>;\n\n /** Get memory statistics across all types */\n getStats(): Promise<Result<TypedMemoryStats, MemoryError>>;\n\n /** Prune expired entries across all memory types */\n pruneExpired(): Promise<Result<TypedMemoryPruneResult, MemoryError>>;\n}\n\n/**\n * Statistics for typed memory usage.\n */\nexport interface TypedMemoryStats {\n readonly totalEntries: number;\n readonly entriesByType: Record<MemoryType, number>;\n readonly oldestEntry?: Date;\n readonly newestEntry?: Date;\n readonly totalSizeBytes?: number;\n}\n\n/**\n * Result of pruning expired entries.\n */\nexport interface TypedMemoryPruneResult {\n readonly prunedCount: number;\n readonly prunedByType: Record<MemoryType, number>;\n readonly freedBytes?: number;\n}\n\n// ============================================================================\n// Relevance Filter Configuration\n// ============================================================================\n\n/**\n * Configuration for role-based memory filtering.\n */\nexport interface RelevanceFilterConfig {\n /** Memory types relevant to each role */\n readonly roleMemoryTypes: Record<AgentRole, readonly MemoryType[]>;\n /** Minimum relevance score to include (0-1) */\n readonly minRelevanceScore: number;\n /** Maximum entries to return per type */\n readonly maxEntriesPerType: number;\n}\n\n/**\n * Default relevance filter configuration.\n * Belief memory is relevant for roles that require reasoning and decision-making.\n */\nexport const DEFAULT_RELEVANCE_CONFIG: RelevanceFilterConfig = {\n roleMemoryTypes: {\n orchestrator: [MemoryType.CORE, MemoryType.EPISODIC, MemoryType.VAULT, MemoryType.BELIEF],\n code_expert: [MemoryType.PROCEDURAL, MemoryType.RESOURCE, MemoryType.EPISODIC],\n architecture_expert: [\n MemoryType.SEMANTIC,\n MemoryType.RESOURCE,\n MemoryType.VAULT,\n MemoryType.BELIEF,\n ],\n security_expert: [\n MemoryType.SEMANTIC,\n MemoryType.VAULT,\n MemoryType.PROCEDURAL,\n MemoryType.BELIEF,\n ],\n documentation_expert: [MemoryType.SEMANTIC, MemoryType.RESOURCE, MemoryType.EPISODIC],\n testing_expert: [MemoryType.SEMANTIC, MemoryType.EPISODIC, MemoryType.VAULT],\n devops_expert: [\n MemoryType.PROCEDURAL,\n MemoryType.RESOURCE,\n MemoryType.EPISODIC,\n MemoryType.VAULT,\n ],\n research_expert: [\n MemoryType.SEMANTIC,\n MemoryType.RESOURCE,\n MemoryType.VAULT,\n MemoryType.EPISODIC,\n ],\n pm_expert: [MemoryType.SEMANTIC, MemoryType.EPISODIC, MemoryType.CORE, MemoryType.BELIEF],\n ux_expert: [MemoryType.SEMANTIC, MemoryType.EPISODIC, MemoryType.RESOURCE],\n infrastructure_expert: [\n MemoryType.PROCEDURAL,\n MemoryType.RESOURCE,\n MemoryType.EPISODIC,\n MemoryType.VAULT,\n ],\n qa_expert: [MemoryType.SEMANTIC, MemoryType.EPISODIC, MemoryType.PROCEDURAL, MemoryType.BELIEF],\n data_visualization_expert: [MemoryType.SEMANTIC, MemoryType.RESOURCE, MemoryType.EPISODIC],\n custom: [MemoryType.SEMANTIC, MemoryType.PROCEDURAL, MemoryType.RESOURCE],\n // TRINITY roles (arXiv:2512.04695) - thinker and verifier benefit from belief memory\n thinker: [MemoryType.SEMANTIC, MemoryType.CORE, MemoryType.VAULT, MemoryType.BELIEF],\n worker: [MemoryType.PROCEDURAL, MemoryType.RESOURCE, MemoryType.EPISODIC],\n verifier: [MemoryType.SEMANTIC, MemoryType.VAULT, MemoryType.PROCEDURAL, MemoryType.BELIEF],\n },\n minRelevanceScore: 0.5,\n maxEntriesPerType: 10,\n};\n","/**\n * nexus-agents/context - Memory Module Types\n *\n * Individual memory module interfaces and data types for the MIRIX-style\n * typed memory system. These are the building blocks for ITypedMemory.\n *\n * @module context/memory-module-types\n * (Source: Issue #101, arXiv:2507.07957 - MIRIX Architecture)\n */\n\nimport { z } from 'zod';\nimport type { Result } from '../core/result.js';\nimport type { AgentRole } from '../core/types/agent.js';\nimport type { MemoryError } from './memory-backend-types.js';\n\n// ============================================================================\n// Core Memory - Agent Identity\n// ============================================================================\n\n/**\n * Core memory stores agent identity, constraints, and role definitions.\n * This is the most persistent memory type, rarely modified after initialization.\n */\nexport interface CoreMemoryData {\n readonly agentId: string;\n readonly role: AgentRole;\n readonly name: string;\n readonly constraints: readonly string[];\n readonly capabilities: readonly string[];\n readonly systemPrompt?: string;\n readonly temperament?: 'cautious' | 'balanced' | 'exploratory';\n}\n\nexport const CoreMemoryDataSchema = z.object({\n agentId: z.string().min(1),\n role: z.string(),\n name: z.string().min(1),\n constraints: z.array(z.string()),\n capabilities: z.array(z.string()),\n systemPrompt: z.string().max(50_000).optional(),\n temperament: z.enum(['cautious', 'balanced', 'exploratory']).optional(),\n});\n\nexport interface ICoreMemory {\n getIdentity(agentId: string): Promise<Result<CoreMemoryData | null, MemoryError>>;\n setIdentity(data: CoreMemoryData): Promise<Result<void, MemoryError>>;\n getConstraints(agentId: string): Promise<Result<readonly string[], MemoryError>>;\n updateConstraints(\n agentId: string,\n constraints: readonly string[]\n ): Promise<Result<void, MemoryError>>;\n}\n\n// ============================================================================\n// Episodic Memory - Task Experiences\n// ============================================================================\n\n/**\n * Episodic memory stores task experiences and interaction history.\n * Used for learning from past interactions and avoiding repeated mistakes.\n */\nexport interface EpisodeData {\n readonly episodeId: string;\n readonly taskId: string;\n readonly agentId: string;\n readonly action: string;\n readonly outcome: 'success' | 'failure' | 'partial';\n readonly context: Record<string, unknown>;\n readonly learnings?: readonly string[];\n readonly timestamp: Date;\n readonly durationMs?: number;\n}\n\nexport const EpisodeDataSchema = z.object({\n episodeId: z.string().min(1),\n taskId: z.string().min(1),\n agentId: z.string().min(1),\n action: z.string().min(1),\n outcome: z.enum(['success', 'failure', 'partial']),\n context: z.record(z.string(), z.unknown()),\n learnings: z.array(z.string()).optional(),\n timestamp: z.date(),\n durationMs: z.number().positive().optional(),\n});\n\nexport interface IEpisodicMemory {\n recordEpisode(episode: EpisodeData): Promise<Result<void, MemoryError>>;\n getEpisodes(\n agentId: string,\n limit?: number\n ): Promise<Result<readonly EpisodeData[], MemoryError>>;\n getEpisodesByTask(taskId: string): Promise<Result<readonly EpisodeData[], MemoryError>>;\n getRecentFailures(\n agentId: string,\n limit?: number\n ): Promise<Result<readonly EpisodeData[], MemoryError>>;\n searchEpisodes(\n query: string,\n limit?: number\n ): Promise<Result<readonly EpisodeData[], MemoryError>>;\n}\n\n// ============================================================================\n// Semantic Memory - Domain Knowledge\n// ============================================================================\n\n/**\n * Semantic memory stores domain facts and learned information.\n * Used for general knowledge that applies across tasks.\n */\nexport interface SemanticFact {\n readonly factId: string;\n readonly domain: string;\n readonly subject: string;\n readonly predicate: string;\n readonly object: string;\n readonly confidence: number;\n readonly source?: string;\n readonly validUntil?: Date;\n}\n\nexport const SemanticFactSchema = z.object({\n factId: z.string().min(1),\n domain: z.string().min(1),\n subject: z.string().min(1),\n predicate: z.string().min(1),\n object: z.string(),\n confidence: z.number().min(0).max(1),\n source: z.string().optional(),\n validUntil: z.date().optional(),\n});\n\nexport interface ISemanticMemory {\n storeFact(fact: SemanticFact): Promise<Result<void, MemoryError>>;\n getFact(factId: string): Promise<Result<SemanticFact | null, MemoryError>>;\n queryByDomain(\n domain: string,\n limit?: number\n ): Promise<Result<readonly SemanticFact[], MemoryError>>;\n queryBySubject(\n subject: string,\n limit?: number\n ): Promise<Result<readonly SemanticFact[], MemoryError>>;\n searchFacts(query: string, limit?: number): Promise<Result<readonly SemanticFact[], MemoryError>>;\n invalidateFact(factId: string): Promise<Result<void, MemoryError>>;\n}\n\n// ============================================================================\n// Procedural Memory - Skills and Workflows\n// ============================================================================\n\n/**\n * Procedural memory stores skills, workflows, and action patterns.\n * Used for learned procedures that can be reused across tasks.\n */\nexport interface ProcedureStep {\n readonly stepId: string;\n readonly action: string;\n readonly parameters?: Record<string, unknown>;\n readonly preconditions?: readonly string[];\n readonly postconditions?: readonly string[];\n}\n\nexport interface Procedure {\n readonly procedureId: string;\n readonly name: string;\n readonly description: string;\n readonly steps: readonly ProcedureStep[];\n readonly triggerConditions: readonly string[];\n readonly successRate: number;\n readonly executionCount: number;\n readonly averageDurationMs?: number;\n readonly tags?: readonly string[];\n}\n\nexport const ProcedureStepSchema = z.object({\n stepId: z.string().min(1),\n action: z.string().min(1),\n parameters: z.record(z.string(), z.unknown()).optional(),\n preconditions: z.array(z.string()).optional(),\n postconditions: z.array(z.string()).optional(),\n});\n\nexport const ProcedureSchema = z.object({\n procedureId: z.string().min(1),\n name: z.string().min(1),\n description: z.string().max(10_000),\n steps: z.array(ProcedureStepSchema).max(100),\n triggerConditions: z.array(z.string()),\n successRate: z.number().min(0).max(1),\n executionCount: z.number().int().min(0),\n averageDurationMs: z.number().positive().optional(),\n tags: z.array(z.string()).optional(),\n});\n\nexport interface IProceduralMemory {\n storeProcedure(procedure: Procedure): Promise<Result<void, MemoryError>>;\n getProcedure(procedureId: string): Promise<Result<Procedure | null, MemoryError>>;\n findProcedures(\n triggerContext: string,\n limit?: number\n ): Promise<Result<readonly Procedure[], MemoryError>>;\n updateSuccessRate(procedureId: string, success: boolean): Promise<Result<void, MemoryError>>;\n searchProcedures(\n query: string,\n limit?: number\n ): Promise<Result<readonly Procedure[], MemoryError>>;\n}\n\n// ============================================================================\n// Resource Memory - External References\n// ============================================================================\n\n/**\n * Resource memory stores references to external data (files, URLs, APIs).\n * Used for tracking data sources and their freshness.\n */\nexport interface ResourceReference {\n readonly resourceId: string;\n readonly type: 'file' | 'url' | 'api' | 'database' | 'other';\n readonly location: string;\n readonly name: string;\n readonly mimeType?: string;\n readonly size?: number;\n readonly hash?: string;\n readonly lastAccessed: Date;\n readonly lastModified?: Date;\n readonly metadata?: Record<string, unknown>;\n}\n\nexport const ResourceReferenceSchema = z.object({\n resourceId: z.string().min(1),\n type: z.enum(['file', 'url', 'api', 'database', 'other']),\n location: z.string().min(1),\n name: z.string().min(1),\n mimeType: z.string().optional(),\n size: z.number().int().positive().optional(),\n hash: z.string().optional(),\n lastAccessed: z.date(),\n lastModified: z.date().optional(),\n metadata: z.record(z.string(), z.unknown()).optional(),\n});\n\nexport interface IResourceMemory {\n storeResource(resource: ResourceReference): Promise<Result<void, MemoryError>>;\n getResource(resourceId: string): Promise<Result<ResourceReference | null, MemoryError>>;\n findByType(\n type: ResourceReference['type'],\n limit?: number\n ): Promise<Result<readonly ResourceReference[], MemoryError>>;\n findByLocation(\n locationPattern: string\n ): Promise<Result<readonly ResourceReference[], MemoryError>>;\n updateLastAccessed(resourceId: string): Promise<Result<void, MemoryError>>;\n searchResources(\n query: string,\n limit?: number\n ): Promise<Result<readonly ResourceReference[], MemoryError>>;\n}\n\n// ============================================================================\n// Knowledge Vault - Persistent Cross-Session Storage\n// ============================================================================\n\n/**\n * Knowledge vault stores persistent data that survives across sessions.\n * Used for long-term knowledge and critical information.\n */\nexport interface VaultEntry {\n readonly vaultId: string;\n readonly category: 'insight' | 'decision' | 'pattern' | 'config' | 'archive';\n readonly title: string;\n readonly content: unknown;\n readonly importance: 'critical' | 'high' | 'normal';\n readonly createdAt: Date;\n readonly updatedAt: Date;\n readonly expiresAt?: Date;\n readonly tags?: readonly string[];\n readonly relatedIds?: readonly string[];\n}\n\nexport const VaultEntrySchema = z.object({\n vaultId: z.string().min(1),\n category: z.enum(['insight', 'decision', 'pattern', 'config', 'archive']),\n title: z.string().min(1),\n content: z.unknown(),\n importance: z.enum(['critical', 'high', 'normal']),\n createdAt: z.date(),\n updatedAt: z.date(),\n expiresAt: z.date().optional(),\n tags: z.array(z.string()).optional(),\n relatedIds: z.array(z.string()).optional(),\n});\n\nexport interface IKnowledgeVault {\n store(entry: VaultEntry): Promise<Result<void, MemoryError>>;\n retrieve(vaultId: string): Promise<Result<VaultEntry | null, MemoryError>>;\n findByCategory(\n category: VaultEntry['category'],\n limit?: number\n ): Promise<Result<readonly VaultEntry[], MemoryError>>;\n findByImportance(\n importance: VaultEntry['importance'],\n limit?: number\n ): Promise<Result<readonly VaultEntry[], MemoryError>>;\n searchVault(query: string, limit?: number): Promise<Result<readonly VaultEntry[], MemoryError>>;\n archive(vaultId: string): Promise<Result<void, MemoryError>>;\n getExpired(): Promise<Result<readonly VaultEntry[], MemoryError>>;\n}\n","/**\n * Typed memory implementation classes.\n *\n * @module context/typed-memory-impl\n * (Source: Issue #101, arXiv:2507.07957 - MIRIX Architecture)\n */\n\nimport type { Result } from '../core/result.js';\nimport { ok, err } from '../core/result.js';\nimport { getTimeProvider } from '../core/index.js';\nimport type { IMemoryBackend, MemoryMetadata, MemoryError } from './memory-backend-types.js';\nimport { MemoryImportance, MemoryError as MemError } from './memory-backend-types.js';\nimport type {\n ICoreMemory,\n IEpisodicMemory,\n ISemanticMemory,\n IProceduralMemory,\n IResourceMemory,\n IKnowledgeVault,\n CoreMemoryData,\n EpisodeData,\n SemanticFact,\n Procedure,\n ResourceReference,\n VaultEntry,\n} from './memory-types.js';\n\n// ============================================================================\n// Core Memory Implementation\n// ============================================================================\n\nexport class CoreMemoryImpl implements ICoreMemory {\n constructor(private readonly backend: IMemoryBackend) {}\n\n async getIdentity(agentId: string): Promise<Result<CoreMemoryData | null, MemoryError>> {\n const result = await this.backend.retrieve(`core:identity:${agentId}`);\n if (!result.ok) return result;\n return ok(result.value as CoreMemoryData | null);\n }\n\n async setIdentity(data: CoreMemoryData): Promise<Result<void, MemoryError>> {\n const meta: MemoryMetadata = {\n importance: MemoryImportance.HIGH,\n tags: ['core', 'identity', data.role],\n };\n return this.backend.store(`core:identity:${data.agentId}`, data, meta);\n }\n\n async getConstraints(agentId: string): Promise<Result<readonly string[], MemoryError>> {\n const result = await this.getIdentity(agentId);\n if (!result.ok) return result;\n return ok(result.value?.constraints ?? []);\n }\n\n async updateConstraints(\n agentId: string,\n constraints: readonly string[]\n ): Promise<Result<void, MemoryError>> {\n const identity = await this.getIdentity(agentId);\n if (!identity.ok) return identity;\n if (identity.value === null) return err(new MemError(`Agent ${agentId} not found`));\n return this.setIdentity({ ...identity.value, constraints });\n }\n}\n\n// ============================================================================\n// Episodic Memory Implementation\n// ============================================================================\n\nexport class EpisodicMemoryImpl implements IEpisodicMemory {\n constructor(private readonly backend: IMemoryBackend) {}\n\n async recordEpisode(episode: EpisodeData): Promise<Result<void, MemoryError>> {\n const importance =\n episode.outcome === 'failure' ? MemoryImportance.HIGH : MemoryImportance.MEDIUM;\n const meta: MemoryMetadata = {\n importance,\n tags: ['episodic', episode.outcome, episode.agentId],\n };\n return this.backend.store(`episodic:${episode.episodeId}`, episode, meta);\n }\n\n async getEpisodes(\n agentId: string,\n limit = 20\n ): Promise<Result<readonly EpisodeData[], MemoryError>> {\n const result = await this.backend.search(`episodic ${agentId}`, limit);\n if (!result.ok) return result;\n return ok(result.value.map((e) => e.value as EpisodeData).filter((e) => e.agentId === agentId));\n }\n\n async getEpisodesByTask(taskId: string): Promise<Result<readonly EpisodeData[], MemoryError>> {\n const result = await this.backend.search(`episodic ${taskId}`, 50);\n if (!result.ok) return result;\n return ok(result.value.map((e) => e.value as EpisodeData).filter((e) => e.taskId === taskId));\n }\n\n async getRecentFailures(\n agentId: string,\n limit = 10\n ): Promise<Result<readonly EpisodeData[], MemoryError>> {\n const result = await this.backend.search(`episodic failure ${agentId}`, limit * 2);\n if (!result.ok) return result;\n const failures = result.value\n .map((e) => e.value as EpisodeData)\n .filter((e) => e.outcome === 'failure' && e.agentId === agentId)\n .slice(0, limit);\n return ok(failures);\n }\n\n async searchEpisodes(\n query: string,\n limit = 20\n ): Promise<Result<readonly EpisodeData[], MemoryError>> {\n const result = await this.backend.search(`episodic ${query}`, limit);\n if (!result.ok) return result;\n return ok(result.value.map((e) => e.value as EpisodeData));\n }\n}\n\n// ============================================================================\n// Semantic Memory Implementation\n// ============================================================================\n\nexport class SemanticMemoryImpl implements ISemanticMemory {\n constructor(private readonly backend: IMemoryBackend) {}\n\n async storeFact(fact: SemanticFact): Promise<Result<void, MemoryError>> {\n const meta: MemoryMetadata = {\n importance: MemoryImportance.MEDIUM,\n tags: ['semantic', fact.domain, fact.subject],\n };\n if (fact.validUntil !== undefined) {\n meta.ttl = fact.validUntil.getTime() - getTimeProvider().now();\n }\n return this.backend.store(`semantic:${fact.factId}`, fact, meta);\n }\n\n async getFact(factId: string): Promise<Result<SemanticFact | null, MemoryError>> {\n const result = await this.backend.retrieve(`semantic:${factId}`);\n if (!result.ok) return result;\n return ok(result.value as SemanticFact | null);\n }\n\n async queryByDomain(\n domain: string,\n limit = 20\n ): Promise<Result<readonly SemanticFact[], MemoryError>> {\n const result = await this.backend.search(`semantic ${domain}`, limit);\n if (!result.ok) return result;\n return ok(result.value.map((e) => e.value as SemanticFact).filter((f) => f.domain === domain));\n }\n\n async queryBySubject(\n subject: string,\n limit = 20\n ): Promise<Result<readonly SemanticFact[], MemoryError>> {\n const result = await this.backend.search(`semantic ${subject}`, limit);\n if (!result.ok) return result;\n return ok(\n result.value.map((e) => e.value as SemanticFact).filter((f) => f.subject === subject)\n );\n }\n\n async searchFacts(\n query: string,\n limit = 20\n ): Promise<Result<readonly SemanticFact[], MemoryError>> {\n const result = await this.backend.search(`semantic ${query}`, limit);\n if (!result.ok) return result;\n return ok(result.value.map((e) => e.value as SemanticFact));\n }\n\n async invalidateFact(factId: string): Promise<Result<void, MemoryError>> {\n const fact = await this.getFact(factId);\n if (!fact.ok) return fact;\n if (fact.value === null) return ok(undefined);\n const updated = { ...fact.value, validUntil: new Date(getTimeProvider().now()) };\n return this.storeFact(updated);\n }\n}\n\n// ============================================================================\n// Procedural Memory Implementation\n// ============================================================================\n\nexport class ProceduralMemoryImpl implements IProceduralMemory {\n constructor(private readonly backend: IMemoryBackend) {}\n\n async storeProcedure(procedure: Procedure): Promise<Result<void, MemoryError>> {\n const tags = ['procedural', procedure.name, ...(procedure.tags ?? [])];\n const meta: MemoryMetadata = { importance: MemoryImportance.MEDIUM, tags };\n return this.backend.store(`procedural:${procedure.procedureId}`, procedure, meta);\n }\n\n async getProcedure(procedureId: string): Promise<Result<Procedure | null, MemoryError>> {\n const result = await this.backend.retrieve(`procedural:${procedureId}`);\n if (!result.ok) return result;\n return ok(result.value as Procedure | null);\n }\n\n async findProcedures(\n triggerContext: string,\n limit = 10\n ): Promise<Result<readonly Procedure[], MemoryError>> {\n const result = await this.backend.search(`procedural ${triggerContext}`, limit * 2);\n if (!result.ok) return result;\n const procs = result.value\n .map((e) => e.value as Procedure)\n .filter((p) =>\n p.triggerConditions.some((t) => triggerContext.toLowerCase().includes(t.toLowerCase()))\n )\n .sort((a, b) => b.successRate - a.successRate)\n .slice(0, limit);\n return ok(procs);\n }\n\n async updateSuccessRate(\n procedureId: string,\n success: boolean\n ): Promise<Result<void, MemoryError>> {\n const proc = await this.getProcedure(procedureId);\n if (!proc.ok) return proc;\n if (proc.value === null) return err(new MemError(`Procedure ${procedureId} not found`));\n const count = proc.value.executionCount + 1;\n const rate = (proc.value.successRate * proc.value.executionCount + (success ? 1 : 0)) / count;\n return this.storeProcedure({ ...proc.value, successRate: rate, executionCount: count });\n }\n\n async searchProcedures(\n query: string,\n limit = 10\n ): Promise<Result<readonly Procedure[], MemoryError>> {\n const result = await this.backend.search(`procedural ${query}`, limit);\n if (!result.ok) return result;\n return ok(result.value.map((e) => e.value as Procedure));\n }\n}\n\n// ============================================================================\n// Resource Memory Implementation\n// ============================================================================\n\nexport class ResourceMemoryImpl implements IResourceMemory {\n constructor(private readonly backend: IMemoryBackend) {}\n\n async storeResource(resource: ResourceReference): Promise<Result<void, MemoryError>> {\n const meta: MemoryMetadata = {\n importance: MemoryImportance.LOW,\n tags: ['resource', resource.type, resource.name],\n };\n return this.backend.store(`resource:${resource.resourceId}`, resource, meta);\n }\n\n async getResource(resourceId: string): Promise<Result<ResourceReference | null, MemoryError>> {\n const result = await this.backend.retrieve(`resource:${resourceId}`);\n if (!result.ok) return result;\n return ok(result.value as ResourceReference | null);\n }\n\n async findByType(\n type: ResourceReference['type'],\n limit = 20\n ): Promise<Result<readonly ResourceReference[], MemoryError>> {\n const result = await this.backend.search(`resource ${type}`, limit);\n if (!result.ok) return result;\n return ok(result.value.map((e) => e.value as ResourceReference).filter((r) => r.type === type));\n }\n\n async findByLocation(\n locationPattern: string\n ): Promise<Result<readonly ResourceReference[], MemoryError>> {\n const result = await this.backend.search(`resource ${locationPattern}`, 50);\n if (!result.ok) return result;\n return ok(\n result.value\n .map((e) => e.value as ResourceReference)\n .filter((r) => r.location.includes(locationPattern))\n );\n }\n\n async updateLastAccessed(resourceId: string): Promise<Result<void, MemoryError>> {\n const res = await this.getResource(resourceId);\n if (!res.ok) return res;\n if (res.value === null) return ok(undefined);\n return this.storeResource({ ...res.value, lastAccessed: new Date(getTimeProvider().now()) });\n }\n\n async searchResources(\n query: string,\n limit = 20\n ): Promise<Result<readonly ResourceReference[], MemoryError>> {\n const result = await this.backend.search(`resource ${query}`, limit);\n if (!result.ok) return result;\n return ok(result.value.map((e) => e.value as ResourceReference));\n }\n}\n\n// ============================================================================\n// Knowledge Vault Implementation\n// ============================================================================\n\nexport class KnowledgeVaultImpl implements IKnowledgeVault {\n constructor(private readonly backend: IMemoryBackend) {}\n\n async store(entry: VaultEntry): Promise<Result<void, MemoryError>> {\n const importance =\n entry.importance === 'critical' ? MemoryImportance.HIGH : MemoryImportance.MEDIUM;\n const tags = ['vault', entry.category, entry.importance, ...(entry.tags ?? [])];\n const meta: MemoryMetadata = { importance, tags };\n if (entry.expiresAt !== undefined) {\n meta.ttl = entry.expiresAt.getTime() - getTimeProvider().now();\n }\n return this.backend.store(`vault:${entry.vaultId}`, entry, meta);\n }\n\n async retrieve(vaultId: string): Promise<Result<VaultEntry | null, MemoryError>> {\n const result = await this.backend.retrieve(`vault:${vaultId}`);\n if (!result.ok) return result;\n return ok(result.value as VaultEntry | null);\n }\n\n async findByCategory(\n category: VaultEntry['category'],\n limit = 20\n ): Promise<Result<readonly VaultEntry[], MemoryError>> {\n const result = await this.backend.search(`vault ${category}`, limit);\n if (!result.ok) return result;\n return ok(\n result.value.map((e) => e.value as VaultEntry).filter((v) => v.category === category)\n );\n }\n\n async findByImportance(\n importance: VaultEntry['importance'],\n limit = 20\n ): Promise<Result<readonly VaultEntry[], MemoryError>> {\n const result = await this.backend.search(`vault ${importance}`, limit);\n if (!result.ok) return result;\n return ok(\n result.value.map((e) => e.value as VaultEntry).filter((v) => v.importance === importance)\n );\n }\n\n async searchVault(\n query: string,\n limit = 20\n ): Promise<Result<readonly VaultEntry[], MemoryError>> {\n const result = await this.backend.search(`vault ${query}`, limit);\n if (!result.ok) return result;\n return ok(result.value.map((e) => e.value as VaultEntry));\n }\n\n async archive(vaultId: string): Promise<Result<void, MemoryError>> {\n const entry = await this.retrieve(vaultId);\n if (!entry.ok) return entry;\n if (entry.value === null) return ok(undefined);\n return this.store({\n ...entry.value,\n category: 'archive',\n updatedAt: new Date(getTimeProvider().now()),\n });\n }\n\n async getExpired(): Promise<Result<readonly VaultEntry[], MemoryError>> {\n const result = await this.backend.search('vault', 100);\n if (!result.ok) return result;\n const now = new Date(getTimeProvider().now());\n const expired = result.value\n .map((e) => e.value as VaultEntry)\n .filter((v) => v.expiresAt !== undefined && v.expiresAt < now);\n return ok(expired);\n }\n}\n","/**\n * nexus-agents/context - Typed Memory Implementation\n *\n * Implements MIRIX-style typed memory system using HybridMemoryBackend.\n *\n * @module context/typed-memory\n * (Source: Issue #101, arXiv:2507.07957 - MIRIX Architecture)\n */\n\nimport type { Result } from '../core/result.js';\nimport { ok } from '../core/result.js';\nimport { getTimeProvider } from '../core/index.js';\nimport type { AgentRole } from '../core/types/agent.js';\nimport { createLogger } from '../core/logger.js';\nimport type { IMemoryBackend, MemoryEntry, MemoryError } from './memory-backend-types.js';\nimport type {\n ITypedMemory,\n ICoreMemory,\n IEpisodicMemory,\n ISemanticMemory,\n IProceduralMemory,\n IResourceMemory,\n IKnowledgeVault,\n TypedMemoryEntry,\n TypedMemoryStats,\n TypedMemoryPruneResult,\n RelevanceFilterConfig,\n} from './memory-types.js';\nimport type { IHindsightBeliefMemory } from './belief-types.js';\nimport { MemoryType, DEFAULT_RELEVANCE_CONFIG } from './memory-types.js';\nimport {\n CoreMemoryImpl,\n EpisodicMemoryImpl,\n SemanticMemoryImpl,\n ProceduralMemoryImpl,\n ResourceMemoryImpl,\n KnowledgeVaultImpl,\n} from './typed-memory-impl.js';\nimport { HindsightBeliefMemory } from './belief-memory.js';\n\nconst logger = createLogger({ component: 'typed-memory' });\n\n/**\n * Typed memory system implementing MIRIX architecture.\n */\nexport class TypedMemory implements ITypedMemory {\n readonly core: ICoreMemory;\n readonly episodic: IEpisodicMemory;\n readonly semantic: ISemanticMemory;\n readonly procedural: IProceduralMemory;\n readonly resource: IResourceMemory;\n readonly vault: IKnowledgeVault;\n readonly belief: IHindsightBeliefMemory;\n\n private readonly backend: IMemoryBackend;\n private readonly config: RelevanceFilterConfig;\n\n constructor(backend: IMemoryBackend, config: RelevanceFilterConfig = DEFAULT_RELEVANCE_CONFIG) {\n this.backend = backend;\n this.config = config;\n this.core = new CoreMemoryImpl(backend);\n this.episodic = new EpisodicMemoryImpl(backend);\n this.semantic = new SemanticMemoryImpl(backend);\n this.procedural = new ProceduralMemoryImpl(backend);\n this.resource = new ResourceMemoryImpl(backend);\n this.vault = new KnowledgeVaultImpl(backend);\n this.belief = new HindsightBeliefMemory();\n logger.info('TypedMemory initialized');\n }\n\n async queryByType(\n type: MemoryType,\n query: string,\n limit = 20\n ): Promise<Result<readonly TypedMemoryEntry[], MemoryError>> {\n const result = await this.backend.search(`${type} ${query}`, limit);\n if (!result.ok) return result;\n return ok(result.value.map((e) => this.toTypedEntry(e, type)));\n }\n\n async filterByRelevance(\n agentRole: AgentRole,\n limit = 50\n ): Promise<Result<readonly TypedMemoryEntry[], MemoryError>> {\n const configuredTypes = this.config.roleMemoryTypes[agentRole];\n const relevantTypes =\n configuredTypes.length > 0 ? configuredTypes : [MemoryType.CORE, MemoryType.VAULT];\n const entries: TypedMemoryEntry[] = [];\n for (const type of relevantTypes) {\n const result = await this.backend.search(type, this.config.maxEntriesPerType);\n if (result.ok) {\n entries.push(...result.value.map((e) => this.toTypedEntry(e, type)));\n }\n }\n return ok(entries.slice(0, limit));\n }\n\n async getStats(): Promise<Result<TypedMemoryStats, MemoryError>> {\n const counts: Record<MemoryType, number> = {\n core: 0,\n episodic: 0,\n semantic: 0,\n procedural: 0,\n resource: 0,\n vault: 0,\n belief: 0,\n };\n let total = 0;\n for (const type of Object.values(MemoryType)) {\n const result = await this.backend.search(type, 1000);\n if (result.ok) {\n counts[type] = result.value.length;\n total += result.value.length;\n }\n }\n return ok({ totalEntries: total, entriesByType: counts });\n }\n\n async pruneExpired(): Promise<Result<TypedMemoryPruneResult, MemoryError>> {\n const result = await this.backend.prune(new Date(getTimeProvider().now()));\n if (!result.ok) return result;\n logger.info('Pruned expired entries', { count: result.value });\n return ok({\n prunedCount: result.value,\n prunedByType: {\n core: 0,\n episodic: 0,\n semantic: 0,\n procedural: 0,\n resource: 0,\n vault: 0,\n belief: 0,\n },\n });\n }\n\n private toTypedEntry(entry: MemoryEntry, type: MemoryType): TypedMemoryEntry {\n return {\n id: entry.key,\n type,\n key: entry.key,\n value: entry.value,\n metadata: entry.metadata,\n createdAt: entry.createdAt,\n accessedAt: entry.accessedAt,\n };\n }\n}\n\n/** Create a typed memory instance. */\nexport function createTypedMemory(\n backend: IMemoryBackend,\n config?: RelevanceFilterConfig\n): ITypedMemory {\n return new TypedMemory(backend, config);\n}\n","/**\n * Phase 5 of #2766 — thin {@link IMemoryBackend} adapters for tool-memory\n * backends so each one becomes discoverable through `getMemoryRegistry()`.\n *\n * Scope is intentionally narrow: each adapter exposes the underlying\n * backend's row count via `stats()` so `memory_stats` can read all four\n * domains from the unified registry. `read`/`write`/`query`/`delete` are\n * left as escape hatches — callers wanting CRUD continue to use the\n * underlying backend directly (HybridMemoryBackend, AgenticMemoryBackend,\n * etc.). Fully folding the storage into nexus-memory's SqliteBackend is\n * a follow-up Phase 5.1.\n *\n * @module mcp/tools/tool-memory-registry-adapters\n */\n\nimport type { BackendStats, CliName, IMemoryBackend, QueryFilter, WriteMeta } from 'nexus-memory';\n\n/** Default cap when a consumer omits `limit` in `query()`. */\nconst DEFAULT_SEARCH_LIMIT = 10;\n\n/**\n * Pull the free-text search term out of a {@link QueryFilter}. Returns\n * `null` when the filter doesn't carry one, so callers can skip the search\n * dispatch entirely. The convention is `filter.where.text` — see\n * docs/architecture/memory-context-retrieval.md (Phase 1 of #2792).\n */\nfunction extractSearchText(filter?: QueryFilter<unknown>): string | null {\n const where: unknown = filter?.where;\n if (where === null || where === undefined || typeof where !== 'object') return null;\n if (!('text' in where)) return null;\n const candidate = where.text;\n return typeof candidate === 'string' && candidate !== '' ? candidate : null;\n}\n\n/** Minimal \"count + close\" shape every tool-memory backend implements. */\nexport interface CountableBackend {\n /** Returns total row count (the heart of `memory_stats`). */\n count(): unknown;\n /** Idempotent close. */\n close?(): Promise<void> | void;\n /**\n * Optional native search surface used by {@link StatsOnlyAdapter.query}\n * (Phase 1 of #2792). When attached from `tool-memory.ts`, each backend\n * wires this to its idiomatic search call — `recallBySubject` for\n * beliefs, `searchAgentic` for A-MEM, `retrieveByPriority` for adaptive,\n * etc. Returns a flat array; the adapter is responsible for unwrapping\n * Result types and projecting to a useful shape (typically the raw\n * entry object, since consumers will project further).\n */\n search?(query: string, limit: number): Promise<readonly unknown[]>;\n}\n\n/**\n * Adapter that surfaces `count()` from an arbitrary tool-memory backend\n * as an `IMemoryBackend`. Methods other than `stats()` and `close()`\n * delegate to no-ops or rejections — call sites doing actual CRUD must\n * keep using the underlying backend directly until a deeper migration\n * folds the storage in.\n */\nexport class StatsOnlyAdapter implements IMemoryBackend<string, unknown> {\n readonly domain: string;\n private readonly backend: CountableBackend;\n\n constructor(domain: string, backend: CountableBackend) {\n this.domain = domain;\n this.backend = backend;\n }\n\n read(_key: string): Promise<unknown> {\n // Reads through the unified registry aren't wired yet. Callers wanting\n // actual data should fetch via the underlying backend.\n return Promise.resolve(undefined);\n }\n\n write(_key: string, _value: unknown, _meta?: WriteMeta): Promise<void> {\n return Promise.reject(\n new Error(\n `nexus-memory: domain \"${this.domain}\" is attached as stats-only; ` +\n `write through the underlying backend instead`\n )\n );\n }\n\n /**\n * Phase 1 of #2792: real query fan-out via the backend's native search.\n * Honors the free-text convention `filter.where.text`. Without a search\n * callback on the underlying backend (or without a text term), returns\n * `[]` — consumers that need full coverage must wire `search()` on every\n * backend they attach. Search exceptions are swallowed; the registry's\n * `memory_stats` consumer relies on `query()` never throwing.\n */\n async query(filter?: QueryFilter<unknown>): Promise<readonly unknown[]> {\n if (this.backend.search === undefined) return [];\n const text = extractSearchText(filter);\n if (text === null) return [];\n const limit = filter?.limit ?? DEFAULT_SEARCH_LIMIT;\n try {\n return await this.backend.search(text, limit);\n } catch {\n return [];\n }\n }\n\n delete(_key: string): Promise<boolean> {\n return Promise.resolve(false);\n }\n\n async stats(): Promise<BackendStats> {\n const rawCount = await Promise.resolve(this.backend.count());\n const count = extractCount(rawCount);\n return {\n domain: this.domain,\n count,\n oldestTimestamp: null,\n newestTimestamp: null,\n };\n }\n\n async close(): Promise<void> {\n if (this.backend.close !== undefined) {\n await Promise.resolve(this.backend.close());\n }\n }\n}\n\n/**\n * Normalize different backend `count()` return shapes:\n * - `number` (e.g., `MobiMem.profile.getEntryCount()`)\n * - `Result<number, MemoryError>` (HybridMemoryBackend)\n * - `Promise<number | Result<number, MemoryError>>` (after await)\n * Anything unrecognized falls back to 0 — the adapter must never throw on\n * a stats read because that would break `memory_stats` for the whole pipeline.\n */\nfunction extractCount(value: unknown): number {\n if (typeof value === 'number') return value;\n if (value !== null && typeof value === 'object') {\n const v = value as { ok?: boolean; value?: unknown };\n if (v.ok === true && typeof v.value === 'number') return v.value;\n }\n return 0;\n}\n\n/** Convenience tag the adapter passes to `WriteMeta.cli` for future writes. */\nexport type AdapterCli = CliName;\n","/**\n * nexus-agents/mcp - Memory Promotion Pipeline\n *\n * Implements automatic memory promotion between layers:\n * - SessionLearning → Belief (high-confidence learnings become structured knowledge)\n * - Belief → AgenticMemory (stable beliefs become searchable knowledge graph entries)\n *\n * @module mcp/tools/memory-promotion\n * (Source: Issue #746 Phase 4 - Memory Promotion Pipeline)\n */\n\nimport type { ILogger } from '../../core/index.js';\nimport { getErrorMessage, createLogger } from '../../core/index.js';\n\nimport type { HindsightBeliefMemory } from '../../context/belief-memory.js';\nimport { BeliefConfidence, BeliefSourceType } from '../../context/belief-core-types.js';\nimport type { Belief } from '../../context/belief-core-types.js';\nimport type { AgenticMemoryBackend } from '../../context/agentic-memory.js';\nimport type { SessionLearning } from '../../context/session-memory-types.js';\nimport { MemoryImportance } from '../../context/memory-backend-types.js';\n\n// ============================================================================\n// Configuration\n// ============================================================================\n\n/**\n * Configuration for memory promotion thresholds.\n * Based on research analysis: arXiv:2512.21567 (Decision-Theoretic Memory)\n */\nexport interface MemoryPromotionConfig {\n /** Minimum confidence for SessionLearning → Belief promotion (default: 0.75) */\n readonly sessionToBeliefConfidence: number;\n /** Minimum confidence level for Belief → Agentic promotion (default: 'medium') */\n readonly beliefToAgenticMinConfidence: BeliefConfidence;\n /** Minimum belief age in ms before promotion to AgenticMemory (default: 7 days) */\n readonly beliefStabilizationMs: number;\n /** Whether to auto-promote on session end (default: true) */\n readonly autoPromoteOnSessionEnd: boolean;\n}\n\n/** Default promotion configuration. */\nexport const DEFAULT_PROMOTION_CONFIG: MemoryPromotionConfig = {\n sessionToBeliefConfidence: 0.75,\n beliefToAgenticMinConfidence: BeliefConfidence.MEDIUM,\n beliefStabilizationMs: 7 * 24 * 60 * 60 * 1000, // 7 days\n autoPromoteOnSessionEnd: true,\n};\n\n// ============================================================================\n// Promotion Statistics\n// ============================================================================\n\n/**\n * Statistics from a promotion run.\n */\nexport interface PromotionStats {\n readonly learningsEvaluated: number;\n readonly learningsPromotedToBelief: number;\n readonly beliefsEvaluated: number;\n readonly beliefsPromotedToAgentic: number;\n readonly errors: number;\n}\n\n// ============================================================================\n// MemoryPromoter\n// ============================================================================\n\n/**\n * Handles memory promotion between layers.\n * Stateless utility class - instantiate with dependencies for each promotion run.\n */\nexport class MemoryPromoter {\n private readonly beliefs: HindsightBeliefMemory;\n private readonly agentic: AgenticMemoryBackend | null;\n private readonly config: MemoryPromotionConfig;\n private readonly log: ILogger;\n\n constructor(\n beliefs: HindsightBeliefMemory,\n agentic: AgenticMemoryBackend | null,\n config: Partial<MemoryPromotionConfig> = {},\n logger?: ILogger\n ) {\n this.beliefs = beliefs;\n this.agentic = agentic;\n this.config = { ...DEFAULT_PROMOTION_CONFIG, ...config };\n this.log = logger ?? createLogger({ component: 'MemoryPromoter' });\n }\n\n /**\n * Promote high-confidence session learnings to structured beliefs.\n * Returns the number of learnings successfully promoted.\n */\n async promoteLearningsToBelief(learnings: readonly SessionLearning[]): Promise<number> {\n let promoted = 0;\n for (const learning of learnings) {\n if (learning.confidence >= this.config.sessionToBeliefConfidence) {\n const success = await this.promoteSingleLearning(learning);\n if (success) promoted++;\n }\n }\n if (promoted > 0) {\n this.log.info('Promoted learnings to beliefs', { count: promoted });\n }\n return promoted;\n }\n\n /**\n * Promote stable, high-confidence beliefs to AgenticMemory knowledge graph.\n * Returns the number of beliefs successfully promoted.\n */\n async promoteBeliefToAgentic(beliefs: readonly Belief[]): Promise<number> {\n if (this.agentic === null) {\n this.log.debug('AgenticMemory unavailable, skipping belief promotion');\n return 0;\n }\n\n let promoted = 0;\n const now = Date.now();\n\n for (const belief of beliefs) {\n // Skip superseded beliefs\n if (belief.superseded) continue;\n\n // Check confidence threshold\n if (!this.meetsConfidenceThreshold(belief.confidence)) continue;\n\n // Check stabilization period\n const ageMs = now - belief.createdAt.getTime();\n if (ageMs < this.config.beliefStabilizationMs) continue;\n\n const success = await this.promoteSingleBelief(belief);\n if (success) promoted++;\n }\n\n if (promoted > 0) {\n this.log.info('Promoted beliefs to AgenticMemory', { count: promoted });\n }\n return promoted;\n }\n\n /**\n * Run full promotion pipeline: learnings → beliefs → agentic.\n */\n async runPromotionPipeline(\n learnings: readonly SessionLearning[],\n beliefs: readonly Belief[]\n ): Promise<PromotionStats> {\n const learningsPromoted = await this.promoteLearningsToBelief(learnings);\n const beliefsPromoted = await this.promoteBeliefToAgentic(beliefs);\n\n return {\n learningsEvaluated: learnings.length,\n learningsPromotedToBelief: learningsPromoted,\n beliefsEvaluated: beliefs.length,\n beliefsPromotedToAgentic: beliefsPromoted,\n errors: 0,\n };\n }\n\n /** Promote a single learning to a belief. */\n private async promoteSingleLearning(learning: SessionLearning): Promise<boolean> {\n try {\n const confidence = this.mapSessionConfidenceToBeliefConfidence(learning.confidence);\n await this.beliefs.retain({\n subject: learning.context,\n predicate: 'learned-pattern',\n object: learning.pattern,\n confidence,\n sourceType: BeliefSourceType.OBSERVATION,\n sourceRef: learning.source ?? 'session-learning',\n });\n return true;\n } catch (error) {\n this.log.debug('Failed to promote learning to belief', {\n pattern: learning.pattern,\n error: getErrorMessage(error),\n });\n return false;\n }\n }\n\n /** Promote a single belief to AgenticMemory. */\n private async promoteSingleBelief(belief: Belief): Promise<boolean> {\n if (this.agentic === null) return false;\n\n try {\n // Create a knowledge entry from the belief triple\n const key = `belief:${belief.subject}:${belief.predicate}`;\n const value = {\n subject: belief.subject,\n predicate: belief.predicate,\n object: belief.object,\n confidence: belief.confidence,\n sourceType: belief.sourceType,\n beliefId: belief.beliefId,\n };\n\n const result = await this.agentic.storeWithAttributes(key, value, {\n importance: this.mapConfidenceToImportance(belief.confidence),\n tags: [belief.predicate, belief.sourceType],\n });\n\n return result.ok;\n } catch (error) {\n this.log.debug('Failed to promote belief to AgenticMemory', {\n beliefId: belief.beliefId,\n error: getErrorMessage(error),\n });\n return false;\n }\n }\n\n /** Map session confidence (0-1) to belief confidence level. */\n private mapSessionConfidenceToBeliefConfidence(confidence: number): BeliefConfidence {\n if (confidence >= 0.9) return BeliefConfidence.HIGH;\n if (confidence >= 0.75) return BeliefConfidence.MEDIUM;\n if (confidence >= 0.5) return BeliefConfidence.LOW;\n return BeliefConfidence.SPECULATIVE;\n }\n\n /** Check if belief confidence meets minimum threshold. */\n private meetsConfidenceThreshold(confidence: BeliefConfidence): boolean {\n const order = [\n BeliefConfidence.SPECULATIVE,\n BeliefConfidence.LOW,\n BeliefConfidence.MEDIUM,\n BeliefConfidence.HIGH,\n ];\n const beliefIndex = order.indexOf(confidence);\n const thresholdIndex = order.indexOf(this.config.beliefToAgenticMinConfidence);\n return beliefIndex >= thresholdIndex;\n }\n\n /** Map belief confidence to memory importance for AgenticMemory. */\n private mapConfidenceToImportance(confidence: BeliefConfidence): MemoryImportance {\n switch (confidence) {\n case BeliefConfidence.HIGH:\n return MemoryImportance.HIGH;\n case BeliefConfidence.MEDIUM:\n return MemoryImportance.MEDIUM;\n default:\n return MemoryImportance.LOW;\n }\n }\n}\n","/**\n * nexus-agents/mcp - Coordinated Memory Decay\n *\n * Implements FADE (Forgetting with Adaptive Decay) principles for coordinated\n * memory management across all memory systems:\n * - SessionMemory (FIFO)\n * - BeliefMemory (age-based)\n * - AgenticMemory (importance-based)\n * - AdaptiveMemory (priority decay)\n * - MobiMem (TTL + capacity)\n *\n * Key features:\n * - Cross-memory reference tracking to prevent orphaned references\n * - Coordinated decay scheduling across memory types\n * - Configurable decay strategies per memory type\n *\n * @module mcp/tools/memory-decay\n * (Source: Issue #746 Phase 5 - Coordinated Decay/Forgetting)\n * (Research: arXiv:2512.21567 - Decision-Theoretic Memory)\n */\n\nimport type { ILogger } from '../../core/index.js';\nimport { getErrorMessage, createLogger, getTimeProvider } from '../../core/index.js';\n\nimport type { HindsightBeliefMemory } from '../../context/belief-memory.js';\nimport type { AgenticMemoryBackend } from '../../context/agentic-memory.js';\nimport type { AdaptiveMemoryBackend } from '../../context/adaptive-memory.js';\nimport type { MobiMem } from '../../context/mobimem.js';\n\n// ============================================================================\n// Configuration\n// ============================================================================\n\n/**\n * Decay strategy for each memory type.\n */\nexport type DecayStrategy = 'fifo' | 'age' | 'importance' | 'ttl' | 'exponential';\n\n/**\n * Configuration for coordinated memory decay.\n * Based on FADE principles from arXiv:2512.21567.\n */\nexport interface MemoryDecayConfig {\n /** Whether decay is enabled (default: true) */\n readonly enabled: boolean;\n\n /** Interval between automatic decay runs in ms (default: 1 hour) */\n readonly decayIntervalMs: number;\n\n /** Belief decay - age in days before pruning superseded beliefs (default: 30) */\n readonly beliefMaxAgeDays: number;\n\n /** Agentic decay - max entries before importance-based eviction (default: 10000) */\n readonly agenticMaxEntries: number;\n\n /** Agentic decay - importance threshold for eviction (default: 0.3) */\n readonly agenticImportanceThreshold: number;\n\n /** Adaptive decay - priority score threshold for eviction (default: 0.2) */\n readonly adaptivePriorityThreshold: number;\n\n /** MobiMem decay - run TTL eviction on coordinated decay (default: true) */\n readonly mobimemEvictOnDecay: boolean;\n\n /** Whether to check cross-references before eviction (default: true) */\n readonly checkCrossReferences: boolean;\n\n /** Grace period in ms before removing items with cross-references (default: 7 days) */\n readonly crossReferenceGracePeriodMs: number;\n}\n\n/** Default decay configuration. */\nexport const DEFAULT_DECAY_CONFIG: MemoryDecayConfig = {\n enabled: true,\n decayIntervalMs: 60 * 60 * 1000, // 1 hour\n beliefMaxAgeDays: 30,\n agenticMaxEntries: 10000,\n agenticImportanceThreshold: 0.3,\n adaptivePriorityThreshold: 0.2,\n mobimemEvictOnDecay: true,\n checkCrossReferences: true,\n crossReferenceGracePeriodMs: 7 * 24 * 60 * 60 * 1000, // 7 days\n};\n\n// ============================================================================\n// Decay Statistics\n// ============================================================================\n\n/**\n * Statistics from a single decay run.\n */\nexport interface DecayRunStats {\n readonly startedAt: Date;\n readonly completedAt: Date;\n readonly beliefsPruned: number;\n readonly agenticEvicted: number;\n readonly adaptiveEvicted: number;\n readonly mobimemEvicted: number;\n readonly crossReferencesPreserved: number;\n readonly errors: readonly string[];\n}\n\n/**\n * Aggregate statistics across multiple decay runs.\n */\nexport interface DecayAggregateStats {\n readonly totalRuns: number;\n readonly lastRunAt: Date | null;\n readonly totalBeliefsPruned: number;\n readonly totalAgenticEvicted: number;\n readonly totalAdaptiveEvicted: number;\n readonly totalMobimemEvicted: number;\n readonly totalCrossReferencesPreserved: number;\n readonly totalErrors: number;\n}\n\n/** Internal results from decay phases. */\ninterface DecayPhaseResults {\n beliefsPruned?: number;\n agenticEvicted?: number;\n adaptiveEvicted?: number;\n mobimemEvicted?: number;\n crossReferencesPreserved?: number;\n errors: string[];\n}\n\n// ============================================================================\n// Cross-Reference Tracking\n// ============================================================================\n\n/**\n * Represents a cross-memory reference.\n */\nexport interface CrossReference {\n readonly sourceMemory: 'session' | 'belief' | 'agentic' | 'adaptive' | 'mobimem';\n readonly sourceKey: string;\n readonly targetMemory: 'session' | 'belief' | 'agentic' | 'adaptive' | 'mobimem';\n readonly targetKey: string;\n readonly createdAt: Date;\n}\n\n/**\n * Tracks cross-references between memory systems.\n * Used to prevent orphaned references during decay.\n */\nexport class CrossReferenceTracker {\n private readonly references: Map<string, CrossReference[]> = new Map();\n private readonly log: ILogger;\n\n constructor(logger?: ILogger) {\n this.log = logger ?? createLogger({ component: 'CrossReferenceTracker' });\n }\n\n /**\n * Register a cross-reference between two memories.\n */\n registerReference(ref: Omit<CrossReference, 'createdAt'>): void {\n const key = this.makeKey(ref.sourceMemory, ref.sourceKey);\n const refs = this.references.get(key) ?? [];\n refs.push({\n ...ref,\n createdAt: new Date(getTimeProvider().now()),\n });\n this.references.set(key, refs);\n this.log.debug('Registered cross-reference', {\n source: `${ref.sourceMemory}:${ref.sourceKey}`,\n target: `${ref.targetMemory}:${ref.targetKey}`,\n });\n }\n\n /**\n * Check if a memory entry has cross-references.\n */\n hasReferences(memory: CrossReference['sourceMemory'], key: string): boolean {\n const refKey = this.makeKey(memory, key);\n const refs = this.references.get(refKey);\n return refs !== undefined && refs.length > 0;\n }\n\n /**\n * Get all references for a memory entry.\n */\n getReferences(memory: CrossReference['sourceMemory'], key: string): readonly CrossReference[] {\n const refKey = this.makeKey(memory, key);\n return this.references.get(refKey) ?? [];\n }\n\n /**\n * Remove references for a deleted memory entry.\n */\n removeReferences(memory: CrossReference['sourceMemory'], key: string): number {\n const refKey = this.makeKey(memory, key);\n const refs = this.references.get(refKey);\n if (refs === undefined) return 0;\n this.references.delete(refKey);\n\n // Also remove any references targeting this key\n let removed = refs.length;\n for (const [k, targetRefs] of this.references.entries()) {\n const filtered = targetRefs.filter(\n (r) => !(r.targetMemory === memory && r.targetKey === key)\n );\n if (filtered.length !== targetRefs.length) {\n removed += targetRefs.length - filtered.length;\n if (filtered.length === 0) {\n this.references.delete(k);\n } else {\n this.references.set(k, filtered);\n }\n }\n }\n return removed;\n }\n\n /**\n * Get statistics about tracked references.\n */\n getStats(): { totalReferences: number; uniqueSources: number } {\n let totalReferences = 0;\n for (const refs of this.references.values()) {\n totalReferences += refs.length;\n }\n return {\n totalReferences,\n uniqueSources: this.references.size,\n };\n }\n\n private makeKey(memory: string, key: string): string {\n return `${memory}:${key}`;\n }\n}\n\n// ============================================================================\n// MemoryDecayManager\n// ============================================================================\n\n/**\n * Manages coordinated decay across all memory systems.\n * Implements FADE (Forgetting with Adaptive Decay) principles.\n */\nexport class MemoryDecayManager {\n private readonly config: MemoryDecayConfig;\n private readonly log: ILogger;\n private readonly tracker: CrossReferenceTracker;\n private readonly runHistory: DecayRunStats[] = [];\n private decayTimer: ReturnType<typeof setInterval> | null = null;\n\n // Memory system references (set during initialization)\n private beliefs: HindsightBeliefMemory | null = null;\n private agentic: AgenticMemoryBackend | null = null;\n private adaptive: AdaptiveMemoryBackend | null = null;\n private mobimem: MobiMem | null = null;\n\n constructor(config: Partial<MemoryDecayConfig> = {}, logger?: ILogger) {\n this.config = { ...DEFAULT_DECAY_CONFIG, ...config };\n this.log = logger ?? createLogger({ component: 'MemoryDecayManager' });\n this.tracker = new CrossReferenceTracker(this.log);\n }\n\n /**\n * Initialize with memory system references.\n */\n initialize(options: {\n beliefs?: HindsightBeliefMemory;\n agentic?: AgenticMemoryBackend | null;\n adaptive?: AdaptiveMemoryBackend | null;\n mobimem?: MobiMem | null;\n }): void {\n this.beliefs = options.beliefs ?? null;\n this.agentic = options.agentic ?? null;\n this.adaptive = options.adaptive ?? null;\n this.mobimem = options.mobimem ?? null;\n this.log.info('MemoryDecayManager initialized', {\n beliefs: this.beliefs !== null,\n agentic: this.agentic !== null,\n adaptive: this.adaptive !== null,\n mobimem: this.mobimem !== null,\n });\n }\n\n /**\n * Start automatic decay scheduling.\n */\n startAutoDecay(): void {\n if (!this.config.enabled) {\n this.log.info('Auto-decay disabled by configuration');\n return;\n }\n if (this.decayTimer !== null) {\n this.log.warn('Auto-decay already running');\n return;\n }\n\n this.decayTimer = setInterval(() => {\n void this.runDecay().catch((error: unknown) => {\n const err = error instanceof Error ? error : new Error(String(error));\n this.log.error('Auto-decay failed', err, {});\n });\n }, this.config.decayIntervalMs);\n\n this.log.info('Auto-decay started', { intervalMs: this.config.decayIntervalMs });\n }\n\n /**\n * Stop automatic decay scheduling.\n */\n stopAutoDecay(): void {\n if (this.decayTimer !== null) {\n clearInterval(this.decayTimer);\n this.decayTimer = null;\n this.log.info('Auto-decay stopped');\n }\n }\n\n /**\n * Run a coordinated decay pass across all memory systems.\n */\n async runDecay(): Promise<DecayRunStats> {\n const startedAt = new Date(getTimeProvider().now());\n this.log.info('Starting coordinated decay run');\n\n const results = await this.executeDecayPhases();\n const stats = this.buildStats(startedAt, results);\n this.recordHistory(stats);\n this.logCompletion(stats);\n\n return stats;\n }\n\n /** Execute all decay phases and collect results. */\n private async executeDecayPhases(): Promise<DecayPhaseResults> {\n const results: DecayPhaseResults = { errors: [] };\n\n // Phase 1: Belief Memory\n const beliefResult = await this.safeDecay('Belief', () => this.decayBeliefs());\n results.beliefsPruned = beliefResult.pruned;\n results.crossReferencesPreserved = beliefResult.preserved;\n if (beliefResult.error !== undefined) results.errors.push(beliefResult.error);\n\n // Phase 2: Agentic Memory\n const agenticResult = await this.safeDecay('Agentic', () => this.decayAgentic());\n results.agenticEvicted = agenticResult.evicted;\n results.crossReferencesPreserved =\n (results.crossReferencesPreserved ?? 0) + agenticResult.preserved;\n if (agenticResult.error !== undefined) results.errors.push(agenticResult.error);\n\n // Phase 3: Adaptive Memory\n const adaptiveResult = await this.safeDecay('Adaptive', () => this.decayAdaptive());\n results.adaptiveEvicted = adaptiveResult.evicted;\n results.crossReferencesPreserved =\n (results.crossReferencesPreserved ?? 0) + adaptiveResult.preserved;\n if (adaptiveResult.error !== undefined) results.errors.push(adaptiveResult.error);\n\n // Phase 4: MobiMem\n results.mobimemEvicted = this.decayMobiMem(results.errors);\n\n return results;\n }\n\n /** Safely execute a decay function with error handling. */\n private async safeDecay(\n name: string,\n fn: () => Promise<{ pruned?: number; evicted?: number; preserved: number }>\n ): Promise<{ pruned: number; evicted: number; preserved: number; error?: string }> {\n try {\n const result = await fn();\n return {\n pruned: result.pruned ?? 0,\n evicted: result.evicted ?? 0,\n preserved: result.preserved,\n };\n } catch (error) {\n const msg = `${name} decay failed: ${getErrorMessage(error)}`;\n this.log.warn(msg);\n return { pruned: 0, evicted: 0, preserved: 0, error: msg };\n }\n }\n\n /** Execute MobiMem maintenance. */\n private decayMobiMem(errors: string[]): number {\n if (this.mobimem === null || !this.config.mobimemEvictOnDecay) return 0;\n try {\n this.mobimem.runMaintenance();\n return this.mobimem.getStats().action.totalEntries > 0 ? 1 : 0;\n } catch (error) {\n const msg = `MobiMem decay failed: ${getErrorMessage(error)}`;\n errors.push(msg);\n this.log.warn(msg);\n return 0;\n }\n }\n\n /** Build DecayRunStats from phase results. */\n private buildStats(startedAt: Date, results: DecayPhaseResults): DecayRunStats {\n return {\n startedAt,\n completedAt: new Date(getTimeProvider().now()),\n beliefsPruned: results.beliefsPruned ?? 0,\n agenticEvicted: results.agenticEvicted ?? 0,\n adaptiveEvicted: results.adaptiveEvicted ?? 0,\n mobimemEvicted: results.mobimemEvicted ?? 0,\n crossReferencesPreserved: results.crossReferencesPreserved ?? 0,\n errors: results.errors,\n };\n }\n\n /** Record stats in history, keeping last 100. */\n private recordHistory(stats: DecayRunStats): void {\n this.runHistory.push(stats);\n if (this.runHistory.length > 100) this.runHistory.shift();\n }\n\n /** Log completion of decay run. */\n private logCompletion(stats: DecayRunStats): void {\n this.log.info('Coordinated decay completed', {\n durationMs: stats.completedAt.getTime() - stats.startedAt.getTime(),\n beliefsPruned: stats.beliefsPruned,\n agenticEvicted: stats.agenticEvicted,\n adaptiveEvicted: stats.adaptiveEvicted,\n mobimemEvicted: stats.mobimemEvicted,\n crossReferencesPreserved: stats.crossReferencesPreserved,\n errors: stats.errors.length,\n });\n }\n\n /**\n * Decay beliefs older than the configured age.\n */\n private async decayBeliefs(): Promise<{ pruned: number; preserved: number }> {\n if (this.beliefs === null) return { pruned: 0, preserved: 0 };\n\n const maxAgeMs = this.config.beliefMaxAgeDays * 24 * 60 * 60 * 1000;\n const cutoffDate = new Date(getTimeProvider().now() - maxAgeMs);\n\n // If cross-reference checking is enabled, we need to check before pruning\n // For now, use the simple age-based pruning\n const result = await this.beliefs.pruneSuperseded(cutoffDate);\n if (!result.ok) {\n throw new Error(result.error.message);\n }\n\n return { pruned: result.value, preserved: 0 };\n }\n\n /**\n * Decay agentic memories with low importance.\n */\n private async decayAgentic(): Promise<{ evicted: number; preserved: number }> {\n if (this.agentic === null) return { evicted: 0, preserved: 0 };\n\n // Use the base prune functionality with age-based cutoff\n // Agentic memory importance-based eviction requires searching all entries\n // For Phase 5, we use a conservative approach: prune entries older than 90 days\n const cutoffDate = new Date(getTimeProvider().now() - 90 * 24 * 60 * 60 * 1000);\n const result = await this.agentic.prune(cutoffDate);\n if (!result.ok) {\n throw new Error(result.error.message);\n }\n\n return { evicted: result.value, preserved: 0 };\n }\n\n /**\n * Decay adaptive memories with low priority scores.\n */\n private async decayAdaptive(): Promise<{ evicted: number; preserved: number }> {\n if (this.adaptive === null) return { evicted: 0, preserved: 0 };\n\n // Use the base prune functionality with age-based cutoff\n // Priority-based eviction would require retrieving all entries and filtering\n // For Phase 5, we use a conservative approach: prune entries older than 60 days\n const cutoffDate = new Date(getTimeProvider().now() - 60 * 24 * 60 * 60 * 1000);\n const result = await this.adaptive.prune(cutoffDate);\n if (!result.ok) {\n throw new Error(result.error.message);\n }\n\n return { evicted: result.value, preserved: 0 };\n }\n\n /**\n * Register a cross-reference between memory systems.\n * Call this when promoting memory between layers.\n */\n registerCrossReference(\n sourceMemory: CrossReference['sourceMemory'],\n sourceKey: string,\n targetMemory: CrossReference['targetMemory'],\n targetKey: string\n ): void {\n this.tracker.registerReference({\n sourceMemory,\n sourceKey,\n targetMemory,\n targetKey,\n });\n }\n\n /**\n * Get aggregate statistics across all decay runs.\n */\n getAggregateStats(): DecayAggregateStats {\n const lastRun = this.runHistory.length > 0 ? this.runHistory[this.runHistory.length - 1] : null;\n\n return {\n totalRuns: this.runHistory.length,\n lastRunAt: lastRun?.completedAt ?? null,\n totalBeliefsPruned: this.runHistory.reduce((sum, r) => sum + r.beliefsPruned, 0),\n totalAgenticEvicted: this.runHistory.reduce((sum, r) => sum + r.agenticEvicted, 0),\n totalAdaptiveEvicted: this.runHistory.reduce((sum, r) => sum + r.adaptiveEvicted, 0),\n totalMobimemEvicted: this.runHistory.reduce((sum, r) => sum + r.mobimemEvicted, 0),\n totalCrossReferencesPreserved: this.runHistory.reduce(\n (sum, r) => sum + r.crossReferencesPreserved,\n 0\n ),\n totalErrors: this.runHistory.reduce((sum, r) => sum + r.errors.length, 0),\n };\n }\n\n /**\n * Get the last N decay run results.\n */\n getRecentRuns(limit = 10): readonly DecayRunStats[] {\n return this.runHistory.slice(-limit);\n }\n\n /**\n * Get cross-reference tracker statistics.\n */\n getCrossReferenceStats(): { totalReferences: number; uniqueSources: number } {\n return this.tracker.getStats();\n }\n\n /**\n * Clean up resources.\n */\n shutdown(): void {\n this.stopAutoDecay();\n this.log.info('MemoryDecayManager shutdown');\n }\n}\n","/**\n * Cross-Memory Query Helpers\n *\n * Standalone functions for querying individual memory backends and\n * scoring relevance. Extracted from ToolMemoryManager (#1671) to\n * reduce tool-memory.ts below the 400-line governance limit.\n *\n * @module mcp/tools/tool-memory-query\n */\n\nimport type { ILogger } from '../../core/index.js';\nimport type { HindsightBeliefMemory, Belief } from '../../context/belief-memory.js';\nimport type { AgenticMemoryBackend } from '../../context/agentic-memory.js';\nimport type { AdaptiveMemoryBackend } from '../../context/adaptive-memory.js';\nimport type { ITypedMemory } from '../../context/memory-types.js';\nimport type { UnifiedMemoryResult } from './tool-memory-types.js';\nimport type { SessionLearning } from '../../context/session-memory-types.js';\n\n// ============================================================================\n// Relevance Scoring\n// ============================================================================\n\n/**\n * Calculate relevance score based on keyword matches (#1227).\n * Uses graduated scoring: base ratio + partial match bonus + exact phrase bonus.\n */\nexport function scoreRelevance(text: string, keywords: readonly string[]): number {\n if (keywords.length === 0) return 0.5;\n const lower = text.toLowerCase();\n const matched = keywords.filter((k) => lower.includes(k));\n const matchRatio = matched.length / keywords.length;\n let tfBonus = 0;\n for (const k of matched) {\n const count = lower.split(k).length - 1;\n if (count > 1) tfBonus += 0.05 * Math.min(count - 1, 3);\n }\n const phrase = keywords.join(' ');\n const phraseBonus = lower.includes(phrase) ? 0.15 : 0;\n return Math.min(1, matchRatio * 0.8 + tfBonus + phraseBonus);\n}\n\n// ============================================================================\n// Per-Backend Query Helpers\n// ============================================================================\n\n/** Query SessionMemory learnings. */\nexport function querySessionMemory(\n learnings: readonly SessionLearning[],\n keywords: readonly string[],\n limit: number\n): UnifiedMemoryResult[] {\n const now = new Date();\n return learnings.slice(0, limit).map((l) => ({\n source: 'session' as const,\n type: 'learning',\n content: `${l.pattern} (${l.context})`,\n relevance: scoreRelevance(l.pattern + ' ' + l.context, keywords),\n timestamp: now,\n metadata: { confidence: l.confidence, source: l.source },\n }));\n}\n\n/** Query BeliefMemory. Falls back to keyword search when exact match misses (#1225). */\nexport async function queryBeliefMemory(\n beliefs: HindsightBeliefMemory,\n query: string,\n keywords: readonly string[],\n limit: number,\n log: ILogger\n): Promise<UnifiedMemoryResult[]> {\n const results: UnifiedMemoryResult[] = [];\n try {\n const beliefResult = await beliefs.recallBySubject(query, limit);\n let matched: readonly Belief[] = [];\n if (beliefResult.ok && beliefResult.value.length > 0) {\n matched = beliefResult.value;\n } else if (keywords.length > 0) {\n const KEYWORD_SCAN_LIMIT = 1000;\n const allResult = await beliefs.query({\n includeSuperseded: false,\n limit: KEYWORD_SCAN_LIMIT,\n });\n if (allResult.ok) {\n matched = allResult.value.filter((b) => {\n const text = (b.subject + ' ' + b.predicate + ' ' + b.object).toLowerCase();\n return keywords.some((k) => text.includes(k));\n });\n }\n }\n for (const b of matched.filter((x) => !x.superseded)) {\n results.push({\n source: 'belief',\n type: 'belief',\n content: `${b.subject} ${b.predicate} ${b.object}`,\n relevance: scoreRelevance(b.subject + ' ' + b.predicate + ' ' + b.object, keywords),\n timestamp: b.createdAt,\n metadata: { confidence: b.confidence },\n });\n }\n } catch (e: unknown) {\n log.debug('Belief memory query failed', { error: String(e) });\n }\n return results;\n}\n\n/** Query AgenticMemory for knowledge. */\nexport async function queryAgenticMemory(\n agentic: AgenticMemoryBackend,\n query: string,\n keywords: readonly string[],\n limit: number,\n log: ILogger\n): Promise<UnifiedMemoryResult[]> {\n const results: UnifiedMemoryResult[] = [];\n try {\n const agResult = await agentic.searchAgentic(query, limit);\n if (agResult.ok) {\n for (const e of agResult.value) {\n results.push({\n source: 'agentic',\n type: 'knowledge',\n content: `${e.key}: ${JSON.stringify(e.value).slice(0, 100)}`,\n relevance: scoreRelevance(e.key + ' ' + e.attributes.keywords.join(' '), keywords),\n timestamp: e.createdAt,\n metadata: { keywords: e.attributes.keywords },\n });\n }\n }\n } catch (e: unknown) {\n log.debug('Agentic memory query failed', { error: String(e) });\n }\n return results;\n}\n\n/** Query TypedMemory for semantic and episodic entries. */\nexport async function queryTypedMemory(\n typed: ITypedMemory,\n query: string,\n keywords: readonly string[],\n limitPerType: number,\n log: ILogger\n): Promise<UnifiedMemoryResult[]> {\n const results: UnifiedMemoryResult[] = [];\n try {\n const [semanticResult, episodicResult] = await Promise.all([\n typed.queryByType('semantic', query, limitPerType),\n typed.queryByType('episodic', query, limitPerType),\n ]);\n for (const r of [semanticResult, episodicResult]) {\n if (r.ok) {\n for (const e of r.value) {\n results.push({\n source: 'typed',\n type: e.type,\n content: String(e.value).slice(0, 150),\n relevance: scoreRelevance(String(e.value), keywords),\n timestamp: e.createdAt,\n });\n }\n }\n }\n } catch (e: unknown) {\n log.debug('Typed memory query failed', { error: String(e) });\n }\n return results;\n}\n\n/** Query AdaptiveMemory for priority-scored entries (#1226). */\nexport async function queryAdaptiveMemory(\n adaptive: AdaptiveMemoryBackend,\n query: string,\n keywords: readonly string[],\n limit: number,\n log: ILogger\n): Promise<UnifiedMemoryResult[]> {\n const results: UnifiedMemoryResult[] = [];\n try {\n const searchResult = await adaptive.search(query, limit);\n if (searchResult.ok) {\n for (const e of searchResult.value) {\n results.push({\n source: 'adaptive',\n type: 'adaptive',\n content: `${e.key}: ${JSON.stringify(e.value).slice(0, 100)}`,\n relevance: scoreRelevance(e.key + ' ' + JSON.stringify(e.value).slice(0, 200), keywords),\n timestamp: e.createdAt,\n metadata: { importance: e.metadata.importance },\n });\n }\n }\n } catch (e: unknown) {\n log.debug('Adaptive memory query failed', { error: String(e) });\n }\n return results;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAcA,YAAYA,SAAQ;AACpB,YAAYC,WAAU;;;ACPtB,SAAS,SAAS;AAgBX,IAAM,mBAAmB;AAAA,EAC9B,KAAK;AAAA,EACL,QAAQ;AAAA,EACR,MAAM;AACR;AAOO,IAAM,yBAAyB,EAAE,KAAK,CAAC,OAAO,UAAU,MAAM,CAAC;AAiB/D,IAAM,uBAAuB,EAAE,OAAO;AAAA,EAC3C,YAAY;AAAA,EACZ,MAAM,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,SAAS;AAAA,EACnC,KAAK,EAAE,OAAO,EAAE,SAAS,EAAE,SAAS;AACtC,CAAC;AAqBM,IAAM,oBAAoB,EAAE,OAAO;AAAA,EACxC,KAAK,EAAE,OAAO,EAAE,IAAI,CAAC;AAAA,EACrB,OAAO,EAAE,QAAQ;AAAA,EACjB,UAAU;AAAA,EACV,WAAW,EAAE,KAAK;AAAA,EAClB,YAAY,EAAE,KAAK;AACrB,CAAC;AAKM,IAAM,cAAN,cAA0B,WAAW;AAAA,EAC1C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F,SAAS,OAAgB;AACvB,WAAK,IAAI,MAAM,+BAA+B;AAAA,QAC5C,OAAO,gBAAgB,KAAK;AAAA,MAC9B,CAAC;AAAA,IACH;AAAA,EACF;AACF;","names":["fs","path","z","z","z","z","z","z","logger","z","logger","logger","logger","z","z","path","logger","path","z","z","z","z","z","logger","logger","z","tokenize","stringifyValue","logger","fs","path","z","z","logger","z","z","z","logger","logger","DEFAULT_DECAY_CONFIG","logger","err","logger"]}
|