cogmem 3.6.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/BENCHMARKS.md +62 -0
- package/CHANGELOG.md +215 -0
- package/CONCURRENT_ACCESS.md +27 -0
- package/CONTRIBUTING.md +32 -0
- package/LICENSE +21 -0
- package/MEMORY_ATLAS.md +101 -0
- package/MEMORY_MODEL.md +179 -0
- package/README.md +751 -0
- package/RECALL_EXPLAINABILITY.md +152 -0
- package/RELEASE_CHECKLIST.md +92 -0
- package/SECURITY.md +21 -0
- package/dist/adapters/MarkdownSourceLoader.d.ts +5 -0
- package/dist/adapters/MarkdownSourceLoader.js +19 -0
- package/dist/adapters/conversation/ConversationMarkdownAdapter.d.ts +9 -0
- package/dist/adapters/conversation/ConversationMarkdownAdapter.js +233 -0
- package/dist/adapters/hermes/HermesStateDbAdapter.d.ts +10 -0
- package/dist/adapters/hermes/HermesStateDbAdapter.js +268 -0
- package/dist/adapters/hermes/HermesWorkspaceProfile.d.ts +15 -0
- package/dist/adapters/hermes/HermesWorkspaceProfile.js +82 -0
- package/dist/adapters/index.d.ts +15 -0
- package/dist/adapters/index.js +12 -0
- package/dist/adapters/openclaw/OpenClawAdapterSupport.d.ts +14 -0
- package/dist/adapters/openclaw/OpenClawAdapterSupport.js +29 -0
- package/dist/adapters/openclaw/OpenClawDailyMemoryAdapter.d.ts +8 -0
- package/dist/adapters/openclaw/OpenClawDailyMemoryAdapter.js +35 -0
- package/dist/adapters/openclaw/OpenClawMemoryIndexAdapter.d.ts +8 -0
- package/dist/adapters/openclaw/OpenClawMemoryIndexAdapter.js +23 -0
- package/dist/adapters/openclaw/OpenClawPersonaAdapter.d.ts +8 -0
- package/dist/adapters/openclaw/OpenClawPersonaAdapter.js +24 -0
- package/dist/adapters/openclaw/OpenClawSessionAdapter.d.ts +8 -0
- package/dist/adapters/openclaw/OpenClawSessionAdapter.js +15 -0
- package/dist/adapters/openclaw/OpenClawUserProfileAdapter.d.ts +8 -0
- package/dist/adapters/openclaw/OpenClawUserProfileAdapter.js +24 -0
- package/dist/adapters/openclaw/OpenClawWorkspaceProfile.d.ts +38 -0
- package/dist/adapters/openclaw/OpenClawWorkspaceProfile.js +199 -0
- package/dist/adapters/soul/SoulMarkdownAdapter.d.ts +14 -0
- package/dist/adapters/soul/SoulMarkdownAdapter.js +255 -0
- package/dist/adapters/types.d.ts +97 -0
- package/dist/adapters/types.js +185 -0
- package/dist/agent/AgentMemoryBackend.d.ts +291 -0
- package/dist/agent/AgentMemoryBackend.js +1272 -0
- package/dist/agent/AgentRecallQueryCompiler.d.ts +20 -0
- package/dist/agent/AgentRecallQueryCompiler.js +289 -0
- package/dist/agent/ContextHygiene.d.ts +9 -0
- package/dist/agent/ContextHygiene.js +20 -0
- package/dist/agent/MemoryUsageReceipt.d.ts +35 -0
- package/dist/agent/MemoryUsageReceipt.js +136 -0
- package/dist/agent/SessionWorkingState.d.ts +20 -0
- package/dist/agent/SessionWorkingState.js +94 -0
- package/dist/agent/index.d.ts +6 -0
- package/dist/agent/index.js +5 -0
- package/dist/algorithm/AlgorithmReviewBackend.d.ts +84 -0
- package/dist/algorithm/AlgorithmReviewBackend.js +261 -0
- package/dist/algorithm/AlgorithmReviewMetrics.d.ts +23 -0
- package/dist/algorithm/AlgorithmReviewMetrics.js +25 -0
- package/dist/algorithm/Phase2ModelAlgorithmReviewBackend.d.ts +38 -0
- package/dist/algorithm/Phase2ModelAlgorithmReviewBackend.js +372 -0
- package/dist/assets/FileAssetIngestionService.d.ts +32 -0
- package/dist/assets/FileAssetIngestionService.js +133 -0
- package/dist/assets/FileAssetStore.d.ts +36 -0
- package/dist/assets/FileAssetStore.js +152 -0
- package/dist/assets/FileBlockStore.d.ts +12 -0
- package/dist/assets/FileBlockStore.js +110 -0
- package/dist/assets/FileChunkStore.d.ts +23 -0
- package/dist/assets/FileChunkStore.js +179 -0
- package/dist/assets/FileChunker.d.ts +10 -0
- package/dist/assets/FileChunker.js +69 -0
- package/dist/assets/FileLoaderRegistry.d.ts +8 -0
- package/dist/assets/FileLoaderRegistry.js +21 -0
- package/dist/assets/FileLoaders.d.ts +37 -0
- package/dist/assets/FileLoaders.js +268 -0
- package/dist/assets/index.d.ts +10 -0
- package/dist/assets/index.js +7 -0
- package/dist/assets/providers/types.d.ts +47 -0
- package/dist/assets/providers/types.js +1 -0
- package/dist/assets/types.d.ts +159 -0
- package/dist/assets/types.js +1 -0
- package/dist/atlas/ActionFrameExtractor.d.ts +15 -0
- package/dist/atlas/ActionFrameExtractor.js +135 -0
- package/dist/atlas/MemoryAtlasIndexer.d.ts +32 -0
- package/dist/atlas/MemoryAtlasIndexer.js +74 -0
- package/dist/atlas/MemoryAtlasQueryCompiler.d.ts +23 -0
- package/dist/atlas/MemoryAtlasQueryCompiler.js +55 -0
- package/dist/atlas/MemoryAtlasService.d.ts +25 -0
- package/dist/atlas/MemoryAtlasService.js +216 -0
- package/dist/atlas/MemoryAtlasTypes.d.ts +107 -0
- package/dist/atlas/MemoryAtlasTypes.js +1 -0
- package/dist/atlas/index.d.ts +6 -0
- package/dist/atlas/index.js +5 -0
- package/dist/backend/SemanticBackend.d.ts +40 -0
- package/dist/backend/SemanticBackend.js +107 -0
- package/dist/batch/IngestionCursorStore.d.ts +52 -0
- package/dist/batch/IngestionCursorStore.js +153 -0
- package/dist/batch/InstalledBatchProcessor.d.ts +88 -0
- package/dist/batch/InstalledBatchProcessor.js +179 -0
- package/dist/batch/SourceOnboarding.d.ts +56 -0
- package/dist/batch/SourceOnboarding.js +366 -0
- package/dist/belief/BeliefGovernanceService.d.ts +59 -0
- package/dist/belief/BeliefGovernanceService.js +183 -0
- package/dist/belief/BeliefStore.d.ts +78 -0
- package/dist/belief/BeliefStore.js +898 -0
- package/dist/benchmark/BenchmarkRegistry.d.ts +16 -0
- package/dist/benchmark/BenchmarkRegistry.js +97 -0
- package/dist/benchmark/BenchmarkReport.d.ts +23 -0
- package/dist/benchmark/BenchmarkReport.js +62 -0
- package/dist/benchmark/BenchmarkRunner.d.ts +27 -0
- package/dist/benchmark/BenchmarkRunner.js +64 -0
- package/dist/benchmark/BrainEval.d.ts +134 -0
- package/dist/benchmark/BrainEval.js +252 -0
- package/dist/benchmark/ExternalBenchmarkRunner.d.ts +8 -0
- package/dist/benchmark/ExternalBenchmarkRunner.js +12 -0
- package/dist/benchmark/LongMemEvalAdapter.d.ts +46 -0
- package/dist/benchmark/LongMemEvalAdapter.js +88 -0
- package/dist/benchmark/LongMemEvalCli.d.ts +6 -0
- package/dist/benchmark/LongMemEvalCli.js +26 -0
- package/dist/bin/CliJson.d.ts +17 -0
- package/dist/bin/CliJson.js +20 -0
- package/dist/bin/brain-eval.d.ts +3 -0
- package/dist/bin/brain-eval.js +46 -0
- package/dist/bin/cogmem.d.ts +3 -0
- package/dist/bin/cogmem.js +95 -0
- package/dist/bin/compact.d.ts +3 -0
- package/dist/bin/compact.js +96 -0
- package/dist/bin/connect.d.ts +3 -0
- package/dist/bin/connect.js +398 -0
- package/dist/bin/doctor.d.ts +3 -0
- package/dist/bin/doctor.js +171 -0
- package/dist/bin/dream.d.ts +3 -0
- package/dist/bin/dream.js +65 -0
- package/dist/bin/episode.d.ts +3 -0
- package/dist/bin/episode.js +268 -0
- package/dist/bin/explain-recall.d.ts +3 -0
- package/dist/bin/explain-recall.js +139 -0
- package/dist/bin/import-hermes.d.ts +3 -0
- package/dist/bin/import-hermes.js +6 -0
- package/dist/bin/import-openclaw.d.ts +3 -0
- package/dist/bin/import-openclaw.js +6 -0
- package/dist/bin/import-support.d.ts +43 -0
- package/dist/bin/import-support.js +528 -0
- package/dist/bin/init.d.ts +30 -0
- package/dist/bin/init.js +761 -0
- package/dist/bin/mcp.d.ts +3 -0
- package/dist/bin/mcp.js +52 -0
- package/dist/bin/memory.d.ts +3 -0
- package/dist/bin/memory.js +803 -0
- package/dist/bin/migrate-vectors.d.ts +3 -0
- package/dist/bin/migrate-vectors.js +74 -0
- package/dist/bin/migrate.d.ts +3 -0
- package/dist/bin/migrate.js +95 -0
- package/dist/bin/normalize-transcript.d.ts +16 -0
- package/dist/bin/normalize-transcript.js +153 -0
- package/dist/bin/openclaw.d.ts +3 -0
- package/dist/bin/openclaw.js +78 -0
- package/dist/bin/prospective.d.ts +3 -0
- package/dist/bin/prospective.js +115 -0
- package/dist/bin/re-embed.d.ts +3 -0
- package/dist/bin/re-embed.js +46 -0
- package/dist/bin/repair.d.ts +3 -0
- package/dist/bin/repair.js +118 -0
- package/dist/bin/snapshot.d.ts +3 -0
- package/dist/bin/snapshot.js +100 -0
- package/dist/bin/strategy.d.ts +3 -0
- package/dist/bin/strategy.js +66 -0
- package/dist/bin/update-release.d.ts +15 -0
- package/dist/bin/update-release.js +62 -0
- package/dist/bin/update.d.ts +3 -0
- package/dist/bin/update.js +215 -0
- package/dist/binding/BindingClassifier.d.ts +19 -0
- package/dist/binding/BindingClassifier.js +270 -0
- package/dist/binding/BindingDecisionEngine.d.ts +11 -0
- package/dist/binding/BindingDecisionEngine.js +13 -0
- package/dist/binding/ClaimKeyGenerator.d.ts +4 -0
- package/dist/binding/ClaimKeyGenerator.js +21 -0
- package/dist/binding/MemoryBindingService.d.ts +28 -0
- package/dist/binding/MemoryBindingService.js +283 -0
- package/dist/binding/MemoryBindingTypes.d.ts +140 -0
- package/dist/binding/MemoryBindingTypes.js +1 -0
- package/dist/binding/TopicPathRegistry.d.ts +5 -0
- package/dist/binding/TopicPathRegistry.js +33 -0
- package/dist/binding/index.d.ts +12 -0
- package/dist/binding/index.js +6 -0
- package/dist/boards/ApprovalBoard.d.ts +14 -0
- package/dist/boards/ApprovalBoard.js +32 -0
- package/dist/boards/Board.d.ts +23 -0
- package/dist/boards/Board.js +1 -0
- package/dist/boards/BoardEventBuffer.d.ts +10 -0
- package/dist/boards/BoardEventBuffer.js +22 -0
- package/dist/boards/BoardEventBus.d.ts +15 -0
- package/dist/boards/BoardEventBus.js +38 -0
- package/dist/boards/BoardEventFilter.d.ts +5 -0
- package/dist/boards/BoardEventFilter.js +1 -0
- package/dist/boards/BoardRegistry.d.ts +11 -0
- package/dist/boards/BoardRegistry.js +15 -0
- package/dist/boards/ContextBoard.d.ts +15 -0
- package/dist/boards/ContextBoard.js +33 -0
- package/dist/boards/MemoryBoard.d.ts +13 -0
- package/dist/boards/MemoryBoard.js +30 -0
- package/dist/boards/ProcessBoard.d.ts +16 -0
- package/dist/boards/ProcessBoard.js +56 -0
- package/dist/boards/ProposalBoard.d.ts +13 -0
- package/dist/boards/ProposalBoard.js +37 -0
- package/dist/boards/ReasoningTraceBoard.d.ts +11 -0
- package/dist/boards/ReasoningTraceBoard.js +34 -0
- package/dist/boards/TaskBoard.d.ts +14 -0
- package/dist/boards/TaskBoard.js +37 -0
- package/dist/boards/index.d.ts +13 -0
- package/dist/boards/index.js +12 -0
- package/dist/config/CogmemConfig.d.ts +43 -0
- package/dist/config/CogmemConfig.js +247 -0
- package/dist/config/VectorDimension.d.ts +13 -0
- package/dist/config/VectorDimension.js +53 -0
- package/dist/context/ContextCortex.d.ts +71 -0
- package/dist/context/ContextCortex.js +156 -0
- package/dist/context/index.d.ts +2 -0
- package/dist/context/index.js +1 -0
- package/dist/core/ImportanceLevels.d.ts +4 -0
- package/dist/core/ImportanceLevels.js +6 -0
- package/dist/core/IntentParser.d.ts +12 -0
- package/dist/core/IntentParser.js +211 -0
- package/dist/core/MemoryGraph.d.ts +100 -0
- package/dist/core/MemoryGraph.js +860 -0
- package/dist/core/Metabolism.d.ts +43 -0
- package/dist/core/Metabolism.js +196 -0
- package/dist/core/Neuron.d.ts +20 -0
- package/dist/core/Neuron.js +51 -0
- package/dist/core/QueryClassifier.d.ts +36 -0
- package/dist/core/QueryClassifier.js +161 -0
- package/dist/core/Reflection.d.ts +42 -0
- package/dist/core/Reflection.js +183 -0
- package/dist/core/ResonanceCore.d.ts +26 -0
- package/dist/core/ResonanceCore.js +115 -0
- package/dist/core/Synapse.d.ts +10 -0
- package/dist/core/Synapse.js +27 -0
- package/dist/core/TwoStagePulseRanker.d.ts +16 -0
- package/dist/core/TwoStagePulseRanker.js +120 -0
- package/dist/dream/DreamScheduler.d.ts +47 -0
- package/dist/dream/DreamScheduler.js +156 -0
- package/dist/dream/index.d.ts +2 -0
- package/dist/dream/index.js +1 -0
- package/dist/embedding/EmbeddingProvider.d.ts +16 -0
- package/dist/embedding/EmbeddingProvider.js +12 -0
- package/dist/embedding/NeuronEmbeddingStore.d.ts +38 -0
- package/dist/embedding/NeuronEmbeddingStore.js +193 -0
- package/dist/embedding/OllamaEmbeddingProvider.d.ts +21 -0
- package/dist/embedding/OllamaEmbeddingProvider.js +65 -0
- package/dist/embedding/QwenAPIEmbeddingProvider.d.ts +26 -0
- package/dist/embedding/QwenAPIEmbeddingProvider.js +53 -0
- package/dist/embedding/ReEmbeddingPipeline.d.ts +30 -0
- package/dist/embedding/ReEmbeddingPipeline.js +119 -0
- package/dist/embedding/ReEmbeddingStatus.d.ts +10 -0
- package/dist/embedding/ReEmbeddingStatus.js +1 -0
- package/dist/embedding/index.d.ts +11 -0
- package/dist/embedding/index.js +5 -0
- package/dist/encryption/AesGcmEncryptionProvider.d.ts +9 -0
- package/dist/encryption/AesGcmEncryptionProvider.js +42 -0
- package/dist/encryption/EncryptionProvider.d.ts +6 -0
- package/dist/encryption/EncryptionProvider.js +3 -0
- package/dist/encryption/index.d.ts +4 -0
- package/dist/encryption/index.js +2 -0
- package/dist/engine/BeliefExtractor.d.ts +48 -0
- package/dist/engine/BeliefExtractor.js +1189 -0
- package/dist/engine/CognitiveGraphCompiler.d.ts +24 -0
- package/dist/engine/CognitiveGraphCompiler.js +243 -0
- package/dist/engine/ConsolidationPipeline.d.ts +66 -0
- package/dist/engine/ConsolidationPipeline.js +376 -0
- package/dist/engine/ConsolidationTrigger.d.ts +18 -0
- package/dist/engine/ConsolidationTrigger.js +41 -0
- package/dist/engine/CrossTopicSynthesizer.d.ts +28 -0
- package/dist/engine/CrossTopicSynthesizer.js +70 -0
- package/dist/engine/CrossTopicTrigger.d.ts +17 -0
- package/dist/engine/CrossTopicTrigger.js +29 -0
- package/dist/engine/DeepWriteConfig.d.ts +14 -0
- package/dist/engine/DeepWriteConfig.js +37 -0
- package/dist/engine/DeepWriteMemoryCompiler.d.ts +43 -0
- package/dist/engine/DeepWriteMemoryCompiler.js +42 -0
- package/dist/engine/DeepWriteMemoryOrchestrator.d.ts +60 -0
- package/dist/engine/DeepWriteMemoryOrchestrator.js +175 -0
- package/dist/engine/DeepWritePromotionPolicy.d.ts +48 -0
- package/dist/engine/DeepWritePromotionPolicy.js +514 -0
- package/dist/engine/DeepWriteRedactor.d.ts +14 -0
- package/dist/engine/DeepWriteRedactor.js +53 -0
- package/dist/engine/DreamCuratorSchedule.d.ts +18 -0
- package/dist/engine/DreamCuratorSchedule.js +95 -0
- package/dist/engine/DreamCuratorWorker.d.ts +67 -0
- package/dist/engine/DreamCuratorWorker.js +908 -0
- package/dist/engine/EntityResolutionEngine.d.ts +45 -0
- package/dist/engine/EntityResolutionEngine.js +105 -0
- package/dist/engine/EpisodicSemanticDistiller.d.ts +25 -0
- package/dist/engine/EpisodicSemanticDistiller.js +68 -0
- package/dist/engine/EvolutionVerifier.d.ts +39 -0
- package/dist/engine/EvolutionVerifier.js +104 -0
- package/dist/engine/FactCompiler.d.ts +41 -0
- package/dist/engine/FactCompiler.js +820 -0
- package/dist/engine/GraphCommunityEngine.d.ts +20 -0
- package/dist/engine/GraphCommunityEngine.js +91 -0
- package/dist/engine/ImportanceSignalDetector.d.ts +11 -0
- package/dist/engine/ImportanceSignalDetector.js +51 -0
- package/dist/engine/IngestionEngine.d.ts +44 -0
- package/dist/engine/IngestionEngine.js +182 -0
- package/dist/engine/InteractionBinder.d.ts +16 -0
- package/dist/engine/InteractionBinder.js +87 -0
- package/dist/engine/LocalSemanticCompiler.d.ts +40 -0
- package/dist/engine/LocalSemanticCompiler.js +111 -0
- package/dist/engine/MemoryConsolidationEngine.d.ts +11 -0
- package/dist/engine/MemoryConsolidationEngine.js +21 -0
- package/dist/engine/MemoryGate.d.ts +10 -0
- package/dist/engine/MemoryGate.js +34 -0
- package/dist/engine/OfflineConsolidationPipeline.d.ts +148 -0
- package/dist/engine/OfflineConsolidationPipeline.js +670 -0
- package/dist/engine/OrphanCleaner.d.ts +15 -0
- package/dist/engine/OrphanCleaner.js +27 -0
- package/dist/engine/PipelineMetrics.d.ts +32 -0
- package/dist/engine/PipelineMetrics.js +126 -0
- package/dist/engine/PrincipleDecayPolicy.d.ts +17 -0
- package/dist/engine/PrincipleDecayPolicy.js +64 -0
- package/dist/engine/TopologyCompiler.d.ts +25 -0
- package/dist/engine/TopologyCompiler.js +276 -0
- package/dist/engine/WorkingMemoryDelta.d.ts +23 -0
- package/dist/engine/WorkingMemoryDelta.js +63 -0
- package/dist/entity/EntityGovernanceService.d.ts +47 -0
- package/dist/entity/EntityGovernanceService.js +215 -0
- package/dist/entity/index.d.ts +3 -0
- package/dist/entity/index.js +1 -0
- package/dist/episode/CogmemBlockStripper.d.ts +11 -0
- package/dist/episode/CogmemBlockStripper.js +58 -0
- package/dist/episode/CorrectionResolver.d.ts +30 -0
- package/dist/episode/CorrectionResolver.js +17 -0
- package/dist/episode/EpisodeAssembler.d.ts +54 -0
- package/dist/episode/EpisodeAssembler.js +203 -0
- package/dist/episode/EpisodeImportIdentity.d.ts +7 -0
- package/dist/episode/EpisodeImportIdentity.js +17 -0
- package/dist/episode/EpisodeSemanticSummarizer.d.ts +4 -0
- package/dist/episode/EpisodeSemanticSummarizer.js +31 -0
- package/dist/episode/EpisodeStore.d.ts +189 -0
- package/dist/episode/EpisodeStore.js +680 -0
- package/dist/episode/EpisodeTypes.d.ts +96 -0
- package/dist/episode/EpisodeTypes.js +1 -0
- package/dist/episode/TurnRelationClassifier.d.ts +40 -0
- package/dist/episode/TurnRelationClassifier.js +205 -0
- package/dist/episode/index.d.ts +9 -0
- package/dist/episode/index.js +8 -0
- package/dist/eval/datasets/contradiction_injection.d.ts +3 -0
- package/dist/eval/datasets/contradiction_injection.js +56 -0
- package/dist/eval/datasets/noisy_tool_output_corpus.d.ts +16 -0
- package/dist/eval/datasets/noisy_tool_output_corpus.js +59 -0
- package/dist/eval/datasets/synthetic_long_conversation.d.ts +40 -0
- package/dist/eval/datasets/synthetic_long_conversation.js +136 -0
- package/dist/eval/runners/EvalRunner.d.ts +12 -0
- package/dist/eval/runners/EvalRunner.js +66 -0
- package/dist/eval/runners/ReportFormatter.d.ts +13 -0
- package/dist/eval/runners/ReportFormatter.js +59 -0
- package/dist/eval/strategy/ContextOutcomeStore.d.ts +12 -0
- package/dist/eval/strategy/ContextOutcomeStore.js +44 -0
- package/dist/eval/strategy/ContextPolicyScorer.d.ts +25 -0
- package/dist/eval/strategy/ContextPolicyScorer.js +58 -0
- package/dist/eval/strategy/MemoryUseJudge.d.ts +49 -0
- package/dist/eval/strategy/MemoryUseJudge.js +75 -0
- package/dist/eval/strategy/StrategyDiversitySelector.d.ts +8 -0
- package/dist/eval/strategy/StrategyDiversitySelector.js +44 -0
- package/dist/eval/strategy/StrategyRolloutEvaluator.d.ts +15 -0
- package/dist/eval/strategy/StrategyRolloutEvaluator.js +30 -0
- package/dist/eval/strategy/index.d.ts +6 -0
- package/dist/eval/strategy/index.js +5 -0
- package/dist/factory.d.ts +726 -0
- package/dist/factory.js +2118 -0
- package/dist/governance/CandidateReviewService.d.ts +33 -0
- package/dist/governance/CandidateReviewService.js +126 -0
- package/dist/governance/ContradictionResolver.d.ts +22 -0
- package/dist/governance/ContradictionResolver.js +54 -0
- package/dist/governance/CredibilityScorer.d.ts +10 -0
- package/dist/governance/CredibilityScorer.js +29 -0
- package/dist/governance/DecayPolicy.d.ts +18 -0
- package/dist/governance/DecayPolicy.js +28 -0
- package/dist/governance/MemoryExplain.d.ts +46 -0
- package/dist/governance/MemoryExplain.js +62 -0
- package/dist/governance/MemoryGovernanceExecutor.d.ts +18 -0
- package/dist/governance/MemoryGovernanceExecutor.js +37 -0
- package/dist/governance/MemoryGovernancePlan.d.ts +36 -0
- package/dist/governance/MemoryGovernancePlan.js +1 -0
- package/dist/governance/MemoryGovernanceValidator.d.ts +13 -0
- package/dist/governance/MemoryGovernanceValidator.js +53 -0
- package/dist/governance/ObservationHygieneRules.d.ts +17 -0
- package/dist/governance/ObservationHygieneRules.js +28 -0
- package/dist/governance/PiiRedactor.d.ts +20 -0
- package/dist/governance/PiiRedactor.js +37 -0
- package/dist/governance/SupersedeChain.d.ts +21 -0
- package/dist/governance/SupersedeChain.js +107 -0
- package/dist/governance/index.d.ts +14 -0
- package/dist/governance/index.js +6 -0
- package/dist/graph/BrainGraphView.d.ts +20 -0
- package/dist/graph/BrainGraphView.js +45 -0
- package/dist/host/openclaw/AutoMemoryPluginInstaller.d.ts +45 -0
- package/dist/host/openclaw/AutoMemoryPluginInstaller.js +1904 -0
- package/dist/internal.d.ts +148 -0
- package/dist/internal.js +144 -0
- package/dist/lexicon/coreMemoryLexicon.d.ts +96 -0
- package/dist/lexicon/coreMemoryLexicon.js +525 -0
- package/dist/lexicon/language-packs/en.d.ts +42 -0
- package/dist/lexicon/language-packs/en.js +41 -0
- package/dist/lexicon/language-packs/zh.d.ts +42 -0
- package/dist/lexicon/language-packs/zh.js +41 -0
- package/dist/lexicon/zh/entities.d.ts +2 -0
- package/dist/lexicon/zh/entities.js +17 -0
- package/dist/lexicon/zh/index.d.ts +5 -0
- package/dist/lexicon/zh/index.js +3 -0
- package/dist/lexicon/zh/stopwords.d.ts +2 -0
- package/dist/lexicon/zh/stopwords.js +22 -0
- package/dist/lexicon/zh/topics.d.ts +6 -0
- package/dist/lexicon/zh/topics.js +52 -0
- package/dist/mcp/CoreMcpTools.d.ts +33 -0
- package/dist/mcp/CoreMcpTools.js +832 -0
- package/dist/mcp/server.d.ts +5 -0
- package/dist/mcp/server.js +29 -0
- package/dist/meta/MetaObservationCollector.d.ts +37 -0
- package/dist/meta/MetaObservationCollector.js +348 -0
- package/dist/meta/PolicyProposalGenerator.d.ts +11 -0
- package/dist/meta/PolicyProposalGenerator.js +159 -0
- package/dist/meta/ProposalApplier.d.ts +18 -0
- package/dist/meta/ProposalApplier.js +91 -0
- package/dist/meta/ProposalConfigOverlay.d.ts +13 -0
- package/dist/meta/ProposalConfigOverlay.js +27 -0
- package/dist/meta/ProposalEvalRunner.d.ts +31 -0
- package/dist/meta/ProposalEvalRunner.js +62 -0
- package/dist/meta/ProposalLedger.d.ts +34 -0
- package/dist/meta/ProposalLedger.js +242 -0
- package/dist/meta/types.d.ts +63 -0
- package/dist/meta/types.js +1 -0
- package/dist/migrations/0001_init.d.ts +4 -0
- package/dist/migrations/0001_init.js +67 -0
- package/dist/migrations/0002_v06_platform.d.ts +10 -0
- package/dist/migrations/0002_v06_platform.js +103 -0
- package/dist/migrations/0003_v07_dialogues.d.ts +9 -0
- package/dist/migrations/0003_v07_dialogues.js +53 -0
- package/dist/migrations/0004_v09_self_improvement.d.ts +9 -0
- package/dist/migrations/0004_v09_self_improvement.js +100 -0
- package/dist/migrations/0005_dialogue_buffer.d.ts +8 -0
- package/dist/migrations/0005_dialogue_buffer.js +44 -0
- package/dist/migrations/0006_deep_write_memory.d.ts +3 -0
- package/dist/migrations/0006_deep_write_memory.js +54 -0
- package/dist/migrations/0007_deep_write_summaries.d.ts +3 -0
- package/dist/migrations/0007_deep_write_summaries.js +24 -0
- package/dist/migrations/0009_memory_importance.d.ts +3 -0
- package/dist/migrations/0009_memory_importance.js +18 -0
- package/dist/migrations/0010_skill_neurons.d.ts +3 -0
- package/dist/migrations/0010_skill_neurons.js +19 -0
- package/dist/migrations/0011_topic_path.d.ts +3 -0
- package/dist/migrations/0011_topic_path.js +19 -0
- package/dist/migrations/0012_governance_security.d.ts +3 -0
- package/dist/migrations/0012_governance_security.js +23 -0
- package/dist/migrations/0015_memory_governance.d.ts +3 -0
- package/dist/migrations/0015_memory_governance.js +74 -0
- package/dist/migrations/0016_entity_governance.d.ts +3 -0
- package/dist/migrations/0016_entity_governance.js +40 -0
- package/dist/migrations/0017_belief_graph.d.ts +3 -0
- package/dist/migrations/0017_belief_graph.js +41 -0
- package/dist/migrations/0018_temporal_memory.d.ts +3 -0
- package/dist/migrations/0018_temporal_memory.js +25 -0
- package/dist/migrations/0019_context_cortex.d.ts +3 -0
- package/dist/migrations/0019_context_cortex.js +19 -0
- package/dist/migrations/0020_prospective_memory.d.ts +3 -0
- package/dist/migrations/0020_prospective_memory.js +42 -0
- package/dist/migrations/0021_strategy_cortex.d.ts +3 -0
- package/dist/migrations/0021_strategy_cortex.js +23 -0
- package/dist/migrations/0022_episode_dream_engine.d.ts +3 -0
- package/dist/migrations/0022_episode_dream_engine.js +74 -0
- package/dist/migrations/0023_episode_dream_hardening.d.ts +3 -0
- package/dist/migrations/0023_episode_dream_hardening.js +65 -0
- package/dist/migrations/0024_episode_ontology_reliability.d.ts +3 -0
- package/dist/migrations/0024_episode_ontology_reliability.js +70 -0
- package/dist/migrations/0025_memory_atlas.d.ts +6 -0
- package/dist/migrations/0025_memory_atlas.js +268 -0
- package/dist/migrations/0026_runtime_governance_atlas_reliability.d.ts +3 -0
- package/dist/migrations/0026_runtime_governance_atlas_reliability.js +72 -0
- package/dist/migrations/0027_openclaw_upgrade_hotfix.d.ts +3 -0
- package/dist/migrations/0027_openclaw_upgrade_hotfix.js +21 -0
- package/dist/migrations/SchemaMigrationRunner.d.ts +21 -0
- package/dist/migrations/SchemaMigrationRunner.js +67 -0
- package/dist/migrations/index.d.ts +36 -0
- package/dist/migrations/index.js +57 -0
- package/dist/models/ModelCapabilityRouter.d.ts +17 -0
- package/dist/models/ModelCapabilityRouter.js +75 -0
- package/dist/models/ModelRegistry.d.ts +15 -0
- package/dist/models/ModelRegistry.js +132 -0
- package/dist/models/ModelRole.d.ts +19 -0
- package/dist/models/ModelRole.js +1 -0
- package/dist/models/UserInsight.d.ts +16 -0
- package/dist/models/UserInsight.js +9 -0
- package/dist/models/UserInsightExtractor.d.ts +19 -0
- package/dist/models/UserInsightExtractor.js +99 -0
- package/dist/models/UserModelManager.d.ts +21 -0
- package/dist/models/UserModelManager.js +41 -0
- package/dist/models/UserModelStore.d.ts +20 -0
- package/dist/models/UserModelStore.js +136 -0
- package/dist/models/WorkingMemoryReporter.d.ts +16 -0
- package/dist/models/WorkingMemoryReporter.js +38 -0
- package/dist/models/adapters/MemoryReviewAdapter.d.ts +12 -0
- package/dist/models/adapters/MemoryReviewAdapter.js +77 -0
- package/dist/models/index.d.ts +8 -0
- package/dist/models/index.js +5 -0
- package/dist/models/providers/AnthropicClient.d.ts +17 -0
- package/dist/models/providers/AnthropicClient.js +40 -0
- package/dist/models/providers/OpenAICompatibleClient.d.ts +24 -0
- package/dist/models/providers/OpenAICompatibleClient.js +76 -0
- package/dist/observability/DecisionExplainer.d.ts +5 -0
- package/dist/observability/DecisionExplainer.js +62 -0
- package/dist/observability/TraceEvent.d.ts +11 -0
- package/dist/observability/TraceEvent.js +1 -0
- package/dist/observability/TraceQuery.d.ts +15 -0
- package/dist/observability/TraceQuery.js +28 -0
- package/dist/observability/TraceStore.d.ts +15 -0
- package/dist/observability/TraceStore.js +110 -0
- package/dist/observability/TraceWriter.d.ts +8 -0
- package/dist/observability/TraceWriter.js +14 -0
- package/dist/ontology/MemoryOntology.d.ts +4 -0
- package/dist/ontology/MemoryOntology.js +7 -0
- package/dist/prospective/ProspectiveMemoryService.d.ts +79 -0
- package/dist/prospective/ProspectiveMemoryService.js +258 -0
- package/dist/prospective/index.d.ts +2 -0
- package/dist/prospective/index.js +1 -0
- package/dist/public.d.ts +160 -0
- package/dist/public.js +115 -0
- package/dist/recall/BrainRecall.d.ts +96 -0
- package/dist/recall/BrainRecall.js +574 -0
- package/dist/recall/HierarchicalRecallRouter.d.ts +24 -0
- package/dist/recall/HierarchicalRecallRouter.js +62 -0
- package/dist/recall/RecallExplanation.d.ts +59 -0
- package/dist/recall/RecallExplanation.js +244 -0
- package/dist/recall/RecallGovernance.d.ts +10 -0
- package/dist/recall/RecallGovernance.js +83 -0
- package/dist/recall/RecallSufficiencyGate.d.ts +40 -0
- package/dist/recall/RecallSufficiencyGate.js +208 -0
- package/dist/recall/SourceContextMetadata.d.ts +49 -0
- package/dist/recall/SourceContextMetadata.js +134 -0
- package/dist/recall/TopicClassifier.d.ts +33 -0
- package/dist/recall/TopicClassifier.js +138 -0
- package/dist/recall/TopicDecayPolicy.d.ts +15 -0
- package/dist/recall/TopicDecayPolicy.js +46 -0
- package/dist/recall/TopicRegistry.d.ts +12 -0
- package/dist/recall/TopicRegistry.js +26 -0
- package/dist/recall/TopicSummaryBoard.d.ts +27 -0
- package/dist/recall/TopicSummaryBoard.js +139 -0
- package/dist/recall/VectorCandidateFilter.d.ts +50 -0
- package/dist/recall/VectorCandidateFilter.js +78 -0
- package/dist/retrieval/ConditionDslEvaluator.d.ts +33 -0
- package/dist/retrieval/ConditionDslEvaluator.js +160 -0
- package/dist/retrieval/EntityActivationIndex.d.ts +14 -0
- package/dist/retrieval/EntityActivationIndex.js +19 -0
- package/dist/retrieval/EvidenceFusionPolicy.d.ts +30 -0
- package/dist/retrieval/EvidenceFusionPolicy.js +112 -0
- package/dist/retrieval/EvidenceFusionRanker.d.ts +13 -0
- package/dist/retrieval/EvidenceFusionRanker.js +17 -0
- package/dist/retrieval/NarrativeRecallAssembler.d.ts +32 -0
- package/dist/retrieval/NarrativeRecallAssembler.js +27 -0
- package/dist/retrieval/NativeQueryParser.d.ts +23 -0
- package/dist/retrieval/NativeQueryParser.js +135 -0
- package/dist/retrieval/PlanDslExecutor.d.ts +67 -0
- package/dist/retrieval/PlanDslExecutor.js +194 -0
- package/dist/retrieval/PolicyRuntimeEvaluator.d.ts +48 -0
- package/dist/retrieval/PolicyRuntimeEvaluator.js +96 -0
- package/dist/retrieval/PolicySideEffectExecutor.d.ts +50 -0
- package/dist/retrieval/PolicySideEffectExecutor.js +202 -0
- package/dist/retrieval/PulseRetrievalEngine.d.ts +37 -0
- package/dist/retrieval/PulseRetrievalEngine.js +51 -0
- package/dist/retrieval/QueryCompiler.d.ts +18 -0
- package/dist/retrieval/QueryCompiler.js +97 -0
- package/dist/retrieval/QueryTimePendingEntityResolver.d.ts +67 -0
- package/dist/retrieval/QueryTimePendingEntityResolver.js +260 -0
- package/dist/retrieval/RetrievalPlanner.d.ts +42 -0
- package/dist/retrieval/RetrievalPlanner.js +209 -0
- package/dist/retrieval/TemporalBranchSearch.d.ts +38 -0
- package/dist/retrieval/TemporalBranchSearch.js +109 -0
- package/dist/retrieval/UniverseNavigator.d.ts +43 -0
- package/dist/retrieval/UniverseNavigator.js +75 -0
- package/dist/retrieval/UniverseTraversalExecutor.d.ts +21 -0
- package/dist/retrieval/UniverseTraversalExecutor.js +77 -0
- package/dist/routing/AnswerEvidenceTrace.d.ts +18 -0
- package/dist/routing/AnswerEvidenceTrace.js +1 -0
- package/dist/routing/BrainToolDispatcher.d.ts +37 -0
- package/dist/routing/BrainToolDispatcher.js +163 -0
- package/dist/routing/ConfidenceGate.d.ts +26 -0
- package/dist/routing/ConfidenceGate.js +40 -0
- package/dist/routing/ConfirmationPhraseMatcher.d.ts +9 -0
- package/dist/routing/ConfirmationPhraseMatcher.js +43 -0
- package/dist/routing/DirectReplyFormatter.d.ts +5 -0
- package/dist/routing/DirectReplyFormatter.js +55 -0
- package/dist/routing/EvidenceBudgetManager.d.ts +30 -0
- package/dist/routing/EvidenceBudgetManager.js +55 -0
- package/dist/routing/ExecutionLoop.d.ts +79 -0
- package/dist/routing/ExecutionLoop.js +234 -0
- package/dist/routing/IntentClassifier.d.ts +15 -0
- package/dist/routing/IntentClassifier.js +97 -0
- package/dist/routing/IntentPatternMatcher.d.ts +12 -0
- package/dist/routing/IntentPatternMatcher.js +206 -0
- package/dist/routing/IterativeLLMClarifier.d.ts +80 -0
- package/dist/routing/IterativeLLMClarifier.js +408 -0
- package/dist/routing/LLMToolSchema.d.ts +60 -0
- package/dist/routing/LLMToolSchema.js +143 -0
- package/dist/routing/MessageRouter.d.ts +20 -0
- package/dist/routing/MessageRouter.js +58 -0
- package/dist/routing/SessionContextSelector.d.ts +12 -0
- package/dist/routing/SessionContextSelector.js +86 -0
- package/dist/routing/SystemIntentClassifier.d.ts +15 -0
- package/dist/routing/SystemIntentClassifier.js +50 -0
- package/dist/routing/TaskPlan.d.ts +31 -0
- package/dist/routing/TaskPlan.js +1 -0
- package/dist/routing/TaskRouter.d.ts +13 -0
- package/dist/routing/TaskRouter.js +111 -0
- package/dist/routing/ToolCallParser.d.ts +16 -0
- package/dist/routing/ToolCallParser.js +123 -0
- package/dist/routing/ToolEvidenceNormalizer.d.ts +13 -0
- package/dist/routing/ToolEvidenceNormalizer.js +96 -0
- package/dist/routing/ToolEvidencePack.d.ts +36 -0
- package/dist/routing/ToolEvidencePack.js +84 -0
- package/dist/routing/ToolResultSanitizer.d.ts +19 -0
- package/dist/routing/ToolResultSanitizer.js +58 -0
- package/dist/routing/ToolUsePolicy.d.ts +78 -0
- package/dist/routing/ToolUsePolicy.js +163 -0
- package/dist/routing/index.d.ts +32 -0
- package/dist/routing/index.js +19 -0
- package/dist/routing/templates/ability_template.d.ts +2 -0
- package/dist/routing/templates/ability_template.js +34 -0
- package/dist/routing/templates/approvals_template.d.ts +2 -0
- package/dist/routing/templates/approvals_template.js +43 -0
- package/dist/routing/templates/context_template.d.ts +2 -0
- package/dist/routing/templates/context_template.js +25 -0
- package/dist/routing/templates/contradictions_template.d.ts +2 -0
- package/dist/routing/templates/contradictions_template.js +36 -0
- package/dist/routing/templates/importance_template.d.ts +2 -0
- package/dist/routing/templates/importance_template.js +23 -0
- package/dist/routing/templates/memory_template.d.ts +2 -0
- package/dist/routing/templates/memory_template.js +37 -0
- package/dist/routing/templates/self_manifest_template.d.ts +5 -0
- package/dist/routing/templates/self_manifest_template.js +64 -0
- package/dist/routing/templates/tasks_template.d.ts +2 -0
- package/dist/routing/templates/tasks_template.js +41 -0
- package/dist/routing/templates/trace_template.d.ts +2 -0
- package/dist/routing/templates/trace_template.js +37 -0
- package/dist/routing/tools/EntityExpandTool.d.ts +25 -0
- package/dist/routing/tools/EntityExpandTool.js +59 -0
- package/dist/routing/tools/NeuronContextTool.d.ts +32 -0
- package/dist/routing/tools/NeuronContextTool.js +66 -0
- package/dist/routing/tools/SecondaryRecallTool.d.ts +27 -0
- package/dist/routing/tools/SecondaryRecallTool.js +30 -0
- package/dist/routing/tools/SkillDiscoveryTool.d.ts +13 -0
- package/dist/routing/tools/SkillDiscoveryTool.js +11 -0
- package/dist/snapshot/SnapshotExporter.d.ts +13 -0
- package/dist/snapshot/SnapshotExporter.js +70 -0
- package/dist/snapshot/SnapshotHeader.d.ts +15 -0
- package/dist/snapshot/SnapshotHeader.js +1 -0
- package/dist/snapshot/SnapshotImporter.d.ts +20 -0
- package/dist/snapshot/SnapshotImporter.js +40 -0
- package/dist/snapshot/errors.d.ts +18 -0
- package/dist/snapshot/errors.js +34 -0
- package/dist/snapshot/index.d.ts +5 -0
- package/dist/snapshot/index.js +3 -0
- package/dist/storage/StorageCompactor.d.ts +30 -0
- package/dist/storage/StorageCompactor.js +95 -0
- package/dist/store/ActivationStore.d.ts +45 -0
- package/dist/store/ActivationStore.js +135 -0
- package/dist/store/BackgroundJobStore.d.ts +49 -0
- package/dist/store/BackgroundJobStore.js +156 -0
- package/dist/store/CandidateReviewStore.d.ts +33 -0
- package/dist/store/CandidateReviewStore.js +67 -0
- package/dist/store/CognitiveGraphStore.d.ts +42 -0
- package/dist/store/CognitiveGraphStore.js +193 -0
- package/dist/store/CompilerConfidenceStore.d.ts +20 -0
- package/dist/store/CompilerConfidenceStore.js +76 -0
- package/dist/store/DeepWriteCandidateStore.d.ts +94 -0
- package/dist/store/DeepWriteCandidateStore.js +290 -0
- package/dist/store/DeterministicEmbedder.d.ts +10 -0
- package/dist/store/DeterministicEmbedder.js +24 -0
- package/dist/store/DreamLedgerStore.d.ts +22 -0
- package/dist/store/DreamLedgerStore.js +84 -0
- package/dist/store/Embedder.d.ts +14 -0
- package/dist/store/Embedder.js +52 -0
- package/dist/store/EmbedderFactory.d.ts +12 -0
- package/dist/store/EmbedderFactory.js +51 -0
- package/dist/store/EntityStore.d.ts +195 -0
- package/dist/store/EntityStore.js +941 -0
- package/dist/store/EventStore.d.ts +118 -0
- package/dist/store/EventStore.js +699 -0
- package/dist/store/FactStore.d.ts +76 -0
- package/dist/store/FactStore.js +356 -0
- package/dist/store/HnswlibVectorStore.d.ts +2 -0
- package/dist/store/HnswlibVectorStore.js +1 -0
- package/dist/store/IVectorStore.d.ts +32 -0
- package/dist/store/IVectorStore.js +1 -0
- package/dist/store/InteractionUnitStore.d.ts +52 -0
- package/dist/store/InteractionUnitStore.js +167 -0
- package/dist/store/MemoryAtlasStore.d.ts +60 -0
- package/dist/store/MemoryAtlasStore.js +500 -0
- package/dist/store/MemoryBindingStore.d.ts +77 -0
- package/dist/store/MemoryBindingStore.js +608 -0
- package/dist/store/MemoryGovernanceStore.d.ts +23 -0
- package/dist/store/MemoryGovernanceStore.js +103 -0
- package/dist/store/MemoryInspectionStore.d.ts +61 -0
- package/dist/store/MemoryInspectionStore.js +215 -0
- package/dist/store/PlanRuntimeStore.d.ts +83 -0
- package/dist/store/PlanRuntimeStore.js +257 -0
- package/dist/store/PolicyExecutionProjector.d.ts +17 -0
- package/dist/store/PolicyExecutionProjector.js +115 -0
- package/dist/store/PolicyExecutionStore.d.ts +62 -0
- package/dist/store/PolicyExecutionStore.js +290 -0
- package/dist/store/PolicyProjectionStore.d.ts +18 -0
- package/dist/store/PolicyProjectionStore.js +61 -0
- package/dist/store/ProjectionObservabilityStore.d.ts +38 -0
- package/dist/store/ProjectionObservabilityStore.js +310 -0
- package/dist/store/ReasoningChainStore.d.ts +13 -0
- package/dist/store/ReasoningChainStore.js +74 -0
- package/dist/store/RuntimeProjectionStore.d.ts +18 -0
- package/dist/store/RuntimeProjectionStore.js +61 -0
- package/dist/store/RuntimeProjector.d.ts +17 -0
- package/dist/store/RuntimeProjector.js +119 -0
- package/dist/store/SqliteVecStore.d.ts +25 -0
- package/dist/store/SqliteVecStore.js +126 -0
- package/dist/store/SummaryStore.d.ts +56 -0
- package/dist/store/SummaryStore.js +225 -0
- package/dist/store/TemporalAdjacencyStore.d.ts +49 -0
- package/dist/store/TemporalAdjacencyStore.js +300 -0
- package/dist/store/TopologyStore.d.ts +89 -0
- package/dist/store/TopologyStore.js +657 -0
- package/dist/store/VectorProjector.d.ts +22 -0
- package/dist/store/VectorProjector.js +125 -0
- package/dist/store/VectorStore.d.ts +35 -0
- package/dist/store/VectorStore.js +201 -0
- package/dist/strategy/StrategyCapsule.d.ts +44 -0
- package/dist/strategy/StrategyCapsule.js +1 -0
- package/dist/strategy/StrategyConditionedCandidateBuilder.d.ts +9 -0
- package/dist/strategy/StrategyConditionedCandidateBuilder.js +11 -0
- package/dist/strategy/StrategyContextFormatter.d.ts +3 -0
- package/dist/strategy/StrategyContextFormatter.js +25 -0
- package/dist/strategy/StrategyCortex.d.ts +28 -0
- package/dist/strategy/StrategyCortex.js +78 -0
- package/dist/strategy/StrategyTemplateRegistry.d.ts +9 -0
- package/dist/strategy/StrategyTemplateRegistry.js +78 -0
- package/dist/strategy/index.d.ts +6 -0
- package/dist/strategy/index.js +5 -0
- package/dist/temporal/TemporalMemoryService.d.ts +62 -0
- package/dist/temporal/TemporalMemoryService.js +128 -0
- package/dist/temporal/index.d.ts +2 -0
- package/dist/temporal/index.js +1 -0
- package/dist/topic/TopicAliasRegistry.d.ts +21 -0
- package/dist/topic/TopicAliasRegistry.js +67 -0
- package/dist/topic/TopicGovernance.d.ts +21 -0
- package/dist/topic/TopicGovernance.js +173 -0
- package/dist/topic/TopicPathRegistry.d.ts +36 -0
- package/dist/topic/TopicPathRegistry.js +105 -0
- package/dist/topic/TopicRelationGraph.d.ts +23 -0
- package/dist/topic/TopicRelationGraph.js +55 -0
- package/dist/topic/TopicTypes.d.ts +73 -0
- package/dist/topic/TopicTypes.js +1 -0
- package/dist/topic/index.d.ts +6 -0
- package/dist/topic/index.js +5 -0
- package/dist/types/AsyncEnrichment.d.ts +62 -0
- package/dist/types/AsyncEnrichment.js +7 -0
- package/dist/types/BrainRecallResult.d.ts +66 -0
- package/dist/types/BrainRecallResult.js +1 -0
- package/dist/types/ExtensionPoints.d.ts +116 -0
- package/dist/types/ExtensionPoints.js +1 -0
- package/dist/types/Migration.d.ts +22 -0
- package/dist/types/Migration.js +1 -0
- package/dist/types/QueryTimePendingEntityResolution.d.ts +11 -0
- package/dist/types/QueryTimePendingEntityResolution.js +23 -0
- package/dist/types/index.d.ts +855 -0
- package/dist/types/index.js +24 -0
- package/dist/types/query-ir.d.ts +71 -0
- package/dist/types/query-ir.js +4 -0
- package/dist/types/reasoning.d.ts +16 -0
- package/dist/types/reasoning.js +4 -0
- package/dist/utils/AAAKGenerator.d.ts +57 -0
- package/dist/utils/AAAKGenerator.js +212 -0
- package/dist/utils/Config.d.ts +78 -0
- package/dist/utils/Config.js +91 -0
- package/dist/utils/ConversationMarkdownNormalization.d.ts +88 -0
- package/dist/utils/ConversationMarkdownNormalization.js +567 -0
- package/dist/utils/Logger.d.ts +22 -0
- package/dist/utils/Logger.js +77 -0
- package/dist/utils/hash.d.ts +33 -0
- package/dist/utils/hash.js +53 -0
- package/dist/utils/text.d.ts +2 -0
- package/dist/utils/text.js +19 -0
- package/dist/utils/vector.d.ts +26 -0
- package/dist/utils/vector.js +38 -0
- package/examples/hermes-backend/AGENTS.md +218 -0
- package/examples/hermes-backend/README.md +153 -0
- package/examples/hermes-backend/SKILL.md +365 -0
- package/examples/hermes-backend/references/operations.md +202 -0
- package/examples/openclaw-backend/AGENTS.md +195 -0
- package/examples/openclaw-backend/README.md +228 -0
- package/examples/openclaw-backend/SKILL.md +464 -0
- package/examples/openclaw-backend/references/operations.md +269 -0
- package/install.sh +84 -0
- package/package.json +90 -0
package/dist/factory.js
ADDED
|
@@ -0,0 +1,2118 @@
|
|
|
1
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
2
|
+
import { BeliefStore } from './belief/BeliefStore.js';
|
|
3
|
+
import { BeliefGovernanceService } from './belief/BeliefGovernanceService.js';
|
|
4
|
+
import { MemoryBindingService, } from './binding/index.js';
|
|
5
|
+
import { IngestionCursorStore } from './batch/IngestionCursorStore.js';
|
|
6
|
+
import { MemoryGraph } from './core/MemoryGraph.js';
|
|
7
|
+
import { Metabolism } from './core/Metabolism.js';
|
|
8
|
+
import { Reflection } from './core/Reflection.js';
|
|
9
|
+
import { TwoStagePulseRanker } from './core/TwoStagePulseRanker.js';
|
|
10
|
+
import { BrainRecall } from './recall/BrainRecall.js';
|
|
11
|
+
import { HierarchicalRecallRouter } from './recall/HierarchicalRecallRouter.js';
|
|
12
|
+
import { isRecallableMemoryEvidence, recallSuppressionReasonFor, } from './recall/RecallGovernance.js';
|
|
13
|
+
import { TopicClassifier } from './recall/TopicClassifier.js';
|
|
14
|
+
import { TopicDecayPolicy } from './recall/TopicDecayPolicy.js';
|
|
15
|
+
import { TopicRegistry } from './recall/TopicRegistry.js';
|
|
16
|
+
import { TopicSummaryBoard } from './recall/TopicSummaryBoard.js';
|
|
17
|
+
import { CognitiveGraphCompiler } from './engine/CognitiveGraphCompiler.js';
|
|
18
|
+
import { ConsolidationPipeline } from './engine/ConsolidationPipeline.js';
|
|
19
|
+
import { ConsolidationTrigger } from './engine/ConsolidationTrigger.js';
|
|
20
|
+
import { CrossTopicSynthesizer } from './engine/CrossTopicSynthesizer.js';
|
|
21
|
+
import { CrossTopicTrigger } from './engine/CrossTopicTrigger.js';
|
|
22
|
+
import { DeepWritePromotionPolicy } from './engine/DeepWritePromotionPolicy.js';
|
|
23
|
+
import { DreamCuratorWorker } from './engine/DreamCuratorWorker.js';
|
|
24
|
+
import { EpisodicSemanticDistiller } from './engine/EpisodicSemanticDistiller.js';
|
|
25
|
+
import { EntityResolutionEngine } from './engine/EntityResolutionEngine.js';
|
|
26
|
+
import { FactCompiler } from './engine/FactCompiler.js';
|
|
27
|
+
import { GraphCommunityEngine } from './engine/GraphCommunityEngine.js';
|
|
28
|
+
import { IngestionEngine } from './engine/IngestionEngine.js';
|
|
29
|
+
import { InteractionBinder } from './engine/InteractionBinder.js';
|
|
30
|
+
import { LocalSemanticCompiler } from './engine/LocalSemanticCompiler.js';
|
|
31
|
+
import { MemoryConsolidationEngine } from './engine/MemoryConsolidationEngine.js';
|
|
32
|
+
import { OfflineConsolidationPipeline } from './engine/OfflineConsolidationPipeline.js';
|
|
33
|
+
import { OrphanCleaner } from './engine/OrphanCleaner.js';
|
|
34
|
+
import { PipelineMetrics } from './engine/PipelineMetrics.js';
|
|
35
|
+
import { PrincipleDecayPolicy } from './engine/PrincipleDecayPolicy.js';
|
|
36
|
+
import { TopologyCompiler } from './engine/TopologyCompiler.js';
|
|
37
|
+
import { WorkingMemoryDelta } from './engine/WorkingMemoryDelta.js';
|
|
38
|
+
import { EntityActivationIndex } from './retrieval/EntityActivationIndex.js';
|
|
39
|
+
import { NarrativeRecallAssembler } from './retrieval/NarrativeRecallAssembler.js';
|
|
40
|
+
import { PulseRetrievalEngine } from './retrieval/PulseRetrievalEngine.js';
|
|
41
|
+
import { QueryCompiler } from './retrieval/QueryCompiler.js';
|
|
42
|
+
import { RetrievalPlanner } from './retrieval/RetrievalPlanner.js';
|
|
43
|
+
import { TemporalBranchSearch } from './retrieval/TemporalBranchSearch.js';
|
|
44
|
+
import { UniverseNavigator } from './retrieval/UniverseNavigator.js';
|
|
45
|
+
import { UniverseTraversalExecutor } from './retrieval/UniverseTraversalExecutor.js';
|
|
46
|
+
import { NeuronEmbeddingStore } from './embedding/NeuronEmbeddingStore.js';
|
|
47
|
+
import { ReEmbeddingPipeline } from './embedding/ReEmbeddingPipeline.js';
|
|
48
|
+
import { TopicAliasRegistry, TopicGovernance, TopicPathRegistry as UserTopicPathRegistry, TopicRelationGraph } from './topic/index.js';
|
|
49
|
+
import { CorrectionResolver } from './episode/CorrectionResolver.js';
|
|
50
|
+
import { CandidateReviewService, MemoryGovernanceExecutor, MemoryGovernanceValidator, PiiRedactor, } from './governance/index.js';
|
|
51
|
+
import { migration_0015, migration_0016, migration_0017, migration_0018, migration_0019, migration_0020, migration_0021, migration_0022, migration_0023, migration_0024, migration_0025, migration_0026, migration_0027, SchemaMigrationRunner } from './migrations/index.js';
|
|
52
|
+
import { EntityGovernanceService } from './entity/index.js';
|
|
53
|
+
import { TemporalMemoryService } from './temporal/index.js';
|
|
54
|
+
import { ContextCortex } from './context/index.js';
|
|
55
|
+
import { ProspectiveMemoryService } from './prospective/index.js';
|
|
56
|
+
import { StrategyCortex } from './strategy/index.js';
|
|
57
|
+
import { ContextOutcomeStore, MemoryUseJudge } from './eval/strategy/index.js';
|
|
58
|
+
import { EpisodeAssembler, EpisodeStore } from './episode/index.js';
|
|
59
|
+
import { DreamScheduler } from './dream/index.js';
|
|
60
|
+
import { loadCogmemConfig, resolveCogmemConfigPath, } from './config/CogmemConfig.js';
|
|
61
|
+
import { ModelRegistry } from './models/ModelRegistry.js';
|
|
62
|
+
import { IterativeLLMClarifier } from './routing/IterativeLLMClarifier.js';
|
|
63
|
+
import { ToolUsePolicy } from './routing/ToolUsePolicy.js';
|
|
64
|
+
import { createConfiguredEmbedder } from './store/EmbedderFactory.js';
|
|
65
|
+
import { CognitiveGraphStore } from './store/CognitiveGraphStore.js';
|
|
66
|
+
import { CompilerConfidenceStore } from './store/CompilerConfidenceStore.js';
|
|
67
|
+
import { DeepWriteCandidateStore } from './store/DeepWriteCandidateStore.js';
|
|
68
|
+
import { CandidateReviewStore } from './store/CandidateReviewStore.js';
|
|
69
|
+
import { DreamLedgerStore } from './store/DreamLedgerStore.js';
|
|
70
|
+
import { ActivationStore } from './store/ActivationStore.js';
|
|
71
|
+
import { EntityStore } from './store/EntityStore.js';
|
|
72
|
+
import { EventStore } from './store/EventStore.js';
|
|
73
|
+
import { FactStore } from './store/FactStore.js';
|
|
74
|
+
import { InteractionUnitStore } from './store/InteractionUnitStore.js';
|
|
75
|
+
import { MemoryBindingStore } from './store/MemoryBindingStore.js';
|
|
76
|
+
import { MemoryAtlasStore } from './store/MemoryAtlasStore.js';
|
|
77
|
+
import { MemoryAtlasIndexer, MemoryAtlasService, } from './atlas/index.js';
|
|
78
|
+
import { MemoryGovernanceStore } from './store/MemoryGovernanceStore.js';
|
|
79
|
+
import { SummaryStore } from './store/SummaryStore.js';
|
|
80
|
+
import { TemporalAdjacencyStore } from './store/TemporalAdjacencyStore.js';
|
|
81
|
+
import { TopologyStore } from './store/TopologyStore.js';
|
|
82
|
+
import { SqliteVecStore } from './store/SqliteVecStore.js';
|
|
83
|
+
import { VectorStore } from './store/VectorStore.js';
|
|
84
|
+
import { config } from './utils/Config.js';
|
|
85
|
+
import { KernelRunningError, SnapshotExporter, SnapshotImporter, } from './snapshot/index.js';
|
|
86
|
+
const CORE_VERSION = '3.6.1';
|
|
87
|
+
const LATEST_SCHEMA_VERSION = 27;
|
|
88
|
+
export class MemoryKernel {
|
|
89
|
+
options;
|
|
90
|
+
memoryGraph;
|
|
91
|
+
eventStore;
|
|
92
|
+
factStore;
|
|
93
|
+
entityStore;
|
|
94
|
+
entityGovernanceService;
|
|
95
|
+
beliefStore;
|
|
96
|
+
beliefGovernanceService;
|
|
97
|
+
temporalMemoryService;
|
|
98
|
+
contextCortex;
|
|
99
|
+
strategyCortex;
|
|
100
|
+
memoryUseJudge;
|
|
101
|
+
contextOutcomeStore;
|
|
102
|
+
prospectiveMemoryService;
|
|
103
|
+
cursorStore;
|
|
104
|
+
vectorStore;
|
|
105
|
+
topicRegistry;
|
|
106
|
+
topologyStore;
|
|
107
|
+
cognitiveGraphStore;
|
|
108
|
+
temporalAdjacencyStore;
|
|
109
|
+
neuronEmbeddingStore;
|
|
110
|
+
dreamLedgerStore;
|
|
111
|
+
activationStore;
|
|
112
|
+
memoryBindingStore;
|
|
113
|
+
memoryAtlasStore;
|
|
114
|
+
memoryAtlasService;
|
|
115
|
+
memoryGovernanceStore;
|
|
116
|
+
memoryGovernanceExecutor;
|
|
117
|
+
pipelineMetrics;
|
|
118
|
+
episodeStore;
|
|
119
|
+
episodeAssembler;
|
|
120
|
+
userTopicPathRegistry;
|
|
121
|
+
topicAliasRegistry;
|
|
122
|
+
topicRelationGraph;
|
|
123
|
+
topicGovernance;
|
|
124
|
+
dbPath;
|
|
125
|
+
embedder;
|
|
126
|
+
embeddingProvider;
|
|
127
|
+
modelRegistry;
|
|
128
|
+
encryptionProvider;
|
|
129
|
+
piiRedactor;
|
|
130
|
+
interactionUnitStore;
|
|
131
|
+
compilerConfidenceStore;
|
|
132
|
+
summaryStore;
|
|
133
|
+
deepWriteCandidateStore;
|
|
134
|
+
deepWritePromotionPolicy;
|
|
135
|
+
candidateReviewStore;
|
|
136
|
+
candidateReviewService;
|
|
137
|
+
dreamCuratorWorker;
|
|
138
|
+
dreamScheduler;
|
|
139
|
+
memoryBindingService;
|
|
140
|
+
memoryAtlasIndexer;
|
|
141
|
+
topicSummaryBoard;
|
|
142
|
+
topicDecayPolicy;
|
|
143
|
+
localSemanticCompiler;
|
|
144
|
+
topicClassifier;
|
|
145
|
+
reflection;
|
|
146
|
+
metabolism;
|
|
147
|
+
ingestionEngine;
|
|
148
|
+
universeNavigator;
|
|
149
|
+
offlineConsolidationPipeline;
|
|
150
|
+
consolidationPipeline;
|
|
151
|
+
topologyCompiler;
|
|
152
|
+
cognitiveGraphCompiler;
|
|
153
|
+
brainRecall;
|
|
154
|
+
ranker;
|
|
155
|
+
reEmbeddingPipeline;
|
|
156
|
+
extensions = new Map();
|
|
157
|
+
lastEmbedSuccessAt;
|
|
158
|
+
lastEmbedErrorAt;
|
|
159
|
+
initialized = false;
|
|
160
|
+
closed = false;
|
|
161
|
+
constructor(options = {}) {
|
|
162
|
+
this.options = options;
|
|
163
|
+
this.dbPath = options.dbPath ?? ':memory:';
|
|
164
|
+
this.encryptionProvider = options.encryptionProvider;
|
|
165
|
+
this.piiRedactor = options.redactionPolicy === false ? undefined : new PiiRedactor(options.redactionPolicy);
|
|
166
|
+
this.memoryGraph = new MemoryGraph(this.dbPath);
|
|
167
|
+
this.eventStore = new EventStore(this.dbPath, this.encryptionProvider);
|
|
168
|
+
this.factStore = new FactStore(this.dbPath, this.encryptionProvider);
|
|
169
|
+
const db = this.factStore.getDatabase();
|
|
170
|
+
db.exec('PRAGMA busy_timeout = 5000;');
|
|
171
|
+
new SchemaMigrationRunner(db, [migration_0015, migration_0016, migration_0017, migration_0018, migration_0019, migration_0020, migration_0021, migration_0022, migration_0023, migration_0024, migration_0025, migration_0026, migration_0027]).run();
|
|
172
|
+
this.ensureMetaTable(db);
|
|
173
|
+
this.entityStore = new EntityStore(db);
|
|
174
|
+
this.ensureGovernanceAuditTable(db);
|
|
175
|
+
const vectorDimension = options.vectorDimension ?? config.vector.dimension;
|
|
176
|
+
this.modelRegistry = options.modelRegistry ?? ModelRegistry.defaults();
|
|
177
|
+
this.beliefStore = new BeliefStore(this.dbPath, this.eventStore);
|
|
178
|
+
this.beliefGovernanceService = new BeliefGovernanceService(db, (eventId) => {
|
|
179
|
+
const event = this.eventStore.getEvent(eventId);
|
|
180
|
+
return event ? { eventId, projectId: event.projectId, role: event.role } : undefined;
|
|
181
|
+
});
|
|
182
|
+
this.temporalMemoryService = new TemporalMemoryService(db);
|
|
183
|
+
this.contextCortex = new ContextCortex(db);
|
|
184
|
+
this.strategyCortex = new StrategyCortex();
|
|
185
|
+
this.memoryUseJudge = new MemoryUseJudge();
|
|
186
|
+
this.contextOutcomeStore = new ContextOutcomeStore(db);
|
|
187
|
+
this.prospectiveMemoryService = new ProspectiveMemoryService(db, (eventId) => {
|
|
188
|
+
const event = this.eventStore.getEvent(eventId);
|
|
189
|
+
return event ? {
|
|
190
|
+
eventId,
|
|
191
|
+
projectId: event.projectId,
|
|
192
|
+
role: event.role,
|
|
193
|
+
globalSeq: event.globalSeq,
|
|
194
|
+
content: eventPayloadText(event.payload),
|
|
195
|
+
} : undefined;
|
|
196
|
+
});
|
|
197
|
+
this.cursorStore = new IngestionCursorStore(this.dbPath);
|
|
198
|
+
this.vectorStore = options.vectorBackend === 'hnswlib'
|
|
199
|
+
? new VectorStore(vectorDimension)
|
|
200
|
+
: new SqliteVecStore(db, vectorDimension);
|
|
201
|
+
this.topicRegistry = new TopicRegistry(this.memoryGraph);
|
|
202
|
+
this.topologyStore = new TopologyStore(this.dbPath);
|
|
203
|
+
this.cognitiveGraphStore = new CognitiveGraphStore(this.dbPath);
|
|
204
|
+
this.temporalAdjacencyStore = new TemporalAdjacencyStore(this.dbPath);
|
|
205
|
+
this.interactionUnitStore = new InteractionUnitStore(this.dbPath);
|
|
206
|
+
this.compilerConfidenceStore = new CompilerConfidenceStore(this.dbPath);
|
|
207
|
+
this.neuronEmbeddingStore = new NeuronEmbeddingStore(db);
|
|
208
|
+
this.dreamLedgerStore = new DreamLedgerStore(db);
|
|
209
|
+
this.episodeStore = new EpisodeStore(db, (eventId) => this.eventStore.getEvent(eventId), { initializeSchemaForTests: false });
|
|
210
|
+
this.userTopicPathRegistry = new UserTopicPathRegistry(db);
|
|
211
|
+
this.topicAliasRegistry = new TopicAliasRegistry(db);
|
|
212
|
+
this.topicRelationGraph = new TopicRelationGraph(db);
|
|
213
|
+
this.topicGovernance = new TopicGovernance(db, this.userTopicPathRegistry, this.topicAliasRegistry, this.topicRelationGraph);
|
|
214
|
+
this.episodeAssembler = new EpisodeAssembler(this.episodeStore, (eventId) => this.eventStore.getEvent(eventId), 30 * 60_000, options.turnRelationReviewer, (primary, episode) => {
|
|
215
|
+
const text = eventPayloadText(primary.payload);
|
|
216
|
+
const matches = this.topicAliasRegistry.matchText(primary.projectId || '', text || '');
|
|
217
|
+
if (!matches.length)
|
|
218
|
+
return {};
|
|
219
|
+
const matchedPaths = [...new Set(matches
|
|
220
|
+
.map((match) => this.userTopicPathRegistry.get(match.topicId)?.topicPath)
|
|
221
|
+
.filter((path) => Boolean(path)))];
|
|
222
|
+
return {
|
|
223
|
+
topicPathMatch: Boolean(episode?.topicPath && matchedPaths.includes(episode.topicPath)),
|
|
224
|
+
currentTopicPath: matchedPaths.length === 1 ? matchedPaths[0] : undefined,
|
|
225
|
+
};
|
|
226
|
+
});
|
|
227
|
+
this.activationStore = new ActivationStore(db);
|
|
228
|
+
this.memoryBindingStore = new MemoryBindingStore(db);
|
|
229
|
+
this.memoryBindingService = new MemoryBindingService(this.memoryBindingStore, this.entityStore);
|
|
230
|
+
this.memoryAtlasStore = new MemoryAtlasStore(db);
|
|
231
|
+
this.memoryAtlasIndexer = new MemoryAtlasIndexer(db, this.eventStore, this.memoryAtlasStore);
|
|
232
|
+
this.memoryAtlasService = new MemoryAtlasService(this.memoryAtlasStore, this.eventStore);
|
|
233
|
+
this.entityGovernanceService = new EntityGovernanceService(db, this.entityStore, (eventId) => {
|
|
234
|
+
const event = this.eventStore.getEvent(eventId);
|
|
235
|
+
return event ? { eventId, projectId: event.projectId, role: event.role } : undefined;
|
|
236
|
+
});
|
|
237
|
+
this.memoryGovernanceStore = new MemoryGovernanceStore(db);
|
|
238
|
+
this.memoryGovernanceExecutor = new MemoryGovernanceExecutor(db, this.memoryGovernanceStore, new MemoryGovernanceValidator((eventId) => {
|
|
239
|
+
const event = this.eventStore.getEvent(eventId);
|
|
240
|
+
return event ? { eventId, projectId: event.projectId, role: event.role } : undefined;
|
|
241
|
+
}), {
|
|
242
|
+
BIND_EVENT: (operation) => {
|
|
243
|
+
const eventId = typeof operation.payload.eventId === 'string' ? operation.payload.eventId : operation.evidenceEventIds[0];
|
|
244
|
+
const event = eventId ? this.eventStore.getEvent(eventId) : null;
|
|
245
|
+
if (!event)
|
|
246
|
+
throw new Error(`BIND_EVENT requires an existing event: ${eventId || 'missing'}`);
|
|
247
|
+
this.memoryBindingService.bindRawEvent(event);
|
|
248
|
+
},
|
|
249
|
+
CREATE_PROSPECTIVE_MEMORY: (operation, context) => {
|
|
250
|
+
const projectId = operation.projectId ?? context.plan.projectId;
|
|
251
|
+
if (!projectId)
|
|
252
|
+
throw new Error('CREATE_PROSPECTIVE_MEMORY requires projectId');
|
|
253
|
+
this.prospectiveMemoryService.propose({
|
|
254
|
+
projectId,
|
|
255
|
+
candidateType: operation.payload.candidateType,
|
|
256
|
+
canonicalKey: requiredGovernancePayloadString(operation.payload, 'canonicalKey'),
|
|
257
|
+
title: requiredGovernancePayloadString(operation.payload, 'title'),
|
|
258
|
+
details: optionalGovernancePayloadString(operation.payload, 'details'),
|
|
259
|
+
evidenceEventIds: operation.evidenceEventIds,
|
|
260
|
+
proposedBy: context.plan.proposedBy,
|
|
261
|
+
dueAt: optionalGovernancePayloadNumber(operation.payload, 'dueAt'),
|
|
262
|
+
});
|
|
263
|
+
},
|
|
264
|
+
RESOLVE_PROSPECTIVE_MEMORY: (operation) => {
|
|
265
|
+
const projectId = operation.projectId;
|
|
266
|
+
if (!projectId)
|
|
267
|
+
throw new Error('RESOLVE_PROSPECTIVE_MEMORY requires projectId');
|
|
268
|
+
const candidateId = requiredGovernancePayloadString(operation.payload, 'candidateId');
|
|
269
|
+
const action = requiredGovernancePayloadString(operation.payload, 'action');
|
|
270
|
+
if (action === 'confirm') {
|
|
271
|
+
const confirmationEvidenceEventId = requiredGovernancePayloadString(operation.payload, 'confirmationEvidenceEventId');
|
|
272
|
+
if (!operation.evidenceEventIds.includes(confirmationEvidenceEventId)) {
|
|
273
|
+
throw new Error('confirmation evidence must be included in governance operation evidence');
|
|
274
|
+
}
|
|
275
|
+
this.prospectiveMemoryService.resolve(candidateId, {
|
|
276
|
+
action,
|
|
277
|
+
confirmationEvidenceEventId,
|
|
278
|
+
}, projectId);
|
|
279
|
+
}
|
|
280
|
+
else if (action === 'defer') {
|
|
281
|
+
const deferredUntil = optionalGovernancePayloadNumber(operation.payload, 'deferredUntil');
|
|
282
|
+
if (deferredUntil === undefined)
|
|
283
|
+
throw new Error('RESOLVE_PROSPECTIVE_MEMORY defer requires deferredUntil');
|
|
284
|
+
this.prospectiveMemoryService.resolve(candidateId, { action, deferredUntil }, projectId);
|
|
285
|
+
}
|
|
286
|
+
else if (action === 'reject' || action === 'complete' || action === 'expire') {
|
|
287
|
+
this.prospectiveMemoryService.resolve(candidateId, { action }, projectId);
|
|
288
|
+
}
|
|
289
|
+
else {
|
|
290
|
+
throw new Error(`invalid_prospective_memory_action:${action}`);
|
|
291
|
+
}
|
|
292
|
+
},
|
|
293
|
+
});
|
|
294
|
+
this.pipelineMetrics = new PipelineMetrics(db);
|
|
295
|
+
this.summaryStore = new SummaryStore(db);
|
|
296
|
+
this.summaryStore.migrateLegacyFactSummaries();
|
|
297
|
+
this.deepWriteCandidateStore = new DeepWriteCandidateStore(db);
|
|
298
|
+
this.dreamCuratorWorker = new DreamCuratorWorker({
|
|
299
|
+
eventStore: this.eventStore,
|
|
300
|
+
dreamLedgerStore: this.dreamLedgerStore,
|
|
301
|
+
candidateStore: this.deepWriteCandidateStore,
|
|
302
|
+
modelRegistry: this.modelRegistry,
|
|
303
|
+
pipelineMetrics: this.pipelineMetrics,
|
|
304
|
+
correctionResolver: new CorrectionResolver(({ projectId, query, entities, limit }) => (this.beliefStore.getActiveBeliefsForQuery({ projectId, query, entities, limit }).map((belief) => ({
|
|
305
|
+
beliefId: belief.id, canonicalKey: belief.canonicalKey,
|
|
306
|
+
statement: `${belief.subject} ${belief.predicate} ${String(belief.objectValue)}`, projectId: belief.projectId,
|
|
307
|
+
})))),
|
|
308
|
+
});
|
|
309
|
+
this.dreamScheduler = new DreamScheduler(this.episodeStore, this.dreamCuratorWorker);
|
|
310
|
+
this.topicSummaryBoard = new TopicSummaryBoard(this.memoryGraph, this.summaryStore);
|
|
311
|
+
this.topicDecayPolicy = new TopicDecayPolicy(this.memoryGraph);
|
|
312
|
+
this.localSemanticCompiler = new LocalSemanticCompiler();
|
|
313
|
+
this.embedder = options.embedder ?? createConfiguredEmbedder(vectorDimension, this.modelRegistry);
|
|
314
|
+
this.embeddingProvider = options.embeddingProvider;
|
|
315
|
+
this.universeNavigator = new UniverseNavigator(new QueryCompiler(this.localSemanticCompiler, new EntityResolutionEngine(this.entityStore)), new RetrievalPlanner(), new TemporalBranchSearch(this.topologyStore, this.temporalAdjacencyStore), new PulseRetrievalEngine(this.temporalAdjacencyStore, new EntityActivationIndex(this.entityStore, this.factStore)), new NarrativeRecallAssembler(), new UniverseTraversalExecutor());
|
|
316
|
+
this.topicClassifier = new TopicClassifier(this.memoryGraph, { confidenceThreshold: 0.25, enableEmbedding: true, embeddingThreshold: 0.75 }, this.topicRegistry, this.embedder);
|
|
317
|
+
this.ranker = new TwoStagePulseRanker(this.vectorStore);
|
|
318
|
+
this.reflection = new Reflection(this.memoryGraph);
|
|
319
|
+
this.metabolism = new Metabolism(this.memoryGraph, this.vectorStore, this.eventStore);
|
|
320
|
+
this.ingestionEngine = new IngestionEngine(this.embedder, undefined, vectorDimension);
|
|
321
|
+
this.ingestionEngine.setDedupDeps((vector, k) => this.vectorStore.search(vector, k), (id) => this.memoryGraph.getNeuron(id), (id) => this.reflection.onNeuronActivated(id));
|
|
322
|
+
const noOpDispatcher = {
|
|
323
|
+
dispatch: async (call) => ({
|
|
324
|
+
toolName: 'brain_recall',
|
|
325
|
+
callId: `memory-kernel-${Date.now()}`,
|
|
326
|
+
success: true,
|
|
327
|
+
result: [],
|
|
328
|
+
durationMs: 0,
|
|
329
|
+
}),
|
|
330
|
+
};
|
|
331
|
+
const makeClarifier = (answer) => new IterativeLLMClarifier(async () => answer, noOpDispatcher, {
|
|
332
|
+
maxIterations: 1,
|
|
333
|
+
policy: new ToolUsePolicy(),
|
|
334
|
+
});
|
|
335
|
+
const memoryConsolidationEngine = new MemoryConsolidationEngine(new ConsolidationTrigger(this.memoryGraph), new EpisodicSemanticDistiller(this.memoryGraph, makeClarifier('Consolidated principle from repeated experience.')));
|
|
336
|
+
const crossTopicSynthesizer = new CrossTopicSynthesizer(this.memoryGraph, new CrossTopicTrigger(this.memoryGraph), makeClarifier('Cross-domain principle from multiple semantic consolidations.'));
|
|
337
|
+
const graphCommunityEngine = new GraphCommunityEngine(this.memoryGraph);
|
|
338
|
+
const orphanCleaner = new OrphanCleaner(this.memoryGraph);
|
|
339
|
+
const principleDecayPolicy = new PrincipleDecayPolicy(this.memoryGraph);
|
|
340
|
+
this.deepWritePromotionPolicy = new DeepWritePromotionPolicy({
|
|
341
|
+
candidateStore: this.deepWriteCandidateStore,
|
|
342
|
+
factStore: this.factStore,
|
|
343
|
+
entityStore: this.entityStore,
|
|
344
|
+
beliefStore: this.beliefStore,
|
|
345
|
+
summaryStore: this.summaryStore,
|
|
346
|
+
minPromoteConfidence: 0.86,
|
|
347
|
+
});
|
|
348
|
+
this.candidateReviewStore = new CandidateReviewStore(db);
|
|
349
|
+
this.candidateReviewService = new CandidateReviewService(db, this.deepWriteCandidateStore, this.candidateReviewStore, this.deepWritePromotionPolicy, (eventId) => this.eventStore.getEvent(eventId));
|
|
350
|
+
const workingMemoryDelta = new WorkingMemoryDelta(db, this.memoryGraph);
|
|
351
|
+
this.offlineConsolidationPipeline = new OfflineConsolidationPipeline({
|
|
352
|
+
factStore: this.factStore,
|
|
353
|
+
entityStore: this.entityStore,
|
|
354
|
+
beliefStore: this.beliefStore,
|
|
355
|
+
compilerConfidenceStore: this.compilerConfidenceStore,
|
|
356
|
+
semanticCompiler: this.localSemanticCompiler,
|
|
357
|
+
deepWritePromotionPolicy: this.deepWritePromotionPolicy,
|
|
358
|
+
topicSummaryBoard: this.topicSummaryBoard,
|
|
359
|
+
topicDecayPolicy: this.topicDecayPolicy,
|
|
360
|
+
memoryConsolidationEngine,
|
|
361
|
+
proceduralLearningBridge: {
|
|
362
|
+
scan: (projectId) => this.getExtension('procedural_bridge')?.scan(projectId),
|
|
363
|
+
},
|
|
364
|
+
crossTopicSynthesizer,
|
|
365
|
+
graphCommunityEngine,
|
|
366
|
+
orphanCleaner,
|
|
367
|
+
principleDecayPolicy,
|
|
368
|
+
pipelineMetrics: this.pipelineMetrics,
|
|
369
|
+
maxBudgetMs: options.maxOfflinePipelineBudgetMs,
|
|
370
|
+
db,
|
|
371
|
+
workingMemoryDelta,
|
|
372
|
+
});
|
|
373
|
+
this.consolidationPipeline = new ConsolidationPipeline(this.beliefStore, new InteractionBinder(this.interactionUnitStore), new FactCompiler(this.factStore, this.entityStore), this.localSemanticCompiler, this.factStore, this.entityStore, this.compilerConfidenceStore, undefined, this.offlineConsolidationPipeline);
|
|
374
|
+
this.topologyCompiler = new TopologyCompiler(this.topologyStore);
|
|
375
|
+
this.cognitiveGraphCompiler = new CognitiveGraphCompiler(this.cognitiveGraphStore, this.entityStore);
|
|
376
|
+
this.brainRecall = new BrainRecall({
|
|
377
|
+
memoryGraph: this.memoryGraph,
|
|
378
|
+
factStore: this.factStore,
|
|
379
|
+
entityStore: this.entityStore,
|
|
380
|
+
beliefStore: this.beliefStore,
|
|
381
|
+
cursorStore: this.cursorStore,
|
|
382
|
+
summaryStore: this.summaryStore,
|
|
383
|
+
hierarchicalRouter: new HierarchicalRecallRouter(this.memoryGraph, { minConfidence: 0.15, maxCandidates: 500 }),
|
|
384
|
+
topicSummaryBoard: this.topicSummaryBoard,
|
|
385
|
+
graphCommunityEngine,
|
|
386
|
+
embeddingProvider: this.embeddingProvider,
|
|
387
|
+
neuronEmbeddingStore: this.neuronEmbeddingStore,
|
|
388
|
+
});
|
|
389
|
+
this.reEmbeddingPipeline = this.embeddingProvider
|
|
390
|
+
? new ReEmbeddingPipeline(this.neuronEmbeddingStore, this.embeddingProvider, this.memoryGraph, db)
|
|
391
|
+
: undefined;
|
|
392
|
+
}
|
|
393
|
+
async initialize(skipWarmup = true) {
|
|
394
|
+
if (this.initialized)
|
|
395
|
+
return;
|
|
396
|
+
if (!skipWarmup)
|
|
397
|
+
await this.embedder.warmup();
|
|
398
|
+
this.initialized = true;
|
|
399
|
+
}
|
|
400
|
+
async start() {
|
|
401
|
+
await this.initialize();
|
|
402
|
+
}
|
|
403
|
+
stop() {
|
|
404
|
+
this.metabolism.stop();
|
|
405
|
+
}
|
|
406
|
+
close() {
|
|
407
|
+
if (this.closed)
|
|
408
|
+
return;
|
|
409
|
+
this.closed = true;
|
|
410
|
+
this.stop();
|
|
411
|
+
this.beliefStore.close();
|
|
412
|
+
this.cursorStore.close();
|
|
413
|
+
this.memoryGraph.close();
|
|
414
|
+
this.eventStore.close();
|
|
415
|
+
this.factStore.close();
|
|
416
|
+
this.entityStore.close();
|
|
417
|
+
this.topologyStore.close();
|
|
418
|
+
this.cognitiveGraphStore.close();
|
|
419
|
+
this.temporalAdjacencyStore.close();
|
|
420
|
+
this.activationStore.close();
|
|
421
|
+
this.interactionUnitStore.close();
|
|
422
|
+
this.compilerConfidenceStore.close();
|
|
423
|
+
}
|
|
424
|
+
async ingest(input) {
|
|
425
|
+
await this.initialize();
|
|
426
|
+
const normalizedInput = await this.normalizeIngestInput(input);
|
|
427
|
+
const prevNeuronSelfHash = this.memoryGraph.getLatestNeuronSelfHash(normalizedInput.projectId);
|
|
428
|
+
const { neuron, isDuplicate } = await this.ingestionEngine.ingest(normalizedInput, { prevNeuronSelfHash });
|
|
429
|
+
if (isDuplicate) {
|
|
430
|
+
this.metabolism.recordActivity();
|
|
431
|
+
return neuron;
|
|
432
|
+
}
|
|
433
|
+
const ingestedEvent = this.eventStore.append({
|
|
434
|
+
streamId: neuron.id,
|
|
435
|
+
streamType: 'neuron',
|
|
436
|
+
eventType: 'INGESTED',
|
|
437
|
+
projectId: neuron.metadata.projectId,
|
|
438
|
+
sourceNeuronId: neuron.id,
|
|
439
|
+
parentEventId: normalizedInput.sourceRefs?.find((ref) => ref.eventId)?.eventId,
|
|
440
|
+
causalityType: normalizedInput.sourceRefs?.some((ref) => ref.eventId) ? 'derived_from' : undefined,
|
|
441
|
+
sourceId: normalizedInput.sourceRefs?.[0]?.sourceId,
|
|
442
|
+
contentHash: normalizedInput.sourceRefs?.[0]?.contentHash,
|
|
443
|
+
payload: {
|
|
444
|
+
neuronId: neuron.id,
|
|
445
|
+
selfHash: neuron.self_hash,
|
|
446
|
+
prevHash: neuron.prev_hash,
|
|
447
|
+
type: neuron.metadata.type,
|
|
448
|
+
createdAt: neuron.metadata.createdAt,
|
|
449
|
+
source: normalizedInput.source,
|
|
450
|
+
sourceRefs: normalizedInput.sourceRefs || [],
|
|
451
|
+
},
|
|
452
|
+
});
|
|
453
|
+
neuron.metadata.sourceEventId = ingestedEvent.eventId;
|
|
454
|
+
neuron.metadata.updatedAt = neuron.metadata.createdAt;
|
|
455
|
+
this.memoryGraph.addNeuron(neuron);
|
|
456
|
+
this.topicRegistry.invalidate(neuron.metadata.projectId);
|
|
457
|
+
this.vectorStore.addVector(neuron.id, neuron.coordinates.V);
|
|
458
|
+
this.queueEmbedding(neuron);
|
|
459
|
+
this.reflection.onNeuronActivated(neuron.id);
|
|
460
|
+
this.reflection.detectAndCreateOverrides(neuron, (vector, k) => this.vectorStore.search(vector, k));
|
|
461
|
+
const consolidation = this.consolidationPipeline.consolidate(neuron, ingestedEvent.eventId);
|
|
462
|
+
const topology = this.topologyCompiler.compile({ neuron, consolidation });
|
|
463
|
+
this.temporalAdjacencyStore.syncBuckets(topology.timeBuckets, neuron.metadata.createdAt);
|
|
464
|
+
const cognitiveGraph = this.cognitiveGraphCompiler.compile({ neuron, consolidation, topology });
|
|
465
|
+
this.eventStore.append({
|
|
466
|
+
streamId: neuron.id,
|
|
467
|
+
streamType: 'neuron',
|
|
468
|
+
eventType: 'TOPOLOGY_COMPILED',
|
|
469
|
+
projectId: neuron.metadata.projectId,
|
|
470
|
+
sourceNeuronId: neuron.id,
|
|
471
|
+
occurredAt: neuron.metadata.createdAt,
|
|
472
|
+
payload: {
|
|
473
|
+
neuronId: neuron.id,
|
|
474
|
+
timeBuckets: topology.timeBuckets.map((bucket) => bucket.bucketId),
|
|
475
|
+
branchIds: topology.branchIds,
|
|
476
|
+
taskIds: topology.taskIds,
|
|
477
|
+
clusterIds: topology.clusterIds,
|
|
478
|
+
},
|
|
479
|
+
});
|
|
480
|
+
this.eventStore.append({
|
|
481
|
+
streamId: neuron.id,
|
|
482
|
+
streamType: 'neuron',
|
|
483
|
+
eventType: 'COGNITIVE_GRAPH_COMPILED',
|
|
484
|
+
projectId: neuron.metadata.projectId,
|
|
485
|
+
sourceNeuronId: neuron.id,
|
|
486
|
+
occurredAt: neuron.metadata.createdAt,
|
|
487
|
+
payload: {
|
|
488
|
+
neuronId: neuron.id,
|
|
489
|
+
seedNodeIds: cognitiveGraph.seedNodeIds,
|
|
490
|
+
edgeCount: cognitiveGraph.edgeCount,
|
|
491
|
+
},
|
|
492
|
+
});
|
|
493
|
+
this.metabolism.recordActivity();
|
|
494
|
+
return neuron;
|
|
495
|
+
}
|
|
496
|
+
recall(query, options = {}) {
|
|
497
|
+
return this.brainRecall.recall(query, options);
|
|
498
|
+
}
|
|
499
|
+
navigateMemory(query, options = {}) {
|
|
500
|
+
const limit = Math.max(1, options.limit ?? 8);
|
|
501
|
+
const seedLimit = Math.min(Math.max(limit * 4, 24), 120);
|
|
502
|
+
const seedNeuronIds = this.memoryGraph.fullTextSearch(query, options.projectId, seedLimit);
|
|
503
|
+
const cognitiveContext = this.cognitiveGraphStore.collectContext({
|
|
504
|
+
projectId: options.projectId,
|
|
505
|
+
terms: extractNavigationTerms(query),
|
|
506
|
+
limit: seedLimit,
|
|
507
|
+
hopLimit: 2,
|
|
508
|
+
});
|
|
509
|
+
const seedTemporalBucketIds = this.topologyStore.listTimeBucketIdsByNeuronIds(seedNeuronIds, options.projectId, seedLimit);
|
|
510
|
+
const navigation = this.universeNavigator.navigate({
|
|
511
|
+
query,
|
|
512
|
+
projectId: options.projectId,
|
|
513
|
+
startTime: options.startTime,
|
|
514
|
+
endTime: options.endTime,
|
|
515
|
+
topologyIds: seedNeuronIds,
|
|
516
|
+
branchIds: [],
|
|
517
|
+
temporalBucketIds: seedTemporalBucketIds,
|
|
518
|
+
temporalNeuronIds: seedNeuronIds,
|
|
519
|
+
graphIds: seedNeuronIds,
|
|
520
|
+
cognitiveGraphIds: cognitiveContext.neuronIds,
|
|
521
|
+
entityNeuronIds: [],
|
|
522
|
+
});
|
|
523
|
+
const candidateIds = uniqueStrings([
|
|
524
|
+
...navigation.pulse.fusedIds,
|
|
525
|
+
...navigation.branchSearch.neuronIds,
|
|
526
|
+
...navigation.branchSearch.temporalTraversal.neuronIds,
|
|
527
|
+
...seedNeuronIds,
|
|
528
|
+
...cognitiveContext.neuronIds,
|
|
529
|
+
]);
|
|
530
|
+
const rawEvidence = candidateIds
|
|
531
|
+
.map((id) => this.memoryGraph.getNeuron(id))
|
|
532
|
+
.filter((item) => Boolean(item))
|
|
533
|
+
.filter((neuron) => !options.projectId || neuron.metadata.projectId === options.projectId);
|
|
534
|
+
const governedEvidence = selectRecallableEvidence(rawEvidence, limit);
|
|
535
|
+
if (governedEvidence.rawEvidence.length > 0) {
|
|
536
|
+
return {
|
|
537
|
+
query,
|
|
538
|
+
projectId: options.projectId,
|
|
539
|
+
recallMode: 'universe_navigation',
|
|
540
|
+
fallbackUsed: false,
|
|
541
|
+
navigation,
|
|
542
|
+
rawEvidence: governedEvidence.rawEvidence,
|
|
543
|
+
filteredEvidence: governedEvidence.filteredEvidence,
|
|
544
|
+
};
|
|
545
|
+
}
|
|
546
|
+
const fallbackEvidence = this.recall(query, {
|
|
547
|
+
projectId: options.projectId,
|
|
548
|
+
limit,
|
|
549
|
+
includeRawEvidence: true,
|
|
550
|
+
}).rawEvidence.filter((neuron) => !options.projectId || neuron.metadata.projectId === options.projectId);
|
|
551
|
+
const governedFallbackEvidence = selectRecallableEvidence(fallbackEvidence, limit);
|
|
552
|
+
return {
|
|
553
|
+
query,
|
|
554
|
+
projectId: options.projectId,
|
|
555
|
+
recallMode: 'brain_recall_fallback',
|
|
556
|
+
fallbackUsed: true,
|
|
557
|
+
navigation,
|
|
558
|
+
rawEvidence: governedFallbackEvidence.rawEvidence,
|
|
559
|
+
filteredEvidence: uniqueFilteredEvidence([
|
|
560
|
+
...governedEvidence.filteredEvidence,
|
|
561
|
+
...governedFallbackEvidence.filteredEvidence,
|
|
562
|
+
]),
|
|
563
|
+
};
|
|
564
|
+
}
|
|
565
|
+
recordRawEvent(input) {
|
|
566
|
+
const text = this.piiRedactor ? this.piiRedactor.redact(input.content).text : input.content;
|
|
567
|
+
const occurredAt = input.occurredAt ?? Date.now();
|
|
568
|
+
return this.eventStore.append({
|
|
569
|
+
eventId: input.eventId,
|
|
570
|
+
streamId: input.threadId,
|
|
571
|
+
streamType: 'thread',
|
|
572
|
+
eventType: 'RAW_EVENT_RECORDED',
|
|
573
|
+
rawEventType: input.rawEventType ?? 'message',
|
|
574
|
+
projectId: input.projectId,
|
|
575
|
+
workspaceId: input.workspaceId,
|
|
576
|
+
actorId: input.role,
|
|
577
|
+
sourceId: input.sourceId,
|
|
578
|
+
contentHash: createHash('sha256').update(text).digest('hex'),
|
|
579
|
+
threadId: input.threadId,
|
|
580
|
+
sessionId: input.sessionId,
|
|
581
|
+
localDate: input.localDate,
|
|
582
|
+
turnId: input.turnId,
|
|
583
|
+
turnSeq: input.turnSeq,
|
|
584
|
+
eventOrdinal: input.eventOrdinal,
|
|
585
|
+
role: input.role,
|
|
586
|
+
parentEventId: input.parentEventId,
|
|
587
|
+
prevEventId: input.prevEventId,
|
|
588
|
+
causalityType: input.causalityType,
|
|
589
|
+
sourceOffset: input.sourceOffset,
|
|
590
|
+
lineStart: input.lineStart,
|
|
591
|
+
lineEnd: input.lineEnd,
|
|
592
|
+
charStart: input.charStart,
|
|
593
|
+
charEnd: input.charEnd,
|
|
594
|
+
occurredAt,
|
|
595
|
+
orderingConfidence: 'high',
|
|
596
|
+
payload: {
|
|
597
|
+
text,
|
|
598
|
+
metadata: input.metadata,
|
|
599
|
+
},
|
|
600
|
+
});
|
|
601
|
+
}
|
|
602
|
+
recordToolCall(input) {
|
|
603
|
+
const text = input.content ?? `Tool call ${input.toolName}: ${stringifyToolPayload(input.input)}`;
|
|
604
|
+
const event = this.recordRawEvent({
|
|
605
|
+
projectId: input.projectId,
|
|
606
|
+
workspaceId: input.workspaceId,
|
|
607
|
+
threadId: input.threadId,
|
|
608
|
+
sessionId: input.sessionId,
|
|
609
|
+
turnId: input.turnId,
|
|
610
|
+
turnSeq: input.turnSeq,
|
|
611
|
+
role: 'assistant',
|
|
612
|
+
rawEventType: 'tool_call',
|
|
613
|
+
content: text,
|
|
614
|
+
eventOrdinal: input.eventOrdinal,
|
|
615
|
+
occurredAt: input.occurredAt,
|
|
616
|
+
parentEventId: input.assistantEventId,
|
|
617
|
+
prevEventId: input.assistantEventId,
|
|
618
|
+
causalityType: input.assistantEventId ? 'triggered_by' : undefined,
|
|
619
|
+
sourceId: input.sourceId,
|
|
620
|
+
metadata: {
|
|
621
|
+
...input.metadata,
|
|
622
|
+
toolCallId: input.toolCallId,
|
|
623
|
+
toolName: input.toolName,
|
|
624
|
+
input: input.input,
|
|
625
|
+
},
|
|
626
|
+
});
|
|
627
|
+
if (input.assistantEventId) {
|
|
628
|
+
this.eventStore.updateNextEventId(input.assistantEventId, event.eventId);
|
|
629
|
+
}
|
|
630
|
+
return {
|
|
631
|
+
...event,
|
|
632
|
+
payload: {
|
|
633
|
+
text: event.payload.text,
|
|
634
|
+
toolCallId: input.toolCallId,
|
|
635
|
+
toolName: input.toolName,
|
|
636
|
+
input: input.input,
|
|
637
|
+
metadata: event.payload.metadata,
|
|
638
|
+
},
|
|
639
|
+
};
|
|
640
|
+
}
|
|
641
|
+
recordToolResult(input) {
|
|
642
|
+
const event = this.recordRawEvent({
|
|
643
|
+
projectId: input.projectId,
|
|
644
|
+
workspaceId: input.workspaceId,
|
|
645
|
+
threadId: input.threadId,
|
|
646
|
+
sessionId: input.sessionId,
|
|
647
|
+
turnId: input.turnId,
|
|
648
|
+
turnSeq: input.turnSeq,
|
|
649
|
+
role: 'tool',
|
|
650
|
+
rawEventType: 'tool_result',
|
|
651
|
+
content: input.output,
|
|
652
|
+
eventOrdinal: input.eventOrdinal,
|
|
653
|
+
occurredAt: input.occurredAt,
|
|
654
|
+
parentEventId: input.toolCallEventId,
|
|
655
|
+
prevEventId: input.toolCallEventId,
|
|
656
|
+
causalityType: 'tool_result_for',
|
|
657
|
+
sourceId: input.sourceId,
|
|
658
|
+
metadata: {
|
|
659
|
+
...input.metadata,
|
|
660
|
+
toolCallId: input.toolCallId,
|
|
661
|
+
toolName: input.toolName,
|
|
662
|
+
},
|
|
663
|
+
});
|
|
664
|
+
this.eventStore.updateNextEventId(input.toolCallEventId, event.eventId);
|
|
665
|
+
return {
|
|
666
|
+
...event,
|
|
667
|
+
payload: {
|
|
668
|
+
text: event.payload.text,
|
|
669
|
+
toolCallId: input.toolCallId,
|
|
670
|
+
toolName: input.toolName,
|
|
671
|
+
output: event.payload.text,
|
|
672
|
+
metadata: event.payload.metadata,
|
|
673
|
+
},
|
|
674
|
+
};
|
|
675
|
+
}
|
|
676
|
+
recordTaskEvent(input) {
|
|
677
|
+
const event = this.recordRawEvent({
|
|
678
|
+
projectId: input.projectId,
|
|
679
|
+
workspaceId: input.workspaceId,
|
|
680
|
+
threadId: input.threadId,
|
|
681
|
+
sessionId: input.sessionId,
|
|
682
|
+
turnId: input.turnId,
|
|
683
|
+
turnSeq: input.turnSeq,
|
|
684
|
+
role: input.role ?? 'system',
|
|
685
|
+
rawEventType: input.rawEventType ?? 'task_event',
|
|
686
|
+
content: input.content,
|
|
687
|
+
eventOrdinal: input.eventOrdinal,
|
|
688
|
+
occurredAt: input.occurredAt,
|
|
689
|
+
parentEventId: input.parentEventId,
|
|
690
|
+
prevEventId: input.parentEventId,
|
|
691
|
+
causalityType: input.parentEventId ? 'triggered_by' : undefined,
|
|
692
|
+
sourceId: input.sourceId,
|
|
693
|
+
metadata: {
|
|
694
|
+
...input.metadata,
|
|
695
|
+
taskId: input.taskId,
|
|
696
|
+
title: input.title,
|
|
697
|
+
},
|
|
698
|
+
});
|
|
699
|
+
return {
|
|
700
|
+
...event,
|
|
701
|
+
payload: {
|
|
702
|
+
text: event.payload.text,
|
|
703
|
+
taskId: input.taskId,
|
|
704
|
+
title: input.title,
|
|
705
|
+
metadata: event.payload.metadata,
|
|
706
|
+
},
|
|
707
|
+
};
|
|
708
|
+
}
|
|
709
|
+
async consolidate(options = {}) {
|
|
710
|
+
const endTime = options.endTime ?? Date.now() + 1;
|
|
711
|
+
const startTime = options.startTime ?? 0;
|
|
712
|
+
const rawEpisodes = this.memoryGraph.listNeuronsByTimeRange(startTime, endTime, options.projectId);
|
|
713
|
+
const provisionalFacts = this.factStore.listFactsByTimeRange(startTime, endTime, {
|
|
714
|
+
statuses: ['provisional', 'provisional_enriched', 'enriched_candidate', 'verified'],
|
|
715
|
+
});
|
|
716
|
+
const provisionalEvents = this.factStore.listEventsByTimeRange(startTime, endTime, {
|
|
717
|
+
statuses: ['provisional', 'verified'],
|
|
718
|
+
});
|
|
719
|
+
const interactionUnits = this.interactionUnitStore.listUnitsByNeuronIds(rawEpisodes.map((episode) => episode.id));
|
|
720
|
+
const provisionalEntities = this.entityStore.listEntitiesUpdatedInRange(startTime, endTime);
|
|
721
|
+
const unresolvedReferences = this.entityStore
|
|
722
|
+
.listPendingResolutions()
|
|
723
|
+
.filter((item) => item.updatedAt >= startTime && item.updatedAt < endTime);
|
|
724
|
+
const lowConfidenceItems = [
|
|
725
|
+
...provisionalFacts
|
|
726
|
+
.filter((fact) => fact.confidence < 0.75 || fact.status === 'enriched_candidate')
|
|
727
|
+
.map((fact) => ({
|
|
728
|
+
source: 'compiler',
|
|
729
|
+
targetType: 'fact',
|
|
730
|
+
targetId: fact.factId,
|
|
731
|
+
confidence: fact.confidence,
|
|
732
|
+
reason: fact.status === 'enriched_candidate'
|
|
733
|
+
? 'enriched_candidate_pending_verification'
|
|
734
|
+
: 'low_confidence_provisional_fact',
|
|
735
|
+
})),
|
|
736
|
+
...provisionalEvents
|
|
737
|
+
.filter((event) => event.confidence < 0.75)
|
|
738
|
+
.map((event) => ({
|
|
739
|
+
source: 'compiler',
|
|
740
|
+
targetType: 'event',
|
|
741
|
+
targetId: event.eventId,
|
|
742
|
+
confidence: event.confidence,
|
|
743
|
+
reason: 'low_confidence_provisional_event',
|
|
744
|
+
})),
|
|
745
|
+
...unresolvedReferences.map((reference) => ({
|
|
746
|
+
source: 'entity_binding',
|
|
747
|
+
targetType: 'reference',
|
|
748
|
+
targetId: reference.pendingId,
|
|
749
|
+
reason: 'pending_reference_unresolved',
|
|
750
|
+
})),
|
|
751
|
+
];
|
|
752
|
+
const recentBeliefs = this.beliefStore.listByTimeRange(startTime, endTime, {
|
|
753
|
+
projectId: options.projectId,
|
|
754
|
+
});
|
|
755
|
+
return this.offlineConsolidationPipeline.run({
|
|
756
|
+
rawEpisodes,
|
|
757
|
+
interactionUnits,
|
|
758
|
+
provisionalFacts,
|
|
759
|
+
provisionalEvents,
|
|
760
|
+
provisionalEntities,
|
|
761
|
+
unresolvedReferences,
|
|
762
|
+
lowConfidenceItems,
|
|
763
|
+
recentBeliefs,
|
|
764
|
+
window: {
|
|
765
|
+
projectId: options.projectId,
|
|
766
|
+
startTime,
|
|
767
|
+
endTime,
|
|
768
|
+
},
|
|
769
|
+
});
|
|
770
|
+
}
|
|
771
|
+
getThreadEvents(threadId, options = {}) {
|
|
772
|
+
return this.eventStore.getThreadEvents(threadId, options);
|
|
773
|
+
}
|
|
774
|
+
getEventContext(eventId, options = {}) {
|
|
775
|
+
return this.eventStore.getEventContext(eventId, options);
|
|
776
|
+
}
|
|
777
|
+
searchRawEvents(query, options = {}) {
|
|
778
|
+
return this.eventStore.searchRawEvents(query, options);
|
|
779
|
+
}
|
|
780
|
+
getDreamBacklogStatus(projectId) {
|
|
781
|
+
return this.dreamLedgerStore.getStatus(projectId);
|
|
782
|
+
}
|
|
783
|
+
markDreamed(projectId, globalSeq, dreamedAt) {
|
|
784
|
+
return this.dreamLedgerStore.markDreamed(projectId, globalSeq, dreamedAt);
|
|
785
|
+
}
|
|
786
|
+
async runDreamCurator(options = {}) {
|
|
787
|
+
return this.dreamCuratorWorker.run(options);
|
|
788
|
+
}
|
|
789
|
+
async runDreamTick(options = {}) {
|
|
790
|
+
return this.dreamScheduler.tick(options);
|
|
791
|
+
}
|
|
792
|
+
assembleEpisodeTurn(events, input) {
|
|
793
|
+
return this.episodeAssembler.appendTurn(events, input);
|
|
794
|
+
}
|
|
795
|
+
assembleEpisodeTurnAsync(events, input) {
|
|
796
|
+
return this.episodeAssembler.appendTurnAsync(events, input);
|
|
797
|
+
}
|
|
798
|
+
appendRawEventToEpisode(event, input) {
|
|
799
|
+
return this.episodeAssembler.appendEvent(event, input);
|
|
800
|
+
}
|
|
801
|
+
appendEpisodeMessage(input) {
|
|
802
|
+
let reservedEventId;
|
|
803
|
+
if (input.externalMessageId) {
|
|
804
|
+
const proposedEventId = `evt-episode-${createHash('sha256')
|
|
805
|
+
.update(JSON.stringify([input.projectId, input.sourceAgent, input.sessionId, input.externalMessageId]))
|
|
806
|
+
.digest('hex')}`;
|
|
807
|
+
this.episodeStore.recordIngestKey({
|
|
808
|
+
projectId: input.projectId,
|
|
809
|
+
sourceAgent: input.sourceAgent,
|
|
810
|
+
sourceSessionId: input.sessionId,
|
|
811
|
+
externalMessageId: input.externalMessageId,
|
|
812
|
+
eventId: proposedEventId,
|
|
813
|
+
now: input.timestamp,
|
|
814
|
+
});
|
|
815
|
+
reservedEventId = this.episodeStore.getIngestedEvent(input.projectId, input.sourceAgent, input.sessionId, input.externalMessageId);
|
|
816
|
+
const existingEvent = reservedEventId ? this.eventStore.getEvent(reservedEventId) : null;
|
|
817
|
+
if (existingEvent) {
|
|
818
|
+
this.assertEpisodeIngestIdentity(existingEvent, input);
|
|
819
|
+
return this.resumeEpisodeMessage(existingEvent, input, false);
|
|
820
|
+
}
|
|
821
|
+
}
|
|
822
|
+
let event;
|
|
823
|
+
try {
|
|
824
|
+
event = this.recordRawEvent({
|
|
825
|
+
eventId: reservedEventId,
|
|
826
|
+
projectId: input.projectId,
|
|
827
|
+
workspaceId: input.projectId,
|
|
828
|
+
threadId: input.threadId || input.sessionId,
|
|
829
|
+
sessionId: input.sessionId,
|
|
830
|
+
role: input.role,
|
|
831
|
+
content: input.text,
|
|
832
|
+
occurredAt: input.timestamp,
|
|
833
|
+
sourceId: `${input.sourceAgent}:${input.sessionId}`,
|
|
834
|
+
metadata: { ...input.metadata, externalMessageId: input.externalMessageId, sourceAgent: input.sourceAgent },
|
|
835
|
+
});
|
|
836
|
+
}
|
|
837
|
+
catch (error) {
|
|
838
|
+
const concurrent = reservedEventId ? this.eventStore.getEvent(reservedEventId) : null;
|
|
839
|
+
if (!concurrent) {
|
|
840
|
+
if (input.externalMessageId)
|
|
841
|
+
this.episodeStore.markIngestState({
|
|
842
|
+
projectId: input.projectId, sourceAgent: input.sourceAgent, sourceSessionId: input.sessionId,
|
|
843
|
+
externalMessageId: input.externalMessageId, state: 'failed', error: error instanceof Error ? error.message : String(error),
|
|
844
|
+
});
|
|
845
|
+
throw error;
|
|
846
|
+
}
|
|
847
|
+
this.assertEpisodeIngestIdentity(concurrent, input);
|
|
848
|
+
if (input.externalMessageId)
|
|
849
|
+
this.episodeStore.markIngestState({
|
|
850
|
+
projectId: input.projectId, sourceAgent: input.sourceAgent, sourceSessionId: input.sessionId,
|
|
851
|
+
externalMessageId: input.externalMessageId, state: 'committed',
|
|
852
|
+
});
|
|
853
|
+
return this.resumeEpisodeMessage(concurrent, input, false);
|
|
854
|
+
}
|
|
855
|
+
if (input.externalMessageId)
|
|
856
|
+
this.episodeStore.markIngestState({
|
|
857
|
+
projectId: input.projectId, sourceAgent: input.sourceAgent, sourceSessionId: input.sessionId,
|
|
858
|
+
externalMessageId: input.externalMessageId, state: 'committed', now: event.occurredAt,
|
|
859
|
+
});
|
|
860
|
+
return this.resumeEpisodeMessage(event, input, true);
|
|
861
|
+
}
|
|
862
|
+
async appendEpisodeMessageAsync(input) {
|
|
863
|
+
let reservedEventId;
|
|
864
|
+
if (input.externalMessageId) {
|
|
865
|
+
const proposedEventId = `evt-episode-${createHash('sha256')
|
|
866
|
+
.update(JSON.stringify([input.projectId, input.sourceAgent, input.sessionId, input.externalMessageId]))
|
|
867
|
+
.digest('hex')}`;
|
|
868
|
+
this.episodeStore.recordIngestKey({
|
|
869
|
+
projectId: input.projectId, sourceAgent: input.sourceAgent, sourceSessionId: input.sessionId,
|
|
870
|
+
externalMessageId: input.externalMessageId, eventId: proposedEventId, now: input.timestamp,
|
|
871
|
+
});
|
|
872
|
+
reservedEventId = this.episodeStore.getIngestedEvent(input.projectId, input.sourceAgent, input.sessionId, input.externalMessageId);
|
|
873
|
+
const existingEvent = reservedEventId ? this.eventStore.getEvent(reservedEventId) : null;
|
|
874
|
+
if (existingEvent) {
|
|
875
|
+
this.assertEpisodeIngestIdentity(existingEvent, input);
|
|
876
|
+
return this.resumeEpisodeMessageAsync(existingEvent, input, false);
|
|
877
|
+
}
|
|
878
|
+
}
|
|
879
|
+
let event;
|
|
880
|
+
try {
|
|
881
|
+
event = this.recordRawEvent({
|
|
882
|
+
eventId: reservedEventId, projectId: input.projectId, workspaceId: input.projectId,
|
|
883
|
+
threadId: input.threadId || input.sessionId, sessionId: input.sessionId, role: input.role,
|
|
884
|
+
content: input.text, occurredAt: input.timestamp, sourceId: `${input.sourceAgent}:${input.sessionId}`,
|
|
885
|
+
metadata: { ...input.metadata, externalMessageId: input.externalMessageId, sourceAgent: input.sourceAgent },
|
|
886
|
+
});
|
|
887
|
+
}
|
|
888
|
+
catch (error) {
|
|
889
|
+
const concurrent = reservedEventId ? this.eventStore.getEvent(reservedEventId) : null;
|
|
890
|
+
if (!concurrent) {
|
|
891
|
+
if (input.externalMessageId)
|
|
892
|
+
this.episodeStore.markIngestState({
|
|
893
|
+
projectId: input.projectId, sourceAgent: input.sourceAgent, sourceSessionId: input.sessionId,
|
|
894
|
+
externalMessageId: input.externalMessageId, state: 'failed', error: error instanceof Error ? error.message : String(error),
|
|
895
|
+
});
|
|
896
|
+
throw error;
|
|
897
|
+
}
|
|
898
|
+
this.assertEpisodeIngestIdentity(concurrent, input);
|
|
899
|
+
if (input.externalMessageId)
|
|
900
|
+
this.episodeStore.markIngestState({
|
|
901
|
+
projectId: input.projectId, sourceAgent: input.sourceAgent, sourceSessionId: input.sessionId,
|
|
902
|
+
externalMessageId: input.externalMessageId, state: 'committed',
|
|
903
|
+
});
|
|
904
|
+
return this.resumeEpisodeMessageAsync(concurrent, input, false);
|
|
905
|
+
}
|
|
906
|
+
if (input.externalMessageId)
|
|
907
|
+
this.episodeStore.markIngestState({
|
|
908
|
+
projectId: input.projectId, sourceAgent: input.sourceAgent, sourceSessionId: input.sessionId,
|
|
909
|
+
externalMessageId: input.externalMessageId, state: 'committed', now: event.occurredAt,
|
|
910
|
+
});
|
|
911
|
+
return this.resumeEpisodeMessageAsync(event, input, true);
|
|
912
|
+
}
|
|
913
|
+
resumeEpisodeMessage(event, input, created) {
|
|
914
|
+
let link = this.episodeStore.getEventLink(event.eventId);
|
|
915
|
+
let ignored = this.episodeStore.hasEventDisposition(event.eventId);
|
|
916
|
+
if (!link && !ignored) {
|
|
917
|
+
const assembly = this.assembleEpisodeTurn([event], {
|
|
918
|
+
projectId: input.projectId,
|
|
919
|
+
sessionId: event.sessionId || input.sessionId,
|
|
920
|
+
sourceAgent: input.sourceAgent,
|
|
921
|
+
conversationThreadId: input.threadId || event.threadId || input.sessionId,
|
|
922
|
+
now: event.occurredAt,
|
|
923
|
+
});
|
|
924
|
+
link = this.episodeStore.getEventLink(event.eventId);
|
|
925
|
+
ignored = assembly.ignoredEventIds.includes(event.eventId);
|
|
926
|
+
}
|
|
927
|
+
const episode = link ? this.episodeStore.getEpisode(link.episodeId) : undefined;
|
|
928
|
+
const receipt = episode?.status === 'sealed'
|
|
929
|
+
? this.episodeStore.listClosureReceipts({ episodeId: episode.episodeId, limit: 1 })[0]
|
|
930
|
+
: undefined;
|
|
931
|
+
return {
|
|
932
|
+
created,
|
|
933
|
+
eventId: event.eventId,
|
|
934
|
+
episodeId: episode?.episodeId,
|
|
935
|
+
assigned: Boolean(link),
|
|
936
|
+
ignored,
|
|
937
|
+
sealed: episode?.status === 'sealed',
|
|
938
|
+
dreamRecommended: Boolean(receipt?.dreamRecommended && !receipt.requiresReview && episode?.dreamStatus !== 'processed'),
|
|
939
|
+
dreamRan: false,
|
|
940
|
+
};
|
|
941
|
+
}
|
|
942
|
+
async resumeEpisodeMessageAsync(event, input, created) {
|
|
943
|
+
let link = this.episodeStore.getEventLink(event.eventId);
|
|
944
|
+
let ignored = this.episodeStore.hasEventDisposition(event.eventId);
|
|
945
|
+
if (!link && !ignored) {
|
|
946
|
+
const assembly = await this.assembleEpisodeTurnAsync([event], {
|
|
947
|
+
projectId: input.projectId, sessionId: event.sessionId || input.sessionId, sourceAgent: input.sourceAgent,
|
|
948
|
+
conversationThreadId: input.threadId || event.threadId || input.sessionId, now: event.occurredAt,
|
|
949
|
+
});
|
|
950
|
+
link = this.episodeStore.getEventLink(event.eventId);
|
|
951
|
+
ignored = assembly.ignoredEventIds.includes(event.eventId);
|
|
952
|
+
}
|
|
953
|
+
const episode = link ? this.episodeStore.getEpisode(link.episodeId) : undefined;
|
|
954
|
+
const receipt = episode?.status === 'sealed'
|
|
955
|
+
? this.episodeStore.listClosureReceipts({ episodeId: episode.episodeId, limit: 1 })[0]
|
|
956
|
+
: undefined;
|
|
957
|
+
return {
|
|
958
|
+
created, eventId: event.eventId, episodeId: episode?.episodeId, assigned: Boolean(link), ignored,
|
|
959
|
+
sealed: episode?.status === 'sealed',
|
|
960
|
+
dreamRecommended: Boolean(receipt?.dreamRecommended && !receipt.requiresReview && episode?.dreamStatus !== 'processed'),
|
|
961
|
+
dreamRan: false,
|
|
962
|
+
};
|
|
963
|
+
}
|
|
964
|
+
assertEpisodeIngestIdentity(event, input) {
|
|
965
|
+
const payload = event.payload;
|
|
966
|
+
const expectedText = this.piiRedactor ? this.piiRedactor.redact(input.text).text : input.text;
|
|
967
|
+
if (event.projectId !== input.projectId
|
|
968
|
+
|| event.sessionId !== input.sessionId
|
|
969
|
+
|| event.role !== input.role
|
|
970
|
+
|| payload?.text !== expectedText
|
|
971
|
+
|| payload?.metadata?.sourceAgent !== input.sourceAgent) {
|
|
972
|
+
throw new Error(`episode_ingest_identity_conflict:${input.externalMessageId || event.eventId}`);
|
|
973
|
+
}
|
|
974
|
+
}
|
|
975
|
+
listEpisodes(options = {}) {
|
|
976
|
+
return this.episodeStore.listEpisodes(options);
|
|
977
|
+
}
|
|
978
|
+
getEpisode(episodeId) {
|
|
979
|
+
return this.episodeStore.getEpisode(episodeId);
|
|
980
|
+
}
|
|
981
|
+
sealEpisode(episodeId, input) {
|
|
982
|
+
return this.episodeStore.sealEpisode(episodeId, input);
|
|
983
|
+
}
|
|
984
|
+
sealImportedEpisode(episodeId, input) {
|
|
985
|
+
const links = this.episodeStore.listEventLinks(episodeId);
|
|
986
|
+
const averageConfidence = links.length
|
|
987
|
+
? links.reduce((total, link) => total + link.confidence, 0) / links.length
|
|
988
|
+
: 0;
|
|
989
|
+
const requiresReview = input.force !== true && averageConfidence < 0.6;
|
|
990
|
+
return this.episodeStore.sealEpisode(episodeId, {
|
|
991
|
+
mode: requiresReview ? 'soft' : 'batch',
|
|
992
|
+
reason: requiresReview ? 'batch_low_confidence_review' : input.reason,
|
|
993
|
+
reasonCode: 'batch_boundary',
|
|
994
|
+
requiresReview,
|
|
995
|
+
now: input.now,
|
|
996
|
+
});
|
|
997
|
+
}
|
|
998
|
+
sealIdleEpisodes(input) {
|
|
999
|
+
return this.episodeStore.sealIdleEpisodes(input);
|
|
1000
|
+
}
|
|
1001
|
+
listEpisodeClosureReceipts(options = {}) {
|
|
1002
|
+
return this.episodeStore.listClosureReceipts(options);
|
|
1003
|
+
}
|
|
1004
|
+
listEpisodeEventLinks(episodeId) {
|
|
1005
|
+
return this.episodeStore.listEventLinks(episodeId);
|
|
1006
|
+
}
|
|
1007
|
+
getEpisodeDreamStatus(projectId) {
|
|
1008
|
+
return this.episodeStore.getDreamStatus(projectId);
|
|
1009
|
+
}
|
|
1010
|
+
retryFailedEpisodeDreams(projectId) {
|
|
1011
|
+
return this.episodeStore.retryFailed(projectId);
|
|
1012
|
+
}
|
|
1013
|
+
repairEpisodes(options = {}) {
|
|
1014
|
+
const page = this.eventStore.queryEvents(1, Math.max(1, Math.min(options.limit ?? 500, 5000)), {
|
|
1015
|
+
projectId: options.projectId ? [options.projectId] : undefined,
|
|
1016
|
+
});
|
|
1017
|
+
const events = page.records
|
|
1018
|
+
.filter((event) => event.eventType === 'RAW_EVENT_RECORDED')
|
|
1019
|
+
.filter((event) => options.sinceGlobalSeq === undefined || (event.globalSeq || 0) >= options.sinceGlobalSeq)
|
|
1020
|
+
.filter((event) => !this.episodeStore.getEventLink(event.eventId))
|
|
1021
|
+
.filter((event) => !this.episodeStore.hasEventDisposition(event.eventId))
|
|
1022
|
+
.sort((a, b) => (a.globalSeq || 0) - (b.globalSeq || 0));
|
|
1023
|
+
let assigned = 0;
|
|
1024
|
+
const unassignedEventIds = [];
|
|
1025
|
+
for (const event of events) {
|
|
1026
|
+
const projectId = event.projectId || options.projectId;
|
|
1027
|
+
const sessionId = event.sessionId || event.threadId;
|
|
1028
|
+
if (!projectId || !sessionId) {
|
|
1029
|
+
unassignedEventIds.push(event.eventId);
|
|
1030
|
+
continue;
|
|
1031
|
+
}
|
|
1032
|
+
try {
|
|
1033
|
+
const metadata = event.payload?.metadata;
|
|
1034
|
+
const sourceAgent = typeof metadata?.sourceAgent === 'string' ? metadata.sourceAgent : undefined;
|
|
1035
|
+
const result = this.assembleEpisodeTurn([event], {
|
|
1036
|
+
projectId, sessionId, sourceAgent, now: event.occurredAt,
|
|
1037
|
+
});
|
|
1038
|
+
if (result.assignedEventIds.includes(event.eventId))
|
|
1039
|
+
assigned += 1;
|
|
1040
|
+
else
|
|
1041
|
+
unassignedEventIds.push(event.eventId);
|
|
1042
|
+
}
|
|
1043
|
+
catch (error) {
|
|
1044
|
+
unassignedEventIds.push(event.eventId);
|
|
1045
|
+
this.pipelineMetrics.recordNonFatal('episode_repair_failed', {
|
|
1046
|
+
projectId, message: error instanceof Error ? error.message : String(error), details: { eventId: event.eventId },
|
|
1047
|
+
});
|
|
1048
|
+
}
|
|
1049
|
+
}
|
|
1050
|
+
return { scanned: events.length, assigned, unassigned: unassignedEventIds.length, unassignedEventIds };
|
|
1051
|
+
}
|
|
1052
|
+
repairEpisode(input) {
|
|
1053
|
+
const now = input.now ?? Date.now();
|
|
1054
|
+
const affected = new Set();
|
|
1055
|
+
const before = {};
|
|
1056
|
+
const previousStatuses = new Map();
|
|
1057
|
+
if (input.operation === 'move-event') {
|
|
1058
|
+
const link = this.episodeStore.getEventLink(input.eventId);
|
|
1059
|
+
const source = link ? this.episodeStore.getEpisode(link.episodeId) : undefined;
|
|
1060
|
+
const target = this.episodeStore.getEpisode(input.targetEpisodeId);
|
|
1061
|
+
if (!source || !target || source.projectId !== input.projectId || target.projectId !== input.projectId) {
|
|
1062
|
+
throw new Error('episode_project_mismatch');
|
|
1063
|
+
}
|
|
1064
|
+
before[source.episodeId] = source;
|
|
1065
|
+
before[target.episodeId] = target;
|
|
1066
|
+
previousStatuses.set(source.episodeId, source.status);
|
|
1067
|
+
previousStatuses.set(target.episodeId, target.status);
|
|
1068
|
+
}
|
|
1069
|
+
if ('episodeId' in input) {
|
|
1070
|
+
const episode = this.episodeStore.getEpisode(input.episodeId);
|
|
1071
|
+
if (!episode || episode.projectId !== input.projectId)
|
|
1072
|
+
throw new Error(`episode_project_mismatch:${input.episodeId}`);
|
|
1073
|
+
before[input.episodeId] = episode;
|
|
1074
|
+
previousStatuses.set(input.episodeId, episode.status);
|
|
1075
|
+
}
|
|
1076
|
+
if ('sourceEpisodeId' in input) {
|
|
1077
|
+
const source = this.episodeStore.getEpisode(input.sourceEpisodeId);
|
|
1078
|
+
const target = this.episodeStore.getEpisode(input.targetEpisodeId);
|
|
1079
|
+
if (!source || !target || source.projectId !== input.projectId || target.projectId !== input.projectId)
|
|
1080
|
+
throw new Error('episode_project_mismatch');
|
|
1081
|
+
before[input.sourceEpisodeId] = source;
|
|
1082
|
+
before[input.targetEpisodeId] = target;
|
|
1083
|
+
previousStatuses.set(input.sourceEpisodeId, source.status);
|
|
1084
|
+
previousStatuses.set(input.targetEpisodeId, target.status);
|
|
1085
|
+
}
|
|
1086
|
+
if (input.operation === 'move-event') {
|
|
1087
|
+
const moved = this.episodeStore.moveEventForRepair(input.eventId, input.targetEpisodeId, now);
|
|
1088
|
+
affected.add(moved.sourceEpisodeId);
|
|
1089
|
+
affected.add(moved.targetEpisodeId);
|
|
1090
|
+
}
|
|
1091
|
+
else if (input.operation === 'reclassify') {
|
|
1092
|
+
this.episodeStore.reclassifyForRepair(input.episodeId, input);
|
|
1093
|
+
affected.add(input.episodeId);
|
|
1094
|
+
}
|
|
1095
|
+
else if (input.operation === 'requeue-dream' || input.operation === 'invalidate-dream-run') {
|
|
1096
|
+
this.episodeStore.requeueDreamForRepair(input.episodeId, input.mode || 'normal', now);
|
|
1097
|
+
affected.add(input.episodeId);
|
|
1098
|
+
}
|
|
1099
|
+
else if (input.operation === 'split') {
|
|
1100
|
+
const source = this.episodeStore.getEpisode(input.episodeId);
|
|
1101
|
+
const sourceLinks = this.episodeStore.listEventLinks(input.episodeId);
|
|
1102
|
+
const selected = sourceLinks.filter((link) => input.eventIds.includes(link.eventId));
|
|
1103
|
+
if (!selected.length || selected.length === sourceLinks.length)
|
|
1104
|
+
throw new Error('episode_split_requires_proper_subset');
|
|
1105
|
+
const firstEvent = this.eventStore.getEvent(selected[0].eventId);
|
|
1106
|
+
if (!firstEvent)
|
|
1107
|
+
throw new Error(`event_not_found:${selected[0].eventId}`);
|
|
1108
|
+
const created = this.episodeStore.createEpisode({
|
|
1109
|
+
projectId: source.projectId, sessionId: source.sessionId, sourceAgent: source.sourceAgent,
|
|
1110
|
+
conversationThreadId: source.conversationThreadId, topicPath: source.topicPath, episodeType: source.episodeType,
|
|
1111
|
+
importance: source.importance, eventId: firstEvent.eventId, globalSeq: firstEvent.globalSeq,
|
|
1112
|
+
occurredAt: firstEvent.occurredAt, episodeTags: source.episodeTags,
|
|
1113
|
+
candidateTypes: source.candidateTypes, importanceSignals: source.importanceSignals, importanceReason: 'repair_split',
|
|
1114
|
+
linkedEpisodeId: source.episodeId,
|
|
1115
|
+
});
|
|
1116
|
+
previousStatuses.set(created.episodeId, source.status);
|
|
1117
|
+
for (const link of selected)
|
|
1118
|
+
this.episodeStore.moveEventForRepair(link.eventId, created.episodeId, now);
|
|
1119
|
+
this.episodeStore.addCrossReference({ projectId: source.projectId, episodeId: created.episodeId,
|
|
1120
|
+
referencedEpisodeId: source.episodeId, relation: 'SPLIT_FROM', createdBy: 'repair', now });
|
|
1121
|
+
affected.add(source.episodeId);
|
|
1122
|
+
affected.add(created.episodeId);
|
|
1123
|
+
}
|
|
1124
|
+
else if (input.operation === 'merge') {
|
|
1125
|
+
for (const link of this.episodeStore.listEventLinks(input.sourceEpisodeId)) {
|
|
1126
|
+
this.episodeStore.moveEventForRepair(link.eventId, input.targetEpisodeId, now);
|
|
1127
|
+
}
|
|
1128
|
+
this.episodeStore.addCrossReference({ projectId: input.projectId, episodeId: input.targetEpisodeId,
|
|
1129
|
+
referencedEpisodeId: input.sourceEpisodeId, relation: 'MERGED_FROM', createdBy: 'repair', now });
|
|
1130
|
+
affected.add(input.sourceEpisodeId);
|
|
1131
|
+
affected.add(input.targetEpisodeId);
|
|
1132
|
+
}
|
|
1133
|
+
if (['move-event', 'split', 'merge', 'reclassify'].includes(input.operation)) {
|
|
1134
|
+
for (const episodeId of affected) {
|
|
1135
|
+
const episode = this.episodeStore.getEpisode(episodeId);
|
|
1136
|
+
if (!episode)
|
|
1137
|
+
continue;
|
|
1138
|
+
const previousStatus = previousStatuses.get(episodeId) || 'open';
|
|
1139
|
+
if (episode.eventCount === 0) {
|
|
1140
|
+
this.episodeStore.sealEpisode(episodeId, {
|
|
1141
|
+
mode: 'soft', reason: 'episode_repair_recomputed_empty', reasonCode: 'repair', requiresReview: true, now,
|
|
1142
|
+
});
|
|
1143
|
+
}
|
|
1144
|
+
else if (previousStatus === 'sealed') {
|
|
1145
|
+
this.episodeStore.sealEpisode(episodeId, {
|
|
1146
|
+
mode: 'manual', reason: 'episode_repair_recomputed', reasonCode: 'repair', now,
|
|
1147
|
+
});
|
|
1148
|
+
}
|
|
1149
|
+
else if (previousStatus === 'soft_sealed') {
|
|
1150
|
+
this.episodeStore.sealEpisode(episodeId, {
|
|
1151
|
+
mode: 'soft', reason: 'episode_repair_recomputed', reasonCode: 'repair', requiresReview: true, now,
|
|
1152
|
+
});
|
|
1153
|
+
}
|
|
1154
|
+
}
|
|
1155
|
+
}
|
|
1156
|
+
const staleCandidateIds = [];
|
|
1157
|
+
for (const candidate of this.deepWriteCandidateStore.listCandidates({ projectId: input.projectId, limit: 5000 })) {
|
|
1158
|
+
const content = candidate.content && typeof candidate.content === 'object' ? candidate.content : {};
|
|
1159
|
+
if (!affected.has(String(content.sourceEpisodeId || '')) || candidate.status === 'superseded')
|
|
1160
|
+
continue;
|
|
1161
|
+
this.deepWriteCandidateStore.updateCandidateStatus(candidate.candidateId, 'superseded', {
|
|
1162
|
+
type: candidate.candidateType, id: candidate.candidateId, reason: 'episode_repair_invalidated_source',
|
|
1163
|
+
});
|
|
1164
|
+
staleCandidateIds.push(candidate.candidateId);
|
|
1165
|
+
}
|
|
1166
|
+
for (const episodeId of affected) {
|
|
1167
|
+
const episode = this.episodeStore.getEpisode(episodeId);
|
|
1168
|
+
if (episode?.eventCount && episode.status === 'sealed') {
|
|
1169
|
+
this.episodeStore.requeueDreamForRepair(episodeId, input.operation === 'invalidate-dream-run' ? input.mode || 'normal' : 'normal', now);
|
|
1170
|
+
}
|
|
1171
|
+
}
|
|
1172
|
+
const after = Object.fromEntries([...affected].map((episodeId) => [episodeId, this.episodeStore.getEpisode(episodeId)]));
|
|
1173
|
+
const repairId = this.episodeStore.recordRepairAudit({ projectId: input.projectId, operation: input.operation, payload: input, before, after, now });
|
|
1174
|
+
return { repairId, operation: input.operation, affectedEpisodeIds: [...affected], staleCandidateIds };
|
|
1175
|
+
}
|
|
1176
|
+
listDreamCandidates(options = {}) {
|
|
1177
|
+
return this.deepWriteCandidateStore.listCandidates(options);
|
|
1178
|
+
}
|
|
1179
|
+
countDreamCandidates(options = {}) {
|
|
1180
|
+
return this.deepWriteCandidateStore.countCandidates(options);
|
|
1181
|
+
}
|
|
1182
|
+
reviewDreamCandidate(input) {
|
|
1183
|
+
return this.candidateReviewService.review(input);
|
|
1184
|
+
}
|
|
1185
|
+
listDreamCandidateReviews(options = {}) {
|
|
1186
|
+
return this.candidateReviewStore.list(options);
|
|
1187
|
+
}
|
|
1188
|
+
bindMemoryEvent(event) {
|
|
1189
|
+
return this.memoryBindingService.bindRawEvent(event);
|
|
1190
|
+
}
|
|
1191
|
+
executeMemoryGovernancePlan(plan) {
|
|
1192
|
+
return this.memoryGovernanceExecutor.execute(plan);
|
|
1193
|
+
}
|
|
1194
|
+
bindRawEvents(options = {}) {
|
|
1195
|
+
const limit = Math.max(1, Math.min(options.limit ?? 500, 5000));
|
|
1196
|
+
const page = this.eventStore.queryEvents(1, limit, {
|
|
1197
|
+
projectId: options.projectId ? [options.projectId] : undefined,
|
|
1198
|
+
workspaceId: options.workspaceId ? [options.workspaceId] : undefined,
|
|
1199
|
+
threadId: options.threadId ? [options.threadId] : undefined,
|
|
1200
|
+
sessionId: options.sessionId ? [options.sessionId] : undefined,
|
|
1201
|
+
});
|
|
1202
|
+
const records = page.records
|
|
1203
|
+
.filter((event) => options.sinceGlobalSeq === undefined || (event.globalSeq || 0) >= options.sinceGlobalSeq)
|
|
1204
|
+
.sort((a, b) => (a.globalSeq || 0) - (b.globalSeq || 0));
|
|
1205
|
+
const result = {
|
|
1206
|
+
projectId: options.projectId,
|
|
1207
|
+
sinceGlobalSeq: options.sinceGlobalSeq,
|
|
1208
|
+
scannedEvents: records.length,
|
|
1209
|
+
bindableEvents: 0,
|
|
1210
|
+
boundEvents: 0,
|
|
1211
|
+
createdBindings: 0,
|
|
1212
|
+
skippedAlreadyBound: 0,
|
|
1213
|
+
failedEvents: 0,
|
|
1214
|
+
errors: [],
|
|
1215
|
+
};
|
|
1216
|
+
for (const event of records) {
|
|
1217
|
+
if (!this.memoryBindingService.isBindableRawEvent(event))
|
|
1218
|
+
continue;
|
|
1219
|
+
result.bindableEvents += 1;
|
|
1220
|
+
if (this.memoryBindingStore.listBindings({ eventId: event.eventId, limit: 1 }).length > 0) {
|
|
1221
|
+
result.skippedAlreadyBound += 1;
|
|
1222
|
+
continue;
|
|
1223
|
+
}
|
|
1224
|
+
try {
|
|
1225
|
+
const bindings = this.bindMemoryEvent(event);
|
|
1226
|
+
if (bindings.length > 0) {
|
|
1227
|
+
result.boundEvents += 1;
|
|
1228
|
+
result.createdBindings += bindings.length;
|
|
1229
|
+
}
|
|
1230
|
+
}
|
|
1231
|
+
catch (error) {
|
|
1232
|
+
result.failedEvents += 1;
|
|
1233
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
1234
|
+
result.errors.push({ eventId: event.eventId, message });
|
|
1235
|
+
this.pipelineMetrics.recordNonFatal('memory_binding_failed', {
|
|
1236
|
+
projectId: event.projectId,
|
|
1237
|
+
message,
|
|
1238
|
+
details: { eventId: event.eventId, source: 'bindRawEvents' },
|
|
1239
|
+
});
|
|
1240
|
+
}
|
|
1241
|
+
}
|
|
1242
|
+
return result;
|
|
1243
|
+
}
|
|
1244
|
+
listMemoryBindings(options = {}) {
|
|
1245
|
+
return this.memoryBindingStore.listBindings(options);
|
|
1246
|
+
}
|
|
1247
|
+
listMemoryClusters(options = {}) {
|
|
1248
|
+
return this.memoryBindingStore.listClusters(options);
|
|
1249
|
+
}
|
|
1250
|
+
listMemoryEdges(options = {}) {
|
|
1251
|
+
return this.memoryBindingStore.listEdges(options);
|
|
1252
|
+
}
|
|
1253
|
+
recallMemoryBindingGraph(query, options = {}) {
|
|
1254
|
+
return this.memoryBindingService.recallGraphAnchors(query, options);
|
|
1255
|
+
}
|
|
1256
|
+
getMemoryBindingStats(projectId) {
|
|
1257
|
+
return this.memoryBindingStore.getStats(projectId);
|
|
1258
|
+
}
|
|
1259
|
+
rebuildMemoryAtlas(options = {}) {
|
|
1260
|
+
return this.memoryAtlasIndexer.rebuild(options);
|
|
1261
|
+
}
|
|
1262
|
+
ensureMemoryAtlas(options) {
|
|
1263
|
+
return this.memoryAtlasIndexer.ensureFresh(options);
|
|
1264
|
+
}
|
|
1265
|
+
prepareMemoryAtlasRead(options) {
|
|
1266
|
+
if (options.refresh === false) {
|
|
1267
|
+
const state = this.memoryAtlasStore.getProjectionState(options.projectId);
|
|
1268
|
+
return { atlasFresh: state?.status === 'clean' };
|
|
1269
|
+
}
|
|
1270
|
+
try {
|
|
1271
|
+
this.ensureMemoryAtlas({ projectId: options.projectId });
|
|
1272
|
+
return { atlasFresh: true };
|
|
1273
|
+
}
|
|
1274
|
+
catch (error) {
|
|
1275
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
1276
|
+
if (options.staleOk !== false && /database is locked|SQLITE_BUSY|SQLITE_LOCKED/i.test(message)) {
|
|
1277
|
+
return { atlasFresh: false, refreshError: message };
|
|
1278
|
+
}
|
|
1279
|
+
throw error;
|
|
1280
|
+
}
|
|
1281
|
+
}
|
|
1282
|
+
withAtlasFreshness(result, freshness) {
|
|
1283
|
+
return Object.assign(result, {
|
|
1284
|
+
atlasFresh: freshness.atlasFresh,
|
|
1285
|
+
...(freshness.refreshError ? { refreshError: freshness.refreshError } : {}),
|
|
1286
|
+
});
|
|
1287
|
+
}
|
|
1288
|
+
graphOverview(options) {
|
|
1289
|
+
const freshness = this.prepareMemoryAtlasRead(options);
|
|
1290
|
+
return this.withAtlasFreshness(this.memoryAtlasService.overview(options), freshness);
|
|
1291
|
+
}
|
|
1292
|
+
graphSearch(query, options) {
|
|
1293
|
+
const freshness = this.prepareMemoryAtlasRead(options);
|
|
1294
|
+
return this.withAtlasFreshness(this.memoryAtlasService.search(query, options), freshness);
|
|
1295
|
+
}
|
|
1296
|
+
graphExplore(query, options) {
|
|
1297
|
+
const freshness = this.prepareMemoryAtlasRead(options);
|
|
1298
|
+
return this.withAtlasFreshness(this.memoryAtlasService.explore(query, options), freshness);
|
|
1299
|
+
}
|
|
1300
|
+
graphNode(nodeId, options) {
|
|
1301
|
+
const freshness = this.prepareMemoryAtlasRead(options);
|
|
1302
|
+
const result = this.memoryAtlasService.node(nodeId, options);
|
|
1303
|
+
return result ? this.withAtlasFreshness(result, freshness) : result;
|
|
1304
|
+
}
|
|
1305
|
+
graphNeighbors(nodeId, options) {
|
|
1306
|
+
const freshness = this.prepareMemoryAtlasRead(options);
|
|
1307
|
+
return this.withAtlasFreshness(this.memoryAtlasService.neighbors(nodeId, options), freshness);
|
|
1308
|
+
}
|
|
1309
|
+
graphPath(from, to, options) {
|
|
1310
|
+
const freshness = this.prepareMemoryAtlasRead(options);
|
|
1311
|
+
return this.withAtlasFreshness(this.memoryAtlasService.path(from, to, options), freshness);
|
|
1312
|
+
}
|
|
1313
|
+
graphTimeline(query, options) {
|
|
1314
|
+
const freshness = this.prepareMemoryAtlasRead(options);
|
|
1315
|
+
return this.withAtlasFreshness(this.memoryAtlasService.timeline(query, options), freshness);
|
|
1316
|
+
}
|
|
1317
|
+
touchMemoryAtlas(input) {
|
|
1318
|
+
if (!input.projectId?.trim())
|
|
1319
|
+
throw new Error('projectId is required');
|
|
1320
|
+
if (!input.reason?.trim())
|
|
1321
|
+
throw new Error('reason is required');
|
|
1322
|
+
const valid = Array.from(new Set(input.nodeIds)).filter((id) => this.memoryAtlasStore.getNode(id, input.projectId)).slice(0, 30);
|
|
1323
|
+
return { touched: this.memoryAtlasStore.recordAccess(input.projectId, valid, input.reason, input.query, input.now) };
|
|
1324
|
+
}
|
|
1325
|
+
countUnboundBindableRawEvents(projectId, limit = 1000) {
|
|
1326
|
+
const page = this.eventStore.queryEvents(1, Math.max(1, limit), {
|
|
1327
|
+
projectId: projectId ? [projectId] : undefined,
|
|
1328
|
+
});
|
|
1329
|
+
let count = 0;
|
|
1330
|
+
for (const event of page.records) {
|
|
1331
|
+
if (!this.memoryBindingService.isBindableRawEvent(event))
|
|
1332
|
+
continue;
|
|
1333
|
+
if (this.memoryBindingStore.listBindings({ eventId: event.eventId, limit: 1 }).length > 0)
|
|
1334
|
+
continue;
|
|
1335
|
+
count += 1;
|
|
1336
|
+
}
|
|
1337
|
+
return count;
|
|
1338
|
+
}
|
|
1339
|
+
promoteDreamCandidates(options = {}) {
|
|
1340
|
+
const decisions = this.deepWritePromotionPolicy.promotePending(options.limit ?? 100, {
|
|
1341
|
+
projectId: options.projectId,
|
|
1342
|
+
});
|
|
1343
|
+
return {
|
|
1344
|
+
projectId: options.projectId,
|
|
1345
|
+
decisions,
|
|
1346
|
+
queue: this.getDreamCandidateQueue(options.projectId),
|
|
1347
|
+
};
|
|
1348
|
+
}
|
|
1349
|
+
getDreamCandidateQueue(projectId) {
|
|
1350
|
+
return {
|
|
1351
|
+
candidate: this.countDreamCandidates({ projectId, statuses: ['candidate'] }),
|
|
1352
|
+
needsConfirmation: this.countDreamCandidates({ projectId, statuses: ['needs_confirmation'] }),
|
|
1353
|
+
promoted: this.countDreamCandidates({ projectId, statuses: ['promoted'] }),
|
|
1354
|
+
rejected: this.countDreamCandidates({ projectId, statuses: ['rejected'] }),
|
|
1355
|
+
superseded: this.countDreamCandidates({ projectId, statuses: ['superseded'] }),
|
|
1356
|
+
shadow: this.countDreamCandidates({ projectId, statuses: ['shadow'] }),
|
|
1357
|
+
};
|
|
1358
|
+
}
|
|
1359
|
+
buildMemoryMap(options = {}) {
|
|
1360
|
+
const projectId = options.projectId;
|
|
1361
|
+
const rawPage = this.eventStore.queryEvents(1, 1, {
|
|
1362
|
+
projectId: projectId ? [projectId] : undefined,
|
|
1363
|
+
});
|
|
1364
|
+
const projectNeurons = projectId
|
|
1365
|
+
? this.memoryGraph.getNeuronIdsByProject(projectId).length
|
|
1366
|
+
: this.memoryGraph.getStats().neuronCount;
|
|
1367
|
+
const dreamBacklog = this.getDreamBacklogStatus(projectId);
|
|
1368
|
+
const dreamCandidateQueue = this.getDreamCandidateQueue(projectId);
|
|
1369
|
+
const activationHotspots = this.activationStore.getTop({ projectId, limit: 20 });
|
|
1370
|
+
const memoryBindingStats = this.getMemoryBindingStats(projectId);
|
|
1371
|
+
const episodes = this.listEpisodes({ projectId, limit: 1000 });
|
|
1372
|
+
const episodeDream = this.getEpisodeDreamStatus(projectId);
|
|
1373
|
+
const unassignedRawEvents = this.episodeStore.countUnassignedRawEvents(projectId);
|
|
1374
|
+
return {
|
|
1375
|
+
version: 'memory_map.v1',
|
|
1376
|
+
generatedAt: Date.now(),
|
|
1377
|
+
projectId,
|
|
1378
|
+
anatomy: [
|
|
1379
|
+
{
|
|
1380
|
+
id: 'raw_ledger',
|
|
1381
|
+
name: 'Raw chronological ledger',
|
|
1382
|
+
role: 'append-only event source for exact source drill-down and vectors=0 recall fallback',
|
|
1383
|
+
currentCount: rawPage.total,
|
|
1384
|
+
},
|
|
1385
|
+
{
|
|
1386
|
+
id: 'compiled_graph',
|
|
1387
|
+
name: 'Compiled semantic graph',
|
|
1388
|
+
role: 'governed neurons, synapses, topology, and cognitive graph for associative recall',
|
|
1389
|
+
currentCount: projectNeurons,
|
|
1390
|
+
},
|
|
1391
|
+
{
|
|
1392
|
+
id: 'belief_cases',
|
|
1393
|
+
name: 'Belief cases',
|
|
1394
|
+
role: 'active beliefs plus support, supersession, and contradiction history',
|
|
1395
|
+
},
|
|
1396
|
+
{
|
|
1397
|
+
id: 'entity_cards',
|
|
1398
|
+
name: 'Entity cards',
|
|
1399
|
+
role: 'resolved people, projects, devices, aliases, attributes, and mention timelines',
|
|
1400
|
+
},
|
|
1401
|
+
{
|
|
1402
|
+
id: 'activation',
|
|
1403
|
+
name: 'Activation layer',
|
|
1404
|
+
role: 'host-visible hot memory traces used by recall packs and maintenance tick',
|
|
1405
|
+
currentCount: activationHotspots.length,
|
|
1406
|
+
},
|
|
1407
|
+
{
|
|
1408
|
+
id: 'memory_binding',
|
|
1409
|
+
name: 'Memory binding layer',
|
|
1410
|
+
role: 'deterministic raw-event bindings, clusters, and graph edges before governed fact promotion',
|
|
1411
|
+
currentCount: memoryBindingStats.bindings,
|
|
1412
|
+
},
|
|
1413
|
+
{
|
|
1414
|
+
id: 'memory_atlas',
|
|
1415
|
+
name: 'Memory Atlas',
|
|
1416
|
+
role: 'bounded, source-anchored content navigation over topics, entities, clusters, episodes, beliefs, actions, and time',
|
|
1417
|
+
},
|
|
1418
|
+
{
|
|
1419
|
+
id: 'episode_assembler',
|
|
1420
|
+
name: 'Episode assembler',
|
|
1421
|
+
role: 'groups raw session events into auditable open, soft-sealed, and sealed consolidation units',
|
|
1422
|
+
currentCount: episodes.length,
|
|
1423
|
+
},
|
|
1424
|
+
{
|
|
1425
|
+
id: 'dream_queue',
|
|
1426
|
+
name: 'Dream curator queue',
|
|
1427
|
+
role: 'sealed-episode candidate-only consolidation backlog controlled by explicit host ticks',
|
|
1428
|
+
currentCount: episodeDream.pending + episodeDream.failed,
|
|
1429
|
+
},
|
|
1430
|
+
],
|
|
1431
|
+
dataLanes: [
|
|
1432
|
+
{
|
|
1433
|
+
id: 'episode_dream',
|
|
1434
|
+
name: 'Episode Dream',
|
|
1435
|
+
route: 'cogmem episode status|repair and cogmem dream tick|status',
|
|
1436
|
+
useWhen: 'Inspect conversation boundaries, repair unassigned raw events, or conditionally consolidate sealed episodes.',
|
|
1437
|
+
},
|
|
1438
|
+
{
|
|
1439
|
+
id: 'agent_recall_pack',
|
|
1440
|
+
name: 'Agent recall pack',
|
|
1441
|
+
route: 'KernelAgentMemoryBackend.recallPack()',
|
|
1442
|
+
useWhen: 'Before an agent answer that needs direct memory, beliefs, entities, and associative neighbors.',
|
|
1443
|
+
},
|
|
1444
|
+
{
|
|
1445
|
+
id: 'collection_routing',
|
|
1446
|
+
name: 'Collection routing',
|
|
1447
|
+
route: 'collection:<name> tags on raw events and neurons',
|
|
1448
|
+
useWhen: 'Store creative Theseus artifacts without polluting default operational recall.',
|
|
1449
|
+
},
|
|
1450
|
+
{
|
|
1451
|
+
id: 'source_drilldown',
|
|
1452
|
+
name: 'Source drill-down',
|
|
1453
|
+
route: 'sourceContext.locator.command',
|
|
1454
|
+
useWhen: 'Audit exact raw events behind any recalled item.',
|
|
1455
|
+
},
|
|
1456
|
+
{
|
|
1457
|
+
id: 'maintenance_tick',
|
|
1458
|
+
name: 'Maintenance tick',
|
|
1459
|
+
route: 'MemoryKernel.runMaintenanceTick() / cogmem memory tick',
|
|
1460
|
+
useWhen: 'Let the host decide when to decay activation, run dream, govern candidates, or re-embed.',
|
|
1461
|
+
},
|
|
1462
|
+
{
|
|
1463
|
+
id: 'memory_binding',
|
|
1464
|
+
name: 'Memory binding',
|
|
1465
|
+
route: 'MemoryKernel.listMemoryBindings(), listMemoryClusters(), listMemoryEdges(), bindRawEvents(), recallMemoryBindingGraph() / cogmem memory map|bind',
|
|
1466
|
+
useWhen: 'Inspect or backfill raw-event topic/entity bindings, claim-key clusters, correction edges, and graph-recall anchors.',
|
|
1467
|
+
},
|
|
1468
|
+
{
|
|
1469
|
+
id: 'memory_atlas',
|
|
1470
|
+
name: 'Memory Atlas navigation',
|
|
1471
|
+
route: 'MemoryKernel.graphOverview(), graphExplore(), graphNode(), graphNeighbors(), graphPath(), graphTimeline() / cogmem memory graph-*',
|
|
1472
|
+
useWhen: 'Inventory broad memory areas, combine query facets, navigate relationships, or revive cold source evidence before exact drill-down.',
|
|
1473
|
+
},
|
|
1474
|
+
],
|
|
1475
|
+
bounds: [
|
|
1476
|
+
'kernel-only memory layer; no notes app, wiki, or UI ownership',
|
|
1477
|
+
'no hidden daemon; cron/systemd/agent adapters explicitly call dream tick or memory tick',
|
|
1478
|
+
'candidate-only self-improvement unless governance promotes the candidate',
|
|
1479
|
+
'sourceContext remains available for drill-down instead of replacing evidence with summaries',
|
|
1480
|
+
'default recall includes untagged and collection:anchor only; collection:theseus requires an explicit collection query',
|
|
1481
|
+
],
|
|
1482
|
+
manual: {
|
|
1483
|
+
commands: [
|
|
1484
|
+
'cogmem memory recall --project <id> --query <q> --json',
|
|
1485
|
+
'cogmem memory recall --project <id> --collection theseus --query <q> --json',
|
|
1486
|
+
'cogmem memory show --event <event-id> --before 2 --after 2',
|
|
1487
|
+
'cogmem memory map --project <id> --json',
|
|
1488
|
+
'cogmem memory graph-explore --project <id> --query <q> --json',
|
|
1489
|
+
'cogmem memory graph-node --project <id> --id <node-id> --json',
|
|
1490
|
+
'cogmem memory graph-path --project <id> --from <node-id> --to <node-id> --json',
|
|
1491
|
+
'cogmem memory tick --project <id> --json',
|
|
1492
|
+
'cogmem memory bind --project <id> --json',
|
|
1493
|
+
'cogmem episode status --project <id> --json',
|
|
1494
|
+
'cogmem episode repair --project <id> --json',
|
|
1495
|
+
'cogmem dream tick --project <id> --mode auto --json',
|
|
1496
|
+
],
|
|
1497
|
+
agentUsage: [
|
|
1498
|
+
'Call recallPack() before answering when the host wants direct recall plus associative, belief, and entity context.',
|
|
1499
|
+
'Use collection "theseus" for creative artifacts and collection "anchor" or no collection for operational memory.',
|
|
1500
|
+
'Use memory map for self-inspection; use maintenance tick for explicit host-owned upkeep signals.',
|
|
1501
|
+
'Run memory bind when maintenance tick reports bind_raw_events for imported or adapter-written raw user events.',
|
|
1502
|
+
'Use episode append/import for hookless agents; call dream tick only from an explicit host schedule or operator action.',
|
|
1503
|
+
'Use memory bindings, claim-key clusters, correction edges, and graph recall anchors as source-anchored organization hints, not as promoted long-term facts.',
|
|
1504
|
+
'Use graph explore for broad inventory or historical questions, then graph node/path/timeline to narrow the source-anchored slice before memory show.',
|
|
1505
|
+
'Treat Atlas activation as visibility ranking only; exact project-scoped facet matches can revive cold nodes without changing their truth status.',
|
|
1506
|
+
],
|
|
1507
|
+
},
|
|
1508
|
+
counters: {
|
|
1509
|
+
rawEvents: rawPage.total,
|
|
1510
|
+
neurons: projectNeurons,
|
|
1511
|
+
vectors: this.vectorStore.getCurrentCount(),
|
|
1512
|
+
activationHotspots: activationHotspots.length,
|
|
1513
|
+
memoryBindings: memoryBindingStats.bindings,
|
|
1514
|
+
memoryBindingTopics: memoryBindingStats.topics,
|
|
1515
|
+
memoryBindingEntities: memoryBindingStats.entities,
|
|
1516
|
+
memoryBindingClusters: memoryBindingStats.clusters,
|
|
1517
|
+
memoryBindingEdges: memoryBindingStats.edges,
|
|
1518
|
+
episodes: episodes.length,
|
|
1519
|
+
unassignedRawEvents,
|
|
1520
|
+
episodeDream,
|
|
1521
|
+
dreamBacklog,
|
|
1522
|
+
dreamCandidateQueue,
|
|
1523
|
+
},
|
|
1524
|
+
};
|
|
1525
|
+
}
|
|
1526
|
+
runMaintenanceTick(options = {}) {
|
|
1527
|
+
const projectId = options.projectId;
|
|
1528
|
+
const ranAt = options.now ?? Date.now();
|
|
1529
|
+
const activationDecay = this.activationStore.decay({
|
|
1530
|
+
projectId,
|
|
1531
|
+
factor: options.activationDecayFactor,
|
|
1532
|
+
floor: options.activationFloor,
|
|
1533
|
+
now: ranAt,
|
|
1534
|
+
});
|
|
1535
|
+
let memoryAtlasRefresh;
|
|
1536
|
+
try {
|
|
1537
|
+
memoryAtlasRefresh = projectId
|
|
1538
|
+
? { ...this.ensureMemoryAtlas({ projectId }), errors: [] }
|
|
1539
|
+
: this.memoryAtlasIndexer.ensureAllFresh();
|
|
1540
|
+
}
|
|
1541
|
+
catch (error) {
|
|
1542
|
+
memoryAtlasRefresh = { documents: this.memoryAtlasStore.countDocuments(projectId), actions: 0, refreshed: false,
|
|
1543
|
+
errors: [{ projectId: projectId || '__global__', error: error instanceof Error ? error.message : String(error) }] };
|
|
1544
|
+
}
|
|
1545
|
+
const memoryAtlasActivationDecay = this.memoryAtlasStore.decay(projectId, options.activationDecayFactor ?? 0.85, ranAt);
|
|
1546
|
+
const memoryAtlasAccessPruned = this.memoryAtlasStore.cleanupAccess({
|
|
1547
|
+
projectId, before: ranAt - (options.atlasAccessRetentionMs ?? 90 * 24 * 60 * 60 * 1000),
|
|
1548
|
+
});
|
|
1549
|
+
const confirmationTtlMs = options.confirmationTtlMs ?? 30 * 24 * 60 * 60 * 1000;
|
|
1550
|
+
const reviewQueueAging = this.deepWriteCandidateStore.expireNeedsConfirmation({
|
|
1551
|
+
projectId,
|
|
1552
|
+
before: ranAt - confirmationTtlMs,
|
|
1553
|
+
now: ranAt,
|
|
1554
|
+
});
|
|
1555
|
+
const dreamBacklog = this.getDreamBacklogStatus(projectId);
|
|
1556
|
+
const episodeDream = this.getEpisodeDreamStatus(projectId);
|
|
1557
|
+
const unassignedEpisodeRawEvents = this.episodeStore.countUnassignedRawEvents(projectId);
|
|
1558
|
+
const queue = this.getDreamCandidateQueue(projectId);
|
|
1559
|
+
const entityConflicts = this.entityStore.listAliasConflicts().filter((conflict) => {
|
|
1560
|
+
if (!projectId)
|
|
1561
|
+
return true;
|
|
1562
|
+
return conflict.entityIds.some((entityId) => {
|
|
1563
|
+
const entity = this.entityStore.findByEntityId(entityId);
|
|
1564
|
+
return entity?.metadata?.projectId === projectId
|
|
1565
|
+
|| this.entityStore.listTimeline({ entityId, projectId, limit: 1 }).length > 0;
|
|
1566
|
+
});
|
|
1567
|
+
}).length;
|
|
1568
|
+
const hotspots = this.activationStore.getTop({ projectId, limit: 10 });
|
|
1569
|
+
const reEmbedding = this.getReEmbeddingStatus();
|
|
1570
|
+
const staleVectors = this.getHealthStatus().hasStaleVectors ? reEmbedding.total - reEmbedding.completed : 0;
|
|
1571
|
+
const candidateQueue = queue.candidate + queue.needsConfirmation + queue.shadow;
|
|
1572
|
+
const unboundRawEvents = this.countUnboundBindableRawEvents(projectId);
|
|
1573
|
+
const bindingFailures = this.pipelineMetrics.getNonFatalCount('memory_binding_failed', { projectId });
|
|
1574
|
+
const suggestedActions = [];
|
|
1575
|
+
if (episodeDream.pending + episodeDream.failed > 0) {
|
|
1576
|
+
suggestedActions.push({
|
|
1577
|
+
kind: 'dream_curator',
|
|
1578
|
+
command: `cogmem dream tick${projectId ? ` --project ${projectId}` : ''} --mode auto`,
|
|
1579
|
+
reason: `${episodeDream.pending + episodeDream.failed} sealed episodes are waiting for candidate-only Dream processing.`,
|
|
1580
|
+
});
|
|
1581
|
+
}
|
|
1582
|
+
if (unassignedEpisodeRawEvents > 0) {
|
|
1583
|
+
suggestedActions.push({
|
|
1584
|
+
kind: 'repair_episodes',
|
|
1585
|
+
command: `cogmem episode repair${projectId ? ` --project ${projectId}` : ''} --json`,
|
|
1586
|
+
reason: `${unassignedEpisodeRawEvents} raw events are not assigned to an episode; the raw evidence remains intact.`,
|
|
1587
|
+
});
|
|
1588
|
+
}
|
|
1589
|
+
if (candidateQueue > 0) {
|
|
1590
|
+
suggestedActions.push({
|
|
1591
|
+
kind: 'govern_candidates',
|
|
1592
|
+
command: `cogmem memory govern${projectId ? ` --project ${projectId}` : ''}`,
|
|
1593
|
+
reason: `${candidateQueue} dream/deep-write candidates need CPU governance.`,
|
|
1594
|
+
});
|
|
1595
|
+
}
|
|
1596
|
+
if (entityConflicts > 0) {
|
|
1597
|
+
suggestedActions.push({
|
|
1598
|
+
kind: 'resolve_entities',
|
|
1599
|
+
command: 'cogmem memory map --json',
|
|
1600
|
+
reason: `${entityConflicts} active entity alias conflicts need host or agent review.`,
|
|
1601
|
+
});
|
|
1602
|
+
}
|
|
1603
|
+
if (staleVectors > 0) {
|
|
1604
|
+
suggestedActions.push({
|
|
1605
|
+
kind: 're_embed',
|
|
1606
|
+
command: `cogmem-re-embed run${projectId ? ` --project ${projectId}` : ''}`,
|
|
1607
|
+
reason: `${staleVectors} embeddings are stale for the configured embedding model.`,
|
|
1608
|
+
});
|
|
1609
|
+
}
|
|
1610
|
+
if (unboundRawEvents > 0) {
|
|
1611
|
+
suggestedActions.push({
|
|
1612
|
+
kind: 'bind_raw_events',
|
|
1613
|
+
command: `cogmem memory bind${projectId ? ` --project ${projectId}` : ''} --json`,
|
|
1614
|
+
reason: `${unboundRawEvents} high-value raw user events are not attached to memory binding clusters yet.`,
|
|
1615
|
+
});
|
|
1616
|
+
}
|
|
1617
|
+
if (bindingFailures > 0) {
|
|
1618
|
+
suggestedActions.push({
|
|
1619
|
+
kind: 'inspect_binding_failures',
|
|
1620
|
+
command: `cogmem memory tick${projectId ? ` --project ${projectId}` : ''} --json`,
|
|
1621
|
+
reason: `${bindingFailures} non-fatal memory binding failures were recorded; raw ledger writes were preserved.`,
|
|
1622
|
+
});
|
|
1623
|
+
}
|
|
1624
|
+
if (hotspots.length > 0) {
|
|
1625
|
+
suggestedActions.push({
|
|
1626
|
+
kind: 'inspect_hotspots',
|
|
1627
|
+
command: `cogmem memory map${projectId ? ` --project ${projectId}` : ''} --json`,
|
|
1628
|
+
reason: `${hotspots.length} activation hotspots remain after decay.`,
|
|
1629
|
+
});
|
|
1630
|
+
}
|
|
1631
|
+
return {
|
|
1632
|
+
version: 'maintenance_tick.v1',
|
|
1633
|
+
projectId,
|
|
1634
|
+
ranAt,
|
|
1635
|
+
hostOwned: true,
|
|
1636
|
+
chargeVector: {
|
|
1637
|
+
dreamBacklog: dreamBacklog.undreamedRawCount,
|
|
1638
|
+
candidateQueue,
|
|
1639
|
+
entityConflicts,
|
|
1640
|
+
activationHotspots: hotspots.length,
|
|
1641
|
+
staleVectors,
|
|
1642
|
+
unboundRawEvents,
|
|
1643
|
+
bindingFailures,
|
|
1644
|
+
expiredConfirmationCandidates: reviewQueueAging.expired,
|
|
1645
|
+
episodeDreamBacklog: episodeDream.pending + episodeDream.failed,
|
|
1646
|
+
unassignedEpisodeRawEvents,
|
|
1647
|
+
},
|
|
1648
|
+
executed: {
|
|
1649
|
+
activationDecay,
|
|
1650
|
+
memoryAtlasRefresh,
|
|
1651
|
+
memoryAtlasActivationDecay,
|
|
1652
|
+
memoryAtlasAccessPruned,
|
|
1653
|
+
reviewQueueAging: {
|
|
1654
|
+
...reviewQueueAging,
|
|
1655
|
+
ttlMs: confirmationTtlMs,
|
|
1656
|
+
},
|
|
1657
|
+
hiddenDaemonStarted: false,
|
|
1658
|
+
},
|
|
1659
|
+
hotspots,
|
|
1660
|
+
suggestedActions,
|
|
1661
|
+
};
|
|
1662
|
+
}
|
|
1663
|
+
async exportSnapshot(outputPath) {
|
|
1664
|
+
const exporter = new SnapshotExporter({
|
|
1665
|
+
embeddingDimension: this.getEmbeddingDimension(),
|
|
1666
|
+
coreVersion: CORE_VERSION,
|
|
1667
|
+
});
|
|
1668
|
+
return exporter.export(this.dbPath, outputPath);
|
|
1669
|
+
}
|
|
1670
|
+
async importSnapshot(snapshotPath, opts = {}) {
|
|
1671
|
+
if (this.initialized)
|
|
1672
|
+
throw new KernelRunningError();
|
|
1673
|
+
if (this.dbPath === ':memory:') {
|
|
1674
|
+
throw new Error('Cannot import a snapshot into an in-memory MemoryKernel (dbPath is ":memory:"). ' +
|
|
1675
|
+
'Provide a file-backed dbPath when creating the kernel.');
|
|
1676
|
+
}
|
|
1677
|
+
this.close();
|
|
1678
|
+
const importer = new SnapshotImporter({ expectedEmbeddingDimension: this.getEmbeddingDimension() });
|
|
1679
|
+
return importer.import(snapshotPath, this.dbPath, opts);
|
|
1680
|
+
}
|
|
1681
|
+
getHealthStatus() {
|
|
1682
|
+
const lastRun = this.pipelineMetrics.getLastRun();
|
|
1683
|
+
const pipelineP99Ms = this.pipelineMetrics.getPipelineP99();
|
|
1684
|
+
return {
|
|
1685
|
+
status: 'ok',
|
|
1686
|
+
package: 'cogmem',
|
|
1687
|
+
dbPath: this.dbPath,
|
|
1688
|
+
stats: this.memoryGraph.getStats(),
|
|
1689
|
+
vectorRecall: this.getVectorRecallStatus(),
|
|
1690
|
+
embeddingModelId: this.embeddingProvider?.modelId,
|
|
1691
|
+
hasStaleVectors: this.embeddingProvider
|
|
1692
|
+
? this.neuronEmbeddingStore.hasStaleVectors(this.embeddingProvider.modelId)
|
|
1693
|
+
: false,
|
|
1694
|
+
pipelineLastRunAt: lastRun?.completedAt,
|
|
1695
|
+
pipelineP99Ms: pipelineP99Ms > 0 ? pipelineP99Ms : undefined,
|
|
1696
|
+
pipelineLastRunAborted: lastRun?.aborted ?? false,
|
|
1697
|
+
reEmbedding: this.getReEmbeddingStatus(),
|
|
1698
|
+
extensionCount: this.extensions.size,
|
|
1699
|
+
};
|
|
1700
|
+
}
|
|
1701
|
+
getReEmbeddingStatus() {
|
|
1702
|
+
const progress = this.neuronEmbeddingStore.getProgress();
|
|
1703
|
+
const completedOrFailed = progress.completed + progress.failed;
|
|
1704
|
+
const remaining = Math.max(0, progress.total - completedOrFailed);
|
|
1705
|
+
const throughput = this.reEmbeddingPipeline?.getRecentThroughput() ?? null;
|
|
1706
|
+
return {
|
|
1707
|
+
isRunning: this.reEmbeddingPipeline?.isRunning() ?? false,
|
|
1708
|
+
total: progress.total,
|
|
1709
|
+
completed: progress.completed,
|
|
1710
|
+
failed: progress.failed,
|
|
1711
|
+
percentComplete: progress.total === 0 ? 100 : Math.min(100, (completedOrFailed / progress.total) * 100),
|
|
1712
|
+
estimatedRemainingMs: progress.completed === 0 || throughput === null ? null : Math.ceil(remaining / throughput),
|
|
1713
|
+
lastUpdatedAt: progress.lastUpdatedAt,
|
|
1714
|
+
};
|
|
1715
|
+
}
|
|
1716
|
+
getStats() {
|
|
1717
|
+
return this.memoryGraph.getStats();
|
|
1718
|
+
}
|
|
1719
|
+
getMetrics() {
|
|
1720
|
+
const stats = this.memoryGraph.getStats();
|
|
1721
|
+
return {
|
|
1722
|
+
queryLatency: 0,
|
|
1723
|
+
queryType: 'STANDARD',
|
|
1724
|
+
neuronCount: stats.neuronCount,
|
|
1725
|
+
synapseCount: stats.synapseCount,
|
|
1726
|
+
energyPropagation: 0,
|
|
1727
|
+
memoryUsage: 0,
|
|
1728
|
+
modelInferenceHealth: this.embedder.isReady() ? 1 : 0,
|
|
1729
|
+
chainIntegrityScore: 1,
|
|
1730
|
+
fallbackCount: 0,
|
|
1731
|
+
};
|
|
1732
|
+
}
|
|
1733
|
+
async startMetabolism() {
|
|
1734
|
+
await this.metabolism.start();
|
|
1735
|
+
}
|
|
1736
|
+
stopMetabolism() {
|
|
1737
|
+
this.metabolism.stop();
|
|
1738
|
+
}
|
|
1739
|
+
getHotMemories() {
|
|
1740
|
+
return this.metabolism.getHotMemories();
|
|
1741
|
+
}
|
|
1742
|
+
async forgetUser(projectId, reason = 'unspecified') {
|
|
1743
|
+
const db = this.factStore.getDatabase();
|
|
1744
|
+
const neuronIds = this.memoryGraph.getNeuronIdsByProject(projectId);
|
|
1745
|
+
const auditId = `audit-${randomUUID()}`;
|
|
1746
|
+
const deleted = {
|
|
1747
|
+
neurons: neuronIds.length,
|
|
1748
|
+
synapses: 0,
|
|
1749
|
+
events: 0,
|
|
1750
|
+
facts: 0,
|
|
1751
|
+
compiledEvents: 0,
|
|
1752
|
+
embeddings: 0,
|
|
1753
|
+
vectors: 0,
|
|
1754
|
+
activations: 0,
|
|
1755
|
+
memoryBindings: 0,
|
|
1756
|
+
episodes: 0,
|
|
1757
|
+
brainProjections: 0,
|
|
1758
|
+
entityRecords: 0,
|
|
1759
|
+
};
|
|
1760
|
+
const projectMentionRows = (neuronIds.length > 0
|
|
1761
|
+
? db.prepare(`
|
|
1762
|
+
SELECT DISTINCT entity_id FROM entity_mentions
|
|
1763
|
+
WHERE project_id = ? OR neuron_id IN (${neuronIds.map(() => '?').join(', ')})
|
|
1764
|
+
`).all(projectId, ...neuronIds)
|
|
1765
|
+
: db.prepare(`SELECT DISTINCT entity_id FROM entity_mentions WHERE project_id = ?`).all(projectId));
|
|
1766
|
+
const projectMentionEntityIds = new Set(projectMentionRows.map((row) => row.entity_id));
|
|
1767
|
+
const projectEntityInstances = db.prepare(`
|
|
1768
|
+
SELECT instance_id, canonical_entity_id, aliases_json, metadata_json
|
|
1769
|
+
FROM entity_instances
|
|
1770
|
+
`).all()
|
|
1771
|
+
.filter((row) => {
|
|
1772
|
+
const ownerProjectId = parseJsonObject(row.metadata_json).projectId;
|
|
1773
|
+
return ownerProjectId === projectId || (!ownerProjectId && projectMentionEntityIds.has(row.instance_id));
|
|
1774
|
+
});
|
|
1775
|
+
const projectEntityIds = projectEntityInstances.map((row) => row.instance_id);
|
|
1776
|
+
const affectedCanonicalEntityIds = uniqueStrings(projectEntityInstances.map((row) => row.canonical_entity_id));
|
|
1777
|
+
const placeholders = neuronIds.map(() => '?').join(', ');
|
|
1778
|
+
const runDelete = (sql, params = []) => {
|
|
1779
|
+
try {
|
|
1780
|
+
return Number(db.prepare(sql).run(...params).changes ?? 0);
|
|
1781
|
+
}
|
|
1782
|
+
catch (error) {
|
|
1783
|
+
if (error instanceof Error && /no such table/i.test(error.message))
|
|
1784
|
+
return 0;
|
|
1785
|
+
throw error;
|
|
1786
|
+
}
|
|
1787
|
+
};
|
|
1788
|
+
db.transaction(() => {
|
|
1789
|
+
if (neuronIds.length > 0) {
|
|
1790
|
+
deleted.synapses += runDelete(`DELETE FROM synapses WHERE source_id IN (${placeholders}) OR target_id IN (${placeholders})`, [...neuronIds, ...neuronIds]);
|
|
1791
|
+
deleted.facts += runDelete(`DELETE FROM facts WHERE neuron_id IN (${placeholders})`, neuronIds);
|
|
1792
|
+
deleted.compiledEvents += runDelete(`DELETE FROM compiled_events WHERE neuron_id IN (${placeholders})`, neuronIds);
|
|
1793
|
+
deleted.embeddings += runDelete(`DELETE FROM neuron_embeddings WHERE neuron_id IN (${placeholders})`, neuronIds);
|
|
1794
|
+
deleted.vectors += runDelete(`DELETE FROM vector_index WHERE neuron_id IN (${placeholders})`, neuronIds);
|
|
1795
|
+
runDelete(`DELETE FROM neurons_fts WHERE id IN (${placeholders})`, neuronIds);
|
|
1796
|
+
runDelete(`UPDATE neurons SET is_deleted = 1, status = 'archived', updated_at = ? WHERE id IN (${placeholders})`, [Date.now(), ...neuronIds]);
|
|
1797
|
+
}
|
|
1798
|
+
deleted.episodes += this.episodeStore.deleteByProject(projectId);
|
|
1799
|
+
deleted.events += runDelete(`DELETE FROM memory_events WHERE project_id = ?`, [projectId]);
|
|
1800
|
+
deleted.activations += this.activationStore.deleteByProject(projectId);
|
|
1801
|
+
deleted.memoryBindings += this.memoryBindingStore.deleteByProject(projectId);
|
|
1802
|
+
runDelete(`DELETE FROM time_bucket_entries WHERE project_id = ?`, [projectId]);
|
|
1803
|
+
runDelete(`DELETE FROM branch_links WHERE parent_branch_id IN (SELECT branch_id FROM project_branches WHERE project_id = ?) OR child_branch_id IN (SELECT branch_id FROM project_branches WHERE project_id = ?)`, [projectId, projectId]);
|
|
1804
|
+
runDelete(`DELETE FROM branch_entries WHERE branch_id IN (SELECT branch_id FROM project_branches WHERE project_id = ?)`, [projectId]);
|
|
1805
|
+
runDelete(`DELETE FROM project_branches WHERE project_id = ?`, [projectId]);
|
|
1806
|
+
runDelete(`DELETE FROM task_branch_entries WHERE task_id IN (SELECT task_id FROM task_branches WHERE project_id = ?)`, [projectId]);
|
|
1807
|
+
runDelete(`DELETE FROM task_branches WHERE project_id = ?`, [projectId]);
|
|
1808
|
+
runDelete(`DELETE FROM event_cluster_entries WHERE cluster_id IN (SELECT cluster_id FROM event_clusters WHERE project_id = ?)`, [projectId]);
|
|
1809
|
+
runDelete(`DELETE FROM event_clusters WHERE project_id = ?`, [projectId]);
|
|
1810
|
+
runDelete(`DELETE FROM topology_membership WHERE project_id = ?`, [projectId]);
|
|
1811
|
+
runDelete(`DELETE FROM cognitive_nodes WHERE project_id = ?`, [projectId]);
|
|
1812
|
+
runDelete(`DELETE FROM cognitive_edges WHERE project_id = ?`, [projectId]);
|
|
1813
|
+
deleted.brainProjections += runDelete(`DELETE FROM prospective_memory_transitions WHERE candidate_id IN (SELECT candidate_id FROM prospective_memories WHERE project_id = ?)`, [projectId]);
|
|
1814
|
+
deleted.brainProjections += runDelete(`DELETE FROM prospective_memories WHERE project_id = ?`, [projectId]);
|
|
1815
|
+
deleted.brainProjections += runDelete(`DELETE FROM context_strategy_outcomes WHERE project_id = ?`, [projectId]);
|
|
1816
|
+
deleted.brainProjections += runDelete(`DELETE FROM context_activation_receipts WHERE project_id = ?`, [projectId]);
|
|
1817
|
+
deleted.brainProjections += runDelete(`DELETE FROM memory_timeline_entries WHERE project_id = ?`, [projectId]);
|
|
1818
|
+
deleted.brainProjections += runDelete(`DELETE FROM belief_graph_evidence WHERE belief_id IN (SELECT belief_id FROM belief_graph_nodes WHERE project_id = ?)`, [projectId]);
|
|
1819
|
+
deleted.brainProjections += runDelete(`DELETE FROM belief_graph_versions WHERE belief_id IN (SELECT belief_id FROM belief_graph_nodes WHERE project_id = ?)`, [projectId]);
|
|
1820
|
+
deleted.brainProjections += runDelete(`DELETE FROM belief_graph_conflicts WHERE project_id = ?`, [projectId]);
|
|
1821
|
+
deleted.brainProjections += runDelete(`DELETE FROM belief_graph_nodes WHERE project_id = ?`, [projectId]);
|
|
1822
|
+
deleted.brainProjections += runDelete(`DELETE FROM entity_resolution_log WHERE candidate_id IN (SELECT candidate_id FROM entity_merge_candidates WHERE project_id = ?)`, [projectId]);
|
|
1823
|
+
deleted.brainProjections += runDelete(`DELETE FROM entity_merge_candidates WHERE project_id = ?`, [projectId]);
|
|
1824
|
+
deleted.brainProjections += runDelete(`DELETE FROM memory_governance_audit WHERE project_id = ?`, [projectId]);
|
|
1825
|
+
deleted.brainProjections += runDelete(`DELETE FROM memory_governance_plans WHERE project_id = ? OR plan_id IN (SELECT plan_id FROM memory_governance_operations WHERE project_id = ?)`, [projectId, projectId]);
|
|
1826
|
+
deleted.brainProjections += runDelete(`DELETE FROM memory_governance_operations WHERE project_id = ?`, [projectId]);
|
|
1827
|
+
deleted.entityRecords += runDelete(`DELETE FROM entity_mentions WHERE project_id = ?`, [projectId]);
|
|
1828
|
+
if (projectEntityIds.length > 0) {
|
|
1829
|
+
const entityPlaceholders = projectEntityIds.map(() => '?').join(', ');
|
|
1830
|
+
deleted.entityRecords += runDelete(`DELETE FROM entity_resolution_log WHERE source_entity_id IN (${entityPlaceholders}) OR target_entity_id IN (${entityPlaceholders})`, [...projectEntityIds, ...projectEntityIds]);
|
|
1831
|
+
deleted.entityRecords += runDelete(`DELETE FROM entity_merge_candidates WHERE source_entity_id IN (${entityPlaceholders}) OR target_entity_id IN (${entityPlaceholders})`, [...projectEntityIds, ...projectEntityIds]);
|
|
1832
|
+
deleted.entityRecords += runDelete(`DELETE FROM entity_aliases WHERE entity_id IN (${entityPlaceholders})`, projectEntityIds);
|
|
1833
|
+
deleted.entityRecords += runDelete(`DELETE FROM entity_attributes WHERE entity_id IN (${entityPlaceholders})`, projectEntityIds);
|
|
1834
|
+
deleted.entityRecords += runDelete(`DELETE FROM entity_relations WHERE source_entity_id IN (${entityPlaceholders}) OR target_entity_id IN (${entityPlaceholders})`, [...projectEntityIds, ...projectEntityIds]);
|
|
1835
|
+
deleted.entityRecords += runDelete(`DELETE FROM pending_entity_resolution WHERE resolved_entity_id IN (${entityPlaceholders})`, projectEntityIds);
|
|
1836
|
+
deleted.entityRecords += runDelete(`DELETE FROM entity_instances WHERE instance_id IN (${entityPlaceholders})`, projectEntityIds);
|
|
1837
|
+
scrubEntityAliasConflicts(db, projectEntityIds);
|
|
1838
|
+
}
|
|
1839
|
+
if (neuronIds.length > 0) {
|
|
1840
|
+
deleted.entityRecords += runDelete(`DELETE FROM entity_attributes WHERE source_neuron_id IN (${placeholders})`, neuronIds);
|
|
1841
|
+
deleted.entityRecords += runDelete(`DELETE FROM entity_relations WHERE source_neuron_id IN (${placeholders})`, neuronIds);
|
|
1842
|
+
deleted.entityRecords += runDelete(`DELETE FROM pending_entity_resolution WHERE context_neuron_id IN (${placeholders})`, neuronIds);
|
|
1843
|
+
}
|
|
1844
|
+
for (const canonicalEntityId of affectedCanonicalEntityIds) {
|
|
1845
|
+
rebuildCanonicalEntityAfterForget(db, canonicalEntityId, runDelete);
|
|
1846
|
+
}
|
|
1847
|
+
db.prepare(`
|
|
1848
|
+
INSERT INTO governance_audit_log (
|
|
1849
|
+
audit_id, action, project_id, reason, details_json, created_at
|
|
1850
|
+
) VALUES (?, ?, ?, ?, ?, ?)
|
|
1851
|
+
`).run(auditId, 'forgetUser', projectId, reason, JSON.stringify({ deleted }), Date.now());
|
|
1852
|
+
})();
|
|
1853
|
+
for (const neuronId of neuronIds) {
|
|
1854
|
+
this.vectorStore.removePoint(neuronId);
|
|
1855
|
+
}
|
|
1856
|
+
this.memoryGraph.rebuildIndexes();
|
|
1857
|
+
this.topicRegistry.invalidate(projectId);
|
|
1858
|
+
return { projectId, auditId, deleted };
|
|
1859
|
+
}
|
|
1860
|
+
getGovernanceAudit(projectId) {
|
|
1861
|
+
const db = this.factStore.getDatabase();
|
|
1862
|
+
this.ensureGovernanceAuditTable(db);
|
|
1863
|
+
const rows = projectId
|
|
1864
|
+
? db.prepare(`
|
|
1865
|
+
SELECT *
|
|
1866
|
+
FROM governance_audit_log
|
|
1867
|
+
WHERE project_id = ?
|
|
1868
|
+
ORDER BY created_at DESC, audit_id DESC
|
|
1869
|
+
`).all(projectId)
|
|
1870
|
+
: db.prepare(`
|
|
1871
|
+
SELECT *
|
|
1872
|
+
FROM governance_audit_log
|
|
1873
|
+
ORDER BY created_at DESC, audit_id DESC
|
|
1874
|
+
`).all();
|
|
1875
|
+
return rows.map((row) => ({
|
|
1876
|
+
auditId: row.audit_id,
|
|
1877
|
+
action: row.action,
|
|
1878
|
+
projectId: row.project_id || undefined,
|
|
1879
|
+
reason: row.reason || undefined,
|
|
1880
|
+
details: row.details_json ? JSON.parse(row.details_json) : undefined,
|
|
1881
|
+
createdAt: Number(row.created_at),
|
|
1882
|
+
}));
|
|
1883
|
+
}
|
|
1884
|
+
getProjectMemories(projectId) {
|
|
1885
|
+
return this.memoryGraph.getAllNeurons().filter((neuron) => neuron.metadata.projectId === projectId);
|
|
1886
|
+
}
|
|
1887
|
+
registerExtension(name, implementation) {
|
|
1888
|
+
this.extensions.set(name, implementation);
|
|
1889
|
+
}
|
|
1890
|
+
hasExtension(name) {
|
|
1891
|
+
return this.extensions.has(name);
|
|
1892
|
+
}
|
|
1893
|
+
getExtension(name) {
|
|
1894
|
+
return this.extensions.get(name);
|
|
1895
|
+
}
|
|
1896
|
+
async normalizeIngestInput(input) {
|
|
1897
|
+
const base = input;
|
|
1898
|
+
const content = this.piiRedactor ? this.piiRedactor.redact(base.content ?? '').text : base.content ?? '';
|
|
1899
|
+
const resolvedTopicPath = base.topicPath ?? (await this.topicClassifier.classifyAsync(content, base.projectId)).topicPath;
|
|
1900
|
+
return {
|
|
1901
|
+
...base,
|
|
1902
|
+
content,
|
|
1903
|
+
topicPath: resolvedTopicPath,
|
|
1904
|
+
type: base.type ?? 'chat',
|
|
1905
|
+
};
|
|
1906
|
+
}
|
|
1907
|
+
queueEmbedding(neuron) {
|
|
1908
|
+
if (!this.embeddingProvider)
|
|
1909
|
+
return;
|
|
1910
|
+
this.embeddingProvider.embed(neuron.content)
|
|
1911
|
+
.then((vector) => {
|
|
1912
|
+
if (vector.length !== this.embeddingProvider.dimensions) {
|
|
1913
|
+
throw new Error(`Embedding dimension mismatch for ${this.embeddingProvider.modelId}: expected ${this.embeddingProvider.dimensions}, got ${vector.length}`);
|
|
1914
|
+
}
|
|
1915
|
+
this.neuronEmbeddingStore.upsert(neuron.id, this.embeddingProvider.modelId, new Float32Array(vector), neuron.metadata.projectId);
|
|
1916
|
+
this.lastEmbedSuccessAt = Date.now();
|
|
1917
|
+
})
|
|
1918
|
+
.catch(() => {
|
|
1919
|
+
this.lastEmbedErrorAt = Date.now();
|
|
1920
|
+
});
|
|
1921
|
+
}
|
|
1922
|
+
getVectorRecallStatus() {
|
|
1923
|
+
if (!this.embeddingProvider)
|
|
1924
|
+
return 'disabled';
|
|
1925
|
+
if (typeof this.lastEmbedErrorAt === 'number'
|
|
1926
|
+
&& (typeof this.lastEmbedSuccessAt !== 'number' || this.lastEmbedErrorAt > this.lastEmbedSuccessAt)) {
|
|
1927
|
+
return 'degraded';
|
|
1928
|
+
}
|
|
1929
|
+
return 'active';
|
|
1930
|
+
}
|
|
1931
|
+
getEmbeddingDimension() {
|
|
1932
|
+
return this.embeddingProvider?.dimensions ?? this.vectorStore.getStats().dimension;
|
|
1933
|
+
}
|
|
1934
|
+
ensureMetaTable(db) {
|
|
1935
|
+
db.exec(`
|
|
1936
|
+
CREATE TABLE IF NOT EXISTS _meta (
|
|
1937
|
+
key TEXT PRIMARY KEY,
|
|
1938
|
+
value TEXT NOT NULL
|
|
1939
|
+
);
|
|
1940
|
+
`);
|
|
1941
|
+
const write = db.prepare(`INSERT OR REPLACE INTO _meta (key, value) VALUES (?, ?)`);
|
|
1942
|
+
write.run('schema_version', String(LATEST_SCHEMA_VERSION));
|
|
1943
|
+
write.run('core_version', CORE_VERSION);
|
|
1944
|
+
}
|
|
1945
|
+
ensureGovernanceAuditTable(db) {
|
|
1946
|
+
db.exec(`
|
|
1947
|
+
CREATE TABLE IF NOT EXISTS governance_audit_log (
|
|
1948
|
+
audit_id TEXT PRIMARY KEY,
|
|
1949
|
+
action TEXT NOT NULL,
|
|
1950
|
+
project_id TEXT,
|
|
1951
|
+
reason TEXT,
|
|
1952
|
+
details_json TEXT,
|
|
1953
|
+
created_at INTEGER NOT NULL
|
|
1954
|
+
);
|
|
1955
|
+
|
|
1956
|
+
CREATE INDEX IF NOT EXISTS idx_governance_audit_project
|
|
1957
|
+
ON governance_audit_log(project_id, created_at DESC);
|
|
1958
|
+
`);
|
|
1959
|
+
}
|
|
1960
|
+
}
|
|
1961
|
+
export function createMemoryKernel(options = {}) {
|
|
1962
|
+
return new MemoryKernel(options);
|
|
1963
|
+
}
|
|
1964
|
+
export function createMemoryKernelFromConfig(input = {}) {
|
|
1965
|
+
const options = typeof input === 'string' ? { configPath: input } : input;
|
|
1966
|
+
const resolution = resolveCogmemConfigPath({
|
|
1967
|
+
configPath: options.configPath,
|
|
1968
|
+
cwd: options.cwd,
|
|
1969
|
+
env: options.env,
|
|
1970
|
+
});
|
|
1971
|
+
if (resolution.kind === 'missing') {
|
|
1972
|
+
throw new Error(`missing_cogmem_config: Missing cogmem config at ${resolution.path}. Run cogmem-init first.`);
|
|
1973
|
+
}
|
|
1974
|
+
const loaded = loadCogmemConfig({
|
|
1975
|
+
configPath: resolution.path,
|
|
1976
|
+
cwd: options.cwd,
|
|
1977
|
+
env: options.env,
|
|
1978
|
+
});
|
|
1979
|
+
const error = loaded.diagnostics.find((diagnostic) => diagnostic.severity === 'error');
|
|
1980
|
+
if (error)
|
|
1981
|
+
throw new Error(`${error.code}: ${error.message}`);
|
|
1982
|
+
const { configPath: _configPath, cwd: _cwd, env: _env, ...explicitOptions } = options;
|
|
1983
|
+
return createMemoryKernel({ ...loaded.options, ...explicitOptions });
|
|
1984
|
+
}
|
|
1985
|
+
function requiredGovernancePayloadString(payload, field) {
|
|
1986
|
+
const value = payload[field];
|
|
1987
|
+
if (typeof value !== 'string' || value.trim() === '')
|
|
1988
|
+
throw new Error(`governance payload requires ${field}`);
|
|
1989
|
+
return value;
|
|
1990
|
+
}
|
|
1991
|
+
function eventPayloadText(payload) {
|
|
1992
|
+
if (!payload || typeof payload !== 'object')
|
|
1993
|
+
return undefined;
|
|
1994
|
+
const text = payload.text;
|
|
1995
|
+
return typeof text === 'string' ? text : undefined;
|
|
1996
|
+
}
|
|
1997
|
+
function parseJsonObject(value) {
|
|
1998
|
+
if (!value)
|
|
1999
|
+
return {};
|
|
2000
|
+
try {
|
|
2001
|
+
const parsed = JSON.parse(value);
|
|
2002
|
+
return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : {};
|
|
2003
|
+
}
|
|
2004
|
+
catch {
|
|
2005
|
+
return {};
|
|
2006
|
+
}
|
|
2007
|
+
}
|
|
2008
|
+
function parseJsonStringArray(value) {
|
|
2009
|
+
if (!value)
|
|
2010
|
+
return [];
|
|
2011
|
+
try {
|
|
2012
|
+
const parsed = JSON.parse(value);
|
|
2013
|
+
return Array.isArray(parsed) ? parsed.filter((item) => typeof item === 'string') : [];
|
|
2014
|
+
}
|
|
2015
|
+
catch {
|
|
2016
|
+
return [];
|
|
2017
|
+
}
|
|
2018
|
+
}
|
|
2019
|
+
function scrubEntityAliasConflicts(db, deletedEntityIds) {
|
|
2020
|
+
const deleted = new Set(deletedEntityIds);
|
|
2021
|
+
const rows = db.prepare(`SELECT conflict_id, entity_ids_json FROM entity_alias_conflicts`).all();
|
|
2022
|
+
for (const row of rows) {
|
|
2023
|
+
const remaining = parseJsonStringArray(row.entity_ids_json).filter((entityId) => !deleted.has(entityId));
|
|
2024
|
+
if (remaining.length < 2) {
|
|
2025
|
+
db.prepare(`DELETE FROM entity_alias_conflicts WHERE conflict_id = ?`).run(row.conflict_id);
|
|
2026
|
+
}
|
|
2027
|
+
else {
|
|
2028
|
+
db.prepare(`UPDATE entity_alias_conflicts SET entity_ids_json = ?, updated_at = ? WHERE conflict_id = ?`)
|
|
2029
|
+
.run(JSON.stringify(remaining), Date.now(), row.conflict_id);
|
|
2030
|
+
}
|
|
2031
|
+
}
|
|
2032
|
+
}
|
|
2033
|
+
function rebuildCanonicalEntityAfterForget(db, canonicalEntityId, runDelete) {
|
|
2034
|
+
const remaining = db.prepare(`
|
|
2035
|
+
SELECT aliases_json FROM entity_instances WHERE canonical_entity_id = ?
|
|
2036
|
+
`).all(canonicalEntityId);
|
|
2037
|
+
if (remaining.length === 0) {
|
|
2038
|
+
runDelete(`DELETE FROM entities WHERE entity_id = ?`, [canonicalEntityId]);
|
|
2039
|
+
return;
|
|
2040
|
+
}
|
|
2041
|
+
const aliases = uniqueStrings(remaining.flatMap((row) => parseJsonStringArray(row.aliases_json)));
|
|
2042
|
+
const canonical = db.prepare(`SELECT metadata_json FROM entities WHERE entity_id = ?`).get(canonicalEntityId);
|
|
2043
|
+
const metadata = parseJsonObject(canonical?.metadata_json);
|
|
2044
|
+
for (const key of ['projectId', 'rawMention', 'answerDisplayName', 'ens1RawMention', 'ens1RawMentions', 'ens1AnswerDisplayName']) {
|
|
2045
|
+
delete metadata[key];
|
|
2046
|
+
}
|
|
2047
|
+
db.prepare(`UPDATE entities SET aliases_json = ?, metadata_json = ?, updated_at = ? WHERE entity_id = ?`)
|
|
2048
|
+
.run(JSON.stringify(aliases), JSON.stringify(metadata), Date.now(), canonicalEntityId);
|
|
2049
|
+
}
|
|
2050
|
+
function optionalGovernancePayloadString(payload, field) {
|
|
2051
|
+
const value = payload[field];
|
|
2052
|
+
if (value === undefined || value === null)
|
|
2053
|
+
return undefined;
|
|
2054
|
+
if (typeof value !== 'string')
|
|
2055
|
+
throw new Error(`governance payload ${field} must be a string`);
|
|
2056
|
+
return value;
|
|
2057
|
+
}
|
|
2058
|
+
function optionalGovernancePayloadNumber(payload, field) {
|
|
2059
|
+
const value = payload[field];
|
|
2060
|
+
if (value === undefined || value === null)
|
|
2061
|
+
return undefined;
|
|
2062
|
+
if (typeof value !== 'number' || !Number.isFinite(value))
|
|
2063
|
+
throw new Error(`governance payload ${field} must be a finite number`);
|
|
2064
|
+
return value;
|
|
2065
|
+
}
|
|
2066
|
+
function uniqueStrings(values) {
|
|
2067
|
+
return Array.from(new Set(values.filter(Boolean)));
|
|
2068
|
+
}
|
|
2069
|
+
function extractNavigationTerms(query) {
|
|
2070
|
+
return uniqueStrings(query
|
|
2071
|
+
.toLowerCase()
|
|
2072
|
+
.split(/[\s,,。!?、::/]+/)
|
|
2073
|
+
.map((token) => token.trim())
|
|
2074
|
+
.filter((token) => token.length >= 2));
|
|
2075
|
+
}
|
|
2076
|
+
function selectRecallableEvidence(neurons, limit) {
|
|
2077
|
+
const recallable = neurons.filter((neuron) => isRecallableMemoryEvidence(neuron));
|
|
2078
|
+
const filteredEvidence = uniqueFilteredEvidence([
|
|
2079
|
+
...neurons
|
|
2080
|
+
.filter((neuron) => !isRecallableMemoryEvidence(neuron))
|
|
2081
|
+
.map((neuron) => ({
|
|
2082
|
+
neuron,
|
|
2083
|
+
reason: 'status_suppressed',
|
|
2084
|
+
governanceReason: recallSuppressionReasonFor(neuron),
|
|
2085
|
+
})),
|
|
2086
|
+
...recallable
|
|
2087
|
+
.slice(limit)
|
|
2088
|
+
.map((neuron) => ({ neuron, reason: 'over_context_limit' })),
|
|
2089
|
+
]);
|
|
2090
|
+
return {
|
|
2091
|
+
rawEvidence: recallable.slice(0, limit),
|
|
2092
|
+
filteredEvidence,
|
|
2093
|
+
};
|
|
2094
|
+
}
|
|
2095
|
+
function uniqueFilteredEvidence(items) {
|
|
2096
|
+
const seen = new Set();
|
|
2097
|
+
const uniqueItems = [];
|
|
2098
|
+
for (const item of items) {
|
|
2099
|
+
const key = `${item.neuron.id}:${item.reason}`;
|
|
2100
|
+
if (seen.has(key))
|
|
2101
|
+
continue;
|
|
2102
|
+
seen.add(key);
|
|
2103
|
+
uniqueItems.push(item);
|
|
2104
|
+
}
|
|
2105
|
+
return uniqueItems;
|
|
2106
|
+
}
|
|
2107
|
+
function stringifyToolPayload(value) {
|
|
2108
|
+
if (value === undefined)
|
|
2109
|
+
return '';
|
|
2110
|
+
if (typeof value === 'string')
|
|
2111
|
+
return value;
|
|
2112
|
+
try {
|
|
2113
|
+
return JSON.stringify(value);
|
|
2114
|
+
}
|
|
2115
|
+
catch {
|
|
2116
|
+
return String(value);
|
|
2117
|
+
}
|
|
2118
|
+
}
|