cognitive-core 0.1.0 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude/settings.json +88 -0
- package/.claude/settings.local.json +11 -0
- package/.entire/settings.json +4 -0
- package/CLAUDE.md +233 -0
- package/README.md +841 -255
- package/dist/atlas.d.ts +150 -12
- package/dist/atlas.d.ts.map +1 -1
- package/dist/atlas.js +391 -31
- package/dist/atlas.js.map +1 -1
- package/dist/bin/cli-utils.d.ts +37 -0
- package/dist/bin/cli-utils.d.ts.map +1 -0
- package/dist/bin/cli-utils.js +176 -0
- package/dist/bin/cli-utils.js.map +1 -0
- package/dist/bin/cognitive-core.d.ts +2 -12
- package/dist/bin/cognitive-core.d.ts.map +1 -1
- package/dist/bin/cognitive-core.js +76 -351
- package/dist/bin/cognitive-core.js.map +1 -1
- package/dist/bin/commands/kb.d.ts +6 -0
- package/dist/bin/commands/kb.d.ts.map +1 -0
- package/dist/bin/commands/kb.js +240 -0
- package/dist/bin/commands/kb.js.map +1 -0
- package/dist/bin/commands/learn.d.ts +6 -0
- package/dist/bin/commands/learn.d.ts.map +1 -0
- package/dist/bin/commands/learn.js +91 -0
- package/dist/bin/commands/learn.js.map +1 -0
- package/dist/bin/commands/legacy.d.ts +12 -0
- package/dist/bin/commands/legacy.d.ts.map +1 -0
- package/dist/bin/commands/legacy.js +142 -0
- package/dist/bin/commands/legacy.js.map +1 -0
- package/dist/bin/commands/run.d.ts +3 -0
- package/dist/bin/commands/run.d.ts.map +1 -0
- package/dist/bin/commands/run.js +99 -0
- package/dist/bin/commands/run.js.map +1 -0
- package/dist/bin/commands/sessions.d.ts +9 -0
- package/dist/bin/commands/sessions.d.ts.map +1 -0
- package/dist/bin/commands/sessions.js +183 -0
- package/dist/bin/commands/sessions.js.map +1 -0
- package/dist/bin/commands/skills.d.ts +6 -0
- package/dist/bin/commands/skills.d.ts.map +1 -0
- package/dist/bin/commands/skills.js +135 -0
- package/dist/bin/commands/skills.js.map +1 -0
- package/dist/embeddings/index.d.ts +1 -0
- package/dist/embeddings/index.d.ts.map +1 -1
- package/dist/embeddings/index.js +2 -0
- package/dist/embeddings/index.js.map +1 -1
- package/dist/embeddings/inverted-index.d.ts +47 -0
- package/dist/embeddings/inverted-index.d.ts.map +1 -0
- package/dist/embeddings/inverted-index.js +122 -0
- package/dist/embeddings/inverted-index.js.map +1 -0
- package/dist/embeddings/manager.d.ts +3 -1
- package/dist/embeddings/manager.d.ts.map +1 -1
- package/dist/embeddings/manager.js +12 -7
- package/dist/embeddings/manager.js.map +1 -1
- package/dist/embeddings/provider.d.ts.map +1 -1
- package/dist/embeddings/provider.js +6 -3
- package/dist/embeddings/provider.js.map +1 -1
- package/dist/embeddings/vector-store.d.ts +7 -3
- package/dist/embeddings/vector-store.d.ts.map +1 -1
- package/dist/embeddings/vector-store.js +22 -6
- package/dist/embeddings/vector-store.js.map +1 -1
- package/dist/factory.d.ts +11 -12
- package/dist/factory.d.ts.map +1 -1
- package/dist/factory.js +20 -7
- package/dist/factory.js.map +1 -1
- package/dist/index.d.ts +11 -8
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +71 -8
- package/dist/index.js.map +1 -1
- package/dist/learning/analyzer.d.ts.map +1 -1
- package/dist/learning/analyzer.js +17 -35
- package/dist/learning/analyzer.js.map +1 -1
- package/dist/learning/energy-evaluator.d.ts +128 -0
- package/dist/learning/energy-evaluator.d.ts.map +1 -0
- package/dist/learning/energy-evaluator.js +175 -0
- package/dist/learning/energy-evaluator.js.map +1 -0
- package/dist/learning/healing-orchestrator.d.ts +182 -0
- package/dist/learning/healing-orchestrator.d.ts.map +1 -0
- package/dist/learning/healing-orchestrator.js +250 -0
- package/dist/learning/healing-orchestrator.js.map +1 -0
- package/dist/learning/index.d.ts +11 -2
- package/dist/learning/index.d.ts.map +1 -1
- package/dist/learning/index.js +20 -3
- package/dist/learning/index.js.map +1 -1
- package/dist/learning/instant-loop.d.ts +87 -0
- package/dist/learning/instant-loop.d.ts.map +1 -0
- package/dist/learning/instant-loop.js +264 -0
- package/dist/learning/instant-loop.js.map +1 -0
- package/dist/learning/knowledge-extractor.d.ts +56 -0
- package/dist/learning/knowledge-extractor.d.ts.map +1 -0
- package/dist/learning/knowledge-extractor.js +336 -0
- package/dist/learning/knowledge-extractor.js.map +1 -0
- package/dist/learning/loop-coordinator.d.ts +61 -0
- package/dist/learning/loop-coordinator.d.ts.map +1 -0
- package/dist/learning/loop-coordinator.js +96 -0
- package/dist/learning/loop-coordinator.js.map +1 -0
- package/dist/learning/maintenance-scheduler.d.ts +141 -0
- package/dist/learning/maintenance-scheduler.d.ts.map +1 -0
- package/dist/learning/maintenance-scheduler.js +186 -0
- package/dist/learning/maintenance-scheduler.js.map +1 -0
- package/dist/learning/meta-learner.d.ts +7 -0
- package/dist/learning/meta-learner.d.ts.map +1 -1
- package/dist/learning/meta-learner.js +47 -21
- package/dist/learning/meta-learner.js.map +1 -1
- package/dist/learning/pipeline.d.ts +55 -4
- package/dist/learning/pipeline.d.ts.map +1 -1
- package/dist/learning/pipeline.js +134 -16
- package/dist/learning/pipeline.js.map +1 -1
- package/dist/learning/reflexion-generator.d.ts +64 -0
- package/dist/learning/reflexion-generator.d.ts.map +1 -0
- package/dist/learning/reflexion-generator.js +194 -0
- package/dist/learning/reflexion-generator.js.map +1 -0
- package/dist/learning/team-ingester.d.ts +152 -0
- package/dist/learning/team-ingester.d.ts.map +1 -0
- package/dist/learning/team-ingester.js +333 -0
- package/dist/learning/team-ingester.js.map +1 -0
- package/dist/learning/team-meta-learner.d.ts +50 -0
- package/dist/learning/team-meta-learner.d.ts.map +1 -0
- package/dist/learning/team-meta-learner.js +417 -0
- package/dist/learning/team-meta-learner.js.map +1 -0
- package/dist/learning/team-pipeline.d.ts +76 -0
- package/dist/learning/team-pipeline.d.ts.map +1 -0
- package/dist/learning/team-pipeline.js +266 -0
- package/dist/learning/team-pipeline.js.map +1 -0
- package/dist/learning/trajectory-sources/dataclaw.d.ts +41 -0
- package/dist/learning/trajectory-sources/dataclaw.d.ts.map +1 -0
- package/dist/learning/trajectory-sources/dataclaw.js +330 -0
- package/dist/learning/trajectory-sources/dataclaw.js.map +1 -0
- package/dist/learning/trajectory-sources/entire.d.ts +31 -0
- package/dist/learning/trajectory-sources/entire.d.ts.map +1 -0
- package/dist/learning/trajectory-sources/entire.js +189 -0
- package/dist/learning/trajectory-sources/entire.js.map +1 -0
- package/dist/learning/trajectory-sources/file.d.ts +23 -0
- package/dist/learning/trajectory-sources/file.d.ts.map +1 -0
- package/dist/learning/trajectory-sources/file.js +101 -0
- package/dist/learning/trajectory-sources/file.js.map +1 -0
- package/dist/learning/trajectory-sources/huggingface.d.ts +36 -0
- package/dist/learning/trajectory-sources/huggingface.d.ts.map +1 -0
- package/dist/learning/trajectory-sources/huggingface.js +157 -0
- package/dist/learning/trajectory-sources/huggingface.js.map +1 -0
- package/dist/learning/trajectory-sources/in-memory.d.ts +21 -0
- package/dist/learning/trajectory-sources/in-memory.d.ts.map +1 -0
- package/dist/learning/trajectory-sources/in-memory.js +43 -0
- package/dist/learning/trajectory-sources/in-memory.js.map +1 -0
- package/dist/learning/trajectory-sources/index.d.ts +7 -0
- package/dist/learning/trajectory-sources/index.d.ts.map +1 -0
- package/dist/learning/trajectory-sources/index.js +7 -0
- package/dist/learning/trajectory-sources/index.js.map +1 -0
- package/dist/learning/trajectory-sources/pipeline.d.ts +24 -0
- package/dist/learning/trajectory-sources/pipeline.d.ts.map +1 -0
- package/dist/learning/trajectory-sources/pipeline.js +47 -0
- package/dist/learning/trajectory-sources/pipeline.js.map +1 -0
- package/dist/learning/unified-pipeline.d.ts +281 -0
- package/dist/learning/unified-pipeline.d.ts.map +1 -0
- package/dist/learning/unified-pipeline.js +637 -0
- package/dist/learning/unified-pipeline.js.map +1 -0
- package/dist/memory/candidate-retrieval.d.ts +43 -0
- package/dist/memory/candidate-retrieval.d.ts.map +1 -0
- package/dist/memory/candidate-retrieval.js +41 -0
- package/dist/memory/candidate-retrieval.js.map +1 -0
- package/dist/memory/causal-store.d.ts +97 -0
- package/dist/memory/causal-store.d.ts.map +1 -0
- package/dist/memory/causal-store.js +209 -0
- package/dist/memory/causal-store.js.map +1 -0
- package/dist/memory/coherence.d.ts +71 -0
- package/dist/memory/coherence.d.ts.map +1 -0
- package/dist/memory/coherence.js +176 -0
- package/dist/memory/coherence.js.map +1 -0
- package/dist/memory/experience.d.ts +39 -6
- package/dist/memory/experience.d.ts.map +1 -1
- package/dist/memory/experience.js +193 -49
- package/dist/memory/experience.js.map +1 -1
- package/dist/memory/graph-layers/base.d.ts +29 -0
- package/dist/memory/graph-layers/base.d.ts.map +1 -0
- package/dist/memory/graph-layers/base.js +143 -0
- package/dist/memory/graph-layers/base.js.map +1 -0
- package/dist/memory/graph-layers/causal.d.ts +14 -0
- package/dist/memory/graph-layers/causal.d.ts.map +1 -0
- package/dist/memory/graph-layers/causal.js +14 -0
- package/dist/memory/graph-layers/causal.js.map +1 -0
- package/dist/memory/graph-layers/entity.d.ts +14 -0
- package/dist/memory/graph-layers/entity.d.ts.map +1 -0
- package/dist/memory/graph-layers/entity.js +14 -0
- package/dist/memory/graph-layers/entity.js.map +1 -0
- package/dist/memory/graph-layers/index.d.ts +6 -0
- package/dist/memory/graph-layers/index.d.ts.map +1 -0
- package/dist/memory/graph-layers/index.js +6 -0
- package/dist/memory/graph-layers/index.js.map +1 -0
- package/dist/memory/graph-layers/semantic.d.ts +14 -0
- package/dist/memory/graph-layers/semantic.d.ts.map +1 -0
- package/dist/memory/graph-layers/semantic.js +14 -0
- package/dist/memory/graph-layers/semantic.js.map +1 -0
- package/dist/memory/graph-layers/temporal.d.ts +14 -0
- package/dist/memory/graph-layers/temporal.d.ts.map +1 -0
- package/dist/memory/graph-layers/temporal.js +14 -0
- package/dist/memory/graph-layers/temporal.js.map +1 -0
- package/dist/memory/index.d.ts +15 -0
- package/dist/memory/index.d.ts.map +1 -1
- package/dist/memory/index.js +22 -0
- package/dist/memory/index.js.map +1 -1
- package/dist/memory/knowledge-bank.d.ts +234 -0
- package/dist/memory/knowledge-bank.d.ts.map +1 -0
- package/dist/memory/knowledge-bank.js +1048 -0
- package/dist/memory/knowledge-bank.js.map +1 -0
- package/dist/memory/knowledge-defrag.d.ts +49 -0
- package/dist/memory/knowledge-defrag.d.ts.map +1 -0
- package/dist/memory/knowledge-defrag.js +257 -0
- package/dist/memory/knowledge-defrag.js.map +1 -0
- package/dist/memory/knowledge-graph.d.ts +41 -0
- package/dist/memory/knowledge-graph.d.ts.map +1 -0
- package/dist/memory/knowledge-graph.js +273 -0
- package/dist/memory/knowledge-graph.js.map +1 -0
- package/dist/memory/meta.d.ts +7 -8
- package/dist/memory/meta.d.ts.map +1 -1
- package/dist/memory/meta.js +73 -79
- package/dist/memory/meta.js.map +1 -1
- package/dist/memory/playbook.d.ts +26 -9
- package/dist/memory/playbook.d.ts.map +1 -1
- package/dist/memory/playbook.js +198 -74
- package/dist/memory/playbook.js.map +1 -1
- package/dist/memory/reasoning-bank.d.ts +130 -0
- package/dist/memory/reasoning-bank.d.ts.map +1 -0
- package/dist/memory/reasoning-bank.js +342 -0
- package/dist/memory/reasoning-bank.js.map +1 -0
- package/dist/memory/reflexion.d.ts +59 -0
- package/dist/memory/reflexion.d.ts.map +1 -0
- package/dist/memory/reflexion.js +96 -0
- package/dist/memory/reflexion.js.map +1 -0
- package/dist/memory/search-provider.d.ts +31 -0
- package/dist/memory/search-provider.d.ts.map +1 -0
- package/dist/memory/search-provider.js +2 -0
- package/dist/memory/search-provider.js.map +1 -0
- package/dist/memory/search-providers/index.d.ts +3 -0
- package/dist/memory/search-providers/index.d.ts.map +1 -0
- package/dist/memory/search-providers/index.js +3 -0
- package/dist/memory/search-providers/index.js.map +1 -0
- package/dist/memory/search-providers/minimem.d.ts +43 -0
- package/dist/memory/search-providers/minimem.d.ts.map +1 -0
- package/dist/memory/search-providers/minimem.js +56 -0
- package/dist/memory/search-providers/minimem.js.map +1 -0
- package/dist/memory/search-providers/text-similarity.d.ts +15 -0
- package/dist/memory/search-providers/text-similarity.d.ts.map +1 -0
- package/dist/memory/search-providers/text-similarity.js +21 -0
- package/dist/memory/search-providers/text-similarity.js.map +1 -0
- package/dist/memory/skill-exporter.d.ts +75 -0
- package/dist/memory/skill-exporter.d.ts.map +1 -0
- package/dist/memory/skill-exporter.js +248 -0
- package/dist/memory/skill-exporter.js.map +1 -0
- package/dist/memory/system.d.ts +20 -3
- package/dist/memory/system.d.ts.map +1 -1
- package/dist/memory/system.js +61 -11
- package/dist/memory/system.js.map +1 -1
- package/dist/memory/team-experience.d.ts +298 -0
- package/dist/memory/team-experience.d.ts.map +1 -0
- package/dist/memory/team-experience.js +355 -0
- package/dist/memory/team-experience.js.map +1 -0
- package/dist/memory/temporal-compressor.d.ts +126 -0
- package/dist/memory/temporal-compressor.d.ts.map +1 -0
- package/dist/memory/temporal-compressor.js +335 -0
- package/dist/memory/temporal-compressor.js.map +1 -0
- package/dist/persistence/index.d.ts +11 -0
- package/dist/persistence/index.d.ts.map +1 -0
- package/dist/persistence/index.js +11 -0
- package/dist/persistence/index.js.map +1 -0
- package/dist/persistence/migrator.d.ts +40 -0
- package/dist/persistence/migrator.d.ts.map +1 -0
- package/dist/persistence/migrator.js +238 -0
- package/dist/persistence/migrator.js.map +1 -0
- package/dist/persistence/serializers.d.ts +45 -0
- package/dist/persistence/serializers.d.ts.map +1 -0
- package/dist/persistence/serializers.js +80 -0
- package/dist/persistence/serializers.js.map +1 -0
- package/dist/persistence/sqlite-persistence.d.ts +228 -0
- package/dist/persistence/sqlite-persistence.d.ts.map +1 -0
- package/dist/persistence/sqlite-persistence.js +588 -0
- package/dist/persistence/sqlite-persistence.js.map +1 -0
- package/dist/runtime/backends/acp-protocol.d.ts +49 -0
- package/dist/runtime/backends/acp-protocol.d.ts.map +1 -0
- package/dist/runtime/backends/acp-protocol.js +166 -0
- package/dist/runtime/backends/acp-protocol.js.map +1 -0
- package/dist/runtime/backends/acp.d.ts +26 -26
- package/dist/runtime/backends/acp.d.ts.map +1 -1
- package/dist/runtime/backends/acp.js +32 -156
- package/dist/runtime/backends/acp.js.map +1 -1
- package/dist/runtime/backends/index.d.ts +3 -1
- package/dist/runtime/backends/index.d.ts.map +1 -1
- package/dist/runtime/backends/index.js +3 -1
- package/dist/runtime/backends/index.js.map +1 -1
- package/dist/runtime/backends/macro-agent.d.ts +104 -0
- package/dist/runtime/backends/macro-agent.d.ts.map +1 -0
- package/dist/runtime/backends/macro-agent.js +107 -0
- package/dist/runtime/backends/macro-agent.js.map +1 -0
- package/dist/runtime/compute-provider.d.ts +87 -0
- package/dist/runtime/compute-provider.d.ts.map +1 -0
- package/dist/runtime/compute-provider.js +87 -0
- package/dist/runtime/compute-provider.js.map +1 -0
- package/dist/runtime/flows/learning.d.ts +10 -12
- package/dist/runtime/flows/learning.d.ts.map +1 -1
- package/dist/runtime/flows/learning.js +10 -23
- package/dist/runtime/flows/learning.js.map +1 -1
- package/dist/runtime/index.d.ts +3 -2
- package/dist/runtime/index.d.ts.map +1 -1
- package/dist/runtime/index.js +3 -1
- package/dist/runtime/index.js.map +1 -1
- package/dist/runtime/manager.d.ts +37 -4
- package/dist/runtime/manager.d.ts.map +1 -1
- package/dist/runtime/manager.js +139 -20
- package/dist/runtime/manager.js.map +1 -1
- package/dist/runtime/types.d.ts +38 -0
- package/dist/runtime/types.d.ts.map +1 -1
- package/dist/search/evaluator.d.ts +7 -0
- package/dist/search/evaluator.d.ts.map +1 -1
- package/dist/search/evaluator.js +24 -4
- package/dist/search/evaluator.js.map +1 -1
- package/dist/search/index.d.ts +2 -0
- package/dist/search/index.d.ts.map +1 -1
- package/dist/search/index.js +4 -0
- package/dist/search/index.js.map +1 -1
- package/dist/search/moe-gate.d.ts +124 -0
- package/dist/search/moe-gate.d.ts.map +1 -0
- package/dist/search/moe-gate.js +234 -0
- package/dist/search/moe-gate.js.map +1 -0
- package/dist/search/refinement-loop.d.ts +17 -0
- package/dist/search/refinement-loop.d.ts.map +1 -1
- package/dist/search/refinement-loop.js +77 -6
- package/dist/search/refinement-loop.js.map +1 -1
- package/dist/search/refinement-types.d.ts +2 -2
- package/dist/search/router.d.ts +32 -2
- package/dist/search/router.d.ts.map +1 -1
- package/dist/search/router.js +87 -4
- package/dist/search/router.js.map +1 -1
- package/dist/search/team-router.d.ts +91 -0
- package/dist/search/team-router.d.ts.map +1 -0
- package/dist/search/team-router.js +315 -0
- package/dist/search/team-router.js.map +1 -0
- package/dist/session-bank/git-reader.d.ts +44 -0
- package/dist/session-bank/git-reader.d.ts.map +1 -0
- package/dist/session-bank/git-reader.js +172 -0
- package/dist/session-bank/git-reader.js.map +1 -0
- package/dist/session-bank/index.d.ts +5 -0
- package/dist/session-bank/index.d.ts.map +1 -0
- package/dist/session-bank/index.js +4 -0
- package/dist/session-bank/index.js.map +1 -0
- package/dist/session-bank/parser.d.ts +50 -0
- package/dist/session-bank/parser.d.ts.map +1 -0
- package/dist/session-bank/parser.js +338 -0
- package/dist/session-bank/parser.js.map +1 -0
- package/dist/session-bank/session-bank.d.ts +40 -0
- package/dist/session-bank/session-bank.d.ts.map +1 -0
- package/dist/session-bank/session-bank.js +347 -0
- package/dist/session-bank/session-bank.js.map +1 -0
- package/dist/session-bank/types.d.ts +132 -0
- package/dist/session-bank/types.d.ts.map +1 -0
- package/dist/session-bank/types.js +7 -0
- package/dist/session-bank/types.js.map +1 -0
- package/dist/surfacing/index.d.ts +4 -0
- package/dist/surfacing/index.d.ts.map +1 -1
- package/dist/surfacing/index.js +3 -0
- package/dist/surfacing/index.js.map +1 -1
- package/dist/surfacing/publisher.d.ts +22 -0
- package/dist/surfacing/publisher.d.ts.map +1 -0
- package/dist/surfacing/publisher.js +9 -0
- package/dist/surfacing/publisher.js.map +1 -0
- package/dist/surfacing/skill-library.d.ts +12 -0
- package/dist/surfacing/skill-library.d.ts.map +1 -1
- package/dist/surfacing/skill-library.js +26 -0
- package/dist/surfacing/skill-library.js.map +1 -1
- package/dist/surfacing/skill-publisher.d.ts +43 -0
- package/dist/surfacing/skill-publisher.d.ts.map +1 -0
- package/dist/surfacing/skill-publisher.js +169 -0
- package/dist/surfacing/skill-publisher.js.map +1 -0
- package/dist/surfacing/sqlite-storage-adapter.d.ts +42 -0
- package/dist/surfacing/sqlite-storage-adapter.d.ts.map +1 -0
- package/dist/surfacing/sqlite-storage-adapter.js +199 -0
- package/dist/surfacing/sqlite-storage-adapter.js.map +1 -0
- package/dist/surfacing/team-skill-library.d.ts +180 -0
- package/dist/surfacing/team-skill-library.d.ts.map +1 -0
- package/dist/surfacing/team-skill-library.js +384 -0
- package/dist/surfacing/team-skill-library.js.map +1 -0
- package/dist/types/config.d.ts +1318 -44
- package/dist/types/config.d.ts.map +1 -1
- package/dist/types/config.js +243 -0
- package/dist/types/config.js.map +1 -1
- package/dist/types/dataclaw.d.ts +286 -0
- package/dist/types/dataclaw.d.ts.map +1 -0
- package/dist/types/dataclaw.js +84 -0
- package/dist/types/dataclaw.js.map +1 -0
- package/dist/types/index.d.ts +9 -2
- package/dist/types/index.d.ts.map +1 -1
- package/dist/types/index.js +13 -1
- package/dist/types/index.js.map +1 -1
- package/dist/types/knowledge-graph.d.ts +148 -0
- package/dist/types/knowledge-graph.d.ts.map +1 -0
- package/dist/types/knowledge-graph.js +40 -0
- package/dist/types/knowledge-graph.js.map +1 -0
- package/dist/types/knowledge.d.ts +280 -0
- package/dist/types/knowledge.d.ts.map +1 -0
- package/dist/types/knowledge.js +191 -0
- package/dist/types/knowledge.js.map +1 -0
- package/dist/types/memory.d.ts +52 -0
- package/dist/types/memory.d.ts.map +1 -1
- package/dist/types/memory.js +13 -0
- package/dist/types/memory.js.map +1 -1
- package/dist/types/playbook.d.ts +4 -0
- package/dist/types/playbook.d.ts.map +1 -1
- package/dist/types/playbook.js.map +1 -1
- package/dist/types/team-meta.d.ts +160 -0
- package/dist/types/team-meta.d.ts.map +1 -0
- package/dist/types/team-meta.js +42 -0
- package/dist/types/team-meta.js.map +1 -0
- package/dist/types/team-playbook.d.ts +276 -0
- package/dist/types/team-playbook.d.ts.map +1 -0
- package/dist/types/team-playbook.js +85 -0
- package/dist/types/team-playbook.js.map +1 -0
- package/dist/types/team-trajectory.d.ts +305 -0
- package/dist/types/team-trajectory.d.ts.map +1 -0
- package/dist/types/team-trajectory.js +304 -0
- package/dist/types/team-trajectory.js.map +1 -0
- package/dist/types/trajectory-source.d.ts +39 -0
- package/dist/types/trajectory-source.d.ts.map +1 -0
- package/dist/types/trajectory-source.js +2 -0
- package/dist/types/trajectory-source.js.map +1 -0
- package/dist/utils/error-classifier.d.ts +30 -0
- package/dist/utils/error-classifier.d.ts.map +1 -0
- package/dist/utils/error-classifier.js +85 -0
- package/dist/utils/error-classifier.js.map +1 -0
- package/dist/utils/frontmatter.d.ts +34 -0
- package/dist/utils/frontmatter.d.ts.map +1 -0
- package/dist/utils/frontmatter.js +93 -0
- package/dist/utils/frontmatter.js.map +1 -0
- package/dist/utils/index.d.ts +4 -0
- package/dist/utils/index.d.ts.map +1 -1
- package/dist/utils/index.js +4 -0
- package/dist/utils/index.js.map +1 -1
- package/dist/utils/partitioned-store.d.ts +93 -0
- package/dist/utils/partitioned-store.d.ts.map +1 -0
- package/dist/utils/partitioned-store.js +251 -0
- package/dist/utils/partitioned-store.js.map +1 -0
- package/dist/utils/trajectory-helpers.d.ts +39 -0
- package/dist/utils/trajectory-helpers.d.ts.map +1 -0
- package/dist/utils/trajectory-helpers.js +57 -0
- package/dist/utils/trajectory-helpers.js.map +1 -0
- package/dist/workspace/index.d.ts +6 -0
- package/dist/workspace/index.d.ts.map +1 -0
- package/dist/workspace/index.js +11 -0
- package/dist/workspace/index.js.map +1 -0
- package/dist/workspace/runner.d.ts +49 -0
- package/dist/workspace/runner.d.ts.map +1 -0
- package/dist/workspace/runner.js +219 -0
- package/dist/workspace/runner.js.map +1 -0
- package/dist/workspace/skill-converter.d.ts +18 -0
- package/dist/workspace/skill-converter.d.ts.map +1 -0
- package/dist/workspace/skill-converter.js +257 -0
- package/dist/workspace/skill-converter.js.map +1 -0
- package/dist/workspace/templates/index.d.ts +11 -0
- package/dist/workspace/templates/index.d.ts.map +1 -0
- package/dist/workspace/templates/index.js +21 -0
- package/dist/workspace/templates/index.js.map +1 -0
- package/dist/workspace/templates/knowledge-defrag.d.ts +25 -0
- package/dist/workspace/templates/knowledge-defrag.d.ts.map +1 -0
- package/dist/workspace/templates/knowledge-defrag.js +154 -0
- package/dist/workspace/templates/knowledge-defrag.js.map +1 -0
- package/dist/workspace/templates/knowledge-extraction.d.ts +25 -0
- package/dist/workspace/templates/knowledge-extraction.d.ts.map +1 -0
- package/dist/workspace/templates/knowledge-extraction.js +246 -0
- package/dist/workspace/templates/knowledge-extraction.js.map +1 -0
- package/dist/workspace/templates/meta-reflection.d.ts +47 -0
- package/dist/workspace/templates/meta-reflection.d.ts.map +1 -0
- package/dist/workspace/templates/meta-reflection.js +135 -0
- package/dist/workspace/templates/meta-reflection.js.map +1 -0
- package/dist/workspace/templates/playbook-extraction.d.ts +20 -0
- package/dist/workspace/templates/playbook-extraction.d.ts.map +1 -0
- package/dist/workspace/templates/playbook-extraction.js +189 -0
- package/dist/workspace/templates/playbook-extraction.js.map +1 -0
- package/dist/workspace/templates/refinement-analysis.d.ts +31 -0
- package/dist/workspace/templates/refinement-analysis.d.ts.map +1 -0
- package/dist/workspace/templates/refinement-analysis.js +107 -0
- package/dist/workspace/templates/refinement-analysis.js.map +1 -0
- package/dist/workspace/templates/solution-evaluation.d.ts +21 -0
- package/dist/workspace/templates/solution-evaluation.d.ts.map +1 -0
- package/dist/workspace/templates/solution-evaluation.js +131 -0
- package/dist/workspace/templates/solution-evaluation.js.map +1 -0
- package/dist/workspace/templates/team-playbook-extraction.d.ts +44 -0
- package/dist/workspace/templates/team-playbook-extraction.d.ts.map +1 -0
- package/dist/workspace/templates/team-playbook-extraction.js +497 -0
- package/dist/workspace/templates/team-playbook-extraction.js.map +1 -0
- package/dist/workspace/templates/team-trajectory-analysis.d.ts +19 -0
- package/dist/workspace/templates/team-trajectory-analysis.d.ts.map +1 -0
- package/dist/workspace/templates/team-trajectory-analysis.js +442 -0
- package/dist/workspace/templates/team-trajectory-analysis.js.map +1 -0
- package/dist/workspace/templates/trajectory-analysis.d.ts +19 -0
- package/dist/workspace/templates/trajectory-analysis.d.ts.map +1 -0
- package/dist/workspace/templates/trajectory-analysis.js +170 -0
- package/dist/workspace/templates/trajectory-analysis.js.map +1 -0
- package/dist/workspace/templates/usage-inference.d.ts +19 -0
- package/dist/workspace/templates/usage-inference.d.ts.map +1 -0
- package/dist/workspace/templates/usage-inference.js +125 -0
- package/dist/workspace/templates/usage-inference.js.map +1 -0
- package/dist/workspace/types.d.ts +152 -0
- package/dist/workspace/types.d.ts.map +1 -0
- package/dist/workspace/types.js +17 -0
- package/dist/workspace/types.js.map +1 -0
- package/docs/DESIGN-agentic-workspace.md +2057 -0
- package/docs/DESIGN-semantic-memory-knowledge-bank.md +1789 -0
- package/docs/DESIGN-session-bank.md +1134 -0
- package/docs/DESIGN-team-extraction-pipeline.md +1369 -0
- package/docs/PROPOSAL-team-aware-learning.md +1080 -0
- package/docs/RESEARCH-semantic-memory-knowledge-structures.md +517 -0
- package/docs/RESEARCH-team-trajectory-learning.md +553 -0
- package/gaps.md +204 -0
- package/package.json +27 -7
- package/references/agent-workspace/CLAUDE.md +74 -0
- package/references/agent-workspace/README.md +587 -0
- package/references/agent-workspace/media/banner.png +0 -0
- package/references/agent-workspace/package-lock.json +2061 -0
- package/references/agent-workspace/package.json +54 -0
- package/references/agent-workspace/src/handle.ts +122 -0
- package/references/agent-workspace/src/index.ts +32 -0
- package/references/agent-workspace/src/manager.ts +102 -0
- package/references/agent-workspace/src/readers/json.ts +71 -0
- package/references/agent-workspace/src/readers/markdown.ts +37 -0
- package/references/agent-workspace/src/readers/raw.ts +27 -0
- package/references/agent-workspace/src/types.ts +68 -0
- package/references/agent-workspace/src/validation.ts +93 -0
- package/references/agent-workspace/src/writers/json.ts +17 -0
- package/references/agent-workspace/src/writers/markdown.ts +27 -0
- package/references/agent-workspace/src/writers/raw.ts +22 -0
- package/references/agent-workspace/tests/errors.test.ts +652 -0
- package/references/agent-workspace/tests/handle.test.ts +144 -0
- package/references/agent-workspace/tests/manager.test.ts +124 -0
- package/references/agent-workspace/tests/readers.test.ts +205 -0
- package/references/agent-workspace/tests/validation.test.ts +196 -0
- package/references/agent-workspace/tests/writers.test.ts +108 -0
- package/references/agent-workspace/tsconfig.json +20 -0
- package/references/agent-workspace/tsup.config.ts +9 -0
- package/references/minimem/.claude/settings.json +7 -0
- package/references/minimem/.sudocode/issues.jsonl +18 -0
- package/references/minimem/.sudocode/specs.jsonl +1 -0
- package/references/minimem/CLAUDE.md +310 -0
- package/references/minimem/README.md +556 -0
- package/references/minimem/claude-plugin/.claude-plugin/plugin.json +10 -0
- package/references/minimem/claude-plugin/.mcp.json +7 -0
- package/references/minimem/claude-plugin/README.md +158 -0
- package/references/minimem/claude-plugin/commands/recall.md +47 -0
- package/references/minimem/claude-plugin/commands/remember.md +41 -0
- package/references/minimem/claude-plugin/hooks/__tests__/hooks.test.ts +272 -0
- package/references/minimem/claude-plugin/hooks/hooks.json +27 -0
- package/references/minimem/claude-plugin/hooks/session-end.sh +86 -0
- package/references/minimem/claude-plugin/hooks/session-start.sh +85 -0
- package/references/minimem/claude-plugin/skills/memory/SKILL.md +108 -0
- package/references/minimem/package-lock.json +5373 -0
- package/references/minimem/package.json +60 -0
- package/references/minimem/scripts/postbuild.js +35 -0
- package/references/minimem/src/__tests__/edge-cases.test.ts +371 -0
- package/references/minimem/src/__tests__/errors.test.ts +265 -0
- package/references/minimem/src/__tests__/helpers.ts +199 -0
- package/references/minimem/src/__tests__/internal.test.ts +407 -0
- package/references/minimem/src/__tests__/knowledge.test.ts +287 -0
- package/references/minimem/src/__tests__/minimem.integration.test.ts +1127 -0
- package/references/minimem/src/__tests__/session.test.ts +190 -0
- package/references/minimem/src/cli/__tests__/commands.test.ts +759 -0
- package/references/minimem/src/cli/commands/__tests__/conflicts.test.ts +141 -0
- package/references/minimem/src/cli/commands/append.ts +76 -0
- package/references/minimem/src/cli/commands/config.ts +262 -0
- package/references/minimem/src/cli/commands/conflicts.ts +413 -0
- package/references/minimem/src/cli/commands/daemon.ts +169 -0
- package/references/minimem/src/cli/commands/index.ts +12 -0
- package/references/minimem/src/cli/commands/init.ts +88 -0
- package/references/minimem/src/cli/commands/mcp.ts +177 -0
- package/references/minimem/src/cli/commands/push-pull.ts +213 -0
- package/references/minimem/src/cli/commands/search.ts +158 -0
- package/references/minimem/src/cli/commands/status.ts +84 -0
- package/references/minimem/src/cli/commands/sync-init.ts +290 -0
- package/references/minimem/src/cli/commands/sync.ts +70 -0
- package/references/minimem/src/cli/commands/upsert.ts +197 -0
- package/references/minimem/src/cli/config.ts +584 -0
- package/references/minimem/src/cli/index.ts +264 -0
- package/references/minimem/src/cli/shared.ts +161 -0
- package/references/minimem/src/cli/sync/__tests__/central.test.ts +152 -0
- package/references/minimem/src/cli/sync/__tests__/conflicts.test.ts +209 -0
- package/references/minimem/src/cli/sync/__tests__/daemon.test.ts +118 -0
- package/references/minimem/src/cli/sync/__tests__/detection.test.ts +207 -0
- package/references/minimem/src/cli/sync/__tests__/integration.test.ts +476 -0
- package/references/minimem/src/cli/sync/__tests__/registry.test.ts +363 -0
- package/references/minimem/src/cli/sync/__tests__/state.test.ts +255 -0
- package/references/minimem/src/cli/sync/__tests__/validation.test.ts +193 -0
- package/references/minimem/src/cli/sync/__tests__/watcher.test.ts +178 -0
- package/references/minimem/src/cli/sync/central.ts +292 -0
- package/references/minimem/src/cli/sync/conflicts.ts +204 -0
- package/references/minimem/src/cli/sync/daemon.ts +407 -0
- package/references/minimem/src/cli/sync/detection.ts +138 -0
- package/references/minimem/src/cli/sync/index.ts +107 -0
- package/references/minimem/src/cli/sync/operations.ts +373 -0
- package/references/minimem/src/cli/sync/registry.ts +279 -0
- package/references/minimem/src/cli/sync/state.ts +355 -0
- package/references/minimem/src/cli/sync/validation.ts +206 -0
- package/references/minimem/src/cli/sync/watcher.ts +234 -0
- package/references/minimem/src/cli/version.ts +34 -0
- package/references/minimem/src/core/index.ts +9 -0
- package/references/minimem/src/core/indexer.ts +628 -0
- package/references/minimem/src/core/searcher.ts +221 -0
- package/references/minimem/src/db/schema.ts +183 -0
- package/references/minimem/src/db/sqlite-vec.ts +24 -0
- package/references/minimem/src/embeddings/__tests__/embeddings.test.ts +431 -0
- package/references/minimem/src/embeddings/batch-gemini.ts +392 -0
- package/references/minimem/src/embeddings/batch-openai.ts +409 -0
- package/references/minimem/src/embeddings/embeddings.ts +434 -0
- package/references/minimem/src/index.ts +109 -0
- package/references/minimem/src/internal.ts +299 -0
- package/references/minimem/src/minimem.ts +1276 -0
- package/references/minimem/src/search/__tests__/hybrid.test.ts +247 -0
- package/references/minimem/src/search/graph.ts +234 -0
- package/references/minimem/src/search/hybrid.ts +151 -0
- package/references/minimem/src/search/search.ts +256 -0
- package/references/minimem/src/server/__tests__/mcp.test.ts +341 -0
- package/references/minimem/src/server/__tests__/tools.test.ts +364 -0
- package/references/minimem/src/server/mcp.ts +326 -0
- package/references/minimem/src/server/tools.ts +720 -0
- package/references/minimem/src/session.ts +460 -0
- package/references/minimem/tsconfig.json +19 -0
- package/references/minimem/tsup.config.ts +26 -0
- package/references/minimem/vitest.config.ts +24 -0
- package/references/sessionlog/.husky/pre-commit +1 -0
- package/references/sessionlog/.lintstagedrc.json +4 -0
- package/references/sessionlog/.prettierignore +4 -0
- package/references/sessionlog/.prettierrc.json +11 -0
- package/references/sessionlog/LICENSE +21 -0
- package/references/sessionlog/README.md +453 -0
- package/references/sessionlog/eslint.config.js +58 -0
- package/references/sessionlog/package-lock.json +3672 -0
- package/references/sessionlog/package.json +65 -0
- package/references/sessionlog/src/__tests__/agent-hooks.test.ts +570 -0
- package/references/sessionlog/src/__tests__/agent-registry.test.ts +127 -0
- package/references/sessionlog/src/__tests__/claude-code-hooks.test.ts +225 -0
- package/references/sessionlog/src/__tests__/claude-generator.test.ts +46 -0
- package/references/sessionlog/src/__tests__/commit-msg.test.ts +86 -0
- package/references/sessionlog/src/__tests__/cursor-agent.test.ts +224 -0
- package/references/sessionlog/src/__tests__/e2e-live.test.ts +890 -0
- package/references/sessionlog/src/__tests__/event-log.test.ts +183 -0
- package/references/sessionlog/src/__tests__/flush-sentinel.test.ts +105 -0
- package/references/sessionlog/src/__tests__/gemini-agent.test.ts +375 -0
- package/references/sessionlog/src/__tests__/git-hooks.test.ts +78 -0
- package/references/sessionlog/src/__tests__/hook-managers.test.ts +121 -0
- package/references/sessionlog/src/__tests__/lifecycle-tasks.test.ts +759 -0
- package/references/sessionlog/src/__tests__/opencode-agent.test.ts +338 -0
- package/references/sessionlog/src/__tests__/redaction.test.ts +136 -0
- package/references/sessionlog/src/__tests__/session-repo.test.ts +353 -0
- package/references/sessionlog/src/__tests__/session-store.test.ts +166 -0
- package/references/sessionlog/src/__tests__/setup-ccweb.test.ts +466 -0
- package/references/sessionlog/src/__tests__/skill-live.test.ts +461 -0
- package/references/sessionlog/src/__tests__/summarize.test.ts +348 -0
- package/references/sessionlog/src/__tests__/task-plan-e2e.test.ts +610 -0
- package/references/sessionlog/src/__tests__/task-plan-live.test.ts +632 -0
- package/references/sessionlog/src/__tests__/transcript-timestamp.test.ts +121 -0
- package/references/sessionlog/src/__tests__/types.test.ts +166 -0
- package/references/sessionlog/src/__tests__/utils.test.ts +333 -0
- package/references/sessionlog/src/__tests__/validation.test.ts +103 -0
- package/references/sessionlog/src/__tests__/worktree.test.ts +57 -0
- package/references/sessionlog/src/agent/agents/claude-code.ts +1089 -0
- package/references/sessionlog/src/agent/agents/cursor.ts +361 -0
- package/references/sessionlog/src/agent/agents/gemini-cli.ts +632 -0
- package/references/sessionlog/src/agent/agents/opencode.ts +540 -0
- package/references/sessionlog/src/agent/registry.ts +143 -0
- package/references/sessionlog/src/agent/session-types.ts +113 -0
- package/references/sessionlog/src/agent/types.ts +220 -0
- package/references/sessionlog/src/cli.ts +597 -0
- package/references/sessionlog/src/commands/clean.ts +133 -0
- package/references/sessionlog/src/commands/disable.ts +84 -0
- package/references/sessionlog/src/commands/doctor.ts +145 -0
- package/references/sessionlog/src/commands/enable.ts +202 -0
- package/references/sessionlog/src/commands/explain.ts +261 -0
- package/references/sessionlog/src/commands/reset.ts +105 -0
- package/references/sessionlog/src/commands/resume.ts +180 -0
- package/references/sessionlog/src/commands/rewind.ts +195 -0
- package/references/sessionlog/src/commands/setup-ccweb.ts +275 -0
- package/references/sessionlog/src/commands/status.ts +172 -0
- package/references/sessionlog/src/config.ts +165 -0
- package/references/sessionlog/src/events/event-log.ts +126 -0
- package/references/sessionlog/src/git-operations.ts +558 -0
- package/references/sessionlog/src/hooks/git-hooks.ts +165 -0
- package/references/sessionlog/src/hooks/lifecycle.ts +391 -0
- package/references/sessionlog/src/index.ts +650 -0
- package/references/sessionlog/src/security/redaction.ts +283 -0
- package/references/sessionlog/src/session/state-machine.ts +452 -0
- package/references/sessionlog/src/store/checkpoint-store.ts +509 -0
- package/references/sessionlog/src/store/native-store.ts +173 -0
- package/references/sessionlog/src/store/provider-types.ts +99 -0
- package/references/sessionlog/src/store/session-store.ts +266 -0
- package/references/sessionlog/src/strategy/attribution.ts +296 -0
- package/references/sessionlog/src/strategy/common.ts +207 -0
- package/references/sessionlog/src/strategy/content-overlap.ts +228 -0
- package/references/sessionlog/src/strategy/manual-commit.ts +988 -0
- package/references/sessionlog/src/strategy/types.ts +279 -0
- package/references/sessionlog/src/summarize/claude-generator.ts +115 -0
- package/references/sessionlog/src/summarize/summarize.ts +432 -0
- package/references/sessionlog/src/types.ts +508 -0
- package/references/sessionlog/src/utils/chunk-files.ts +49 -0
- package/references/sessionlog/src/utils/commit-message.ts +65 -0
- package/references/sessionlog/src/utils/detect-agent.ts +36 -0
- package/references/sessionlog/src/utils/hook-managers.ts +125 -0
- package/references/sessionlog/src/utils/ide-tags.ts +32 -0
- package/references/sessionlog/src/utils/paths.ts +79 -0
- package/references/sessionlog/src/utils/preview-rewind.ts +80 -0
- package/references/sessionlog/src/utils/rewind-conflict.ts +121 -0
- package/references/sessionlog/src/utils/shadow-branch.ts +109 -0
- package/references/sessionlog/src/utils/string-utils.ts +46 -0
- package/references/sessionlog/src/utils/todo-extract.ts +188 -0
- package/references/sessionlog/src/utils/trailers.ts +187 -0
- package/references/sessionlog/src/utils/transcript-parse.ts +177 -0
- package/references/sessionlog/src/utils/transcript-timestamp.ts +59 -0
- package/references/sessionlog/src/utils/tree-ops.ts +219 -0
- package/references/sessionlog/src/utils/tty.ts +72 -0
- package/references/sessionlog/src/utils/validation.ts +65 -0
- package/references/sessionlog/src/utils/worktree.ts +58 -0
- package/references/sessionlog/src/wire-types.ts +59 -0
- package/references/sessionlog/templates/setup-env.sh +153 -0
- package/references/sessionlog/tsconfig.json +18 -0
- package/references/sessionlog/vitest.config.ts +12 -0
- package/references/skill-tree/.claude/settings.json +6 -0
- package/references/skill-tree/.sudocode/issues.jsonl +19 -0
- package/references/skill-tree/.sudocode/specs.jsonl +3 -0
- package/references/skill-tree/CLAUDE.md +126 -0
- package/references/skill-tree/README.md +372 -0
- package/references/skill-tree/docs/GAPS_v1.md +221 -0
- package/references/skill-tree/docs/INTEGRATION_PLAN.md +467 -0
- package/references/skill-tree/docs/TODOS.md +91 -0
- package/references/skill-tree/docs/anthropic_skill_guide.md +1364 -0
- package/references/skill-tree/docs/design/federated-skill-trees.md +524 -0
- package/references/skill-tree/docs/design/multi-agent-sync.md +759 -0
- package/references/skill-tree/docs/scraper/BRAINSTORM.md +583 -0
- package/references/skill-tree/docs/scraper/POC_PLAN.md +420 -0
- package/references/skill-tree/docs/scraper/README.md +170 -0
- package/references/skill-tree/examples/basic-usage.ts +164 -0
- package/references/skill-tree/package-lock.json +1852 -0
- package/references/skill-tree/package.json +66 -0
- package/references/skill-tree/scraper/README.md +123 -0
- package/references/skill-tree/scraper/docs/DESIGN.md +683 -0
- package/references/skill-tree/scraper/docs/PLAN.md +336 -0
- package/references/skill-tree/scraper/drizzle.config.ts +10 -0
- package/references/skill-tree/scraper/package-lock.json +6329 -0
- package/references/skill-tree/scraper/package.json +68 -0
- package/references/skill-tree/scraper/test/fixtures/invalid-skill/missing-description.md +7 -0
- package/references/skill-tree/scraper/test/fixtures/invalid-skill/missing-name.md +7 -0
- package/references/skill-tree/scraper/test/fixtures/minimal-skill/SKILL.md +27 -0
- package/references/skill-tree/scraper/test/fixtures/skill-json/SKILL.json +21 -0
- package/references/skill-tree/scraper/test/fixtures/skill-with-meta/SKILL.md +54 -0
- package/references/skill-tree/scraper/test/fixtures/skill-with-meta/_meta.json +24 -0
- package/references/skill-tree/scraper/test/fixtures/valid-skill/SKILL.md +93 -0
- package/references/skill-tree/scraper/test/fixtures/valid-skill/_meta.json +22 -0
- package/references/skill-tree/scraper/tsup.config.ts +14 -0
- package/references/skill-tree/scraper/vitest.config.ts +17 -0
- package/references/skill-tree/scripts/convert-to-vitest.ts +166 -0
- package/references/skill-tree/skills/skill-writer/SKILL.md +339 -0
- package/references/skill-tree/skills/skill-writer/references/examples.md +326 -0
- package/references/skill-tree/skills/skill-writer/references/patterns.md +210 -0
- package/references/skill-tree/skills/skill-writer/references/quality-checklist.md +123 -0
- package/references/skill-tree/test/run-all.ts +106 -0
- package/references/skill-tree/test/utils.ts +128 -0
- package/references/skill-tree/vitest.config.ts +16 -0
- package/src/atlas.ts +583 -41
- package/src/bin/cli-utils.ts +220 -0
- package/src/bin/cognitive-core.ts +84 -392
- package/src/bin/commands/kb.ts +266 -0
- package/src/bin/commands/learn.ts +100 -0
- package/src/bin/commands/legacy.ts +182 -0
- package/src/bin/commands/run.ts +113 -0
- package/src/bin/commands/sessions.ts +221 -0
- package/src/bin/commands/skills.ts +146 -0
- package/src/embeddings/index.ts +3 -0
- package/src/embeddings/inverted-index.ts +134 -0
- package/src/embeddings/manager.ts +13 -8
- package/src/embeddings/provider.ts +10 -3
- package/src/embeddings/vector-store.ts +21 -9
- package/src/factory.ts +33 -16
- package/src/index.ts +231 -9
- package/src/learning/analyzer.ts +21 -37
- package/src/learning/energy-evaluator.ts +282 -0
- package/src/learning/healing-orchestrator.ts +383 -0
- package/src/learning/index.ts +104 -13
- package/src/learning/instant-loop.ts +357 -0
- package/src/learning/knowledge-extractor.ts +470 -0
- package/src/learning/maintenance-scheduler.ts +271 -0
- package/src/learning/meta-learner.ts +59 -23
- package/src/learning/reflexion-generator.ts +273 -0
- package/src/learning/team-ingester.ts +499 -0
- package/src/learning/team-meta-learner.ts +558 -0
- package/src/learning/team-pipeline.ts +364 -0
- package/src/learning/trajectory-sources/dataclaw.ts +403 -0
- package/src/learning/trajectory-sources/entire.ts +251 -0
- package/src/learning/trajectory-sources/file.ts +136 -0
- package/src/learning/trajectory-sources/huggingface.ts +248 -0
- package/src/learning/trajectory-sources/in-memory.ts +61 -0
- package/src/learning/trajectory-sources/index.ts +15 -0
- package/src/learning/trajectory-sources/pipeline.ts +69 -0
- package/src/learning/unified-pipeline.ts +921 -0
- package/src/memory/candidate-retrieval.ts +71 -0
- package/src/memory/causal-store.ts +273 -0
- package/src/memory/coherence.ts +252 -0
- package/src/memory/experience.ts +217 -50
- package/src/memory/graph-layers/base.ts +184 -0
- package/src/memory/graph-layers/causal.ts +16 -0
- package/src/memory/graph-layers/entity.ts +16 -0
- package/src/memory/graph-layers/index.ts +5 -0
- package/src/memory/graph-layers/semantic.ts +16 -0
- package/src/memory/graph-layers/temporal.ts +16 -0
- package/src/memory/index.ts +88 -0
- package/src/memory/knowledge-bank.ts +1317 -0
- package/src/memory/knowledge-defrag.ts +329 -0
- package/src/memory/knowledge-graph.ts +361 -0
- package/src/memory/meta.ts +78 -96
- package/src/memory/playbook.ts +239 -75
- package/src/memory/reasoning-bank.ts +458 -0
- package/src/memory/reflexion.ts +122 -0
- package/src/memory/search-provider.ts +35 -0
- package/src/memory/search-providers/index.ts +3 -0
- package/src/memory/search-providers/minimem.ts +84 -0
- package/src/memory/search-providers/text-similarity.ts +35 -0
- package/src/memory/skill-exporter.ts +357 -0
- package/src/memory/system.ts +80 -11
- package/src/memory/team-experience.ts +604 -0
- package/src/memory/temporal-compressor.ts +409 -0
- package/src/persistence/index.ts +37 -0
- package/src/persistence/migrator.ts +298 -0
- package/src/persistence/serializers.ts +79 -0
- package/src/persistence/sqlite-persistence.ts +925 -0
- package/src/runtime/backends/acp-protocol.ts +231 -0
- package/src/runtime/backends/acp.ts +57 -196
- package/src/runtime/backends/index.ts +14 -0
- package/src/runtime/backends/macro-agent.ts +177 -0
- package/src/runtime/compute-provider.ts +206 -0
- package/src/runtime/flows/learning.ts +25 -42
- package/src/runtime/index.ts +22 -0
- package/src/runtime/manager.ts +167 -23
- package/src/runtime/types.ts +41 -0
- package/src/search/evaluator.ts +29 -4
- package/src/search/index.ts +19 -0
- package/src/search/moe-gate.ts +304 -0
- package/src/search/refinement-loop.ts +106 -12
- package/src/search/router.ts +111 -4
- package/src/search/team-router.ts +459 -0
- package/src/session-bank/git-reader.ts +200 -0
- package/src/session-bank/index.ts +26 -0
- package/src/session-bank/parser.ts +548 -0
- package/src/session-bank/session-bank.ts +485 -0
- package/src/session-bank/types.ts +176 -0
- package/src/surfacing/index.ts +23 -0
- package/src/surfacing/publisher.ts +23 -0
- package/src/surfacing/skill-library.ts +31 -0
- package/src/surfacing/skill-publisher.ts +191 -0
- package/src/surfacing/sqlite-storage-adapter.ts +285 -0
- package/src/surfacing/team-skill-library.ts +610 -0
- package/src/types/config.ts +282 -0
- package/src/types/dataclaw.ts +99 -0
- package/src/types/huggingface-transformers.d.ts +12 -0
- package/src/types/index.ts +159 -0
- package/src/types/knowledge-graph.ts +246 -0
- package/src/types/knowledge.ts +388 -0
- package/src/types/memory.ts +30 -0
- package/src/types/playbook.ts +4 -0
- package/src/types/team-meta.ts +212 -0
- package/src/types/team-playbook.ts +384 -0
- package/src/types/team-trajectory.ts +673 -0
- package/src/types/trajectory-source.ts +47 -0
- package/src/utils/error-classifier.ts +113 -0
- package/src/utils/frontmatter.ts +118 -0
- package/src/utils/index.ts +25 -0
- package/src/utils/partitioned-store.ts +299 -0
- package/src/utils/trajectory-helpers.ts +79 -0
- package/src/workspace/index.ts +48 -0
- package/src/workspace/runner.ts +281 -0
- package/src/workspace/skill-converter.ts +288 -0
- package/src/workspace/templates/index.ts +64 -0
- package/src/workspace/templates/knowledge-defrag.ts +223 -0
- package/src/workspace/templates/knowledge-extraction.ts +337 -0
- package/src/workspace/templates/meta-reflection.ts +208 -0
- package/src/workspace/templates/playbook-extraction.ts +240 -0
- package/src/workspace/templates/refinement-analysis.ts +162 -0
- package/src/workspace/templates/solution-evaluation.ts +199 -0
- package/src/workspace/templates/team-playbook-extraction.ts +631 -0
- package/src/workspace/templates/team-trajectory-analysis.ts +564 -0
- package/src/workspace/templates/trajectory-analysis.ts +234 -0
- package/src/workspace/templates/usage-inference.ts +163 -0
- package/src/workspace/types.ts +241 -0
- package/tests/atlas-knowledge.test.ts +165 -0
- package/tests/embeddings/inverted-index.test.ts +138 -0
- package/tests/feature-toggles.test.ts +275 -0
- package/tests/gap-fixes.test.ts +1116 -0
- package/tests/integration/cli-e2e.test.ts +621 -0
- package/tests/integration/dataclaw-e2e.test.ts +559 -0
- package/tests/integration/e2e.test.ts +412 -4
- package/tests/integration/entire-e2e.test.ts +376 -0
- package/tests/integration/huggingface-e2e.test.ts +627 -0
- package/tests/integration/persistence-e2e.test.ts +741 -0
- package/tests/integration/phase-e2e.test.ts +1143 -0
- package/tests/integration/session-bank.test.ts +231 -0
- package/tests/integration/sessionlog-e2e.test.ts +329 -0
- package/tests/integration/skill-tree-wiring.test.ts +152 -0
- package/tests/integration/unified-pipeline-e2e.test.ts +634 -0
- package/tests/learning/analyzer.test.ts +1 -1
- package/tests/learning/dataclaw-trajectory-source.test.ts +642 -0
- package/tests/learning/energy-evaluator.test.ts +180 -0
- package/tests/learning/entire-trajectory-source.test.ts +380 -0
- package/tests/learning/healing-orchestrator.test.ts +269 -0
- package/tests/learning/huggingface-trajectory-source.test.ts +817 -0
- package/tests/learning/instant-loop.test.ts +243 -0
- package/tests/learning/knowledge-extractor.test.ts +491 -0
- package/tests/learning/maintenance-scheduler.test.ts +191 -0
- package/tests/learning/reflexion-generator.test.ts +411 -0
- package/tests/learning/team-ingester.test.ts +349 -0
- package/tests/learning/team-meta-learner.test.ts +618 -0
- package/tests/learning/team-pipeline.test.ts +334 -0
- package/tests/learning/trajectory-sources.test.ts +320 -0
- package/tests/learning/unified-pipeline.test.ts +322 -0
- package/tests/mcp/playbook-server.test.ts +6 -1
- package/tests/memory/causal-store.test.ts +276 -0
- package/tests/memory/coherence.test.ts +232 -0
- package/tests/memory/experience.test.ts +8 -3
- package/tests/memory/graph-layers/semantic.test.ts +219 -0
- package/tests/memory/knowledge-bank-extraction.test.ts +558 -0
- package/tests/memory/knowledge-bank.test.ts +705 -0
- package/tests/memory/knowledge-defrag.test.ts +366 -0
- package/tests/memory/knowledge-evolution.test.ts +563 -0
- package/tests/memory/knowledge-graph.test.ts +492 -0
- package/tests/memory/knowledge-inbox.test.ts +258 -0
- package/tests/memory/knowledge-minimem.test.ts +251 -0
- package/tests/memory/playbook.test.ts +307 -1
- package/tests/memory/provenance.test.ts +11 -2
- package/tests/memory/reasoning-bank.test.ts +239 -0
- package/tests/memory/reflexion.test.ts +166 -0
- package/tests/memory/skill-exporter.test.ts +475 -0
- package/tests/memory/system.test.ts +6 -1
- package/tests/memory/team-experience.test.ts +411 -0
- package/tests/memory/temporal-compressor.test.ts +318 -0
- package/tests/persistence/migrator.test.ts +1009 -0
- package/tests/persistence/sqlite-persistence.test.ts +635 -0
- package/tests/runtime/agent-manager.test.ts +7 -2
- package/tests/runtime/compute-provider.test.ts +288 -0
- package/tests/runtime/delegate.test.ts +354 -0
- package/tests/runtime/macro-agent-backend.test.ts +266 -0
- package/tests/search/moe-gate.test.ts +250 -0
- package/tests/search/refinement-loop.test.ts +11 -2
- package/tests/search/router.test.ts +81 -2
- package/tests/search/team-router.test.ts +376 -0
- package/tests/session-bank/fixtures/multi-tool-session/full.jsonl +12 -0
- package/tests/session-bank/fixtures/multi-tool-session/metadata.json +28 -0
- package/tests/session-bank/fixtures/root-metadata.json +18 -0
- package/tests/session-bank/fixtures/sessionlog-root-metadata.json +16 -0
- package/tests/session-bank/fixtures/sessionlog-session/full.jsonl +6 -0
- package/tests/session-bank/fixtures/sessionlog-session/metadata.json +55 -0
- package/tests/session-bank/fixtures/simple-session/full.jsonl +6 -0
- package/tests/session-bank/fixtures/simple-session/metadata.json +38 -0
- package/tests/session-bank/git-reader.test.ts +232 -0
- package/tests/session-bank/parser.test.ts +453 -0
- package/tests/session-bank/session-bank.test.ts +546 -0
- package/tests/surfacing/skill-library.test.ts +6 -1
- package/tests/surfacing/skill-publisher.test.ts +364 -0
- package/tests/surfacing/sqlite-storage-adapter.test.ts +206 -0
- package/tests/surfacing/team-skill-library.test.ts +444 -0
- package/tests/types/team-meta.test.ts +147 -0
- package/tests/types/team-playbook.test.ts +246 -0
- package/tests/types/team-trajectory.test.ts +557 -0
- package/tests/utils/frontmatter.test.ts +208 -0
- package/tests/utils/partitioned-store.test.ts +230 -0
- package/tests/workspace/full-flow.test.ts +845 -0
- package/tests/workspace/manager.test.ts +215 -0
- package/tests/workspace/runner.test.ts +336 -0
- package/tests/workspace/skill-converter.test.ts +205 -0
- package/tests/workspace/templates/knowledge-extraction.test.ts +235 -0
- package/tests/workspace/templates/team-playbook-extraction.test.ts +341 -0
- package/tests/workspace/templates/team-trajectory-analysis.test.ts +417 -0
- package/src/learning/llm-extractor.ts +0 -542
- package/src/learning/pipeline.ts +0 -244
- package/tests/learning/pipeline.test.ts +0 -176
|
@@ -0,0 +1,1276 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import fs from "node:fs/promises";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { DatabaseSync } from "node:sqlite";
|
|
5
|
+
import chokidar, { type FSWatcher } from "chokidar";
|
|
6
|
+
|
|
7
|
+
import {
|
|
8
|
+
buildFileEntry,
|
|
9
|
+
chunkMarkdown,
|
|
10
|
+
ensureDir,
|
|
11
|
+
extractChunkMetadata,
|
|
12
|
+
hashText,
|
|
13
|
+
listMemoryFiles,
|
|
14
|
+
logError,
|
|
15
|
+
type MemoryChunk,
|
|
16
|
+
type MemoryFileEntry,
|
|
17
|
+
parseEmbedding,
|
|
18
|
+
vectorToBlob,
|
|
19
|
+
} from "./internal.js";
|
|
20
|
+
import { bm25RankToScore, buildFtsQuery, mergeHybridResults } from "./search/hybrid.js";
|
|
21
|
+
import { searchKeyword, searchVector, buildKnowledgeFilterSql } from "./search/search.js";
|
|
22
|
+
import { ensureMemoryIndexSchema } from "./db/schema.js";
|
|
23
|
+
import { parseFrontmatter, type MemoryFrontmatter, type KnowledgeLink } from "./session.js";
|
|
24
|
+
import {
|
|
25
|
+
getLinksFrom,
|
|
26
|
+
getLinksTo,
|
|
27
|
+
getNeighbors,
|
|
28
|
+
getPathBetween,
|
|
29
|
+
type GraphLink,
|
|
30
|
+
type GraphNeighbor,
|
|
31
|
+
} from "./search/graph.js";
|
|
32
|
+
import { loadSqliteVecExtension } from "./db/sqlite-vec.js";
|
|
33
|
+
import {
|
|
34
|
+
createEmbeddingProvider,
|
|
35
|
+
type EmbeddingProvider,
|
|
36
|
+
type EmbeddingProviderOptions,
|
|
37
|
+
type OpenAiEmbeddingClient,
|
|
38
|
+
type GeminiEmbeddingClient,
|
|
39
|
+
} from "./embeddings/embeddings.js";
|
|
40
|
+
import { runOpenAiEmbeddingBatches, type OpenAiBatchRequest, OPENAI_BATCH_ENDPOINT } from "./embeddings/batch-openai.js";
|
|
41
|
+
import { runGeminiEmbeddingBatches, type GeminiBatchRequest } from "./embeddings/batch-gemini.js";
|
|
42
|
+
|
|
43
|
+
const META_KEY = "memory_index_meta_v1";
|
|
44
|
+
const SNIPPET_MAX_CHARS = 700;
|
|
45
|
+
const VECTOR_TABLE = "chunks_vec";
|
|
46
|
+
const FTS_TABLE = "chunks_fts";
|
|
47
|
+
const EMBEDDING_CACHE_TABLE = "embedding_cache";
|
|
48
|
+
const EMBEDDING_BATCH_MAX_TOKENS = 8000;
|
|
49
|
+
const EMBEDDING_APPROX_CHARS_PER_TOKEN = 1;
|
|
50
|
+
const EMBEDDING_INDEX_CONCURRENCY = 4;
|
|
51
|
+
const EMBEDDING_RETRY_MAX_ATTEMPTS = 3;
|
|
52
|
+
const EMBEDDING_RETRY_BASE_DELAY_MS = 500;
|
|
53
|
+
const EMBEDDING_RETRY_MAX_DELAY_MS = 8000;
|
|
54
|
+
const VECTOR_LOAD_TIMEOUT_MS = 30_000;
|
|
55
|
+
const EMBEDDING_QUERY_TIMEOUT_REMOTE_MS = 60_000;
|
|
56
|
+
const EMBEDDING_QUERY_TIMEOUT_LOCAL_MS = 5 * 60_000;
|
|
57
|
+
|
|
58
|
+
export type MinimemConfig = {
|
|
59
|
+
/** Directory containing memory files (MEMORY.md, memory/*.md) */
|
|
60
|
+
memoryDir: string;
|
|
61
|
+
/** Path to SQLite database. Defaults to memoryDir/.minimem/index.db */
|
|
62
|
+
dbPath?: string;
|
|
63
|
+
/** Embedding provider options */
|
|
64
|
+
embedding: EmbeddingProviderOptions;
|
|
65
|
+
/** Chunking configuration */
|
|
66
|
+
chunking?: {
|
|
67
|
+
/** Tokens per chunk (default: 256) */
|
|
68
|
+
tokens?: number;
|
|
69
|
+
/** Overlap tokens between chunks (default: 32) */
|
|
70
|
+
overlap?: number;
|
|
71
|
+
};
|
|
72
|
+
/** Embedding cache configuration */
|
|
73
|
+
cache?: {
|
|
74
|
+
/** Enable embedding cache (default: true) */
|
|
75
|
+
enabled?: boolean;
|
|
76
|
+
/** Max cache entries before LRU pruning (default: 10000) */
|
|
77
|
+
maxEntries?: number;
|
|
78
|
+
};
|
|
79
|
+
/** Hybrid search configuration */
|
|
80
|
+
hybrid?: {
|
|
81
|
+
/** Enable hybrid search (default: true) */
|
|
82
|
+
enabled?: boolean;
|
|
83
|
+
/** Weight for vector search (default: 0.7) */
|
|
84
|
+
vectorWeight?: number;
|
|
85
|
+
/** Weight for keyword search (default: 0.3) */
|
|
86
|
+
textWeight?: number;
|
|
87
|
+
/** Candidate multiplier for search (default: 2.0) */
|
|
88
|
+
candidateMultiplier?: number;
|
|
89
|
+
};
|
|
90
|
+
/** Query configuration */
|
|
91
|
+
query?: {
|
|
92
|
+
/** Max results (default: 10) */
|
|
93
|
+
maxResults?: number;
|
|
94
|
+
/** Min score threshold (default: 0.3) */
|
|
95
|
+
minScore?: number;
|
|
96
|
+
};
|
|
97
|
+
/** File watching configuration */
|
|
98
|
+
watch?: {
|
|
99
|
+
/** Enable file watching (default: true) */
|
|
100
|
+
enabled?: boolean;
|
|
101
|
+
/** Debounce delay in ms (default: 1000) */
|
|
102
|
+
debounceMs?: number;
|
|
103
|
+
};
|
|
104
|
+
/** Batch embedding configuration */
|
|
105
|
+
batch?: {
|
|
106
|
+
/** Enable batch embedding API (default: false) */
|
|
107
|
+
enabled?: boolean;
|
|
108
|
+
/** Wait for batch completion (default: true) */
|
|
109
|
+
wait?: boolean;
|
|
110
|
+
/** Concurrent batch requests (default: 2) */
|
|
111
|
+
concurrency?: number;
|
|
112
|
+
/** Poll interval in ms (default: 2000) */
|
|
113
|
+
pollIntervalMs?: number;
|
|
114
|
+
/** Timeout in ms (default: 60 minutes) */
|
|
115
|
+
timeoutMs?: number;
|
|
116
|
+
};
|
|
117
|
+
/** sqlite-vec extension path (optional) */
|
|
118
|
+
vectorExtensionPath?: string;
|
|
119
|
+
/** Debug logging function */
|
|
120
|
+
debug?: (message: string, data?: Record<string, unknown>) => void;
|
|
121
|
+
};
|
|
122
|
+
|
|
123
|
+
export type MinimemSearchResult = {
|
|
124
|
+
path: string;
|
|
125
|
+
startLine: number;
|
|
126
|
+
endLine: number;
|
|
127
|
+
score: number;
|
|
128
|
+
snippet: string;
|
|
129
|
+
};
|
|
130
|
+
|
|
131
|
+
type MemoryIndexMeta = {
|
|
132
|
+
model: string;
|
|
133
|
+
provider: string;
|
|
134
|
+
providerKey?: string;
|
|
135
|
+
chunkTokens: number;
|
|
136
|
+
chunkOverlap: number;
|
|
137
|
+
vectorDims?: number;
|
|
138
|
+
};
|
|
139
|
+
|
|
140
|
+
export class Minimem {
|
|
141
|
+
private readonly memoryDir: string;
|
|
142
|
+
private readonly dbPath: string;
|
|
143
|
+
private readonly chunking: { tokens: number; overlap: number };
|
|
144
|
+
private readonly cache: { enabled: boolean; maxEntries: number };
|
|
145
|
+
private readonly hybrid: {
|
|
146
|
+
enabled: boolean;
|
|
147
|
+
vectorWeight: number;
|
|
148
|
+
textWeight: number;
|
|
149
|
+
candidateMultiplier: number;
|
|
150
|
+
};
|
|
151
|
+
private readonly queryConfig: { maxResults: number; minScore: number };
|
|
152
|
+
private readonly watchConfig: { enabled: boolean; debounceMs: number };
|
|
153
|
+
private readonly batchConfig: {
|
|
154
|
+
enabled: boolean;
|
|
155
|
+
wait: boolean;
|
|
156
|
+
concurrency: number;
|
|
157
|
+
pollIntervalMs: number;
|
|
158
|
+
timeoutMs: number;
|
|
159
|
+
};
|
|
160
|
+
private readonly vectorExtensionPath?: string;
|
|
161
|
+
private readonly debug?: (message: string, data?: Record<string, unknown>) => void;
|
|
162
|
+
|
|
163
|
+
private provider!: EmbeddingProvider;
|
|
164
|
+
private openAi?: OpenAiEmbeddingClient;
|
|
165
|
+
private gemini?: GeminiEmbeddingClient;
|
|
166
|
+
private providerKey: string = "";
|
|
167
|
+
private providerFallbackReason?: string;
|
|
168
|
+
private db!: DatabaseSync;
|
|
169
|
+
|
|
170
|
+
private readonly vector: {
|
|
171
|
+
enabled: boolean;
|
|
172
|
+
available: boolean | null;
|
|
173
|
+
extensionPath?: string;
|
|
174
|
+
loadError?: string;
|
|
175
|
+
dims?: number;
|
|
176
|
+
};
|
|
177
|
+
private readonly fts: {
|
|
178
|
+
enabled: boolean;
|
|
179
|
+
available: boolean;
|
|
180
|
+
loadError?: string;
|
|
181
|
+
};
|
|
182
|
+
|
|
183
|
+
private vectorReady: Promise<boolean> | null = null;
|
|
184
|
+
private watcher: FSWatcher | null = null;
|
|
185
|
+
private watchTimer: NodeJS.Timeout | null = null;
|
|
186
|
+
private closed = false;
|
|
187
|
+
private dirty = true;
|
|
188
|
+
private syncing: Promise<void> | null = null;
|
|
189
|
+
private syncLock = false;
|
|
190
|
+
private embeddingOptions: EmbeddingProviderOptions;
|
|
191
|
+
|
|
192
|
+
private constructor(config: MinimemConfig) {
|
|
193
|
+
this.memoryDir = path.resolve(config.memoryDir);
|
|
194
|
+
this.dbPath = config.dbPath ?? path.join(this.memoryDir, ".minimem", "index.db");
|
|
195
|
+
this.chunking = {
|
|
196
|
+
tokens: config.chunking?.tokens ?? 256,
|
|
197
|
+
overlap: config.chunking?.overlap ?? 32,
|
|
198
|
+
};
|
|
199
|
+
this.cache = {
|
|
200
|
+
enabled: config.cache?.enabled ?? true,
|
|
201
|
+
maxEntries: config.cache?.maxEntries ?? 10000,
|
|
202
|
+
};
|
|
203
|
+
this.hybrid = {
|
|
204
|
+
enabled: config.hybrid?.enabled ?? true,
|
|
205
|
+
vectorWeight: config.hybrid?.vectorWeight ?? 0.7,
|
|
206
|
+
textWeight: config.hybrid?.textWeight ?? 0.3,
|
|
207
|
+
candidateMultiplier: config.hybrid?.candidateMultiplier ?? 2.0,
|
|
208
|
+
};
|
|
209
|
+
this.queryConfig = {
|
|
210
|
+
maxResults: config.query?.maxResults ?? 10,
|
|
211
|
+
minScore: config.query?.minScore ?? 0.3,
|
|
212
|
+
};
|
|
213
|
+
this.watchConfig = {
|
|
214
|
+
enabled: config.watch?.enabled ?? true,
|
|
215
|
+
debounceMs: config.watch?.debounceMs ?? 1000,
|
|
216
|
+
};
|
|
217
|
+
this.batchConfig = {
|
|
218
|
+
enabled: config.batch?.enabled ?? false,
|
|
219
|
+
wait: config.batch?.wait ?? true,
|
|
220
|
+
concurrency: config.batch?.concurrency ?? 2,
|
|
221
|
+
pollIntervalMs: config.batch?.pollIntervalMs ?? 2000,
|
|
222
|
+
timeoutMs: config.batch?.timeoutMs ?? 60 * 60 * 1000,
|
|
223
|
+
};
|
|
224
|
+
this.vectorExtensionPath = config.vectorExtensionPath;
|
|
225
|
+
this.debug = config.debug;
|
|
226
|
+
this.embeddingOptions = config.embedding;
|
|
227
|
+
|
|
228
|
+
this.vector = {
|
|
229
|
+
enabled: true,
|
|
230
|
+
available: null,
|
|
231
|
+
extensionPath: this.vectorExtensionPath,
|
|
232
|
+
};
|
|
233
|
+
this.fts = { enabled: this.hybrid.enabled, available: false };
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
static async create(config: MinimemConfig): Promise<Minimem> {
|
|
237
|
+
const instance = new Minimem(config);
|
|
238
|
+
await instance.initialize();
|
|
239
|
+
return instance;
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
private async initialize(): Promise<void> {
|
|
243
|
+
// Create embedding provider
|
|
244
|
+
const providerResult = await createEmbeddingProvider(this.embeddingOptions);
|
|
245
|
+
this.provider = providerResult.provider;
|
|
246
|
+
this.openAi = providerResult.openAi;
|
|
247
|
+
this.gemini = providerResult.gemini;
|
|
248
|
+
this.providerKey = this.computeProviderKey();
|
|
249
|
+
this.providerFallbackReason = providerResult.fallbackReason;
|
|
250
|
+
|
|
251
|
+
// Log warning if in BM25-only fallback mode
|
|
252
|
+
if (this.provider.id === "none") {
|
|
253
|
+
this.debug?.("Running in BM25-only mode (no embedding API available)");
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
// Open database
|
|
257
|
+
this.db = this.openDatabase();
|
|
258
|
+
this.ensureSchema();
|
|
259
|
+
|
|
260
|
+
// Check for existing vector dims
|
|
261
|
+
const meta = this.readMeta();
|
|
262
|
+
if (meta?.vectorDims) {
|
|
263
|
+
this.vector.dims = meta.vectorDims;
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
// Start file watcher
|
|
267
|
+
if (this.watchConfig.enabled) {
|
|
268
|
+
this.ensureWatcher();
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
private openDatabase(): DatabaseSync {
|
|
273
|
+
const dbDir = path.dirname(this.dbPath);
|
|
274
|
+
ensureDir(dbDir);
|
|
275
|
+
return new DatabaseSync(this.dbPath);
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
private ensureSchema(): void {
|
|
279
|
+
const result = ensureMemoryIndexSchema({
|
|
280
|
+
db: this.db,
|
|
281
|
+
embeddingCacheTable: EMBEDDING_CACHE_TABLE,
|
|
282
|
+
ftsTable: FTS_TABLE,
|
|
283
|
+
ftsEnabled: this.fts.enabled,
|
|
284
|
+
});
|
|
285
|
+
this.fts.available = result.ftsAvailable;
|
|
286
|
+
if (result.ftsError) {
|
|
287
|
+
this.fts.loadError = result.ftsError;
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
private computeProviderKey(): string {
|
|
292
|
+
const parts: string[] = [this.provider.id, this.provider.model];
|
|
293
|
+
if (this.openAi) {
|
|
294
|
+
parts.push(this.openAi.baseUrl);
|
|
295
|
+
}
|
|
296
|
+
if (this.gemini) {
|
|
297
|
+
parts.push(this.gemini.baseUrl);
|
|
298
|
+
}
|
|
299
|
+
return hashText(parts.join(":"));
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
private readMeta(): MemoryIndexMeta | null {
|
|
303
|
+
try {
|
|
304
|
+
const row = this.db.prepare(`SELECT value FROM meta WHERE key = ?`).get(META_KEY) as
|
|
305
|
+
| { value: string }
|
|
306
|
+
| undefined;
|
|
307
|
+
if (!row?.value) return null;
|
|
308
|
+
return JSON.parse(row.value) as MemoryIndexMeta;
|
|
309
|
+
} catch {
|
|
310
|
+
return null;
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
private writeMeta(meta: MemoryIndexMeta): void {
|
|
315
|
+
this.db
|
|
316
|
+
.prepare(`INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)`)
|
|
317
|
+
.run(META_KEY, JSON.stringify(meta));
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
private ensureWatcher(): void {
|
|
321
|
+
if (this.watcher) return;
|
|
322
|
+
const memorySubDir = path.join(this.memoryDir, "memory");
|
|
323
|
+
const memoryFile = path.join(this.memoryDir, "MEMORY.md");
|
|
324
|
+
|
|
325
|
+
this.watcher = chokidar.watch([memoryFile, memorySubDir], {
|
|
326
|
+
ignoreInitial: true,
|
|
327
|
+
persistent: true,
|
|
328
|
+
awaitWriteFinish: { stabilityThreshold: 200, pollInterval: 50 },
|
|
329
|
+
});
|
|
330
|
+
|
|
331
|
+
const scheduleSync = () => {
|
|
332
|
+
this.dirty = true;
|
|
333
|
+
if (this.watchTimer) clearTimeout(this.watchTimer);
|
|
334
|
+
this.watchTimer = setTimeout(() => {
|
|
335
|
+
void this.sync({ reason: "watch" }).catch((err) => {
|
|
336
|
+
this.debug?.(`memory sync failed (watch): ${String(err)}`);
|
|
337
|
+
});
|
|
338
|
+
}, this.watchConfig.debounceMs);
|
|
339
|
+
};
|
|
340
|
+
|
|
341
|
+
this.watcher.on("add", scheduleSync);
|
|
342
|
+
this.watcher.on("change", scheduleSync);
|
|
343
|
+
this.watcher.on("unlink", scheduleSync);
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
/**
|
|
347
|
+
* Check if the index is stale by comparing file mtimes against stored values.
|
|
348
|
+
* This is a lightweight check (stat calls only, no file reads).
|
|
349
|
+
*/
|
|
350
|
+
private async isStale(): Promise<boolean> {
|
|
351
|
+
try {
|
|
352
|
+
const files = await listMemoryFiles(this.memoryDir);
|
|
353
|
+
|
|
354
|
+
// Get stored file records
|
|
355
|
+
const stored = this.db
|
|
356
|
+
.prepare(`SELECT path, mtime FROM files WHERE source = ?`)
|
|
357
|
+
.all("memory") as Array<{ path: string; mtime: number }>;
|
|
358
|
+
|
|
359
|
+
// Quick check: different file count means stale
|
|
360
|
+
if (files.length !== stored.length) {
|
|
361
|
+
this.debug?.(`Stale: file count changed (${stored.length} -> ${files.length})`);
|
|
362
|
+
return true;
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
// Build lookup map of stored mtimes
|
|
366
|
+
const storedMap = new Map(stored.map((f) => [f.path, f.mtime]));
|
|
367
|
+
|
|
368
|
+
// Check each file's mtime against stored value
|
|
369
|
+
for (const absPath of files) {
|
|
370
|
+
const relPath = path.relative(this.memoryDir, absPath).replace(/\\/g, "/");
|
|
371
|
+
const storedMtime = storedMap.get(relPath);
|
|
372
|
+
|
|
373
|
+
// File not in index = stale
|
|
374
|
+
if (storedMtime === undefined) {
|
|
375
|
+
this.debug?.(`Stale: new file ${relPath}`);
|
|
376
|
+
return true;
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
// Check mtime
|
|
380
|
+
const stat = await fs.stat(absPath);
|
|
381
|
+
const currentMtime = Math.floor(stat.mtimeMs);
|
|
382
|
+
if (currentMtime !== storedMtime) {
|
|
383
|
+
this.debug?.(`Stale: mtime changed for ${relPath}`);
|
|
384
|
+
return true;
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
return false;
|
|
389
|
+
} catch (err) {
|
|
390
|
+
// On error, assume stale to be safe
|
|
391
|
+
this.debug?.(`Stale check failed: ${String(err)}`);
|
|
392
|
+
return true;
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
async search(
|
|
397
|
+
query: string,
|
|
398
|
+
opts?: { maxResults?: number; minScore?: number; type?: string },
|
|
399
|
+
): Promise<MinimemSearchResult[]> {
|
|
400
|
+
// Check staleness: use dirty flag if watcher is on, otherwise check mtimes
|
|
401
|
+
if (this.dirty || (!this.watchConfig.enabled && (await this.isStale()))) {
|
|
402
|
+
await this.sync({ reason: "search" });
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
const cleaned = query.trim();
|
|
406
|
+
if (!cleaned) return [];
|
|
407
|
+
|
|
408
|
+
const minScore = opts?.minScore ?? this.queryConfig.minScore;
|
|
409
|
+
const maxResults = opts?.maxResults ?? this.queryConfig.maxResults;
|
|
410
|
+
const candidates = Math.min(
|
|
411
|
+
200,
|
|
412
|
+
Math.max(1, Math.floor(maxResults * this.hybrid.candidateMultiplier)),
|
|
413
|
+
);
|
|
414
|
+
|
|
415
|
+
const sourceFilter = { sql: "", params: [] as string[] };
|
|
416
|
+
|
|
417
|
+
const keywordResults = this.hybrid.enabled && this.fts.available
|
|
418
|
+
? await searchKeyword({
|
|
419
|
+
db: this.db,
|
|
420
|
+
ftsTable: FTS_TABLE,
|
|
421
|
+
providerModel: this.provider.model,
|
|
422
|
+
query: cleaned,
|
|
423
|
+
limit: candidates,
|
|
424
|
+
snippetMaxChars: SNIPPET_MAX_CHARS,
|
|
425
|
+
sourceFilter,
|
|
426
|
+
buildFtsQuery,
|
|
427
|
+
bm25RankToScore,
|
|
428
|
+
}).catch(() => [])
|
|
429
|
+
: [];
|
|
430
|
+
|
|
431
|
+
const queryVec = await this.embedQueryWithTimeout(cleaned);
|
|
432
|
+
const hasVector = queryVec.some((v) => v !== 0);
|
|
433
|
+
const vectorResults = hasVector
|
|
434
|
+
? await searchVector({
|
|
435
|
+
db: this.db,
|
|
436
|
+
vectorTable: VECTOR_TABLE,
|
|
437
|
+
providerModel: this.provider.model,
|
|
438
|
+
queryVec,
|
|
439
|
+
limit: candidates,
|
|
440
|
+
snippetMaxChars: SNIPPET_MAX_CHARS,
|
|
441
|
+
ensureVectorReady: (dims) => this.ensureVectorReady(dims),
|
|
442
|
+
sourceFilterVec: sourceFilter,
|
|
443
|
+
sourceFilterChunks: sourceFilter,
|
|
444
|
+
}).catch(() => [])
|
|
445
|
+
: [];
|
|
446
|
+
|
|
447
|
+
// Apply type filter if specified
|
|
448
|
+
const typeFilterFn = opts?.type
|
|
449
|
+
? (id: string) => {
|
|
450
|
+
const row = this.db
|
|
451
|
+
.prepare(`SELECT type FROM chunks WHERE id = ?`)
|
|
452
|
+
.get(id) as { type: string | null } | undefined;
|
|
453
|
+
return row?.type === opts.type;
|
|
454
|
+
}
|
|
455
|
+
: undefined;
|
|
456
|
+
|
|
457
|
+
if (!this.hybrid.enabled) {
|
|
458
|
+
let results = vectorResults;
|
|
459
|
+
if (typeFilterFn) results = results.filter((r) => typeFilterFn(r.id));
|
|
460
|
+
return results
|
|
461
|
+
.filter((entry) => entry.score >= minScore)
|
|
462
|
+
.slice(0, maxResults)
|
|
463
|
+
.map((r) => ({
|
|
464
|
+
path: r.path,
|
|
465
|
+
startLine: r.startLine,
|
|
466
|
+
endLine: r.endLine,
|
|
467
|
+
score: r.score,
|
|
468
|
+
snippet: r.snippet,
|
|
469
|
+
}));
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
let filteredVector = vectorResults;
|
|
473
|
+
let filteredKeyword = keywordResults;
|
|
474
|
+
if (typeFilterFn) {
|
|
475
|
+
filteredVector = vectorResults.filter((r) => typeFilterFn(r.id));
|
|
476
|
+
filteredKeyword = keywordResults.filter((r) => typeFilterFn(r.id));
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
const merged = mergeHybridResults({
|
|
480
|
+
vector: filteredVector.map((r) => ({
|
|
481
|
+
id: r.id,
|
|
482
|
+
path: r.path,
|
|
483
|
+
startLine: r.startLine,
|
|
484
|
+
endLine: r.endLine,
|
|
485
|
+
source: r.source,
|
|
486
|
+
snippet: r.snippet,
|
|
487
|
+
vectorScore: r.score,
|
|
488
|
+
})),
|
|
489
|
+
keyword: filteredKeyword.map((r) => ({
|
|
490
|
+
id: r.id,
|
|
491
|
+
path: r.path,
|
|
492
|
+
startLine: r.startLine,
|
|
493
|
+
endLine: r.endLine,
|
|
494
|
+
source: r.source,
|
|
495
|
+
snippet: r.snippet,
|
|
496
|
+
textScore: r.textScore,
|
|
497
|
+
})),
|
|
498
|
+
vectorWeight: this.hybrid.vectorWeight,
|
|
499
|
+
textWeight: this.hybrid.textWeight,
|
|
500
|
+
});
|
|
501
|
+
|
|
502
|
+
return merged
|
|
503
|
+
.filter((entry) => entry.score >= minScore)
|
|
504
|
+
.slice(0, maxResults)
|
|
505
|
+
.map((r) => ({
|
|
506
|
+
path: r.path,
|
|
507
|
+
startLine: r.startLine,
|
|
508
|
+
endLine: r.endLine,
|
|
509
|
+
score: r.score,
|
|
510
|
+
snippet: r.snippet,
|
|
511
|
+
}));
|
|
512
|
+
}
|
|
513
|
+
|
|
514
|
+
async sync(opts?: { reason?: string; force?: boolean }): Promise<void> {
|
|
515
|
+
// If a sync is already running, wait for it instead of starting another
|
|
516
|
+
if (this.syncing) {
|
|
517
|
+
await this.syncing;
|
|
518
|
+
return;
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
// Use a synchronous flag to prevent the race window between
|
|
522
|
+
// checking this.syncing and assigning to it
|
|
523
|
+
if (this.syncLock) {
|
|
524
|
+
return;
|
|
525
|
+
}
|
|
526
|
+
this.syncLock = true;
|
|
527
|
+
|
|
528
|
+
this.syncing = this.runSync(opts);
|
|
529
|
+
try {
|
|
530
|
+
await this.syncing;
|
|
531
|
+
} finally {
|
|
532
|
+
this.syncing = null;
|
|
533
|
+
this.syncLock = false;
|
|
534
|
+
}
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
private async runSync(opts?: { reason?: string; force?: boolean }): Promise<void> {
|
|
538
|
+
this.debug?.(`memory sync starting`, { reason: opts?.reason });
|
|
539
|
+
|
|
540
|
+
await this.ensureVectorReady();
|
|
541
|
+
const meta = this.readMeta();
|
|
542
|
+
const needsFullReindex =
|
|
543
|
+
opts?.force ||
|
|
544
|
+
!meta ||
|
|
545
|
+
meta.model !== this.provider.model ||
|
|
546
|
+
meta.provider !== this.provider.id ||
|
|
547
|
+
meta.providerKey !== this.providerKey ||
|
|
548
|
+
meta.chunkTokens !== this.chunking.tokens ||
|
|
549
|
+
meta.chunkOverlap !== this.chunking.overlap ||
|
|
550
|
+
(this.vector.available && !meta?.vectorDims);
|
|
551
|
+
|
|
552
|
+
const files = await listMemoryFiles(this.memoryDir);
|
|
553
|
+
const activePaths = new Set<string>();
|
|
554
|
+
|
|
555
|
+
for (const absPath of files) {
|
|
556
|
+
const entry = await buildFileEntry(absPath, this.memoryDir);
|
|
557
|
+
activePaths.add(entry.path);
|
|
558
|
+
|
|
559
|
+
const record = this.db
|
|
560
|
+
.prepare(`SELECT hash FROM files WHERE path = ? AND source = ?`)
|
|
561
|
+
.get(entry.path, "memory") as { hash: string } | undefined;
|
|
562
|
+
|
|
563
|
+
if (!needsFullReindex && record?.hash === entry.hash) {
|
|
564
|
+
continue;
|
|
565
|
+
}
|
|
566
|
+
|
|
567
|
+
await this.indexFile(entry);
|
|
568
|
+
}
|
|
569
|
+
|
|
570
|
+
// Delete stale entries
|
|
571
|
+
const staleRows = this.db
|
|
572
|
+
.prepare(`SELECT path FROM files WHERE source = ?`)
|
|
573
|
+
.all("memory") as Array<{ path: string }>;
|
|
574
|
+
|
|
575
|
+
for (const stale of staleRows) {
|
|
576
|
+
if (activePaths.has(stale.path)) continue;
|
|
577
|
+
this.db.prepare(`DELETE FROM files WHERE path = ? AND source = ?`).run(stale.path, "memory");
|
|
578
|
+
try {
|
|
579
|
+
this.db
|
|
580
|
+
.prepare(
|
|
581
|
+
`DELETE FROM ${VECTOR_TABLE} WHERE id IN (SELECT id FROM chunks WHERE path = ? AND source = ?)`,
|
|
582
|
+
)
|
|
583
|
+
.run(stale.path, "memory");
|
|
584
|
+
} catch (err) {
|
|
585
|
+
logError("deleteStaleVectorEntries", err, this.debug);
|
|
586
|
+
}
|
|
587
|
+
this.db.prepare(`DELETE FROM chunks WHERE path = ? AND source = ?`).run(stale.path, "memory");
|
|
588
|
+
this.db.prepare(`DELETE FROM knowledge_links WHERE source_path = ?`).run(stale.path);
|
|
589
|
+
if (this.fts.enabled && this.fts.available) {
|
|
590
|
+
try {
|
|
591
|
+
this.db
|
|
592
|
+
.prepare(`DELETE FROM ${FTS_TABLE} WHERE path = ? AND source = ? AND model = ?`)
|
|
593
|
+
.run(stale.path, "memory", this.provider.model);
|
|
594
|
+
} catch (err) {
|
|
595
|
+
logError("deleteStaleFtsEntries", err, this.debug);
|
|
596
|
+
}
|
|
597
|
+
}
|
|
598
|
+
}
|
|
599
|
+
|
|
600
|
+
// Write meta
|
|
601
|
+
this.writeMeta({
|
|
602
|
+
model: this.provider.model,
|
|
603
|
+
provider: this.provider.id,
|
|
604
|
+
providerKey: this.providerKey,
|
|
605
|
+
chunkTokens: this.chunking.tokens,
|
|
606
|
+
chunkOverlap: this.chunking.overlap,
|
|
607
|
+
vectorDims: this.vector.dims,
|
|
608
|
+
});
|
|
609
|
+
|
|
610
|
+
// Prune embedding cache
|
|
611
|
+
this.pruneEmbeddingCacheIfNeeded();
|
|
612
|
+
|
|
613
|
+
this.dirty = false;
|
|
614
|
+
this.debug?.(`memory sync complete`, { files: files.length });
|
|
615
|
+
}
|
|
616
|
+
|
|
617
|
+
private async indexFile(entry: MemoryFileEntry): Promise<void> {
|
|
618
|
+
const content = await fs.readFile(entry.absPath, "utf-8");
|
|
619
|
+
const chunks = chunkMarkdown(content, this.chunking);
|
|
620
|
+
|
|
621
|
+
// Extract knowledge frontmatter
|
|
622
|
+
const { frontmatter } = parseFrontmatter(content);
|
|
623
|
+
const knowledgeType = frontmatter?.type ?? null;
|
|
624
|
+
const knowledgeId = frontmatter?.id ?? null;
|
|
625
|
+
const domains = frontmatter?.domain ?? null;
|
|
626
|
+
const entities = frontmatter?.entities ?? null;
|
|
627
|
+
const confidence = frontmatter?.confidence ?? null;
|
|
628
|
+
const links = frontmatter?.links ?? null;
|
|
629
|
+
|
|
630
|
+
// Get embeddings
|
|
631
|
+
const embeddings = await this.embedChunks(chunks);
|
|
632
|
+
|
|
633
|
+
// Update files table
|
|
634
|
+
this.db
|
|
635
|
+
.prepare(
|
|
636
|
+
`INSERT OR REPLACE INTO files (path, source, hash, mtime, size) VALUES (?, ?, ?, ?, ?)`,
|
|
637
|
+
)
|
|
638
|
+
.run(entry.path, "memory", entry.hash, Math.floor(entry.mtimeMs), entry.size);
|
|
639
|
+
|
|
640
|
+
// Delete old chunks for this file
|
|
641
|
+
try {
|
|
642
|
+
this.db
|
|
643
|
+
.prepare(
|
|
644
|
+
`DELETE FROM ${VECTOR_TABLE} WHERE id IN (SELECT id FROM chunks WHERE path = ? AND source = ?)`,
|
|
645
|
+
)
|
|
646
|
+
.run(entry.path, "memory");
|
|
647
|
+
} catch (err) {
|
|
648
|
+
logError("deleteOldVectorChunks", err, this.debug);
|
|
649
|
+
}
|
|
650
|
+
this.db.prepare(`DELETE FROM chunks WHERE path = ? AND source = ?`).run(entry.path, "memory");
|
|
651
|
+
if (this.fts.enabled && this.fts.available) {
|
|
652
|
+
try {
|
|
653
|
+
this.db
|
|
654
|
+
.prepare(`DELETE FROM ${FTS_TABLE} WHERE path = ? AND source = ? AND model = ?`)
|
|
655
|
+
.run(entry.path, "memory", this.provider.model);
|
|
656
|
+
} catch (err) {
|
|
657
|
+
logError("deleteOldFtsChunks", err, this.debug);
|
|
658
|
+
}
|
|
659
|
+
}
|
|
660
|
+
|
|
661
|
+
// Delete old knowledge links for this file path on re-index
|
|
662
|
+
this.db.prepare(`DELETE FROM knowledge_links WHERE source_path = ?`).run(entry.path);
|
|
663
|
+
|
|
664
|
+
// Insert new chunks
|
|
665
|
+
const now = Date.now();
|
|
666
|
+
for (let i = 0; i < chunks.length; i++) {
|
|
667
|
+
const chunk = chunks[i];
|
|
668
|
+
const embedding = embeddings[i] ?? [];
|
|
669
|
+
const chunkId = randomUUID();
|
|
670
|
+
const meta = extractChunkMetadata(chunk.text);
|
|
671
|
+
|
|
672
|
+
this.db
|
|
673
|
+
.prepare(
|
|
674
|
+
`INSERT INTO chunks (id, path, source, start_line, end_line, hash, model, text, embedding, updated_at, type, knowledge_type, knowledge_id, domains, entities, confidence)
|
|
675
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
|
676
|
+
)
|
|
677
|
+
.run(
|
|
678
|
+
chunkId,
|
|
679
|
+
entry.path,
|
|
680
|
+
"memory",
|
|
681
|
+
chunk.startLine,
|
|
682
|
+
chunk.endLine,
|
|
683
|
+
chunk.hash,
|
|
684
|
+
this.provider.model,
|
|
685
|
+
chunk.text,
|
|
686
|
+
JSON.stringify(embedding),
|
|
687
|
+
now,
|
|
688
|
+
meta.type ?? null,
|
|
689
|
+
knowledgeType,
|
|
690
|
+
knowledgeId,
|
|
691
|
+
domains ? JSON.stringify(domains) : null,
|
|
692
|
+
entities ? JSON.stringify(entities) : null,
|
|
693
|
+
confidence,
|
|
694
|
+
);
|
|
695
|
+
|
|
696
|
+
// Insert into vector table if available
|
|
697
|
+
if (this.vector.available && embedding.length > 0) {
|
|
698
|
+
if (!this.vector.dims) {
|
|
699
|
+
this.vector.dims = embedding.length;
|
|
700
|
+
this.ensureVectorTable(embedding.length);
|
|
701
|
+
}
|
|
702
|
+
try {
|
|
703
|
+
this.db
|
|
704
|
+
.prepare(`INSERT INTO ${VECTOR_TABLE} (id, embedding) VALUES (?, ?)`)
|
|
705
|
+
.run(chunkId, vectorToBlob(embedding));
|
|
706
|
+
} catch (err) {
|
|
707
|
+
logError("insertVectorChunk", err, this.debug);
|
|
708
|
+
}
|
|
709
|
+
}
|
|
710
|
+
|
|
711
|
+
// Insert into FTS table if available
|
|
712
|
+
if (this.fts.enabled && this.fts.available) {
|
|
713
|
+
try {
|
|
714
|
+
this.db
|
|
715
|
+
.prepare(
|
|
716
|
+
`INSERT INTO ${FTS_TABLE} (text, id, path, source, model, start_line, end_line)
|
|
717
|
+
VALUES (?, ?, ?, ?, ?, ?, ?)`,
|
|
718
|
+
)
|
|
719
|
+
.run(
|
|
720
|
+
chunk.text,
|
|
721
|
+
chunkId,
|
|
722
|
+
entry.path,
|
|
723
|
+
"memory",
|
|
724
|
+
this.provider.model,
|
|
725
|
+
chunk.startLine,
|
|
726
|
+
chunk.endLine,
|
|
727
|
+
);
|
|
728
|
+
} catch (err) {
|
|
729
|
+
logError("insertFtsChunk", err, this.debug);
|
|
730
|
+
}
|
|
731
|
+
}
|
|
732
|
+
}
|
|
733
|
+
|
|
734
|
+
// Upsert knowledge links if present
|
|
735
|
+
if (links && knowledgeId) {
|
|
736
|
+
const upsertLink = this.db.prepare(
|
|
737
|
+
`INSERT OR REPLACE INTO knowledge_links (from_id, to_id, relation, layer, weight, source_path, created_at)
|
|
738
|
+
VALUES (?, ?, ?, ?, ?, ?, ?)`,
|
|
739
|
+
);
|
|
740
|
+
for (const link of links) {
|
|
741
|
+
upsertLink.run(
|
|
742
|
+
knowledgeId,
|
|
743
|
+
link.target,
|
|
744
|
+
link.relation,
|
|
745
|
+
link.layer ?? null,
|
|
746
|
+
0.5,
|
|
747
|
+
entry.path,
|
|
748
|
+
now,
|
|
749
|
+
);
|
|
750
|
+
}
|
|
751
|
+
}
|
|
752
|
+
}
|
|
753
|
+
|
|
754
|
+
private async embedChunks(chunks: MemoryChunk[]): Promise<number[][]> {
|
|
755
|
+
if (chunks.length === 0) return [];
|
|
756
|
+
|
|
757
|
+
const hashes = chunks.map((c) => c.hash);
|
|
758
|
+
const cached = this.loadEmbeddingCache(hashes);
|
|
759
|
+
const missing: Array<{ index: number; chunk: MemoryChunk }> = [];
|
|
760
|
+
|
|
761
|
+
for (let i = 0; i < chunks.length; i++) {
|
|
762
|
+
if (!cached.has(hashes[i])) {
|
|
763
|
+
missing.push({ index: i, chunk: chunks[i] });
|
|
764
|
+
}
|
|
765
|
+
}
|
|
766
|
+
|
|
767
|
+
if (missing.length > 0) {
|
|
768
|
+
const texts = missing.map((m) => m.chunk.text);
|
|
769
|
+
const newEmbeddings = await this.embedBatchWithRetry(texts);
|
|
770
|
+
|
|
771
|
+
for (let i = 0; i < missing.length; i++) {
|
|
772
|
+
const hash = missing[i].chunk.hash;
|
|
773
|
+
const embedding = newEmbeddings[i] ?? [];
|
|
774
|
+
cached.set(hash, embedding);
|
|
775
|
+
this.upsertEmbeddingCache(hash, embedding);
|
|
776
|
+
}
|
|
777
|
+
}
|
|
778
|
+
|
|
779
|
+
return hashes.map((h) => cached.get(h) ?? []);
|
|
780
|
+
}
|
|
781
|
+
|
|
782
|
+
private async embedBatchWithRetry(texts: string[]): Promise<number[][]> {
|
|
783
|
+
if (texts.length === 0) return [];
|
|
784
|
+
|
|
785
|
+
// Try batch API first if enabled
|
|
786
|
+
if (this.batchConfig.enabled) {
|
|
787
|
+
try {
|
|
788
|
+
return await this.embedWithBatchApi(texts);
|
|
789
|
+
} catch (err) {
|
|
790
|
+
this.debug?.(`batch embedding failed, falling back to direct: ${String(err)}`);
|
|
791
|
+
}
|
|
792
|
+
}
|
|
793
|
+
|
|
794
|
+
// Fall back to direct embedding
|
|
795
|
+
let lastError: Error | null = null;
|
|
796
|
+
for (let attempt = 0; attempt < EMBEDDING_RETRY_MAX_ATTEMPTS; attempt++) {
|
|
797
|
+
try {
|
|
798
|
+
return await this.provider.embedBatch(texts);
|
|
799
|
+
} catch (err) {
|
|
800
|
+
lastError = err instanceof Error ? err : new Error(String(err));
|
|
801
|
+
if (attempt < EMBEDDING_RETRY_MAX_ATTEMPTS - 1) {
|
|
802
|
+
const delay = Math.min(
|
|
803
|
+
EMBEDDING_RETRY_MAX_DELAY_MS,
|
|
804
|
+
EMBEDDING_RETRY_BASE_DELAY_MS * Math.pow(2, attempt),
|
|
805
|
+
);
|
|
806
|
+
await new Promise((resolve) => setTimeout(resolve, delay));
|
|
807
|
+
}
|
|
808
|
+
}
|
|
809
|
+
}
|
|
810
|
+
throw lastError;
|
|
811
|
+
}
|
|
812
|
+
|
|
813
|
+
private async embedWithBatchApi(texts: string[]): Promise<number[][]> {
|
|
814
|
+
if (this.openAi) {
|
|
815
|
+
const requests: OpenAiBatchRequest[] = texts.map((text, i) => ({
|
|
816
|
+
custom_id: `chunk-${i}`,
|
|
817
|
+
method: "POST",
|
|
818
|
+
url: OPENAI_BATCH_ENDPOINT,
|
|
819
|
+
body: { model: this.openAi!.model, input: text },
|
|
820
|
+
}));
|
|
821
|
+
|
|
822
|
+
const results = await runOpenAiEmbeddingBatches({
|
|
823
|
+
openAi: this.openAi,
|
|
824
|
+
source: "minimem",
|
|
825
|
+
requests,
|
|
826
|
+
wait: this.batchConfig.wait,
|
|
827
|
+
pollIntervalMs: this.batchConfig.pollIntervalMs,
|
|
828
|
+
timeoutMs: this.batchConfig.timeoutMs,
|
|
829
|
+
concurrency: this.batchConfig.concurrency,
|
|
830
|
+
debug: this.debug,
|
|
831
|
+
});
|
|
832
|
+
|
|
833
|
+
return texts.map((_, i) => results.get(`chunk-${i}`) ?? []);
|
|
834
|
+
}
|
|
835
|
+
|
|
836
|
+
if (this.gemini) {
|
|
837
|
+
const requests: GeminiBatchRequest[] = texts.map((text, i) => ({
|
|
838
|
+
custom_id: `chunk-${i}`,
|
|
839
|
+
content: { parts: [{ text }] },
|
|
840
|
+
taskType: "RETRIEVAL_DOCUMENT",
|
|
841
|
+
}));
|
|
842
|
+
|
|
843
|
+
const results = await runGeminiEmbeddingBatches({
|
|
844
|
+
gemini: this.gemini,
|
|
845
|
+
source: "minimem",
|
|
846
|
+
requests,
|
|
847
|
+
wait: this.batchConfig.wait,
|
|
848
|
+
pollIntervalMs: this.batchConfig.pollIntervalMs,
|
|
849
|
+
timeoutMs: this.batchConfig.timeoutMs,
|
|
850
|
+
concurrency: this.batchConfig.concurrency,
|
|
851
|
+
debug: this.debug,
|
|
852
|
+
});
|
|
853
|
+
|
|
854
|
+
return texts.map((_, i) => results.get(`chunk-${i}`) ?? []);
|
|
855
|
+
}
|
|
856
|
+
|
|
857
|
+
throw new Error("Batch API not available for local embeddings");
|
|
858
|
+
}
|
|
859
|
+
|
|
860
|
+
private async embedQueryWithTimeout(text: string): Promise<number[]> {
|
|
861
|
+
const timeout =
|
|
862
|
+
this.provider.id === "local" ? EMBEDDING_QUERY_TIMEOUT_LOCAL_MS : EMBEDDING_QUERY_TIMEOUT_REMOTE_MS;
|
|
863
|
+
|
|
864
|
+
const ac = new AbortController();
|
|
865
|
+
const timer = setTimeout(() => ac.abort(), timeout);
|
|
866
|
+
|
|
867
|
+
try {
|
|
868
|
+
const result = await Promise.race([
|
|
869
|
+
this.provider.embedQuery(text),
|
|
870
|
+
new Promise<number[]>((_, reject) => {
|
|
871
|
+
ac.signal.addEventListener("abort", () =>
|
|
872
|
+
reject(new Error("embedding query timeout")),
|
|
873
|
+
);
|
|
874
|
+
}),
|
|
875
|
+
]);
|
|
876
|
+
return result;
|
|
877
|
+
} finally {
|
|
878
|
+
clearTimeout(timer);
|
|
879
|
+
}
|
|
880
|
+
}
|
|
881
|
+
|
|
882
|
+
private loadEmbeddingCache(hashes: string[]): Map<string, number[]> {
|
|
883
|
+
const result = new Map<string, number[]>();
|
|
884
|
+
if (!this.cache.enabled || hashes.length === 0) return result;
|
|
885
|
+
|
|
886
|
+
const placeholders = hashes.map(() => "?").join(",");
|
|
887
|
+
const rows = this.db
|
|
888
|
+
.prepare(
|
|
889
|
+
`SELECT hash, embedding FROM ${EMBEDDING_CACHE_TABLE}
|
|
890
|
+
WHERE provider = ? AND model = ? AND provider_key = ? AND hash IN (${placeholders})`,
|
|
891
|
+
)
|
|
892
|
+
.all(this.provider.id, this.provider.model, this.providerKey, ...hashes) as Array<{
|
|
893
|
+
hash: string;
|
|
894
|
+
embedding: string;
|
|
895
|
+
}>;
|
|
896
|
+
|
|
897
|
+
const now = Date.now();
|
|
898
|
+
for (const row of rows) {
|
|
899
|
+
result.set(row.hash, parseEmbedding(row.embedding));
|
|
900
|
+
// Touch for LRU
|
|
901
|
+
this.db
|
|
902
|
+
.prepare(
|
|
903
|
+
`UPDATE ${EMBEDDING_CACHE_TABLE} SET updated_at = ?
|
|
904
|
+
WHERE provider = ? AND model = ? AND provider_key = ? AND hash = ?`,
|
|
905
|
+
)
|
|
906
|
+
.run(now, this.provider.id, this.provider.model, this.providerKey, row.hash);
|
|
907
|
+
}
|
|
908
|
+
|
|
909
|
+
return result;
|
|
910
|
+
}
|
|
911
|
+
|
|
912
|
+
private upsertEmbeddingCache(hash: string, embedding: number[]): void {
|
|
913
|
+
if (!this.cache.enabled) return;
|
|
914
|
+
const now = Date.now();
|
|
915
|
+
this.db
|
|
916
|
+
.prepare(
|
|
917
|
+
`INSERT OR REPLACE INTO ${EMBEDDING_CACHE_TABLE}
|
|
918
|
+
(provider, model, provider_key, hash, embedding, dims, updated_at)
|
|
919
|
+
VALUES (?, ?, ?, ?, ?, ?, ?)`,
|
|
920
|
+
)
|
|
921
|
+
.run(
|
|
922
|
+
this.provider.id,
|
|
923
|
+
this.provider.model,
|
|
924
|
+
this.providerKey,
|
|
925
|
+
hash,
|
|
926
|
+
JSON.stringify(embedding),
|
|
927
|
+
embedding.length,
|
|
928
|
+
now,
|
|
929
|
+
);
|
|
930
|
+
}
|
|
931
|
+
|
|
932
|
+
private pruneEmbeddingCacheIfNeeded(): void {
|
|
933
|
+
if (!this.cache.enabled) return;
|
|
934
|
+
const row = this.db
|
|
935
|
+
.prepare(`SELECT COUNT(*) as count FROM ${EMBEDDING_CACHE_TABLE}`)
|
|
936
|
+
.get() as { count: number };
|
|
937
|
+
if (row.count <= this.cache.maxEntries) return;
|
|
938
|
+
|
|
939
|
+
const excess = row.count - this.cache.maxEntries;
|
|
940
|
+
this.db
|
|
941
|
+
.prepare(
|
|
942
|
+
`DELETE FROM ${EMBEDDING_CACHE_TABLE}
|
|
943
|
+
WHERE rowid IN (
|
|
944
|
+
SELECT rowid FROM ${EMBEDDING_CACHE_TABLE}
|
|
945
|
+
ORDER BY updated_at ASC
|
|
946
|
+
LIMIT ?
|
|
947
|
+
)`,
|
|
948
|
+
)
|
|
949
|
+
.run(excess);
|
|
950
|
+
}
|
|
951
|
+
|
|
952
|
+
private async ensureVectorReady(dimensions?: number): Promise<boolean> {
|
|
953
|
+
if (this.vector.available === true) return true;
|
|
954
|
+
if (this.vector.available === false) return false;
|
|
955
|
+
|
|
956
|
+
if (!this.vectorReady) {
|
|
957
|
+
this.vectorReady = this.loadVectorExtension();
|
|
958
|
+
}
|
|
959
|
+
|
|
960
|
+
const ready = await this.vectorReady;
|
|
961
|
+
if (ready && dimensions && !this.vector.dims) {
|
|
962
|
+
this.vector.dims = dimensions;
|
|
963
|
+
this.ensureVectorTable(dimensions);
|
|
964
|
+
}
|
|
965
|
+
return ready;
|
|
966
|
+
}
|
|
967
|
+
|
|
968
|
+
private async loadVectorExtension(): Promise<boolean> {
|
|
969
|
+
const result = await loadSqliteVecExtension({
|
|
970
|
+
db: this.db,
|
|
971
|
+
extensionPath: this.vectorExtensionPath,
|
|
972
|
+
});
|
|
973
|
+
|
|
974
|
+
this.vector.available = result.ok;
|
|
975
|
+
if (result.error) {
|
|
976
|
+
this.vector.loadError = result.error;
|
|
977
|
+
this.debug?.(`sqlite-vec load failed: ${result.error}`);
|
|
978
|
+
}
|
|
979
|
+
if (result.extensionPath) {
|
|
980
|
+
this.vector.extensionPath = result.extensionPath;
|
|
981
|
+
}
|
|
982
|
+
|
|
983
|
+
return result.ok;
|
|
984
|
+
}
|
|
985
|
+
|
|
986
|
+
private ensureVectorTable(dimensions: number): void {
|
|
987
|
+
if (!this.vector.available) return;
|
|
988
|
+
try {
|
|
989
|
+
this.db.exec(
|
|
990
|
+
`CREATE VIRTUAL TABLE IF NOT EXISTS ${VECTOR_TABLE} USING vec0(
|
|
991
|
+
id TEXT PRIMARY KEY,
|
|
992
|
+
embedding FLOAT[${dimensions}]
|
|
993
|
+
)`,
|
|
994
|
+
);
|
|
995
|
+
} catch (err) {
|
|
996
|
+
this.debug?.(`vector table creation failed: ${String(err)}`);
|
|
997
|
+
}
|
|
998
|
+
}
|
|
999
|
+
|
|
1000
|
+
async readFile(relativePath: string): Promise<string | null> {
|
|
1001
|
+
const absPath = path.join(this.memoryDir, relativePath);
|
|
1002
|
+
try {
|
|
1003
|
+
return await fs.readFile(absPath, "utf-8");
|
|
1004
|
+
} catch {
|
|
1005
|
+
return null;
|
|
1006
|
+
}
|
|
1007
|
+
}
|
|
1008
|
+
|
|
1009
|
+
/**
|
|
1010
|
+
* Read specific lines from a memory file
|
|
1011
|
+
*/
|
|
1012
|
+
async readLines(
|
|
1013
|
+
relativePath: string,
|
|
1014
|
+
opts?: { from?: number; lines?: number },
|
|
1015
|
+
): Promise<{ content: string; startLine: number; endLine: number } | null> {
|
|
1016
|
+
const content = await this.readFile(relativePath);
|
|
1017
|
+
if (content === null) return null;
|
|
1018
|
+
|
|
1019
|
+
const allLines = content.split("\n");
|
|
1020
|
+
const from = Math.max(1, opts?.from ?? 1);
|
|
1021
|
+
const lines = opts?.lines ?? allLines.length;
|
|
1022
|
+
|
|
1023
|
+
const startIdx = from - 1;
|
|
1024
|
+
const endIdx = Math.min(startIdx + lines, allLines.length);
|
|
1025
|
+
const selectedLines = allLines.slice(startIdx, endIdx);
|
|
1026
|
+
|
|
1027
|
+
return {
|
|
1028
|
+
content: selectedLines.join("\n"),
|
|
1029
|
+
startLine: from,
|
|
1030
|
+
endLine: startIdx + selectedLines.length,
|
|
1031
|
+
};
|
|
1032
|
+
}
|
|
1033
|
+
|
|
1034
|
+
/**
|
|
1035
|
+
* Write content to a memory file (creates or overwrites)
|
|
1036
|
+
*/
|
|
1037
|
+
async writeFile(relativePath: string, content: string): Promise<void> {
|
|
1038
|
+
this.validateMemoryPath(relativePath);
|
|
1039
|
+
const absPath = path.join(this.memoryDir, relativePath);
|
|
1040
|
+
const dir = path.dirname(absPath);
|
|
1041
|
+
await fs.mkdir(dir, { recursive: true });
|
|
1042
|
+
await fs.writeFile(absPath, content, "utf-8");
|
|
1043
|
+
this.dirty = true;
|
|
1044
|
+
this.debug?.(`memory write: ${relativePath}`);
|
|
1045
|
+
}
|
|
1046
|
+
|
|
1047
|
+
/**
|
|
1048
|
+
* Append content to a memory file (creates if doesn't exist)
|
|
1049
|
+
*/
|
|
1050
|
+
async appendFile(relativePath: string, content: string): Promise<void> {
|
|
1051
|
+
this.validateMemoryPath(relativePath);
|
|
1052
|
+
const absPath = path.join(this.memoryDir, relativePath);
|
|
1053
|
+
const dir = path.dirname(absPath);
|
|
1054
|
+
await fs.mkdir(dir, { recursive: true });
|
|
1055
|
+
|
|
1056
|
+
// Ensure newline separation
|
|
1057
|
+
let toAppend = content;
|
|
1058
|
+
try {
|
|
1059
|
+
const existing = await fs.readFile(absPath, "utf-8");
|
|
1060
|
+
if (existing.length > 0 && !existing.endsWith("\n")) {
|
|
1061
|
+
toAppend = "\n" + content;
|
|
1062
|
+
}
|
|
1063
|
+
} catch {
|
|
1064
|
+
// File doesn't exist, will be created
|
|
1065
|
+
}
|
|
1066
|
+
|
|
1067
|
+
await fs.appendFile(absPath, toAppend, "utf-8");
|
|
1068
|
+
this.dirty = true;
|
|
1069
|
+
this.debug?.(`memory append: ${relativePath}`);
|
|
1070
|
+
}
|
|
1071
|
+
|
|
1072
|
+
/**
|
|
1073
|
+
* Append content to today's daily log (memory/YYYY-MM-DD.md)
|
|
1074
|
+
*/
|
|
1075
|
+
async appendToday(content: string): Promise<string> {
|
|
1076
|
+
const today = new Date().toISOString().split("T")[0]; // YYYY-MM-DD
|
|
1077
|
+
const relativePath = `memory/${today}.md`;
|
|
1078
|
+
await this.appendFile(relativePath, content);
|
|
1079
|
+
return relativePath;
|
|
1080
|
+
}
|
|
1081
|
+
|
|
1082
|
+
/**
|
|
1083
|
+
* List all memory files
|
|
1084
|
+
*/
|
|
1085
|
+
async listFiles(): Promise<string[]> {
|
|
1086
|
+
const files = await listMemoryFiles(this.memoryDir);
|
|
1087
|
+
return files.map((f) => path.relative(this.memoryDir, f).replace(/\\/g, "/"));
|
|
1088
|
+
}
|
|
1089
|
+
|
|
1090
|
+
/**
|
|
1091
|
+
* Validate that a path is within allowed memory locations
|
|
1092
|
+
*/
|
|
1093
|
+
private validateMemoryPath(relativePath: string): void {
|
|
1094
|
+
const normalized = relativePath.replace(/\\/g, "/").replace(/^\.\//, "");
|
|
1095
|
+
|
|
1096
|
+
// Allow MEMORY.md at root
|
|
1097
|
+
if (normalized === "MEMORY.md" || normalized === "memory.md") {
|
|
1098
|
+
return;
|
|
1099
|
+
}
|
|
1100
|
+
|
|
1101
|
+
// Allow anything under memory/
|
|
1102
|
+
if (normalized.startsWith("memory/") && normalized.endsWith(".md")) {
|
|
1103
|
+
// Prevent path traversal
|
|
1104
|
+
if (normalized.includes("..")) {
|
|
1105
|
+
throw new Error(`Invalid memory path: ${relativePath} (path traversal not allowed)`);
|
|
1106
|
+
}
|
|
1107
|
+
return;
|
|
1108
|
+
}
|
|
1109
|
+
|
|
1110
|
+
throw new Error(
|
|
1111
|
+
`Invalid memory path: ${relativePath}. Must be MEMORY.md or memory/*.md`,
|
|
1112
|
+
);
|
|
1113
|
+
}
|
|
1114
|
+
|
|
1115
|
+
async status(): Promise<{
|
|
1116
|
+
memoryDir: string;
|
|
1117
|
+
dbPath: string;
|
|
1118
|
+
provider: string;
|
|
1119
|
+
model: string;
|
|
1120
|
+
vectorAvailable: boolean;
|
|
1121
|
+
ftsAvailable: boolean;
|
|
1122
|
+
bm25Only: boolean;
|
|
1123
|
+
fallbackReason?: string;
|
|
1124
|
+
fileCount: number;
|
|
1125
|
+
chunkCount: number;
|
|
1126
|
+
cacheCount: number;
|
|
1127
|
+
}> {
|
|
1128
|
+
const fileRow = this.db.prepare(`SELECT COUNT(*) as count FROM files`).get() as { count: number };
|
|
1129
|
+
const chunkRow = this.db.prepare(`SELECT COUNT(*) as count FROM chunks`).get() as { count: number };
|
|
1130
|
+
const cacheRow = this.db
|
|
1131
|
+
.prepare(`SELECT COUNT(*) as count FROM ${EMBEDDING_CACHE_TABLE}`)
|
|
1132
|
+
.get() as { count: number };
|
|
1133
|
+
|
|
1134
|
+
return {
|
|
1135
|
+
memoryDir: this.memoryDir,
|
|
1136
|
+
dbPath: this.dbPath,
|
|
1137
|
+
provider: this.provider.id,
|
|
1138
|
+
model: this.provider.model,
|
|
1139
|
+
vectorAvailable: this.vector.available === true,
|
|
1140
|
+
ftsAvailable: this.fts.available,
|
|
1141
|
+
bm25Only: this.provider.id === "none",
|
|
1142
|
+
fallbackReason: this.providerFallbackReason,
|
|
1143
|
+
fileCount: fileRow.count,
|
|
1144
|
+
chunkCount: chunkRow.count,
|
|
1145
|
+
cacheCount: cacheRow.count,
|
|
1146
|
+
};
|
|
1147
|
+
}
|
|
1148
|
+
|
|
1149
|
+
/**
|
|
1150
|
+
* Search with knowledge metadata filters (domain, entities, confidence, type).
|
|
1151
|
+
* Runs a standard search then post-filters by knowledge columns.
|
|
1152
|
+
*/
|
|
1153
|
+
async knowledgeSearch(
|
|
1154
|
+
query: string,
|
|
1155
|
+
opts?: {
|
|
1156
|
+
maxResults?: number;
|
|
1157
|
+
minScore?: number;
|
|
1158
|
+
domain?: string[];
|
|
1159
|
+
entities?: string[];
|
|
1160
|
+
minConfidence?: number;
|
|
1161
|
+
knowledgeType?: string;
|
|
1162
|
+
},
|
|
1163
|
+
): Promise<MinimemSearchResult[]> {
|
|
1164
|
+
// Ensure index is up to date
|
|
1165
|
+
if (this.dirty || (!this.watchConfig.enabled && (await this.isStale()))) {
|
|
1166
|
+
await this.sync({ reason: "knowledgeSearch" });
|
|
1167
|
+
}
|
|
1168
|
+
|
|
1169
|
+
const cleaned = query.trim();
|
|
1170
|
+
if (!cleaned) return [];
|
|
1171
|
+
|
|
1172
|
+
const minScore = opts?.minScore ?? this.queryConfig.minScore;
|
|
1173
|
+
const maxResults = opts?.maxResults ?? this.queryConfig.maxResults;
|
|
1174
|
+
|
|
1175
|
+
// Build knowledge filter SQL
|
|
1176
|
+
const { sql: knowledgeWhere, params: knowledgeParams } =
|
|
1177
|
+
buildKnowledgeFilterSql({
|
|
1178
|
+
domain: opts?.domain,
|
|
1179
|
+
entities: opts?.entities,
|
|
1180
|
+
minConfidence: opts?.minConfidence,
|
|
1181
|
+
knowledgeType: opts?.knowledgeType,
|
|
1182
|
+
});
|
|
1183
|
+
|
|
1184
|
+
// If no knowledge filters, delegate to regular search
|
|
1185
|
+
if (!knowledgeWhere) {
|
|
1186
|
+
return this.search(query, { maxResults, minScore });
|
|
1187
|
+
}
|
|
1188
|
+
|
|
1189
|
+
// Get all chunk IDs matching knowledge filters
|
|
1190
|
+
const matchingRows = this.db
|
|
1191
|
+
.prepare(
|
|
1192
|
+
`SELECT id FROM chunks c WHERE c.model = ? AND c.source = 'memory'${knowledgeWhere}`,
|
|
1193
|
+
)
|
|
1194
|
+
.all(this.provider.model, ...knowledgeParams) as Array<{ id: string }>;
|
|
1195
|
+
|
|
1196
|
+
const matchingIds = new Set(matchingRows.map((r) => r.id));
|
|
1197
|
+
|
|
1198
|
+
if (matchingIds.size === 0) return [];
|
|
1199
|
+
|
|
1200
|
+
// Run standard search with extra candidates to compensate for filtering
|
|
1201
|
+
const overFetch = Math.max(maxResults * 3, 30);
|
|
1202
|
+
const results = await this.search(query, {
|
|
1203
|
+
maxResults: overFetch,
|
|
1204
|
+
minScore,
|
|
1205
|
+
});
|
|
1206
|
+
|
|
1207
|
+
// Post-filter: look up chunk IDs for each result and keep only matching ones
|
|
1208
|
+
const filtered: MinimemSearchResult[] = [];
|
|
1209
|
+
for (const r of results) {
|
|
1210
|
+
const row = this.db
|
|
1211
|
+
.prepare(
|
|
1212
|
+
`SELECT id FROM chunks WHERE path = ? AND start_line = ? AND end_line = ? AND model = ?`,
|
|
1213
|
+
)
|
|
1214
|
+
.get(r.path, r.startLine, r.endLine, this.provider.model) as { id: string } | undefined;
|
|
1215
|
+
if (row && matchingIds.has(row.id)) {
|
|
1216
|
+
filtered.push(r);
|
|
1217
|
+
if (filtered.length >= maxResults) break;
|
|
1218
|
+
}
|
|
1219
|
+
}
|
|
1220
|
+
|
|
1221
|
+
return filtered;
|
|
1222
|
+
}
|
|
1223
|
+
|
|
1224
|
+
/**
|
|
1225
|
+
* Get knowledge graph links from or to a node.
|
|
1226
|
+
*/
|
|
1227
|
+
getLinks(
|
|
1228
|
+
nodeId: string,
|
|
1229
|
+
direction: "from" | "to" = "from",
|
|
1230
|
+
opts?: { relation?: string; layer?: string },
|
|
1231
|
+
): GraphLink[] {
|
|
1232
|
+
if (direction === "from") {
|
|
1233
|
+
return getLinksFrom(this.db, nodeId, opts);
|
|
1234
|
+
}
|
|
1235
|
+
return getLinksTo(this.db, nodeId, opts);
|
|
1236
|
+
}
|
|
1237
|
+
|
|
1238
|
+
/**
|
|
1239
|
+
* Get neighbor nodes via BFS traversal.
|
|
1240
|
+
*/
|
|
1241
|
+
getGraphNeighbors(
|
|
1242
|
+
nodeId: string,
|
|
1243
|
+
depth: number = 1,
|
|
1244
|
+
opts?: { relation?: string; layer?: string },
|
|
1245
|
+
): GraphNeighbor[] {
|
|
1246
|
+
return getNeighbors(this.db, nodeId, depth, opts);
|
|
1247
|
+
}
|
|
1248
|
+
|
|
1249
|
+
/**
|
|
1250
|
+
* Find shortest path between two knowledge nodes.
|
|
1251
|
+
*/
|
|
1252
|
+
getGraphPath(fromId: string, toId: string, maxDepth: number = 3): GraphLink[] {
|
|
1253
|
+
return getPathBetween(this.db, fromId, toId, maxDepth);
|
|
1254
|
+
}
|
|
1255
|
+
|
|
1256
|
+
close(): void {
|
|
1257
|
+
if (this.closed) return;
|
|
1258
|
+
this.closed = true;
|
|
1259
|
+
|
|
1260
|
+
if (this.watchTimer) {
|
|
1261
|
+
clearTimeout(this.watchTimer);
|
|
1262
|
+
this.watchTimer = null;
|
|
1263
|
+
}
|
|
1264
|
+
|
|
1265
|
+
if (this.watcher) {
|
|
1266
|
+
void this.watcher.close();
|
|
1267
|
+
this.watcher = null;
|
|
1268
|
+
}
|
|
1269
|
+
|
|
1270
|
+
try {
|
|
1271
|
+
this.db.close();
|
|
1272
|
+
} catch (err) {
|
|
1273
|
+
logError("dbClose", err, this.debug);
|
|
1274
|
+
}
|
|
1275
|
+
}
|
|
1276
|
+
}
|