cognitive-core 0.2.0 → 0.2.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude/settings.json +111 -2
- package/.sessionlog/settings.json +4 -0
- package/dist/atlas.d.ts +10 -0
- package/dist/atlas.d.ts.map +1 -1
- package/dist/atlas.js +65 -0
- package/dist/atlas.js.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +5 -1
- package/dist/index.js.map +1 -1
- package/dist/learning/index.d.ts +1 -1
- package/dist/learning/index.d.ts.map +1 -1
- package/dist/learning/index.js.map +1 -1
- package/dist/learning/pipeline.d.ts +4 -31
- package/dist/learning/pipeline.d.ts.map +1 -1
- package/dist/learning/pipeline.js +12 -64
- package/dist/learning/pipeline.js.map +1 -1
- package/dist/learning/unified-pipeline.d.ts +30 -0
- package/dist/learning/unified-pipeline.d.ts.map +1 -1
- package/dist/learning/unified-pipeline.js +207 -0
- package/dist/learning/unified-pipeline.js.map +1 -1
- package/dist/memory/candidate-retrieval.d.ts.map +1 -1
- package/dist/memory/candidate-retrieval.js +3 -1
- package/dist/memory/candidate-retrieval.js.map +1 -1
- package/dist/memory/curated-loader.d.ts +21 -4
- package/dist/memory/curated-loader.d.ts.map +1 -1
- package/dist/memory/curated-loader.js +53 -16
- package/dist/memory/curated-loader.js.map +1 -1
- package/dist/memory/index.d.ts +2 -1
- package/dist/memory/index.d.ts.map +1 -1
- package/dist/memory/index.js +3 -1
- package/dist/memory/index.js.map +1 -1
- package/dist/memory/playbook.d.ts +6 -0
- package/dist/memory/playbook.d.ts.map +1 -1
- package/dist/memory/playbook.js +15 -0
- package/dist/memory/playbook.js.map +1 -1
- package/dist/memory/source-resolver.d.ts +120 -0
- package/dist/memory/source-resolver.d.ts.map +1 -0
- package/dist/memory/source-resolver.js +300 -0
- package/dist/memory/source-resolver.js.map +1 -0
- package/dist/types/config.d.ts +141 -0
- package/dist/types/config.d.ts.map +1 -1
- package/dist/types/config.js +40 -0
- package/dist/types/config.js.map +1 -1
- package/dist/types/index.d.ts +1 -1
- package/dist/types/index.d.ts.map +1 -1
- package/dist/types/index.js +1 -1
- package/dist/types/index.js.map +1 -1
- package/dist/utils/error-classifier.js +8 -8
- package/dist/utils/error-classifier.js.map +1 -1
- package/dist/workspace/efficacy-toolkit.d.ts +164 -0
- package/dist/workspace/efficacy-toolkit.d.ts.map +1 -0
- package/dist/workspace/efficacy-toolkit.js +281 -0
- package/dist/workspace/efficacy-toolkit.js.map +1 -0
- package/dist/workspace/index.d.ts +2 -1
- package/dist/workspace/index.d.ts.map +1 -1
- package/dist/workspace/index.js +3 -1
- package/dist/workspace/index.js.map +1 -1
- package/dist/workspace/templates/index.d.ts +3 -0
- package/dist/workspace/templates/index.d.ts.map +1 -1
- package/dist/workspace/templates/index.js +6 -0
- package/dist/workspace/templates/index.js.map +1 -1
- package/dist/workspace/templates/playbook-decay-detection.d.ts +46 -0
- package/dist/workspace/templates/playbook-decay-detection.d.ts.map +1 -0
- package/dist/workspace/templates/playbook-decay-detection.js +197 -0
- package/dist/workspace/templates/playbook-decay-detection.js.map +1 -0
- package/dist/workspace/templates/playbook-efficacy-audit.d.ts +46 -0
- package/dist/workspace/templates/playbook-efficacy-audit.d.ts.map +1 -0
- package/dist/workspace/templates/playbook-efficacy-audit.js +160 -0
- package/dist/workspace/templates/playbook-efficacy-audit.js.map +1 -0
- package/dist/workspace/templates/playbook-lifecycle-review.d.ts +51 -0
- package/dist/workspace/templates/playbook-lifecycle-review.d.ts.map +1 -0
- package/dist/workspace/templates/playbook-lifecycle-review.js +187 -0
- package/dist/workspace/templates/playbook-lifecycle-review.js.map +1 -0
- package/dist/workspace/types.d.ts +12 -54
- package/dist/workspace/types.d.ts.map +1 -1
- package/dist/workspace/types.js.map +1 -1
- package/package.json +8 -2
- package/playbooks/compound-engineering/adversarial-review.json +51 -0
- package/playbooks/compound-engineering/agent-native-architecture.json +59 -0
- package/playbooks/compound-engineering/agent-native-review.json +54 -0
- package/playbooks/compound-engineering/api-contract-review.json +52 -0
- package/playbooks/compound-engineering/brainstorm-requirements.json +55 -0
- package/playbooks/compound-engineering/bug-reproduction.json +62 -0
- package/playbooks/compound-engineering/confidence-calibration.json +49 -0
- package/playbooks/compound-engineering/correctness-review.json +49 -0
- package/playbooks/compound-engineering/data-migration-safety.json +59 -0
- package/playbooks/compound-engineering/deployment-verification.json +63 -0
- package/playbooks/compound-engineering/error-recovery-patterns.json +53 -0
- package/playbooks/compound-engineering/implementation-planning.json +64 -0
- package/playbooks/compound-engineering/issue-pattern-analysis.json +53 -0
- package/playbooks/compound-engineering/knowledge-compounding.json +63 -0
- package/playbooks/compound-engineering/learnings-research.json +54 -0
- package/playbooks/compound-engineering/maintainability-review.json +49 -0
- package/playbooks/compound-engineering/performance-review.json +54 -0
- package/playbooks/compound-engineering/plan-adversarial-review.json +56 -0
- package/playbooks/compound-engineering/plan-feasibility-review.json +56 -0
- package/playbooks/compound-engineering/project-standards-review.json +52 -0
- package/playbooks/compound-engineering/reliability-review.json +53 -0
- package/playbooks/compound-engineering/review-orchestration.json +64 -0
- package/playbooks/compound-engineering/security-review.json +54 -0
- package/playbooks/compound-engineering/systematic-execution.json +64 -0
- package/playbooks/compound-engineering/testing-review.json +50 -0
- package/src/atlas.ts +96 -0
- package/src/index.ts +27 -0
- package/src/learning/index.ts +1 -0
- package/src/learning/unified-pipeline.ts +271 -1
- package/src/memory/candidate-retrieval.ts +2 -1
- package/src/memory/curated-loader.ts +69 -16
- package/src/memory/index.ts +16 -0
- package/src/memory/playbook.ts +19 -0
- package/src/memory/source-resolver.ts +422 -0
- package/src/types/config.ts +46 -0
- package/src/types/index.ts +4 -0
- package/src/utils/error-classifier.ts +8 -8
- package/src/workspace/efficacy-toolkit.ts +496 -0
- package/src/workspace/index.ts +29 -0
- package/src/workspace/templates/index.ts +24 -0
- package/src/workspace/templates/playbook-decay-detection.ts +272 -0
- package/src/workspace/templates/playbook-efficacy-audit.ts +246 -0
- package/src/workspace/templates/playbook-lifecycle-review.ts +274 -0
- package/src/workspace/types.ts +22 -78
- package/tests/fixtures/behavioral-trajectories.ts +210 -0
- package/tests/integration/curated-sources-e2e.test.ts +502 -0
- package/tests/integration/pipeline-data-correctness.test.ts +794 -0
- package/tests/learning/meta-learner.test.ts +418 -0
- package/tests/learning/pipeline-memory-updates.test.ts +721 -0
- package/tests/learning/unified-pipeline-efficacy.test.ts +232 -0
- package/tests/memory/candidate-retrieval.test.ts +167 -0
- package/tests/memory/compound-engineering-seed.test.ts +338 -0
- package/tests/memory/curated-loader-extended.test.ts +225 -0
- package/tests/memory/meta.test.ts +399 -0
- package/tests/memory/playbook-quality-validation.test.ts +430 -0
- package/tests/memory/source-resolver.test.ts +700 -0
- package/tests/search/evaluator.test.ts +257 -0
- package/tests/search/verification-runner.test.ts +357 -0
- package/tests/utils/error-classifier.test.ts +149 -0
- package/tests/utils/trajectory-helpers.test.ts +163 -0
- package/tests/workspace/efficacy-toolkit.test.ts +404 -0
- package/tests/workspace/templates/playbook-efficacy.test.ts +377 -0
- package/.claude/settings.local.json +0 -11
- package/dist/learning/llm-extractor.d.ts +0 -88
- package/dist/learning/llm-extractor.d.ts.map +0 -1
- package/dist/learning/llm-extractor.js +0 -372
- package/dist/learning/llm-extractor.js.map +0 -1
- package/dist/learning/loop-coordinator.d.ts +0 -61
- package/dist/learning/loop-coordinator.d.ts.map +0 -1
- package/dist/learning/loop-coordinator.js +0 -96
- package/dist/learning/loop-coordinator.js.map +0 -1
- package/references/agent-workspace/CLAUDE.md +0 -74
- package/references/agent-workspace/README.md +0 -587
- package/references/agent-workspace/media/banner.png +0 -0
- package/references/agent-workspace/package-lock.json +0 -2061
- package/references/agent-workspace/package.json +0 -54
- package/references/agent-workspace/src/handle.ts +0 -122
- package/references/agent-workspace/src/index.ts +0 -32
- package/references/agent-workspace/src/manager.ts +0 -102
- package/references/agent-workspace/src/readers/json.ts +0 -71
- package/references/agent-workspace/src/readers/markdown.ts +0 -37
- package/references/agent-workspace/src/readers/raw.ts +0 -27
- package/references/agent-workspace/src/types.ts +0 -68
- package/references/agent-workspace/src/validation.ts +0 -93
- package/references/agent-workspace/src/writers/json.ts +0 -17
- package/references/agent-workspace/src/writers/markdown.ts +0 -27
- package/references/agent-workspace/src/writers/raw.ts +0 -22
- package/references/agent-workspace/tests/errors.test.ts +0 -652
- package/references/agent-workspace/tests/handle.test.ts +0 -144
- package/references/agent-workspace/tests/manager.test.ts +0 -124
- package/references/agent-workspace/tests/readers.test.ts +0 -205
- package/references/agent-workspace/tests/validation.test.ts +0 -196
- package/references/agent-workspace/tests/writers.test.ts +0 -108
- package/references/agent-workspace/tsconfig.json +0 -20
- package/references/agent-workspace/tsup.config.ts +0 -9
- package/references/minimem/.claude/settings.json +0 -7
- package/references/minimem/.sudocode/issues.jsonl +0 -18
- package/references/minimem/.sudocode/specs.jsonl +0 -1
- package/references/minimem/CLAUDE.md +0 -310
- package/references/minimem/README.md +0 -556
- package/references/minimem/claude-plugin/.claude-plugin/plugin.json +0 -10
- package/references/minimem/claude-plugin/.mcp.json +0 -7
- package/references/minimem/claude-plugin/README.md +0 -158
- package/references/minimem/claude-plugin/commands/recall.md +0 -47
- package/references/minimem/claude-plugin/commands/remember.md +0 -41
- package/references/minimem/claude-plugin/hooks/__tests__/hooks.test.ts +0 -272
- package/references/minimem/claude-plugin/hooks/hooks.json +0 -27
- package/references/minimem/claude-plugin/hooks/session-end.sh +0 -86
- package/references/minimem/claude-plugin/hooks/session-start.sh +0 -85
- package/references/minimem/claude-plugin/skills/memory/SKILL.md +0 -108
- package/references/minimem/package-lock.json +0 -5373
- package/references/minimem/package.json +0 -60
- package/references/minimem/scripts/postbuild.js +0 -35
- package/references/minimem/src/__tests__/edge-cases.test.ts +0 -371
- package/references/minimem/src/__tests__/errors.test.ts +0 -265
- package/references/minimem/src/__tests__/helpers.ts +0 -199
- package/references/minimem/src/__tests__/internal.test.ts +0 -407
- package/references/minimem/src/__tests__/knowledge.test.ts +0 -287
- package/references/minimem/src/__tests__/minimem.integration.test.ts +0 -1127
- package/references/minimem/src/__tests__/session.test.ts +0 -190
- package/references/minimem/src/cli/__tests__/commands.test.ts +0 -759
- package/references/minimem/src/cli/commands/__tests__/conflicts.test.ts +0 -141
- package/references/minimem/src/cli/commands/append.ts +0 -76
- package/references/minimem/src/cli/commands/config.ts +0 -262
- package/references/minimem/src/cli/commands/conflicts.ts +0 -413
- package/references/minimem/src/cli/commands/daemon.ts +0 -169
- package/references/minimem/src/cli/commands/index.ts +0 -12
- package/references/minimem/src/cli/commands/init.ts +0 -88
- package/references/minimem/src/cli/commands/mcp.ts +0 -177
- package/references/minimem/src/cli/commands/push-pull.ts +0 -213
- package/references/minimem/src/cli/commands/search.ts +0 -158
- package/references/minimem/src/cli/commands/status.ts +0 -84
- package/references/minimem/src/cli/commands/sync-init.ts +0 -290
- package/references/minimem/src/cli/commands/sync.ts +0 -70
- package/references/minimem/src/cli/commands/upsert.ts +0 -197
- package/references/minimem/src/cli/config.ts +0 -584
- package/references/minimem/src/cli/index.ts +0 -264
- package/references/minimem/src/cli/shared.ts +0 -161
- package/references/minimem/src/cli/sync/__tests__/central.test.ts +0 -152
- package/references/minimem/src/cli/sync/__tests__/conflicts.test.ts +0 -209
- package/references/minimem/src/cli/sync/__tests__/daemon.test.ts +0 -118
- package/references/minimem/src/cli/sync/__tests__/detection.test.ts +0 -207
- package/references/minimem/src/cli/sync/__tests__/integration.test.ts +0 -476
- package/references/minimem/src/cli/sync/__tests__/registry.test.ts +0 -363
- package/references/minimem/src/cli/sync/__tests__/state.test.ts +0 -255
- package/references/minimem/src/cli/sync/__tests__/validation.test.ts +0 -193
- package/references/minimem/src/cli/sync/__tests__/watcher.test.ts +0 -178
- package/references/minimem/src/cli/sync/central.ts +0 -292
- package/references/minimem/src/cli/sync/conflicts.ts +0 -204
- package/references/minimem/src/cli/sync/daemon.ts +0 -407
- package/references/minimem/src/cli/sync/detection.ts +0 -138
- package/references/minimem/src/cli/sync/index.ts +0 -107
- package/references/minimem/src/cli/sync/operations.ts +0 -373
- package/references/minimem/src/cli/sync/registry.ts +0 -279
- package/references/minimem/src/cli/sync/state.ts +0 -355
- package/references/minimem/src/cli/sync/validation.ts +0 -206
- package/references/minimem/src/cli/sync/watcher.ts +0 -234
- package/references/minimem/src/cli/version.ts +0 -34
- package/references/minimem/src/core/index.ts +0 -9
- package/references/minimem/src/core/indexer.ts +0 -628
- package/references/minimem/src/core/searcher.ts +0 -221
- package/references/minimem/src/db/schema.ts +0 -183
- package/references/minimem/src/db/sqlite-vec.ts +0 -24
- package/references/minimem/src/embeddings/__tests__/embeddings.test.ts +0 -431
- package/references/minimem/src/embeddings/batch-gemini.ts +0 -392
- package/references/minimem/src/embeddings/batch-openai.ts +0 -409
- package/references/minimem/src/embeddings/embeddings.ts +0 -434
- package/references/minimem/src/index.ts +0 -109
- package/references/minimem/src/internal.ts +0 -299
- package/references/minimem/src/minimem.ts +0 -1276
- package/references/minimem/src/search/__tests__/hybrid.test.ts +0 -247
- package/references/minimem/src/search/graph.ts +0 -234
- package/references/minimem/src/search/hybrid.ts +0 -151
- package/references/minimem/src/search/search.ts +0 -256
- package/references/minimem/src/server/__tests__/mcp.test.ts +0 -341
- package/references/minimem/src/server/__tests__/tools.test.ts +0 -364
- package/references/minimem/src/server/mcp.ts +0 -326
- package/references/minimem/src/server/tools.ts +0 -720
- package/references/minimem/src/session.ts +0 -460
- package/references/minimem/tsconfig.json +0 -19
- package/references/minimem/tsup.config.ts +0 -26
- package/references/minimem/vitest.config.ts +0 -24
- package/references/sessionlog/.husky/pre-commit +0 -1
- package/references/sessionlog/.lintstagedrc.json +0 -4
- package/references/sessionlog/.prettierignore +0 -4
- package/references/sessionlog/.prettierrc.json +0 -11
- package/references/sessionlog/LICENSE +0 -21
- package/references/sessionlog/README.md +0 -453
- package/references/sessionlog/eslint.config.js +0 -58
- package/references/sessionlog/package-lock.json +0 -3672
- package/references/sessionlog/package.json +0 -65
- package/references/sessionlog/src/__tests__/agent-hooks.test.ts +0 -570
- package/references/sessionlog/src/__tests__/agent-registry.test.ts +0 -127
- package/references/sessionlog/src/__tests__/claude-code-hooks.test.ts +0 -225
- package/references/sessionlog/src/__tests__/claude-generator.test.ts +0 -46
- package/references/sessionlog/src/__tests__/commit-msg.test.ts +0 -86
- package/references/sessionlog/src/__tests__/cursor-agent.test.ts +0 -224
- package/references/sessionlog/src/__tests__/e2e-live.test.ts +0 -890
- package/references/sessionlog/src/__tests__/event-log.test.ts +0 -183
- package/references/sessionlog/src/__tests__/flush-sentinel.test.ts +0 -105
- package/references/sessionlog/src/__tests__/gemini-agent.test.ts +0 -375
- package/references/sessionlog/src/__tests__/git-hooks.test.ts +0 -78
- package/references/sessionlog/src/__tests__/hook-managers.test.ts +0 -121
- package/references/sessionlog/src/__tests__/lifecycle-tasks.test.ts +0 -759
- package/references/sessionlog/src/__tests__/opencode-agent.test.ts +0 -338
- package/references/sessionlog/src/__tests__/redaction.test.ts +0 -136
- package/references/sessionlog/src/__tests__/session-repo.test.ts +0 -353
- package/references/sessionlog/src/__tests__/session-store.test.ts +0 -166
- package/references/sessionlog/src/__tests__/setup-ccweb.test.ts +0 -466
- package/references/sessionlog/src/__tests__/skill-live.test.ts +0 -461
- package/references/sessionlog/src/__tests__/summarize.test.ts +0 -348
- package/references/sessionlog/src/__tests__/task-plan-e2e.test.ts +0 -610
- package/references/sessionlog/src/__tests__/task-plan-live.test.ts +0 -632
- package/references/sessionlog/src/__tests__/transcript-timestamp.test.ts +0 -121
- package/references/sessionlog/src/__tests__/types.test.ts +0 -166
- package/references/sessionlog/src/__tests__/utils.test.ts +0 -333
- package/references/sessionlog/src/__tests__/validation.test.ts +0 -103
- package/references/sessionlog/src/__tests__/worktree.test.ts +0 -57
- package/references/sessionlog/src/agent/agents/claude-code.ts +0 -1089
- package/references/sessionlog/src/agent/agents/cursor.ts +0 -361
- package/references/sessionlog/src/agent/agents/gemini-cli.ts +0 -632
- package/references/sessionlog/src/agent/agents/opencode.ts +0 -540
- package/references/sessionlog/src/agent/registry.ts +0 -143
- package/references/sessionlog/src/agent/session-types.ts +0 -113
- package/references/sessionlog/src/agent/types.ts +0 -220
- package/references/sessionlog/src/cli.ts +0 -597
- package/references/sessionlog/src/commands/clean.ts +0 -133
- package/references/sessionlog/src/commands/disable.ts +0 -84
- package/references/sessionlog/src/commands/doctor.ts +0 -145
- package/references/sessionlog/src/commands/enable.ts +0 -202
- package/references/sessionlog/src/commands/explain.ts +0 -261
- package/references/sessionlog/src/commands/reset.ts +0 -105
- package/references/sessionlog/src/commands/resume.ts +0 -180
- package/references/sessionlog/src/commands/rewind.ts +0 -195
- package/references/sessionlog/src/commands/setup-ccweb.ts +0 -275
- package/references/sessionlog/src/commands/status.ts +0 -172
- package/references/sessionlog/src/config.ts +0 -165
- package/references/sessionlog/src/events/event-log.ts +0 -126
- package/references/sessionlog/src/git-operations.ts +0 -558
- package/references/sessionlog/src/hooks/git-hooks.ts +0 -165
- package/references/sessionlog/src/hooks/lifecycle.ts +0 -391
- package/references/sessionlog/src/index.ts +0 -650
- package/references/sessionlog/src/security/redaction.ts +0 -283
- package/references/sessionlog/src/session/state-machine.ts +0 -452
- package/references/sessionlog/src/store/checkpoint-store.ts +0 -509
- package/references/sessionlog/src/store/native-store.ts +0 -173
- package/references/sessionlog/src/store/provider-types.ts +0 -99
- package/references/sessionlog/src/store/session-store.ts +0 -266
- package/references/sessionlog/src/strategy/attribution.ts +0 -296
- package/references/sessionlog/src/strategy/common.ts +0 -207
- package/references/sessionlog/src/strategy/content-overlap.ts +0 -228
- package/references/sessionlog/src/strategy/manual-commit.ts +0 -988
- package/references/sessionlog/src/strategy/types.ts +0 -279
- package/references/sessionlog/src/summarize/claude-generator.ts +0 -115
- package/references/sessionlog/src/summarize/summarize.ts +0 -432
- package/references/sessionlog/src/types.ts +0 -508
- package/references/sessionlog/src/utils/chunk-files.ts +0 -49
- package/references/sessionlog/src/utils/commit-message.ts +0 -65
- package/references/sessionlog/src/utils/detect-agent.ts +0 -36
- package/references/sessionlog/src/utils/hook-managers.ts +0 -125
- package/references/sessionlog/src/utils/ide-tags.ts +0 -32
- package/references/sessionlog/src/utils/paths.ts +0 -79
- package/references/sessionlog/src/utils/preview-rewind.ts +0 -80
- package/references/sessionlog/src/utils/rewind-conflict.ts +0 -121
- package/references/sessionlog/src/utils/shadow-branch.ts +0 -109
- package/references/sessionlog/src/utils/string-utils.ts +0 -46
- package/references/sessionlog/src/utils/todo-extract.ts +0 -188
- package/references/sessionlog/src/utils/trailers.ts +0 -187
- package/references/sessionlog/src/utils/transcript-parse.ts +0 -177
- package/references/sessionlog/src/utils/transcript-timestamp.ts +0 -59
- package/references/sessionlog/src/utils/tree-ops.ts +0 -219
- package/references/sessionlog/src/utils/tty.ts +0 -72
- package/references/sessionlog/src/utils/validation.ts +0 -65
- package/references/sessionlog/src/utils/worktree.ts +0 -58
- package/references/sessionlog/src/wire-types.ts +0 -59
- package/references/sessionlog/templates/setup-env.sh +0 -153
- package/references/sessionlog/tsconfig.json +0 -18
- package/references/sessionlog/vitest.config.ts +0 -12
- package/references/skill-tree/.claude/settings.json +0 -6
- package/references/skill-tree/.sudocode/issues.jsonl +0 -19
- package/references/skill-tree/.sudocode/specs.jsonl +0 -3
- package/references/skill-tree/CLAUDE.md +0 -126
- package/references/skill-tree/README.md +0 -372
- package/references/skill-tree/docs/GAPS_v1.md +0 -221
- package/references/skill-tree/docs/INTEGRATION_PLAN.md +0 -467
- package/references/skill-tree/docs/TODOS.md +0 -91
- package/references/skill-tree/docs/anthropic_skill_guide.md +0 -1364
- package/references/skill-tree/docs/design/federated-skill-trees.md +0 -524
- package/references/skill-tree/docs/design/multi-agent-sync.md +0 -759
- package/references/skill-tree/docs/scraper/BRAINSTORM.md +0 -583
- package/references/skill-tree/docs/scraper/POC_PLAN.md +0 -420
- package/references/skill-tree/docs/scraper/README.md +0 -170
- package/references/skill-tree/examples/basic-usage.ts +0 -164
- package/references/skill-tree/package-lock.json +0 -1852
- package/references/skill-tree/package.json +0 -66
- package/references/skill-tree/scraper/README.md +0 -123
- package/references/skill-tree/scraper/docs/DESIGN.md +0 -683
- package/references/skill-tree/scraper/docs/PLAN.md +0 -336
- package/references/skill-tree/scraper/drizzle.config.ts +0 -10
- package/references/skill-tree/scraper/package-lock.json +0 -6329
- package/references/skill-tree/scraper/package.json +0 -68
- package/references/skill-tree/scraper/test/fixtures/invalid-skill/missing-description.md +0 -7
- package/references/skill-tree/scraper/test/fixtures/invalid-skill/missing-name.md +0 -7
- package/references/skill-tree/scraper/test/fixtures/minimal-skill/SKILL.md +0 -27
- package/references/skill-tree/scraper/test/fixtures/skill-json/SKILL.json +0 -21
- package/references/skill-tree/scraper/test/fixtures/skill-with-meta/SKILL.md +0 -54
- package/references/skill-tree/scraper/test/fixtures/skill-with-meta/_meta.json +0 -24
- package/references/skill-tree/scraper/test/fixtures/valid-skill/SKILL.md +0 -93
- package/references/skill-tree/scraper/test/fixtures/valid-skill/_meta.json +0 -22
- package/references/skill-tree/scraper/tsup.config.ts +0 -14
- package/references/skill-tree/scraper/vitest.config.ts +0 -17
- package/references/skill-tree/scripts/convert-to-vitest.ts +0 -166
- package/references/skill-tree/skills/skill-writer/SKILL.md +0 -339
- package/references/skill-tree/skills/skill-writer/references/examples.md +0 -326
- package/references/skill-tree/skills/skill-writer/references/patterns.md +0 -210
- package/references/skill-tree/skills/skill-writer/references/quality-checklist.md +0 -123
- package/references/skill-tree/test/run-all.ts +0 -106
- package/references/skill-tree/test/utils.ts +0 -128
- package/references/skill-tree/vitest.config.ts +0 -16
|
@@ -1,1276 +0,0 @@
|
|
|
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
|
-
}
|