@vpxa/aikit 0.1.58 → 0.1.60
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +38 -3
- package/package.json +2 -1
- package/packages/aikit-client/dist/index.d.ts +146 -4
- package/packages/aikit-client/dist/index.js +5 -1
- package/packages/analyzers/dist/index.d.ts +309 -11
- package/packages/analyzers/dist/index.js +54 -1
- package/packages/chunker/dist/index.d.ts +451 -18
- package/packages/chunker/dist/index.js +24 -1
- package/packages/cli/dist/{commands/init/constants.js → constants-D3v4VDf0.js} +1 -1
- package/packages/cli/dist/index.js +15 -2
- package/packages/cli/dist/init-D0CiV9PX.js +7 -0
- package/packages/cli/dist/scaffold-CJwkHf-q.js +2 -0
- package/packages/cli/dist/{commands/init/templates.js → templates-DJ7EC5vw.js} +1 -1
- package/packages/cli/dist/user-HmJYNt5b.js +5 -0
- package/packages/core/dist/index.d.ts +357 -6
- package/packages/core/dist/index.js +1 -1
- package/packages/dashboard/dist/assets/{index-Cdke3KDK.js → index-C6D-PCp0.js} +7 -7
- package/packages/dashboard/dist/assets/index-C6D-PCp0.js.map +1 -0
- package/packages/dashboard/dist/index.html +1 -1
- package/packages/elicitation/dist/index.d.ts +139 -4
- package/packages/elicitation/dist/index.js +1 -1
- package/packages/embeddings/dist/index.d.ts +45 -2
- package/packages/embeddings/dist/index.js +1 -1
- package/packages/enterprise-bridge/dist/index.d.ts +275 -7
- package/packages/enterprise-bridge/dist/index.js +1 -1
- package/packages/flows/dist/index.d.ts +345 -12
- package/packages/flows/dist/index.js +15 -1
- package/packages/indexer/dist/index.d.ts +196 -6
- package/packages/indexer/dist/index.js +1 -1
- package/packages/present/dist/index.html +315 -314
- package/packages/server/dist/curated-manager-DX-_oJg0.js +5 -0
- package/packages/server/dist/index.d.ts +139 -1
- package/packages/server/dist/index.js +1 -1
- package/packages/server/dist/server-eMZ64H9b.js +1274 -0
- package/packages/store/dist/index.d.ts +316 -5
- package/packages/store/dist/index.js +90 -1
- package/packages/store/dist/lance-store-jdHZp-V4.js +1 -0
- package/packages/tools/dist/index.d.ts +2161 -61
- package/packages/tools/dist/index.js +117 -1
- package/packages/tui/dist/{App-CoMyn2kt.js → App-DobfqTPH.js} +1 -1
- package/packages/tui/dist/App.d.ts +1 -1
- package/packages/tui/dist/App.js +1 -1
- package/packages/tui/dist/{LogPanel-CDItCD0E.js → LogPanel-DGeptKim.js} +3 -3
- package/packages/tui/dist/hooks/useKBClient.d.ts +1 -1
- package/packages/tui/dist/{index-MXJeXmCf.d.ts → index-floZQwfo.d.ts} +2 -1
- package/packages/tui/dist/index.d.ts +1 -1
- package/packages/tui/dist/index.js +1 -1
- package/packages/tui/dist/panels/LogPanel.js +1 -1
- package/scaffold/definitions/bodies.mjs +47 -0
- package/scaffold/definitions/protocols.mjs +9 -0
- package/scaffold/definitions/tools.mjs +15 -0
- package/scaffold/general/agents/Debugger.agent.md +9 -0
- package/scaffold/general/agents/Documenter.agent.md +9 -0
- package/scaffold/general/agents/Frontend.agent.md +9 -0
- package/scaffold/general/agents/Implementer.agent.md +9 -0
- package/scaffold/general/agents/Orchestrator.agent.md +47 -0
- package/scaffold/general/agents/Planner.agent.md +9 -0
- package/scaffold/general/agents/Refactor.agent.md +9 -0
- package/scaffold/general/agents/Security.agent.md +9 -0
- package/scaffold/general/agents/_shared/code-agent-base.md +9 -0
- package/scaffold/general/skills/aikit/SKILL.md +71 -7
- package/scaffold/general/skills/c4-architecture/SKILL.md +87 -1
- package/scaffold/general/skills/c4-architecture/references/html-design-system.md +337 -0
- package/scaffold/general/skills/c4-architecture/references/html-template.html +627 -0
- package/scaffold/general/skills/present/SKILL.md +180 -0
- package/packages/aikit-client/dist/direct-client.d.ts +0 -37
- package/packages/aikit-client/dist/direct-client.js +0 -1
- package/packages/aikit-client/dist/mcp-client.d.ts +0 -19
- package/packages/aikit-client/dist/mcp-client.js +0 -4
- package/packages/aikit-client/dist/parsers.d.ts +0 -35
- package/packages/aikit-client/dist/parsers.js +0 -2
- package/packages/aikit-client/dist/types.d.ts +0 -62
- package/packages/aikit-client/dist/types.js +0 -1
- package/packages/analyzers/dist/blast-radius-analyzer.d.ts +0 -19
- package/packages/analyzers/dist/blast-radius-analyzer.js +0 -6
- package/packages/analyzers/dist/dependency-analyzer.d.ts +0 -32
- package/packages/analyzers/dist/dependency-analyzer.js +0 -8
- package/packages/analyzers/dist/diagram-generator.d.ts +0 -16
- package/packages/analyzers/dist/diagram-generator.js +0 -2
- package/packages/analyzers/dist/entry-point-analyzer.d.ts +0 -40
- package/packages/analyzers/dist/entry-point-analyzer.js +0 -4
- package/packages/analyzers/dist/knowledge-producer.d.ts +0 -40
- package/packages/analyzers/dist/knowledge-producer.js +0 -26
- package/packages/analyzers/dist/pattern-analyzer.d.ts +0 -15
- package/packages/analyzers/dist/pattern-analyzer.js +0 -2
- package/packages/analyzers/dist/regex-call-graph.d.ts +0 -10
- package/packages/analyzers/dist/regex-call-graph.js +0 -1
- package/packages/analyzers/dist/structure-analyzer.d.ts +0 -19
- package/packages/analyzers/dist/structure-analyzer.js +0 -4
- package/packages/analyzers/dist/symbol-analyzer.d.ts +0 -14
- package/packages/analyzers/dist/symbol-analyzer.js +0 -9
- package/packages/analyzers/dist/ts-call-graph.d.ts +0 -29
- package/packages/analyzers/dist/ts-call-graph.js +0 -1
- package/packages/analyzers/dist/types.d.ts +0 -110
- package/packages/analyzers/dist/types.js +0 -1
- package/packages/chunker/dist/call-graph-extractor.d.ts +0 -25
- package/packages/chunker/dist/call-graph-extractor.js +0 -1
- package/packages/chunker/dist/chunker-factory.d.ts +0 -19
- package/packages/chunker/dist/chunker-factory.js +0 -1
- package/packages/chunker/dist/chunker.interface.d.ts +0 -13
- package/packages/chunker/dist/chunker.interface.js +0 -1
- package/packages/chunker/dist/code-chunker.d.ts +0 -17
- package/packages/chunker/dist/code-chunker.js +0 -11
- package/packages/chunker/dist/extractors/call-extractor.d.ts +0 -24
- package/packages/chunker/dist/extractors/call-extractor.js +0 -1
- package/packages/chunker/dist/extractors/entry-point-detector.d.ts +0 -14
- package/packages/chunker/dist/extractors/entry-point-detector.js +0 -1
- package/packages/chunker/dist/extractors/import-extractor.d.ts +0 -14
- package/packages/chunker/dist/extractors/import-extractor.js +0 -1
- package/packages/chunker/dist/extractors/pattern-detector.d.ts +0 -14
- package/packages/chunker/dist/extractors/pattern-detector.js +0 -1
- package/packages/chunker/dist/extractors/scope-resolver.d.ts +0 -26
- package/packages/chunker/dist/extractors/scope-resolver.js +0 -1
- package/packages/chunker/dist/extractors/symbol-extractor.d.ts +0 -14
- package/packages/chunker/dist/extractors/symbol-extractor.js +0 -3
- package/packages/chunker/dist/extractors/types.d.ts +0 -44
- package/packages/chunker/dist/extractors/types.js +0 -1
- package/packages/chunker/dist/generic-chunker.d.ts +0 -15
- package/packages/chunker/dist/generic-chunker.js +0 -5
- package/packages/chunker/dist/markdown-chunker.d.ts +0 -17
- package/packages/chunker/dist/markdown-chunker.js +0 -3
- package/packages/chunker/dist/wasm/languages.d.ts +0 -18
- package/packages/chunker/dist/wasm/languages.js +0 -1
- package/packages/chunker/dist/wasm/query-executor.d.ts +0 -70
- package/packages/chunker/dist/wasm/query-executor.js +0 -1
- package/packages/chunker/dist/wasm/runtime.d.ts +0 -44
- package/packages/chunker/dist/wasm/runtime.js +0 -1
- package/packages/chunker/dist/wasm/types.d.ts +0 -84
- package/packages/chunker/dist/wasm/types.js +0 -1
- package/packages/chunker/dist/wasm-chunker.d.ts +0 -23
- package/packages/chunker/dist/wasm-chunker.js +0 -6
- package/packages/cli/dist/aikit-init.d.ts +0 -59
- package/packages/cli/dist/aikit-init.js +0 -1
- package/packages/cli/dist/commands/analyze.d.ts +0 -6
- package/packages/cli/dist/commands/analyze.js +0 -2
- package/packages/cli/dist/commands/context-cmds.d.ts +0 -6
- package/packages/cli/dist/commands/context-cmds.js +0 -1
- package/packages/cli/dist/commands/environment.d.ts +0 -6
- package/packages/cli/dist/commands/environment.js +0 -1
- package/packages/cli/dist/commands/execution.d.ts +0 -6
- package/packages/cli/dist/commands/execution.js +0 -1
- package/packages/cli/dist/commands/flow.d.ts +0 -6
- package/packages/cli/dist/commands/flow.js +0 -1
- package/packages/cli/dist/commands/graph.d.ts +0 -6
- package/packages/cli/dist/commands/graph.js +0 -6
- package/packages/cli/dist/commands/init/adapters.d.ts +0 -28
- package/packages/cli/dist/commands/init/adapters.js +0 -1
- package/packages/cli/dist/commands/init/config.d.ts +0 -10
- package/packages/cli/dist/commands/init/config.js +0 -3
- package/packages/cli/dist/commands/init/constants.d.ts +0 -46
- package/packages/cli/dist/commands/init/curated.d.ts +0 -7
- package/packages/cli/dist/commands/init/curated.js +0 -1
- package/packages/cli/dist/commands/init/frontmatter.d.ts +0 -79
- package/packages/cli/dist/commands/init/frontmatter.js +0 -2
- package/packages/cli/dist/commands/init/index.d.ts +0 -36
- package/packages/cli/dist/commands/init/index.js +0 -5
- package/packages/cli/dist/commands/init/manifest.d.ts +0 -72
- package/packages/cli/dist/commands/init/manifest.js +0 -1
- package/packages/cli/dist/commands/init/scaffold.d.ts +0 -58
- package/packages/cli/dist/commands/init/scaffold.js +0 -1
- package/packages/cli/dist/commands/init/templates.d.ts +0 -9
- package/packages/cli/dist/commands/init/user.d.ts +0 -61
- package/packages/cli/dist/commands/init/user.js +0 -5
- package/packages/cli/dist/commands/knowledge.d.ts +0 -6
- package/packages/cli/dist/commands/knowledge.js +0 -1
- package/packages/cli/dist/commands/search.d.ts +0 -6
- package/packages/cli/dist/commands/search.js +0 -1
- package/packages/cli/dist/commands/system.d.ts +0 -6
- package/packages/cli/dist/commands/system.js +0 -4
- package/packages/cli/dist/commands/upgrade.d.ts +0 -6
- package/packages/cli/dist/commands/upgrade.js +0 -1
- package/packages/cli/dist/commands/workspace.d.ts +0 -6
- package/packages/cli/dist/commands/workspace.js +0 -1
- package/packages/cli/dist/context.d.ts +0 -7
- package/packages/cli/dist/context.js +0 -1
- package/packages/cli/dist/helpers.d.ts +0 -55
- package/packages/cli/dist/helpers.js +0 -5
- package/packages/cli/dist/types.d.ts +0 -9
- package/packages/cli/dist/types.js +0 -1
- package/packages/core/dist/constants.d.ts +0 -74
- package/packages/core/dist/constants.js +0 -1
- package/packages/core/dist/content-detector.d.ts +0 -13
- package/packages/core/dist/content-detector.js +0 -1
- package/packages/core/dist/errors.d.ts +0 -20
- package/packages/core/dist/errors.js +0 -1
- package/packages/core/dist/global-registry.d.ts +0 -69
- package/packages/core/dist/global-registry.js +0 -1
- package/packages/core/dist/logger.d.ts +0 -32
- package/packages/core/dist/logger.js +0 -1
- package/packages/core/dist/types.d.ts +0 -149
- package/packages/core/dist/types.js +0 -1
- package/packages/dashboard/dist/assets/index-Cdke3KDK.js.map +0 -1
- package/packages/elicitation/dist/build.d.ts +0 -14
- package/packages/elicitation/dist/build.js +0 -1
- package/packages/elicitation/dist/fields.d.ts +0 -32
- package/packages/elicitation/dist/fields.js +0 -1
- package/packages/elicitation/dist/normalize.d.ts +0 -15
- package/packages/elicitation/dist/normalize.js +0 -1
- package/packages/elicitation/dist/types.d.ts +0 -88
- package/packages/elicitation/dist/types.js +0 -1
- package/packages/embeddings/dist/embedder.interface.d.ts +0 -26
- package/packages/embeddings/dist/embedder.interface.js +0 -1
- package/packages/embeddings/dist/onnx-embedder.d.ts +0 -23
- package/packages/embeddings/dist/onnx-embedder.js +0 -1
- package/packages/enterprise-bridge/dist/cache.d.ts +0 -28
- package/packages/enterprise-bridge/dist/cache.js +0 -1
- package/packages/enterprise-bridge/dist/er-client.d.ts +0 -37
- package/packages/enterprise-bridge/dist/er-client.js +0 -1
- package/packages/enterprise-bridge/dist/evolution-collector.d.ts +0 -62
- package/packages/enterprise-bridge/dist/evolution-collector.js +0 -1
- package/packages/enterprise-bridge/dist/policy-store.d.ts +0 -45
- package/packages/enterprise-bridge/dist/policy-store.js +0 -1
- package/packages/enterprise-bridge/dist/push-adapter.d.ts +0 -23
- package/packages/enterprise-bridge/dist/push-adapter.js +0 -1
- package/packages/enterprise-bridge/dist/result-merger.d.ts +0 -14
- package/packages/enterprise-bridge/dist/result-merger.js +0 -1
- package/packages/enterprise-bridge/dist/types.d.ts +0 -81
- package/packages/enterprise-bridge/dist/types.js +0 -1
- package/packages/flows/dist/adapters/claude-plugin.d.ts +0 -25
- package/packages/flows/dist/adapters/claude-plugin.js +0 -3
- package/packages/flows/dist/adapters/copilot.d.ts +0 -12
- package/packages/flows/dist/adapters/copilot.js +0 -1
- package/packages/flows/dist/adapters/index.d.ts +0 -12
- package/packages/flows/dist/adapters/index.js +0 -1
- package/packages/flows/dist/adapters/native.d.ts +0 -10
- package/packages/flows/dist/adapters/native.js +0 -1
- package/packages/flows/dist/adapters/openspec.d.ts +0 -40
- package/packages/flows/dist/adapters/openspec.js +0 -1
- package/packages/flows/dist/builtins.d.ts +0 -16
- package/packages/flows/dist/builtins.js +0 -1
- package/packages/flows/dist/foundation.d.ts +0 -20
- package/packages/flows/dist/foundation.js +0 -11
- package/packages/flows/dist/git.d.ts +0 -53
- package/packages/flows/dist/git.js +0 -2
- package/packages/flows/dist/loader.d.ts +0 -13
- package/packages/flows/dist/loader.js +0 -2
- package/packages/flows/dist/registry.d.ts +0 -23
- package/packages/flows/dist/registry.js +0 -1
- package/packages/flows/dist/state-machine.d.ts +0 -23
- package/packages/flows/dist/state-machine.js +0 -1
- package/packages/flows/dist/symlinks.d.ts +0 -17
- package/packages/flows/dist/symlinks.js +0 -1
- package/packages/flows/dist/types.d.ts +0 -127
- package/packages/flows/dist/types.js +0 -1
- package/packages/indexer/dist/file-hasher.d.ts +0 -13
- package/packages/indexer/dist/file-hasher.js +0 -1
- package/packages/indexer/dist/filesystem-crawler.d.ts +0 -29
- package/packages/indexer/dist/filesystem-crawler.js +0 -1
- package/packages/indexer/dist/graph-extractor.d.ts +0 -22
- package/packages/indexer/dist/graph-extractor.js +0 -1
- package/packages/indexer/dist/hash-cache.d.ts +0 -24
- package/packages/indexer/dist/hash-cache.js +0 -1
- package/packages/indexer/dist/incremental-indexer.d.ts +0 -73
- package/packages/indexer/dist/incremental-indexer.js +0 -1
- package/packages/indexer/dist/smart-index-scheduler.d.ts +0 -47
- package/packages/indexer/dist/smart-index-scheduler.js +0 -1
- package/packages/server/dist/api.d.ts +0 -3
- package/packages/server/dist/api.js +0 -1
- package/packages/server/dist/auto-gc.d.ts +0 -30
- package/packages/server/dist/auto-gc.js +0 -1
- package/packages/server/dist/background-task.d.ts +0 -47
- package/packages/server/dist/background-task.js +0 -1
- package/packages/server/dist/completions.d.ts +0 -14
- package/packages/server/dist/completions.js +0 -1
- package/packages/server/dist/compression-interceptor.d.ts +0 -12
- package/packages/server/dist/compression-interceptor.js +0 -1
- package/packages/server/dist/config.d.ts +0 -16
- package/packages/server/dist/cross-workspace.d.ts +0 -43
- package/packages/server/dist/cross-workspace.js +0 -1
- package/packages/server/dist/curated-manager.d.ts +0 -92
- package/packages/server/dist/curated-manager.js +0 -5
- package/packages/server/dist/dashboard-static.d.ts +0 -27
- package/packages/server/dist/elicitor.d.ts +0 -18
- package/packages/server/dist/elicitor.js +0 -1
- package/packages/server/dist/idle-timer.d.ts +0 -33
- package/packages/server/dist/idle-timer.js +0 -1
- package/packages/server/dist/mcp-logging.d.ts +0 -11
- package/packages/server/dist/mcp-logging.js +0 -1
- package/packages/server/dist/memory-monitor.d.ts +0 -37
- package/packages/server/dist/memory-monitor.js +0 -1
- package/packages/server/dist/output-schemas.d.ts +0 -244
- package/packages/server/dist/output-schemas.js +0 -1
- package/packages/server/dist/prompts.d.ts +0 -13
- package/packages/server/dist/prompts.js +0 -13
- package/packages/server/dist/replay-interceptor.d.ts +0 -23
- package/packages/server/dist/replay-interceptor.js +0 -1
- package/packages/server/dist/resource-links.d.ts +0 -34
- package/packages/server/dist/resource-links.js +0 -1
- package/packages/server/dist/resources/curated-resources.d.ts +0 -13
- package/packages/server/dist/resources/curated-resources.js +0 -2
- package/packages/server/dist/resources/resource-notifier.d.ts +0 -45
- package/packages/server/dist/resources/resource-notifier.js +0 -1
- package/packages/server/dist/resources/resources.d.ts +0 -8
- package/packages/server/dist/resources/resources.js +0 -2
- package/packages/server/dist/sampling.d.ts +0 -41
- package/packages/server/dist/sampling.js +0 -2
- package/packages/server/dist/server.d.ts +0 -63
- package/packages/server/dist/server.js +0 -3
- package/packages/server/dist/structured-content-guard.d.ts +0 -28
- package/packages/server/dist/structured-content-guard.js +0 -1
- package/packages/server/dist/task-manager.d.ts +0 -40
- package/packages/server/dist/task-manager.js +0 -1
- package/packages/server/dist/tool-metadata.d.ts +0 -38
- package/packages/server/dist/tool-metadata.js +0 -1
- package/packages/server/dist/tool-prefix.d.ts +0 -12
- package/packages/server/dist/tool-prefix.js +0 -1
- package/packages/server/dist/tool-timeout.d.ts +0 -27
- package/packages/server/dist/tool-timeout.js +0 -1
- package/packages/server/dist/tools/analyze.tools.d.ts +0 -14
- package/packages/server/dist/tools/analyze.tools.js +0 -8
- package/packages/server/dist/tools/audit.tool.d.ts +0 -8
- package/packages/server/dist/tools/audit.tool.js +0 -1
- package/packages/server/dist/tools/brainstorm.tool.d.ts +0 -7
- package/packages/server/dist/tools/brainstorm.tool.js +0 -9
- package/packages/server/dist/tools/bridge.tools.d.ts +0 -34
- package/packages/server/dist/tools/bridge.tools.js +0 -15
- package/packages/server/dist/tools/config.tool.d.ts +0 -8
- package/packages/server/dist/tools/config.tool.js +0 -12
- package/packages/server/dist/tools/context.tools.d.ts +0 -15
- package/packages/server/dist/tools/context.tools.js +0 -10
- package/packages/server/dist/tools/evolution.tools.d.ts +0 -7
- package/packages/server/dist/tools/evolution.tools.js +0 -5
- package/packages/server/dist/tools/execution.tools.d.ts +0 -14
- package/packages/server/dist/tools/execution.tools.js +0 -4
- package/packages/server/dist/tools/flow.tools.d.ts +0 -7
- package/packages/server/dist/tools/flow.tools.js +0 -16
- package/packages/server/dist/tools/forge.tools.d.ts +0 -13
- package/packages/server/dist/tools/forge.tools.js +0 -10
- package/packages/server/dist/tools/forget.tool.d.ts +0 -8
- package/packages/server/dist/tools/forget.tool.js +0 -1
- package/packages/server/dist/tools/graph.tool.d.ts +0 -7
- package/packages/server/dist/tools/graph.tool.js +0 -29
- package/packages/server/dist/tools/infra.tools.d.ts +0 -10
- package/packages/server/dist/tools/infra.tools.js +0 -5
- package/packages/server/dist/tools/list.tool.d.ts +0 -7
- package/packages/server/dist/tools/list.tool.js +0 -2
- package/packages/server/dist/tools/lookup.tool.d.ts +0 -7
- package/packages/server/dist/tools/lookup.tool.js +0 -3
- package/packages/server/dist/tools/manipulation.tools.d.ts +0 -10
- package/packages/server/dist/tools/manipulation.tools.js +0 -4
- package/packages/server/dist/tools/onboard.tool.d.ts +0 -12
- package/packages/server/dist/tools/onboard.tool.js +0 -2
- package/packages/server/dist/tools/persistence.tools.d.ts +0 -10
- package/packages/server/dist/tools/persistence.tools.js +0 -5
- package/packages/server/dist/tools/policy.tools.d.ts +0 -7
- package/packages/server/dist/tools/policy.tools.js +0 -3
- package/packages/server/dist/tools/present/browser.d.ts +0 -4
- package/packages/server/dist/tools/present/browser.js +0 -93
- package/packages/server/dist/tools/present/helpers.d.ts +0 -19
- package/packages/server/dist/tools/present/helpers.js +0 -16
- package/packages/server/dist/tools/present/html.d.ts +0 -18
- package/packages/server/dist/tools/present/html.js +0 -5
- package/packages/server/dist/tools/present/index.d.ts +0 -2
- package/packages/server/dist/tools/present/index.js +0 -1
- package/packages/server/dist/tools/present/markdown.d.ts +0 -32
- package/packages/server/dist/tools/present/markdown.js +0 -11
- package/packages/server/dist/tools/present/templates.d.ts +0 -14
- package/packages/server/dist/tools/present/templates.js +0 -472
- package/packages/server/dist/tools/present/tool.d.ts +0 -27
- package/packages/server/dist/tools/present/tool.js +0 -39
- package/packages/server/dist/tools/present-blocks.d.ts +0 -46
- package/packages/server/dist/tools/present-blocks.js +0 -27
- package/packages/server/dist/tools/present-charts.d.ts +0 -31
- package/packages/server/dist/tools/present-charts.js +0 -34
- package/packages/server/dist/tools/present-theme.d.ts +0 -14
- package/packages/server/dist/tools/present-theme.js +0 -396
- package/packages/server/dist/tools/present-utils.d.ts +0 -11
- package/packages/server/dist/tools/present-utils.js +0 -1
- package/packages/server/dist/tools/present.tool.d.ts +0 -2
- package/packages/server/dist/tools/present.tool.js +0 -1
- package/packages/server/dist/tools/produce.tool.d.ts +0 -7
- package/packages/server/dist/tools/produce.tool.js +0 -4
- package/packages/server/dist/tools/read.tool.d.ts +0 -7
- package/packages/server/dist/tools/read.tool.js +0 -2
- package/packages/server/dist/tools/reindex.tool.d.ts +0 -11
- package/packages/server/dist/tools/reindex.tool.js +0 -9
- package/packages/server/dist/tools/remember.tool.d.ts +0 -9
- package/packages/server/dist/tools/remember.tool.js +0 -4
- package/packages/server/dist/tools/replay.tool.d.ts +0 -6
- package/packages/server/dist/tools/replay.tool.js +0 -3
- package/packages/server/dist/tools/restore.tool.d.ts +0 -6
- package/packages/server/dist/tools/restore.tool.js +0 -3
- package/packages/server/dist/tools/search.tool.d.ts +0 -11
- package/packages/server/dist/tools/search.tool.js +0 -10
- package/packages/server/dist/tools/status.tool.d.ts +0 -28
- package/packages/server/dist/tools/status.tool.js +0 -3
- package/packages/server/dist/tools/update.tool.d.ts +0 -8
- package/packages/server/dist/tools/update.tool.js +0 -1
- package/packages/server/dist/tools/utility.tools.d.ts +0 -15
- package/packages/server/dist/tools/utility.tools.js +0 -13
- package/packages/server/dist/version-check.d.ts +0 -32
- package/packages/store/dist/graph-store.interface.d.ts +0 -159
- package/packages/store/dist/graph-store.interface.js +0 -1
- package/packages/store/dist/lance-store.d.ts +0 -46
- package/packages/store/dist/lance-store.js +0 -1
- package/packages/store/dist/sqlite-graph-store.d.ts +0 -57
- package/packages/store/dist/sqlite-graph-store.js +0 -90
- package/packages/store/dist/store-factory.d.ts +0 -12
- package/packages/store/dist/store-factory.js +0 -1
- package/packages/store/dist/store.interface.d.ts +0 -54
- package/packages/store/dist/store.interface.js +0 -1
- package/packages/tools/dist/audit.d.ts +0 -65
- package/packages/tools/dist/audit.js +0 -6
- package/packages/tools/dist/batch.d.ts +0 -23
- package/packages/tools/dist/batch.js +0 -1
- package/packages/tools/dist/changelog.d.ts +0 -36
- package/packages/tools/dist/changelog.js +0 -2
- package/packages/tools/dist/check.d.ts +0 -48
- package/packages/tools/dist/check.js +0 -2
- package/packages/tools/dist/checkpoint.d.ts +0 -19
- package/packages/tools/dist/checkpoint.js +0 -1
- package/packages/tools/dist/codemod.d.ts +0 -39
- package/packages/tools/dist/codemod.js +0 -2
- package/packages/tools/dist/compact.d.ts +0 -47
- package/packages/tools/dist/compact.js +0 -3
- package/packages/tools/dist/compress-output.d.ts +0 -38
- package/packages/tools/dist/compress-output.js +0 -1
- package/packages/tools/dist/compression/delta-cache.d.ts +0 -29
- package/packages/tools/dist/compression/delta-cache.js +0 -1
- package/packages/tools/dist/compression/engine.d.ts +0 -34
- package/packages/tools/dist/compression/engine.js +0 -4
- package/packages/tools/dist/compression/litm.d.ts +0 -20
- package/packages/tools/dist/compression/litm.js +0 -1
- package/packages/tools/dist/compression/mmr.d.ts +0 -24
- package/packages/tools/dist/compression/mmr.js +0 -1
- package/packages/tools/dist/compression/rules/docker.d.ts +0 -11
- package/packages/tools/dist/compression/rules/docker.js +0 -3
- package/packages/tools/dist/compression/rules/generic.d.ts +0 -11
- package/packages/tools/dist/compression/rules/generic.js +0 -3
- package/packages/tools/dist/compression/rules/git.d.ts +0 -11
- package/packages/tools/dist/compression/rules/git.js +0 -3
- package/packages/tools/dist/compression/rules/index.d.ts +0 -14
- package/packages/tools/dist/compression/rules/index.js +0 -1
- package/packages/tools/dist/compression/rules/kubectl.d.ts +0 -11
- package/packages/tools/dist/compression/rules/kubectl.js +0 -3
- package/packages/tools/dist/compression/rules/lint.d.ts +0 -11
- package/packages/tools/dist/compression/rules/lint.js +0 -3
- package/packages/tools/dist/compression/rules/npm.d.ts +0 -11
- package/packages/tools/dist/compression/rules/npm.js +0 -3
- package/packages/tools/dist/compression/rules/test-runner.d.ts +0 -11
- package/packages/tools/dist/compression/rules/test-runner.js +0 -3
- package/packages/tools/dist/compression/scoring.d.ts +0 -26
- package/packages/tools/dist/compression/scoring.js +0 -1
- package/packages/tools/dist/compression/types.d.ts +0 -61
- package/packages/tools/dist/compression/types.js +0 -1
- package/packages/tools/dist/config-extractor.d.ts +0 -9
- package/packages/tools/dist/config-extractor.js +0 -7
- package/packages/tools/dist/data-transform.d.ts +0 -12
- package/packages/tools/dist/data-transform.js +0 -1
- package/packages/tools/dist/dead-symbols.d.ts +0 -28
- package/packages/tools/dist/dead-symbols.js +0 -2
- package/packages/tools/dist/delegate.d.ts +0 -36
- package/packages/tools/dist/delegate.js +0 -1
- package/packages/tools/dist/diagram-builder.d.ts +0 -9
- package/packages/tools/dist/diagram-builder.js +0 -9
- package/packages/tools/dist/diff-parse.d.ts +0 -28
- package/packages/tools/dist/diff-parse.js +0 -3
- package/packages/tools/dist/digest.d.ts +0 -55
- package/packages/tools/dist/digest.js +0 -6
- package/packages/tools/dist/dogfood-log.d.ts +0 -49
- package/packages/tools/dist/dogfood-log.js +0 -2
- package/packages/tools/dist/encode.d.ts +0 -16
- package/packages/tools/dist/encode.js +0 -1
- package/packages/tools/dist/env-info.d.ts +0 -30
- package/packages/tools/dist/env-info.js +0 -1
- package/packages/tools/dist/eval.d.ts +0 -15
- package/packages/tools/dist/eval.js +0 -2
- package/packages/tools/dist/evidence-map.d.ts +0 -92
- package/packages/tools/dist/evidence-map.js +0 -2
- package/packages/tools/dist/file-cache.d.ts +0 -41
- package/packages/tools/dist/file-cache.js +0 -3
- package/packages/tools/dist/file-summary.d.ts +0 -52
- package/packages/tools/dist/file-summary.js +0 -2
- package/packages/tools/dist/file-walk.d.ts +0 -6
- package/packages/tools/dist/file-walk.js +0 -1
- package/packages/tools/dist/find-examples.d.ts +0 -29
- package/packages/tools/dist/find-examples.js +0 -3
- package/packages/tools/dist/find.d.ts +0 -49
- package/packages/tools/dist/find.js +0 -1
- package/packages/tools/dist/forge-classify.d.ts +0 -44
- package/packages/tools/dist/forge-classify.js +0 -2
- package/packages/tools/dist/forge-ground.d.ts +0 -61
- package/packages/tools/dist/forge-ground.js +0 -1
- package/packages/tools/dist/git-context.d.ts +0 -25
- package/packages/tools/dist/git-context.js +0 -3
- package/packages/tools/dist/graph-query.d.ts +0 -98
- package/packages/tools/dist/graph-query.js +0 -1
- package/packages/tools/dist/guide.d.ts +0 -25
- package/packages/tools/dist/guide.js +0 -1
- package/packages/tools/dist/health.d.ts +0 -16
- package/packages/tools/dist/health.js +0 -2
- package/packages/tools/dist/http-request.d.ts +0 -25
- package/packages/tools/dist/http-request.js +0 -1
- package/packages/tools/dist/lane.d.ts +0 -41
- package/packages/tools/dist/lane.js +0 -6
- package/packages/tools/dist/measure.d.ts +0 -42
- package/packages/tools/dist/measure.js +0 -2
- package/packages/tools/dist/onboard-utils.d.ts +0 -12
- package/packages/tools/dist/onboard-utils.js +0 -1
- package/packages/tools/dist/onboard.d.ts +0 -50
- package/packages/tools/dist/onboard.js +0 -18
- package/packages/tools/dist/parse-output.d.ts +0 -84
- package/packages/tools/dist/parse-output.js +0 -2
- package/packages/tools/dist/path-resolver.d.ts +0 -14
- package/packages/tools/dist/path-resolver.js +0 -1
- package/packages/tools/dist/process-manager.d.ts +0 -20
- package/packages/tools/dist/process-manager.js +0 -1
- package/packages/tools/dist/queue.d.ts +0 -40
- package/packages/tools/dist/queue.js +0 -1
- package/packages/tools/dist/regex-test.d.ts +0 -33
- package/packages/tools/dist/regex-test.js +0 -1
- package/packages/tools/dist/regex-utils.d.ts +0 -8
- package/packages/tools/dist/regex-utils.js +0 -1
- package/packages/tools/dist/rename.d.ts +0 -31
- package/packages/tools/dist/rename.js +0 -2
- package/packages/tools/dist/replay.d.ts +0 -59
- package/packages/tools/dist/replay.js +0 -4
- package/packages/tools/dist/response-envelope.d.ts +0 -43
- package/packages/tools/dist/response-envelope.js +0 -1
- package/packages/tools/dist/restore-points.d.ts +0 -22
- package/packages/tools/dist/restore-points.js +0 -1
- package/packages/tools/dist/schema-validate.d.ts +0 -25
- package/packages/tools/dist/schema-validate.js +0 -1
- package/packages/tools/dist/scope-map.d.ts +0 -51
- package/packages/tools/dist/scope-map.js +0 -1
- package/packages/tools/dist/snippet.d.ts +0 -35
- package/packages/tools/dist/snippet.js +0 -1
- package/packages/tools/dist/stash.d.ts +0 -14
- package/packages/tools/dist/stash.js +0 -1
- package/packages/tools/dist/stratum-card.d.ts +0 -30
- package/packages/tools/dist/stratum-card.js +0 -4
- package/packages/tools/dist/symbol.d.ts +0 -45
- package/packages/tools/dist/symbol.js +0 -3
- package/packages/tools/dist/synthesis-engine.d.ts +0 -13
- package/packages/tools/dist/synthesis-engine.js +0 -6
- package/packages/tools/dist/test-run.d.ts +0 -28
- package/packages/tools/dist/test-run.js +0 -2
- package/packages/tools/dist/text-utils.d.ts +0 -24
- package/packages/tools/dist/text-utils.js +0 -2
- package/packages/tools/dist/time-utils.d.ts +0 -20
- package/packages/tools/dist/time-utils.js +0 -1
- package/packages/tools/dist/trace.d.ts +0 -43
- package/packages/tools/dist/trace.js +0 -2
- package/packages/tools/dist/truncation.d.ts +0 -66
- package/packages/tools/dist/truncation.js +0 -11
- package/packages/tools/dist/watch.d.ts +0 -32
- package/packages/tools/dist/watch.js +0 -1
- package/packages/tools/dist/web-fetch.d.ts +0 -47
- package/packages/tools/dist/web-fetch.js +0 -8
- package/packages/tools/dist/web-search.d.ts +0 -25
- package/packages/tools/dist/web-search.js +0 -1
- package/packages/tools/dist/workset.d.ts +0 -47
- package/packages/tools/dist/workset.js +0 -1
- package/scaffold/__tests__/copilot-inline-shared-protocols.test.mjs +0 -39
- /package/packages/server/dist/{config.js → config-C5IU9Lau.js} +0 -0
- /package/packages/server/dist/{dashboard-static.js → dashboard-static-BfIe0Si1.js} +0 -0
- /package/packages/server/dist/{version-check.js → version-check-D4j0Pykd.js} +0 -0
|
@@ -1,11 +0,0 @@
|
|
|
1
|
-
import { ISamplingClient } from "../sampling.js";
|
|
2
|
-
import { BridgeComponents } from "./bridge.tools.js";
|
|
3
|
-
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
4
|
-
import { EvolutionCollector } from "../../../enterprise-bridge/dist/index.js";
|
|
5
|
-
import { IGraphStore, IKnowledgeStore } from "../../../store/dist/index.js";
|
|
6
|
-
import { IEmbedder } from "../../../embeddings/dist/index.js";
|
|
7
|
-
|
|
8
|
-
//#region packages/server/src/tools/search.tool.d.ts
|
|
9
|
-
declare function registerSearchTool(server: McpServer, embedder: IEmbedder, store: IKnowledgeStore, graphStore?: IGraphStore, bridge?: BridgeComponents, evolutionCollector?: EvolutionCollector, samplingClient?: ISamplingClient): void;
|
|
10
|
-
//#endregion
|
|
11
|
-
export { registerSearchTool };
|
|
@@ -1,10 +0,0 @@
|
|
|
1
|
-
import{getToolMeta as e}from"../tool-metadata.js";import{SearchOutputSchema as t}from"../output-schemas.js";import{fanOutFtsSearch as n,fanOutSearch as r,openWorkspaceStores as i,resolveWorkspaces as a}from"../cross-workspace.js";import{curatedResourceLink as o,extractCuratedPath as s}from"../resource-links.js";import{basename as c}from"node:path";import{z as l}from"zod";import{stat as u}from"node:fs/promises";import{CONTENT_TYPES as d,KNOWLEDGE_ORIGINS as f,SOURCE_TYPES as p,computePartitionKey as m,createLogger as h,serializeError as g}from"../../../core/dist/index.js";import{bookendReorder as _,graphAugmentSearch as v,stashGet as y,truncateToTokenBudget as b}from"../../../tools/dist/index.js";import{mergeResults as x}from"../../../enterprise-bridge/dist/index.js";const S=h(`tools`);function ee(e){let t=[],n=c(process.cwd());n&&t.push(`[project: ${n}]`);let r=y(`__context_boost`);return r&&t.push(`[focus: ${r.value}]`),t.length===0?e:`${t.join(` `)} ${e}`}async function C(e,t,n,r,i){if(!e||t>=e.config.fallbackThreshold&&n.length>0)return{results:n,triggered:!1,cacheHit:!1};let a=!1;try{let t=e.cache.get(r);return t?a=!0:(t=await e.client.search(r,i),t.length>0&&e.cache.set(r,t)),t.length>0?{results:x(n,t,i).map(e=>({record:{id:`er:${e.sourcePath}`,content:e.content,sourcePath:e.source===`er`?`[ER] ${e.sourcePath}`:e.sourcePath,startLine:e.startLine??0,endLine:e.endLine??0,contentType:e.contentType??`documentation`,headingPath:e.headingPath,origin:e.source===`er`?`curated`:e.origin??`indexed`,category:e.category,tags:e.tags??[],chunkIndex:0,totalChunks:1,fileHash:``,indexedAt:new Date().toISOString(),version:1},score:e.score})),triggered:!0,cacheHit:a}:{results:n,triggered:!0,cacheHit:a}}catch(e){return S.warn(`ER fallback failed`,g(e)),{results:n,triggered:!0,cacheHit:a}}}function te(e,t,n=60){let r=new Map;for(let t=0;t<e.length;t++){let i=e[t];r.set(i.record.id,{record:i.record,score:1/(n+t+1)})}for(let e=0;e<t.length;e++){let i=t[e],a=r.get(i.record.id);a?a.score+=1/(n+e+1):r.set(i.record.id,{record:i.record,score:1/(n+e+1)})}return[...r.values()].sort((e,t)=>t.score-e.score).map(({record:e,score:t})=>({record:e,score:t}))}function w(e,t){let n=t.toLowerCase().split(/\s+/).filter(e=>e.length>=2);return n.length<2?e:e.map(e=>{let t=e.record.content.toLowerCase();if(t.length>5e3)return e;let r=n.map(e=>{let n=[],r=t.indexOf(e);for(;r!==-1&&n.length<10;)n.push(r),r=t.indexOf(e,r+1);return n});if(r.some(e=>e.length===0))return e;let i=t.length;for(let e of r[0]){let t=e,a=e+n[0].length;for(let i=1;i<r.length;i++){let o=r[i][0],s=Math.abs(o-e);for(let t=1;t<r[i].length;t++){let n=Math.abs(r[i][t]-e);n<s&&(s=n,o=r[i][t])}t=Math.min(t,o),a=Math.max(a,o+n[i].length)}i=Math.min(i,a-t)}let a=1+.25/(1+i/200);return{record:e.record,score:e.score*a}}).sort((e,t)=>t.score-e.score)}function T(e,t,n=8){let r=new Set(t.toLowerCase().split(/\s+/).filter(e=>e.length>=2)),i=new Map,a=e.length;for(let t of e){let e=t.record.content.split(/[^a-zA-Z0-9_]+/).filter(e=>e.length>=3&&!E.has(e.toLowerCase())),n=new Set;for(let t of e){let e=t.toLowerCase();/[_A-Z]/.test(t)&&i.set(`__id__${e}`,1),n.has(e)||(n.add(e),i.set(e,(i.get(e)??0)+1))}}let o=[];for(let[e,t]of i){if(e.startsWith(`__id__`)||r.has(e)||t>a*.8)continue;let n=Math.log(a/t),s=+!!i.has(`__id__${e}`),c=e.length>8?.5:0;o.push({term:e,score:n+s+c})}return o.sort((e,t)=>t.score-e.score).slice(0,n).map(e=>e.term)}const E=new Set(`the.and.for.are.but.not.you.all.can.had.her.was.one.our.out.has.have.from.this.that.with.they.been.said.each.which.their.will.other.about.many.then.them.these.some.would.make.like.into.could.time.very.when.come.just.know.take.people.also.back.after.only.more.than.over.such.import.export.const.function.return.true.false.null.undefined.string.number.boolean.void.type.interface`.split(`.`));async function D(e,t){try{let n=await e.getStats();if(!n.lastIndexedAt)return;let r=new Date(n.lastIndexedAt).getTime(),i=Date.now(),a=[...new Set(t.map(e=>e.record.sourcePath))].filter(e=>!e.startsWith(`[ER]`)).slice(0,5);if(a.length===0)return;let o=0;for(let e of a)try{(await u(e)).mtimeMs>r&&o++}catch{o++}if(o>0){let e=i-r,t=Math.floor(e/6e4),n=t<1?`<1 min`:`${t} min`;return`> ⚠️ **Index may be stale** — ${o} file(s) modified since last index (${n} ago). Use \`reindex\` to refresh.`}}catch{}}function O(c,u,h,y,x,E,O){let k=e(`search`);c.registerTool(`search`,{title:k.title,description:`Search AI Kit for code, docs, and prior decisions. Default choice for discovery. Modes: hybrid (default), semantic, keyword. For multi-strategy precision queries use find; for a known file path use lookup.`,outputSchema:t,inputSchema:{query:l.string().max(5e3).describe(`Natural language search query`),limit:l.number().min(1).max(20).default(5).describe(`Maximum results to return`),search_mode:l.enum([`hybrid`,`semantic`,`keyword`]).default(`hybrid`).describe(`Search strategy: hybrid (vector + FTS + RRF fusion, default), semantic (vector only), keyword (FTS only)`),content_type:l.enum(d).optional().describe(`Filter by content type`),source_type:l.enum(p).optional().describe(`Coarse filter: "source" (code only), "documentation" (md, curated), "test", "config". Overrides content_type if both set.`),origin:l.enum(f).optional().describe(`Filter by knowledge origin`),category:l.string().optional().describe(`Filter by category (e.g., decisions, patterns, conventions)`),tags:l.array(l.string()).optional().describe(`Filter by tags (returns results matching ANY of the specified tags)`),min_score:l.number().min(0).max(1).default(.25).describe(`Minimum similarity score`),graph_hops:l.number().min(0).max(3).default(1).describe(`Number of graph hops to augment results with connected entities (0 = disabled, 1 = direct connections, 2-3 = deeper traversal). Default 1 provides module/symbol context automatically.`),max_tokens:l.number().min(100).max(5e4).optional().describe(`Maximum token budget for the response. When set, output is truncated to fit.`),dedup:l.enum([`file`,`chunk`]).default(`chunk`).describe(`Deduplication mode: "chunk" (default, show all matching chunks) or "file" (collapse chunks from same file into single result with merged line ranges)`),workspaces:l.array(l.string()).optional().describe(`Cross-workspace search: partition names or folder basenames to include. Use ["*"] for all registered workspaces. Only works in user-level install mode.`)},annotations:k.annotations},async({query:e,limit:t,search_mode:c,content_type:l,source_type:d,origin:f,category:p,tags:k,min_score:ne,graph_hops:A,max_tokens:j,dedup:M,workspaces:N})=>{try{let P={limit:t,minScore:ne,contentType:l,sourceType:d,origin:f,category:p,tags:k},F,I=!1,L=!1,R=``,z=ee(e);if(c===`keyword`)F=await h.ftsSearch(e,P),F=F.slice(0,t);else if(c===`semantic`){let n=await u.embedQuery(z);F=await h.search(n,P);let r=await C(x,F[0]?.score??0,F,e,t);F=r.results,I=r.triggered,L=r.cacheHit}else{let n=await u.embedQuery(z),[r,i]=await Promise.all([h.search(n,{...P,limit:t*2}),h.ftsSearch(e,{...P,limit:t*2}).catch(()=>[])]);F=te(r,i).slice(0,t);let a=await C(x,r[0]?.score??0,F,e,t);F=a.results,I=a.triggered,L=a.cacheHit}E&&E.recordSearch(e,I,L),F.length>1&&(F=w(F,e));let B=``;if(N&&N.length>0){let o=a(N,m(process.cwd()));if(o.length>0){let{stores:a,closeAll:s}=await i(o);try{let i;i=c===`keyword`?await n(a,e,{...P,limit:t}):await r(a,await u.embedQuery(e),{...P,limit:t});for(let e of i)F.push({record:{...e.record,sourcePath:`[${e.workspace}] ${e.record.sourcePath}`},score:e.score});F=F.sort((e,t)=>t.score-e.score).slice(0,t),B=` + ${o.length} workspace(s)`}finally{await s()}}}if(M===`file`&&F.length>1){let e=new Map;for(let t of F){let n=t.record.sourcePath,r=e.get(n);r?(t.score>r.best.score&&(r.best=t),r.ranges.push({start:t.record.startLine,end:t.record.endLine})):e.set(n,{best:t,ranges:[{start:t.record.startLine,end:t.record.endLine}]})}F=[...e.values()].sort((e,t)=>t.best.score-e.best.score).map(({best:e,ranges:t})=>({record:{...e.record,content:t.length>1?`${e.record.content}\n\n_Matched ${t.length} sections: ${t.sort((e,t)=>e.start-t.start).map(e=>`L${e.start}-${e.end}`).join(`, `)}_`:e.record.content},score:e.score}))}if(F.length===0){if(O?.available)try{let t=(await O.createMessage({prompt:`The search query "${e}" returned 0 results in AI Kit code search. Suggest ONE alternative search query that might find relevant results. Reply with ONLY the alternative query, nothing else.`,systemPrompt:`You are a search query optimizer for AI Kit code search. Generate a single alternative query.`,maxTokens:100})).text.trim().split(`
|
|
2
|
-
`)[0].slice(0,500);if(t&&t!==e){let n=await u.embedQuery(t),r=await h.search(n,P);r.length>0&&(F=r,R=`> _Original query "${e}" returned 0 results. Auto-reformulated to "${t}"._\n\n`,S.info(`Smart search fallback succeeded`,{originalQuery:e,altQuery:t,resultCount:r.length}))}}catch(e){S.debug(`Smart search fallback failed`,{error:String(e)})}if(F.length===0)return{content:[{type:`text`,text:`No results found for the given query.`}],structuredContent:{results:[],totalResults:0,searchMode:c,query:e}}}let V,H;if(A>0&&!y&&(H="> **Note:** `graph_hops` was set but no graph store is available. Graph augmentation skipped."),A>0&&y)try{let e=await v(y,F.map(e=>({recordId:e.record.id,score:e.score,sourcePath:e.record.sourcePath})),{hops:A,maxPerHit:5});V=new Map;for(let t of e)if(t.graphContext.nodes.length>0){let e=t.graphContext.nodes.slice(0,5).map(e=>` - **${e.name}** (${e.type})`).join(`
|
|
3
|
-
`),n=t.graphContext.edges.slice(0,5).map(e=>` - ${e.fromId} —[${e.type}]→ ${e.toId}`).join(`
|
|
4
|
-
`),r=[`- **Graph Context** (${A} hop${A>1?`s`:``}):`];e&&r.push(` Entities:\n${e}`),n&&r.push(` Relationships:\n${n}`),V.set(t.recordId,r.join(`
|
|
5
|
-
`))}}catch(e){S.warn(`Graph augmentation failed`,g(e)),H=`> **Note:** Graph augmentation failed. Results shown without graph context.`}let U=Date.now();for(let e of F)if(e.record.origin===`curated`&&e.record.indexedAt){let t=U-new Date(e.record.indexedAt).getTime(),n=Math.max(0,t/864e5);e.score*=.95**n}F.sort((e,t)=>t.score-e.score),F=_(F);let W=F.map((e,t)=>{let n=e.record;return`${`### Result ${t+1} (score: ${e.score.toFixed(3)})`}\n${[`- **Source**: ${n.sourcePath}`,n.headingPath?`- **Section**: ${n.headingPath}`:null,`- **Type**: ${n.contentType}`,n.startLine?`- **Lines**: ${n.startLine}-${n.endLine}`:null,n.origin===`indexed`?null:`- **Origin**: ${n.origin}`,n.category?`- **Category**: ${n.category}`:null,n.tags?.length?`- **Tags**: ${n.tags.join(`, `)}`:null,V?.get(n.id)??null].filter(Boolean).join(`
|
|
6
|
-
`)}\n\n${n.content}`}).join(`
|
|
7
|
-
|
|
8
|
-
---
|
|
9
|
-
|
|
10
|
-
`),G=(c===`hybrid`?`hybrid (vector + keyword RRF)`:c===`keyword`?`keyword (FTS)`:`semantic (vector)`)+B,K=T(F,e),q=K.length>0?`\n_Distinctive terms: ${K.map(e=>`\`${e}\``).join(`, `)}_`:``,J=await D(h,F),Y=[];if(F.length===0)Y.push("`reindex` — no results found, index may be stale"),Y.push("`find` — try federated search with glob/regex");else{let e=F[0]?.record.sourcePath;e&&Y.push(`\`lookup\` — see all chunks from \`${e}\``),Y.push("`symbol` — resolve a specific symbol from the results"),Y.push("`compact` — compress a result file for focused reading")}let X=[H?`${H}\n\n`:``,J?`${J}\n\n`:``,W,`\n\n---\n_Search mode: ${G} | ${F.length} results_${q}`,`\n_Next: ${Y.join(` | `)}_`],Z=R+X.join(``);j&&(Z=b(Z,j));let Q=new Set,$=[];for(let e of F){if(e.record.origin!==`curated`||e.record.sourcePath.startsWith(`[`))continue;let t=s(e.record.sourcePath);if(!t)continue;let n=o(t,e.record.headingPath??t);n&&!Q.has(n.uri)&&(Q.add(n.uri),$.push(n))}return{content:[{type:`text`,text:Z},...$],structuredContent:{results:F.map(e=>({sourcePath:e.record.sourcePath,contentType:e.record.contentType,score:e.score,...e.record.headingPath?{headingPath:e.record.headingPath}:{},...e.record.startLine?{startLine:e.record.startLine}:{},...e.record.endLine?{endLine:e.record.endLine}:{},...e.record.origin===`indexed`?{}:{origin:e.record.origin},...e.record.category?{category:e.record.category}:{},...e.record.tags?.length?{tags:e.record.tags}:{}})),totalResults:F.length,searchMode:c,query:e}}}catch(e){return S.error(`Search failed`,g(e)),{content:[{type:`text`,text:`Search failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}export{O as registerSearchTool};
|
|
@@ -1,28 +0,0 @@
|
|
|
1
|
-
import { CuratedKnowledgeManager } from "../curated-manager.js";
|
|
2
|
-
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
3
|
-
import { KBConfig } from "../../../core/dist/index.js";
|
|
4
|
-
import { IGraphStore, IKnowledgeStore } from "../../../store/dist/index.js";
|
|
5
|
-
|
|
6
|
-
//#region packages/server/src/tools/status.tool.d.ts
|
|
7
|
-
interface OnboardState {
|
|
8
|
-
onboardComplete: boolean;
|
|
9
|
-
onboardTimestamp?: string;
|
|
10
|
-
}
|
|
11
|
-
declare function getScaffoldVersion(): string | null;
|
|
12
|
-
declare function getWorkspaceScaffoldVersion(): string | null;
|
|
13
|
-
/**
|
|
14
|
-
* Lightweight status tool registered during init — returns version info
|
|
15
|
-
* without needing the AI Kit store, graph, or curated manager.
|
|
16
|
-
*/
|
|
17
|
-
declare function registerEarlyStatusTool(server: McpServer): void;
|
|
18
|
-
interface SmartSchedulerState {
|
|
19
|
-
mode: string;
|
|
20
|
-
queueSize: number;
|
|
21
|
-
changedFilesSize: number;
|
|
22
|
-
intervalMs: number;
|
|
23
|
-
batchSize: number;
|
|
24
|
-
running: boolean;
|
|
25
|
-
}
|
|
26
|
-
declare function registerStatusTool(server: McpServer, store: IKnowledgeStore, graphStore?: IGraphStore, curated?: CuratedKnowledgeManager, onboardState?: OnboardState, config?: KBConfig, indexMode?: string, getSmartState?: (() => SmartSchedulerState) | null): void;
|
|
27
|
-
//#endregion
|
|
28
|
-
export { OnboardState, SmartSchedulerState, getScaffoldVersion, getWorkspaceScaffoldVersion, registerEarlyStatusTool, registerStatusTool };
|
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
import{getGcStatus as e}from"../auto-gc.js";import{getToolTelemetry as t}from"../replay-interceptor.js";import{getToolMeta as n}from"../tool-metadata.js";import{StatusOutputSchema as r}from"../output-schemas.js";import{autoUpgradeScaffold as i,getCurrentVersion as a,getUpgradeState as o}from"../version-check.js";import{existsSync as s,readFileSync as c,statSync as l}from"node:fs";import{resolve as u}from"node:path";import{homedir as d}from"node:os";import{AIKIT_PATHS as f,createLogger as p,serializeError as m}from"../../../core/dist/index.js";import{WasmRuntime as h}from"../../../chunker/dist/index.js";const g=p(`tools`);function _(e,t,n,r=15e3){let i,a=new Promise(e=>{i=setTimeout(()=>{g.warn(`Status sub-operation "${n}" timed out after ${r}ms`),e({value:t,timedOut:!0})},r)});return Promise.race([e.then(e=>(clearTimeout(i),{value:e,timedOut:!1}),e=>(clearTimeout(i),g.warn(`Status sub-operation "${n}" failed: ${e instanceof Error?e.message:String(e)}`),{value:t,timedOut:!1})),a])}const v=5*6e4;let y=null,b=null;function x(e,t,n,r){let i=Math.min(e/2e4,1),a=Math.min((t+n)/5e4,1),o=Math.min(r/200,1);return Math.round(i*40+a*35+o*25)}function S(){let e=Date.now();if(y&&e-y.ts<v)return y.value;try{let t=u(d(),`.copilot`,`.aikit-scaffold.json`);if(!s(t))return y={value:null,ts:e},null;let n=JSON.parse(c(t,`utf-8`)).version??null;return y={value:n,ts:e},n}catch{return y={value:null,ts:e},null}}function C(){let e=Date.now();if(b&&e-b.ts<v)return b.value;try{let t=u(process.cwd(),`.github`,`.aikit-scaffold.json`);if(!s(t))return b={value:null,ts:e},null;let n=JSON.parse(c(t,`utf-8`)).version??null;return b={value:n,ts:e},n}catch{return b={value:null,ts:e},null}}function w(e){let t=n(`status`);e.registerTool(`status`,{title:t.title,description:`Get the current status and statistics of the AI Kit index.`,outputSchema:r,annotations:t.annotations},async()=>{let e=a(),t=S(),n=C(),r=t!=null&&t!==e,s=n!=null&&n!==e,c=[`## AI Kit Status`,``,`⏳ **AI Kit is initializing** — index stats will be available shortly.`,``,`### Runtime`,`- **Tree-sitter (WASM)**: ${h.get()?`✅ Available (AST analysis)`:`⚠ Unavailable (regex fallback)`}`,``,`### Version`,`- **Server**: ${e}`,`- **Scaffold (user)**: ${t??`not installed`}`,`- **Scaffold (workspace)**: ${n??`not installed`}`];if(r||s){let a=o(),l=[];r&&l.push(`user scaffold v${t}`),s&&l.push(`workspace scaffold v${n}`);let u=l.join(`, `);a.state===`success`?c.push(``,`### ✅ Upgrade Applied`,`- Server v${e} — ${u} auto-upgraded successfully.`,`- _Restart the MCP server to use the updated version._`):a.state===`pending`?c.push(``,`### ⏳ Upgrade In Progress`,`- Server v${e} ≠ ${u}`,`- Auto-upgrade is running in the background…`):a.state===`failed`?(i(),c.push(``,`### ⬆ Upgrade Available (auto-upgrade failed, retrying)`,`- Server v${e} ≠ ${u}`,`- Error: ${a.error??`unknown`}`)):(i(),c.push(``,`### ⬆ Upgrade Available`,`- Server v${e} ≠ ${u}`,`- Auto-upgrade triggered — check again shortly.`))}let l={totalRecords:0,totalFiles:0,lastIndexedAt:null,onboarded:!1,onboardDir:``,contentTypes:{},wasmAvailable:!!h.get(),graphStats:null,curatedCount:0,serverVersion:e,scaffoldVersion:t??null,workspaceScaffoldVersion:n??null,upgradeAvailable:r||s,contextPressure:0};return{content:[{type:`text`,text:c.join(`
|
|
2
|
-
`)}],structuredContent:l}})}function T(c,d,p,v,y,b,w,T){let E=n(`status`);c.registerTool(`status`,{title:E.title,description:`Get the current status and statistics of the AI Kit index.`,outputSchema:r,annotations:E.annotations},async()=>{let n=[];try{let[r,c]=await Promise.all([_(d.getStats(),{totalRecords:0,totalFiles:0,lastIndexedAt:null,contentTypeBreakdown:{}},`store.getStats`),_(d.listSourcePaths(),[],`store.listSourcePaths`)]),m=r.value;r.timedOut&&n.push(`⚠ Index stats timed out — values may be incomplete`);let g=c.value;c.timedOut&&n.push(`⚠ File listing timed out`);let E=null,D=0,O=[`## AI Kit Status`,``,`- **Total Records**: ${m.totalRecords}`,`- **Total Files**: ${m.totalFiles}`,`- **Last Indexed**: ${m.lastIndexedAt??`Never`}`,``,`### Content Types`,...Object.entries(m.contentTypeBreakdown).map(([e,t])=>`- ${e}: ${t}`),``,`### Indexed Files`,...g.slice(0,50).map(e=>`- ${e}`),g.length>50?`\n... and ${g.length-50} more files`:``];if(p)try{let e=await _(p.getStats(),{nodeCount:0,edgeCount:0,nodeTypes:{},edgeTypes:{}},`graphStore.getStats`);if(e.timedOut)n.push(`⚠ Graph stats timed out`),O.push(``,`### Knowledge Graph`,`- Graph stats timed out`);else{let t=e.value;E={nodes:t.nodeCount,edges:t.edgeCount},O.push(``,`### Knowledge Graph`,`- **Nodes**: ${t.nodeCount}`,`- **Edges**: ${t.edgeCount}`,...Object.entries(t.nodeTypes).map(([e,t])=>` - ${e}: ${t}`));try{let e=await _(p.validate(),{valid:!0,danglingEdges:[],orphanNodes:[],stats:{nodeCount:0,edgeCount:0,nodeTypes:{},edgeTypes:{}}},`graphStore.validate`);if(!e.timedOut){let t=e.value;t.valid||O.push(`- **⚠ Integrity Issues**: ${t.danglingEdges.length} dangling edges`),t.orphanNodes.length>0&&O.push(`- **Orphan nodes**: ${t.orphanNodes.length}`)}}catch{}}}catch{O.push(``,`### Knowledge Graph`,`- Graph store unavailable`)}let k=b?.onboardDir??u(process.cwd(),f.aiContext),A=s(k),j=y?.onboardComplete||A;if(O.push(``,`### Onboard Status`,j?`- ✅ Complete${y?.onboardTimestamp?` (last: ${y.onboardTimestamp})`:``}`:'- ❌ Not run — call `onboard({ path: "." })` to analyze the codebase',`- **Onboard Directory**: \`${k}\``),v)try{let e=await _(v.list(),[],`curated.list`);if(e.timedOut)n.push(`⚠ Curated knowledge listing timed out`),O.push(``,`### Curated Knowledge`,`- Listing timed out`);else{let t=e.value;D=t.length,O.push(``,`### Curated Knowledge`,t.length>0?`- ${t.length} entries`:"- Empty — use `remember()` to persist decisions")}}catch{O.push(``,`### Curated Knowledge`,`- Unable to read curated entries`)}let M=x(m.totalRecords,E?.nodes??0,E?.edges??0,D);O.push(``),O.push(`## 📊 Context Pressure: ${M}/100`),M>=80?O.push(`⚠️ High pressure — consider pruning stale entries or compacting context.`):M>=50?O.push(`ℹ️ Moderate pressure — knowledge base is well-populated.`):O.push(`✅ Low pressure — plenty of headroom for more content.`);let N=0;if(m.lastIndexedAt){N=new Date(m.lastIndexedAt).getTime();let e=(Date.now()-N)/(1e3*60*60);O.push(``,`### Index Freshness`,e>24?w===`smart`?`- ⚠ Last indexed ${Math.floor(e)}h ago — smart indexing will refresh automatically`:`- ⚠ Last indexed ${Math.floor(e)}h ago — may be stale. Run \`reindex({})\``:`- ✅ Last indexed ${e<1?`less than 1h`:`${Math.floor(e)}h`} ago`)}if(w===`smart`)if(O.push(``,`### Smart Indexing`),T){let e=T();e?O.push(`- **Mode**: Smart (trickle)`,`- **Status**: ${e.running?`✅ Running`:`⏸ Stopped`}`,`- **Queue**: ${e.queueSize} files pending`,`- **Changed files**: ${e.changedFilesSize} detected`,`- **Interval**: ${Math.round(e.intervalMs/1e3)}s per batch of ${e.batchSize}`):O.push(`- **Mode**: Smart (trickle)`,`- **Status**: scheduler state unavailable (init may have failed)`)}else O.push(`- **Mode**: Smart (trickle) — scheduler state unavailable`);{try{let e=u(process.cwd(),f.data,`stash`);if(s(e)){let t=l(e).mtimeMs;t>N&&(N=t)}}catch{}let e=[];if(v)try{let t=D>0?await v.list():[];for(let e of t){let t=new Date(e.updated||e.created).getTime();t>N&&(N=t)}e.push(...t.sort((e,t)=>new Date(t.updated).getTime()-new Date(e.updated).getTime()).slice(0,5))}catch{}let t=N>0?Date.now()-N:0;if(t>=144e5){let n=Math.floor(t/36e5);if(O.push(``,`### 🌅 Session Briefing`,`_${n}+ hours since last activity — here's what to pick up:_`,``),e.length>0){O.push(`**Recent decisions/notes:**`);for(let t of e)O.push(`- **${t.title}** (${t.category??`note`}) — ${(t.contentPreview??``).slice(0,80)}…`)}O.push(``,`**Suggested next steps:**`,'- `search({ query: "SESSION CHECKPOINT", origin: "curated" })` — find your last checkpoint',"- `restore({})` — resume from a saved checkpoint","- `list()` — browse all stored knowledge")}}O.push(``,`### Runtime`,`- **Tree-sitter (WASM)**: ${h.get()?`✅ Available (AST analysis)`:`⚠ Unavailable (regex fallback)`}`);let P=S(),F=C(),I=a(),L=P!=null&&P!==I,R=F!=null&&F!==I;if(L||R){let e=o(),t=[];L&&t.push(`user scaffold v${P}`),R&&t.push(`workspace scaffold v${F}`);let n=t.join(`, `);e.state===`success`?O.push(``,`### ✅ Upgrade Applied`,`- Server v${I} — ${n} auto-upgraded successfully.`,`- _Restart the MCP server to use the updated version._`):e.state===`pending`?O.push(``,`### ⏳ Upgrade In Progress`,`- Server v${I} ≠ ${n}`,`- Auto-upgrade is running in the background…`):e.state===`failed`?(i(),O.push(``,`### ⬆ Upgrade Available (auto-upgrade failed, retrying)`,`- Server v${I} ≠ ${n}`,`- Error: ${e.error??`unknown`}`)):(i(),O.push(``,`### ⬆ Upgrade Available`,`- Server v${I} ≠ ${n}`,`- Auto-upgrade triggered — check again shortly.`))}n.length>0&&O.push(``,`### ⚠ Warnings`,...n.map(e=>`- ${e}`));let z=t();if(z.length>0){let e=z.sort((e,t)=>t.callCount-e.callCount);O.push(``,`### Tool Usage This Session`,``),O.push(`| Tool | Calls | Tokens In | Tokens Out | Errors | Avg Latency |`),O.push(`|------|-------|-----------|------------|--------|-------------|`);for(let t of e.slice(0,15)){let e=Math.round(t.totalInputChars/4),n=Math.round(t.totalOutputChars/4),r=Math.round(t.totalDurationMs/t.callCount);O.push(`| ${t.tool} | ${t.callCount} | ${e.toLocaleString()} | ${n.toLocaleString()} | ${t.errorCount} | ${r}ms |`)}}let B=e();if(B.bufferSize>=10){let e=B.state===`healthy`?`🟢`:B.state===`degraded`?`🔴`:`🟡`;O.push(``,`### Auto-GC: ${e} ${B.state}`),O.push(`- p95 latency: ${B.p95}ms | buffer: ${B.bufferSize} samples`),B.gcCount>0&&O.push(`- GC cycles triggered: ${B.gcCount}`)}let V=O.join(`
|
|
3
|
-
`),H={totalRecords:m.totalRecords,totalFiles:m.totalFiles,lastIndexedAt:m.lastIndexedAt??null,onboarded:j,onboardDir:k,contentTypes:m.contentTypeBreakdown,wasmAvailable:!!h.get(),graphStats:E,curatedCount:D,serverVersion:I,scaffoldVersion:P??null,workspaceScaffoldVersion:F??null,upgradeAvailable:L||R,contextPressure:M};return{content:[{type:`text`,text:V+(w===`smart`?"\n\n---\n_Next: Use `search` to query indexed content or `graph({action:'find_nodes', name_pattern:'<top-level-module>'})` → then `graph({action:'neighbors', node_id})` for relationships. Smart indexing handles updates automatically._":"\n\n---\n_Next: Use `search` to query indexed content, `graph({action:'find_nodes', name_pattern:'<top-level-module>'})` → then `graph({action:'neighbors', node_id})` for relationships, or `reindex` to refresh the index._")}],structuredContent:H}}catch(e){return g.error(`Status failed`,m(e)),{content:[{type:`text`,text:`Status check failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}export{S as getScaffoldVersion,C as getWorkspaceScaffoldVersion,w as registerEarlyStatusTool,T as registerStatusTool};
|
|
@@ -1,8 +0,0 @@
|
|
|
1
|
-
import { CuratedKnowledgeManager } from "../curated-manager.js";
|
|
2
|
-
import { ResourceNotifier } from "../resources/resource-notifier.js";
|
|
3
|
-
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
4
|
-
|
|
5
|
-
//#region packages/server/src/tools/update.tool.d.ts
|
|
6
|
-
declare function registerUpdateTool(server: McpServer, curated: CuratedKnowledgeManager, resourceNotifier?: ResourceNotifier): void;
|
|
7
|
-
//#endregion
|
|
8
|
-
export { registerUpdateTool };
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{getToolMeta as e}from"../tool-metadata.js";import{z as t}from"zod";import{createLogger as n,serializeError as r}from"../../../core/dist/index.js";const i=n(`tools`);function a(n,a,o){let s=e(`update`);n.registerTool(`update`,{title:s.title,description:`Update an existing curated knowledge entry. Increments version and records the reason in the changelog.`,inputSchema:{path:t.string().describe(`Relative path within .ai/curated/ (e.g., "decisions/use-lancedb.md")`),content:t.string().min(10).max(1e5).describe(`New markdown content to replace existing content`),reason:t.string().min(3).max(1e3).describe(`Why this update is being made (recorded in changelog)`)},annotations:s.annotations},async({path:e,content:t,reason:n})=>{try{let r=await a.update(e,t,n);return o&&o.notifyAfterCuratedWrite(e).catch(()=>{}),{content:[{type:`text`,text:`Updated: \`.ai/curated/${r.path}\` → version ${r.version}\n\nReason: ${n}\n\n---\n_Next: Use \`read\` to verify the updated content, or \`search\` to test searchability._`}]}}catch(e){return i.error(`Update failed`,r(e)),{content:[{type:`text`,text:`Update failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}export{a as registerUpdateTool};
|
|
@@ -1,15 +0,0 @@
|
|
|
1
|
-
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
2
|
-
|
|
3
|
-
//#region packages/server/src/tools/utility.tools.d.ts
|
|
4
|
-
declare function registerWebSearchTool(server: McpServer): void;
|
|
5
|
-
declare function registerHttpTool(server: McpServer): void;
|
|
6
|
-
declare function registerRegexTestTool(server: McpServer): void;
|
|
7
|
-
declare function registerEncodeTool(server: McpServer): void;
|
|
8
|
-
declare function registerMeasureTool(server: McpServer): void;
|
|
9
|
-
declare function registerChangelogTool(server: McpServer): void;
|
|
10
|
-
declare function registerSchemaValidateTool(server: McpServer): void;
|
|
11
|
-
declare function registerSnippetTool(server: McpServer): void;
|
|
12
|
-
declare function registerEnvTool(server: McpServer): void;
|
|
13
|
-
declare function registerTimeTool(server: McpServer): void;
|
|
14
|
-
//#endregion
|
|
15
|
-
export { registerChangelogTool, registerEncodeTool, registerEnvTool, registerHttpTool, registerMeasureTool, registerRegexTestTool, registerSchemaValidateTool, registerSnippetTool, registerTimeTool, registerWebSearchTool };
|
|
@@ -1,13 +0,0 @@
|
|
|
1
|
-
import{getToolMeta as e}from"../tool-metadata.js";import{EnvOutputSchema as t,MeasureOutputSchema as n,TimeOutputSchema as r}from"../output-schemas.js";import{z as i}from"zod";import{createLogger as a,serializeError as o}from"../../../core/dist/index.js";import{changelog as s,encode as c,envInfo as l,httpRequest as u,measure as d,regexTest as f,schemaValidate as p,snippet as m,timeUtils as h,webSearch as g}from"../../../tools/dist/index.js";const _=a(`tools`);function v(t){let n=e(`web_search`);t.registerTool(`web_search`,{title:n.title,description:`PREFERRED web search — search the web via DuckDuckGo (no API key). Pass one query or multiple for parallel searching. Returns structured results with title, URL, and snippet.`,inputSchema:{queries:i.array(i.string().max(2e3)).min(1).max(5).describe('Search queries (1–5). Single: `["react hooks"]`. Multiple searched in parallel.'),limit:i.number().min(1).max(20).default(5).describe(`Max results per query`),site:i.string().optional().describe(`Restrict to domain (e.g., "docs.aws.amazon.com")`)},annotations:n.annotations},async({queries:e,limit:t,site:n})=>{let r=e,i=async e=>{let r=await g({query:e,limit:t,site:n}),i=[`## Search: ${r.query}`,``];if(r.results.length===0)i.push(`No results found.`);else for(let e of r.results)i.push(`### [${e.title}](${e.url})`,e.snippet,``);return i.join(`
|
|
2
|
-
`)};if(r.length===1)try{return{content:[{type:`text`,text:`${await i(r[0])}\n---\n_Next: Use \`web_fetch\` to read any of these pages in full._`}]}}catch(e){return _.error(`Web search failed`,o(e)),{content:[{type:`text`,text:`Web search failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}let a=await Promise.allSettled(r.map(e=>i(e))),s=[],c=0;for(let e=0;e<a.length;e++){let t=a[e];if(t.status===`fulfilled`)s.push(t.value);else{c++;let n=t.reason instanceof Error?t.reason.message:String(t.reason);_.error(`Web search failed`,{query:r[e],error:n}),s.push(`## ❌ Search failed: ${r[e]}\n\n${n}`)}}let l=`_Searched ${a.length-c}/${a.length} queries successfully._`;return s.push(``,`---`,l,"_Next: Use `web_fetch` to read any of these pages in full._"),{content:[{type:`text`,text:s.join(`
|
|
3
|
-
|
|
4
|
-
`)}],...c===a.length?{isError:!0}:{}}})}function y(t){let n=e(`http`);t.registerTool(`http`,{title:n.title,description:`Make HTTP requests (GET/POST/PUT/PATCH/DELETE/HEAD) for API testing. Returns status, headers, and formatted body with timing info.`,inputSchema:{url:i.string().url().describe(`Request URL (http/https only)`),method:i.enum([`GET`,`POST`,`PUT`,`PATCH`,`DELETE`,`HEAD`]).default(`GET`).describe(`HTTP method`),headers:i.record(i.string(),i.string()).optional().describe(`Request headers as key-value pairs`),body:i.string().optional().describe(`Request body (for POST/PUT/PATCH)`),timeout:i.number().min(1e3).max(6e4).default(15e3).describe(`Timeout in milliseconds`)},annotations:n.annotations},async({url:e,method:t,headers:n,body:r,timeout:i})=>{try{let a=await u({url:e,method:t,headers:n,body:r,timeout:i}),o=[`## ${t} ${e}`,``,`**Status:** ${a.status} ${a.statusText}`,`**Time:** ${a.durationMs}ms`,`**Size:** ${a.sizeBytes} bytes`,`**Content-Type:** ${a.contentType}`,``,`### Headers`,"```json",JSON.stringify(a.headers),"```",``,`### Body`,a.contentType.includes(`json`)?"```json":"```",a.body,"```"];return a.truncated&&o.push(``,`_Response truncated — total size: ${a.sizeBytes} bytes_`),{content:[{type:`text`,text:o.join(`
|
|
5
|
-
`)}]}}catch(e){return _.error(`HTTP request failed`,o(e)),{content:[{type:`text`,text:`HTTP request failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function b(t){let n=e(`regex_test`);t.registerTool(`regex_test`,{title:n.title,description:`Test a regex pattern against sample strings. Supports match, replace, and split modes.`,inputSchema:{pattern:i.string().max(500).describe(`Regex pattern (without delimiters)`),flags:i.string().max(10).regex(/^[gimsuy]*$/).default(``).describe(`Regex flags (g, i, m, s, etc.)`),test_strings:i.array(i.string().max(1e4)).max(50).describe(`Strings to test the pattern against`),mode:i.enum([`match`,`replace`,`split`]).default(`match`).describe(`Test mode`),replacement:i.string().optional().describe(`Replacement string (for replace mode)`)},annotations:n.annotations},async({pattern:e,flags:t,test_strings:n,mode:r,replacement:i})=>{let a=f({pattern:e,flags:t,testStrings:n,mode:r,replacement:i});if(!a.valid)return{content:[{type:`text`,text:`Invalid regex: ${a.error}`}],isError:!0};let o=[`## Regex: \`/${a.pattern}/${a.flags}\``,``,`Mode: ${r}`,``];for(let e of a.results){if(o.push(`**Input:** \`${e.input}\``),o.push(`**Matched:** ${e.matched}`),e.matches)for(let t of e.matches){let e=t.groups.length>0?` groups: [${t.groups.join(`, `)}]`:``;o.push(` - "${t.full}" at index ${t.index}${e}`)}e.replaced!==void 0&&o.push(`**Result:** \`${e.replaced}\``),e.split&&o.push(`**Split:** ${JSON.stringify(e.split)}`),o.push(``)}return{content:[{type:`text`,text:o.join(`
|
|
6
|
-
`)}]}})}function x(t){let n=e(`encode`);t.registerTool(`encode`,{title:n.title,description:`Encode, decode, or hash text. Supports base64, URL encoding, SHA-256, MD5, JWT decode, hex.`,inputSchema:{operation:i.enum([`base64_encode`,`base64_decode`,`url_encode`,`url_decode`,`sha256`,`md5`,`jwt_decode`,`hex_encode`,`hex_decode`]).describe(`Operation to perform`),input:i.string().max(1e6).describe(`Input text`)},annotations:n.annotations},async({operation:e,input:t})=>{try{let n=c({operation:e,input:t});return{content:[{type:`text`,text:`## ${e}\n\n**Input:** \`${t.length>100?`${t.slice(0,100)}...`:t}\`\n**Output:**\n\`\`\`\n${n.output}\n\`\`\``}]}}catch(e){return _.error(`Encode failed`,o(e)),{content:[{type:`text`,text:`Encode failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function S(t){let r=e(`measure`);t.registerTool(`measure`,{title:r.title,description:`Measure code complexity, line counts, and function counts for a file or directory. Returns per-file metrics sorted by complexity.`,outputSchema:n,inputSchema:{path:i.string().describe(`File or directory path to measure`),extensions:i.array(i.string()).optional().describe(`File extensions to include (default: .ts,.tsx,.js,.jsx)`)},annotations:r.annotations},async({path:e,extensions:t})=>{try{let n=await d({path:e,extensions:t}),r=[`## Code Metrics`,``,`**Files:** ${n.summary.totalFiles}`,`**Total lines:** ${n.summary.totalLines} (${n.summary.totalCodeLines} code)`,`**Functions:** ${n.summary.totalFunctions}`,`**Avg complexity:** ${n.summary.avgComplexity}`,`**Max complexity:** ${n.summary.maxComplexity.value} (${n.summary.maxComplexity.file})`,``,`### Top files by complexity`,``,`| File | Lines | Code | Complexity | Cognitive | Functions | Imports |`,`|------|-------|------|------------|-----------|-----------|---------|`];for(let e of n.files.slice(0,20)){let t=e.cognitiveComplexity===void 0?`—`:String(e.cognitiveComplexity);r.push(`| ${e.path} | ${e.lines.total} | ${e.lines.code} | ${e.complexity} | ${t} | ${e.functions} | ${e.imports} |`)}n.files.length>20&&r.push(``,`_...and ${n.files.length-20} more files_`);let i={summary:{totalFiles:n.summary.totalFiles,totalLines:n.summary.totalLines,totalCodeLines:n.summary.totalCodeLines,totalFunctions:n.summary.totalFunctions,avgComplexity:n.summary.avgComplexity,maxComplexity:{value:n.summary.maxComplexity.value,file:n.summary.maxComplexity.file}},files:n.files.map(e=>({path:e.path,lines:e.lines.total,code:e.lines.code,complexity:e.complexity,functions:e.functions}))};return{content:[{type:`text`,text:r.join(`
|
|
7
|
-
`)}],structuredContent:i}}catch(e){return _.error(`Measure failed`,o(e)),{content:[{type:`text`,text:`Measure failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function C(t){let n=e(`changelog`);t.registerTool(`changelog`,{title:n.title,description:`Generate a changelog from git history between two refs. Groups by conventional commit type.`,inputSchema:{from:i.string().max(200).describe(`Start ref (tag, SHA, HEAD~N)`),to:i.string().max(200).default(`HEAD`).describe(`End ref (default: HEAD)`),format:i.enum([`grouped`,`chronological`,`per-scope`]).default(`grouped`).describe(`Output format`),include_breaking:i.boolean().default(!0).describe(`Highlight breaking changes`),cwd:i.string().optional().describe(`Repository root or working directory`)},annotations:n.annotations},async({from:e,to:t,format:n,include_breaking:r,cwd:i})=>{try{let a=s({from:e,to:t,format:n,includeBreaking:r,cwd:i}),o=`${a.stats.total} commits (${Object.entries(a.stats.types).map(([e,t])=>`${t} ${e}`).join(`, `)})`;return{content:[{type:`text`,text:`${a.markdown}\n---\n_${o}_`}]}}catch(e){return _.error(`Changelog failed`,o(e)),{content:[{type:`text`,text:`Changelog failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function w(t){let n=e(`schema_validate`);t.registerTool(`schema_validate`,{title:n.title,description:`Validate JSON data against a JSON Schema. Supports type, required, properties, items, enum, pattern, min/max.`,inputSchema:{data:i.string().max(5e5).describe(`JSON data to validate (as string)`),schema:i.string().max(5e5).describe(`JSON Schema to validate against (as string)`)},annotations:n.annotations},async({data:e,schema:t})=>{try{let n=p({data:JSON.parse(e),schema:JSON.parse(t)});if(n.valid)return{content:[{type:`text`,text:`## Validation: PASSED
|
|
8
|
-
|
|
9
|
-
Data matches the schema.`}]};let r=[`## Validation: FAILED`,``,`**${n.errors.length} error(s):**`,``];for(let e of n.errors){let t=e.expected?` (expected: ${e.expected}, got: ${e.received})`:``;r.push(`- \`${e.path}\`: ${e.message}${t}`)}return{content:[{type:`text`,text:r.join(`
|
|
10
|
-
`)}]}}catch(e){return _.error(`Schema validation failed`,o(e)),{content:[{type:`text`,text:`Schema validation failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function T(t){let n=e(`snippet`);t.registerTool(`snippet`,{title:n.title,description:`Save, retrieve, search, and manage persistent code snippets/templates.`,inputSchema:{action:i.enum([`save`,`get`,`list`,`search`,`delete`]).describe(`Operation to perform`),name:i.string().optional().describe(`Snippet name (required for save/get/delete)`),language:i.string().optional().describe(`Language tag (for save)`),code:i.string().max(1e5).optional().describe(`Code content (for save)`),tags:i.array(i.string()).optional().describe(`Tags for categorization (for save)`),query:i.string().optional().describe(`Search query (for search)`)},annotations:n.annotations},async({action:e,name:t,language:n,code:r,tags:i,query:a})=>{try{let o=m({action:e,name:t,language:n,code:r,tags:i,query:a});if(`deleted`in o)return{content:[{type:`text`,text:o.deleted?`Snippet "${t}" deleted.`:`Snippet "${t}" not found.`}]};if(`snippets`in o){if(o.snippets.length===0)return{content:[{type:`text`,text:`No snippets found.`}]};let e=[`## Snippets`,``];for(let t of o.snippets){let n=t.tags.length>0?` [${t.tags.join(`, `)}]`:``;e.push(`- **${t.name}** (${t.language})${n}`)}return{content:[{type:`text`,text:e.join(`
|
|
11
|
-
`)}]}}let s=o,c=s.tags.length>0?`\nTags: ${s.tags.join(`, `)}`:``;return{content:[{type:`text`,text:`## ${s.name} (${s.language})${c}\n\n\`\`\`${s.language}\n${s.code}\n\`\`\``}]}}catch(e){return _.error(`Snippet failed`,o(e)),{content:[{type:`text`,text:`Snippet failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function E(n){let r=e(`env`);n.registerTool(`env`,{title:r.title,description:`Get system and runtime environment info. Sensitive env vars are redacted by default.`,outputSchema:t,inputSchema:{include_env:i.boolean().default(!1).describe(`Include environment variables`),filter_env:i.string().optional().describe(`Filter env vars by name substring`),show_sensitive:i.boolean().default(!1).describe(`Show sensitive values (keys, tokens, etc.) — redacted by default`)},annotations:r.annotations},async({include_env:e,filter_env:t,show_sensitive:n})=>{let r=l({includeEnv:e,filterEnv:t,showSensitive:n}),i=[`## Environment`,``,`**Platform:** ${r.system.platform} ${r.system.arch}`,`**OS:** ${r.system.type} ${r.system.release}`,`**Host:** ${r.system.hostname}`,`**CPUs:** ${r.system.cpus}`,`**Memory:** ${r.system.memoryFreeGb}GB free / ${r.system.memoryTotalGb}GB total`,``,`**Node:** ${r.runtime.node}`,`**V8:** ${r.runtime.v8}`,`**CWD:** ${r.cwd}`];if(r.env){i.push(``,`### Environment Variables`,``);for(let[e,t]of Object.entries(r.env))i.push(`- \`${e}\`: ${t}`)}let a={platform:r.system.platform,arch:r.system.arch,nodeVersion:r.runtime.node,cwd:r.cwd,cpus:r.system.cpus,memoryFreeGb:r.system.memoryFreeGb,memoryTotalGb:r.system.memoryTotalGb};return{content:[{type:`text`,text:i.join(`
|
|
12
|
-
`)}],structuredContent:a}})}function D(t){let n=e(`time`);t.registerTool(`time`,{title:n.title,description:`Parse dates, convert timezones, calculate durations, add time. Supports ISO 8601, unix timestamps, and human-readable formats.`,outputSchema:r,inputSchema:{operation:i.enum([`now`,`parse`,`convert`,`diff`,`add`]).describe(`now: current time | parse: parse a date string | convert: timezone conversion | diff: duration between two dates | add: add duration to date`),input:i.string().optional().describe(`Date input (ISO, unix timestamp, or parseable string). For diff: two comma-separated dates`),timezone:i.string().optional().describe(`Target timezone (e.g., "America/New_York", "Asia/Tokyo")`),duration:i.string().optional().describe(`Duration to add (e.g., "2h30m", "1d", "30s") — for add operation`)},annotations:n.annotations},async({operation:e,input:t,timezone:n,duration:r})=>{try{let i=h({operation:e,input:t,timezone:n,duration:r}),a=[`**${i.output}**`,``,`ISO: ${i.iso}`,`Unix: ${i.unix}`];i.details&&a.push(``,"```json",JSON.stringify(i.details),"```");let o={iso:i.iso,unix:i.unix,timezone:n??Intl.DateTimeFormat().resolvedOptions().timeZone,formatted:i.output};return{content:[{type:`text`,text:a.join(`
|
|
13
|
-
`)}],structuredContent:o}}catch(e){return _.error(`Time failed`,o(e)),{content:[{type:`text`,text:`Time failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}export{C as registerChangelogTool,x as registerEncodeTool,E as registerEnvTool,y as registerHttpTool,S as registerMeasureTool,b as registerRegexTestTool,w as registerSchemaValidateTool,T as registerSnippetTool,D as registerTimeTool,v as registerWebSearchTool};
|
|
@@ -1,32 +0,0 @@
|
|
|
1
|
-
//#region packages/server/src/version-check.d.ts
|
|
2
|
-
/**
|
|
3
|
-
* Non-blocking check for newer @vpxa/aikit versions on npm.
|
|
4
|
-
* Logs a warning to stderr if the running version is outdated.
|
|
5
|
-
* Auto-upgrades scaffold files when server version ≠ scaffold version.
|
|
6
|
-
*/
|
|
7
|
-
declare function getCurrentVersion(): string;
|
|
8
|
-
/**
|
|
9
|
-
* Check for a newer version on npm and log a warning if outdated.
|
|
10
|
-
* This is fire-and-forget — it never throws and never blocks startup.
|
|
11
|
-
*/
|
|
12
|
-
declare function checkForUpdates(): void;
|
|
13
|
-
/** Upgrade state visible to other modules (e.g. the status tool). */
|
|
14
|
-
type UpgradeState = 'idle' | 'pending' | 'success' | 'failed';
|
|
15
|
-
/** Return the current auto-upgrade state. */
|
|
16
|
-
declare function getUpgradeState(): {
|
|
17
|
-
state: UpgradeState;
|
|
18
|
-
error: string | null;
|
|
19
|
-
};
|
|
20
|
-
/**
|
|
21
|
-
* Auto-upgrade scaffold files when the running server version differs from
|
|
22
|
-
* the installed scaffold version. This is fire-and-forget — it never throws
|
|
23
|
-
* and never blocks startup. The upgrade process runs in a detached child so
|
|
24
|
-
* the MCP server stays responsive.
|
|
25
|
-
*
|
|
26
|
-
* State is tracked via `getUpgradeState()` so the status tool can report
|
|
27
|
-
* whether the upgrade is pending, succeeded, or failed without asking the
|
|
28
|
-
* LLM to run a terminal command.
|
|
29
|
-
*/
|
|
30
|
-
declare function autoUpgradeScaffold(): void;
|
|
31
|
-
//#endregion
|
|
32
|
-
export { UpgradeState, autoUpgradeScaffold, checkForUpdates, getCurrentVersion, getUpgradeState };
|
|
@@ -1,159 +0,0 @@
|
|
|
1
|
-
//#region packages/store/src/graph-store.interface.d.ts
|
|
2
|
-
/**
|
|
3
|
-
* Knowledge graph store abstraction — typed nodes + edges for entity-relationship storage.
|
|
4
|
-
* Complements the vector store: vector search finds similar content,
|
|
5
|
-
* graph traversal finds connected concepts.
|
|
6
|
-
*/
|
|
7
|
-
/** A node in the knowledge graph (entity, concept, service, etc.) */
|
|
8
|
-
interface GraphNode {
|
|
9
|
-
/** Unique identifier */
|
|
10
|
-
id: string;
|
|
11
|
-
/** Node type (e.g., 'entity', 'service', 'api', 'concept', 'decision') */
|
|
12
|
-
type: string;
|
|
13
|
-
/** Display name */
|
|
14
|
-
name: string;
|
|
15
|
-
/** Arbitrary properties */
|
|
16
|
-
properties: Record<string, unknown>;
|
|
17
|
-
/** Back-link to KnowledgeRecord.id that produced this node */
|
|
18
|
-
sourceRecordId?: string;
|
|
19
|
-
/** Source file path (for cleanup on re-index) */
|
|
20
|
-
sourcePath?: string;
|
|
21
|
-
/** ISO timestamp */
|
|
22
|
-
createdAt?: string;
|
|
23
|
-
/** Community/cluster label from community detection */
|
|
24
|
-
community?: string;
|
|
25
|
-
}
|
|
26
|
-
/** An edge connecting two nodes */
|
|
27
|
-
interface GraphEdge {
|
|
28
|
-
/** Unique identifier */
|
|
29
|
-
id: string;
|
|
30
|
-
/** Source node ID */
|
|
31
|
-
fromId: string;
|
|
32
|
-
/** Target node ID */
|
|
33
|
-
toId: string;
|
|
34
|
-
/** Relationship type (e.g., 'depends-on', 'implements', 'calls', 'affects') */
|
|
35
|
-
type: string;
|
|
36
|
-
/** Optional weight (0-1) */
|
|
37
|
-
weight?: number;
|
|
38
|
-
/** Optional confidence score (0-1) for relationship certainty */
|
|
39
|
-
confidence?: number;
|
|
40
|
-
/** Arbitrary properties */
|
|
41
|
-
properties?: Record<string, unknown>;
|
|
42
|
-
}
|
|
43
|
-
/** Options for graph traversal */
|
|
44
|
-
interface GraphTraversalOptions {
|
|
45
|
-
/** Relationship type filter */
|
|
46
|
-
edgeType?: string;
|
|
47
|
-
/** Max traversal depth (default: 2) */
|
|
48
|
-
maxDepth?: number;
|
|
49
|
-
/** Direction: outgoing from start, incoming to start, or both */
|
|
50
|
-
direction?: 'outgoing' | 'incoming' | 'both';
|
|
51
|
-
/** Max total nodes returned (default: 50) */
|
|
52
|
-
limit?: number;
|
|
53
|
-
}
|
|
54
|
-
/** Result of a graph traversal */
|
|
55
|
-
interface GraphTraversalResult {
|
|
56
|
-
nodes: GraphNode[];
|
|
57
|
-
edges: GraphEdge[];
|
|
58
|
-
}
|
|
59
|
-
/** Graph statistics */
|
|
60
|
-
interface GraphStats {
|
|
61
|
-
nodeCount: number;
|
|
62
|
-
edgeCount: number;
|
|
63
|
-
nodeTypes: Record<string, number>;
|
|
64
|
-
edgeTypes: Record<string, number>;
|
|
65
|
-
}
|
|
66
|
-
/** Result of graph validation */
|
|
67
|
-
interface GraphValidationResult {
|
|
68
|
-
valid: boolean;
|
|
69
|
-
orphanNodes: string[];
|
|
70
|
-
danglingEdges: Array<{
|
|
71
|
-
edgeId: string;
|
|
72
|
-
missingNodeId: string;
|
|
73
|
-
}>;
|
|
74
|
-
stats: GraphStats;
|
|
75
|
-
}
|
|
76
|
-
/** Depth-grouped traversal result — nodes bucketed by distance from start */
|
|
77
|
-
interface DepthGroupedResult {
|
|
78
|
-
[depth: number]: GraphNode[];
|
|
79
|
-
}
|
|
80
|
-
/** Execution flow / process info */
|
|
81
|
-
interface ProcessInfo {
|
|
82
|
-
id: string;
|
|
83
|
-
entryNodeId: string;
|
|
84
|
-
label: string;
|
|
85
|
-
properties: Record<string, unknown>;
|
|
86
|
-
steps: string[];
|
|
87
|
-
createdAt?: string;
|
|
88
|
-
}
|
|
89
|
-
/** 360-degree symbol view — full context around a node */
|
|
90
|
-
interface Symbol360 {
|
|
91
|
-
node: GraphNode;
|
|
92
|
-
incoming: GraphEdge[];
|
|
93
|
-
outgoing: GraphEdge[];
|
|
94
|
-
community: string | null;
|
|
95
|
-
processes: ProcessInfo[];
|
|
96
|
-
}
|
|
97
|
-
/** Knowledge graph store interface */
|
|
98
|
-
interface IGraphStore {
|
|
99
|
-
/** Initialize the store (create tables, indices) */
|
|
100
|
-
initialize(): Promise<void>;
|
|
101
|
-
/** Add or update a single node */
|
|
102
|
-
upsertNode(node: GraphNode): Promise<void>;
|
|
103
|
-
/** Add or update a single edge */
|
|
104
|
-
upsertEdge(edge: GraphEdge): Promise<void>;
|
|
105
|
-
/** Batch add/update nodes */
|
|
106
|
-
upsertNodes(nodes: GraphNode[]): Promise<void>;
|
|
107
|
-
/** Batch add/update edges */
|
|
108
|
-
upsertEdges(edges: GraphEdge[]): Promise<void>;
|
|
109
|
-
/** Get a node by ID */
|
|
110
|
-
getNode(id: string): Promise<GraphNode | null>;
|
|
111
|
-
/** Get direct neighbors of a node */
|
|
112
|
-
getNeighbors(nodeId: string, options?: GraphTraversalOptions): Promise<GraphTraversalResult>;
|
|
113
|
-
/** Multi-hop traversal from a starting node */
|
|
114
|
-
traverse(startId: string, options?: GraphTraversalOptions): Promise<GraphTraversalResult>;
|
|
115
|
-
/** Find nodes by type and/or name pattern */
|
|
116
|
-
findNodes(filter: {
|
|
117
|
-
type?: string;
|
|
118
|
-
namePattern?: string;
|
|
119
|
-
sourcePath?: string;
|
|
120
|
-
limit?: number;
|
|
121
|
-
}): Promise<GraphNode[]>;
|
|
122
|
-
/** Find edges by type between optional node filters */
|
|
123
|
-
findEdges(filter: {
|
|
124
|
-
type?: string;
|
|
125
|
-
fromId?: string;
|
|
126
|
-
toId?: string;
|
|
127
|
-
limit?: number;
|
|
128
|
-
}): Promise<GraphEdge[]>;
|
|
129
|
-
/** Delete a node and all its edges */
|
|
130
|
-
deleteNode(id: string): Promise<void>;
|
|
131
|
-
/** Delete all nodes/edges originating from a source path */
|
|
132
|
-
deleteBySourcePath(sourcePath: string): Promise<number>;
|
|
133
|
-
/** Delete all nodes and edges (full reset) */
|
|
134
|
-
clear(): Promise<void>;
|
|
135
|
-
/** Get graph statistics */
|
|
136
|
-
getStats(): Promise<GraphStats>;
|
|
137
|
-
/** Validate graph integrity — check for orphan nodes and dangling edges */
|
|
138
|
-
validate(): Promise<GraphValidationResult>;
|
|
139
|
-
/** Set community label on a node */
|
|
140
|
-
setNodeCommunity(nodeId: string, community: string): Promise<void>;
|
|
141
|
-
/** Run label-propagation community detection, returns community -> nodeId[] map */
|
|
142
|
-
detectCommunities(): Promise<Record<string, string[]>>;
|
|
143
|
-
/** Trace execution flow from entry node via outgoing 'calls' edges, store as process */
|
|
144
|
-
traceProcess(entryNodeId: string, label: string): Promise<ProcessInfo>;
|
|
145
|
-
/** List processes, optionally filtered to those containing a specific node */
|
|
146
|
-
getProcesses(nodeId?: string): Promise<ProcessInfo[]>;
|
|
147
|
-
/** Delete a process and its steps */
|
|
148
|
-
deleteProcess(processId: string): Promise<void>;
|
|
149
|
-
/** Traverse with results grouped by depth: { 1: [...], 2: [...], 3: [...] } */
|
|
150
|
-
depthGroupedTraversal(startId: string, maxDepth?: number, options?: GraphTraversalOptions): Promise<DepthGroupedResult>;
|
|
151
|
-
/** Cohesion score for a community: internal edges / (internal + external edges) */
|
|
152
|
-
getCohesionScore(community: string): Promise<number>;
|
|
153
|
-
/** 360-degree view of a node: incoming, outgoing, community, processes */
|
|
154
|
-
getSymbol360(nodeId: string): Promise<Symbol360>;
|
|
155
|
-
/** Close the store */
|
|
156
|
-
close(): Promise<void>;
|
|
157
|
-
}
|
|
158
|
-
//#endregion
|
|
159
|
-
export { DepthGroupedResult, GraphEdge, GraphNode, GraphStats, GraphTraversalOptions, GraphTraversalResult, GraphValidationResult, IGraphStore, ProcessInfo, Symbol360 };
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export{};
|
|
@@ -1,46 +0,0 @@
|
|
|
1
|
-
import { IKnowledgeStore, SearchOptions } from "./store.interface.js";
|
|
2
|
-
import { IndexStats, KnowledgeRecord, SearchResult } from "../../core/dist/index.js";
|
|
3
|
-
|
|
4
|
-
//#region packages/store/src/lance-store.d.ts
|
|
5
|
-
declare class LanceStore implements IKnowledgeStore {
|
|
6
|
-
private db;
|
|
7
|
-
private table;
|
|
8
|
-
private readonly dbPath;
|
|
9
|
-
private readonly tableName;
|
|
10
|
-
private _draining;
|
|
11
|
-
private _priorityQueue;
|
|
12
|
-
private _normalQueue;
|
|
13
|
-
private _ftsReady;
|
|
14
|
-
private _ftsRecoveryAttemptAt;
|
|
15
|
-
private static readonly FTS_RECOVERY_COOLDOWN_MS;
|
|
16
|
-
private enqueueWrite;
|
|
17
|
-
private _drain;
|
|
18
|
-
constructor(options?: {
|
|
19
|
-
path?: string;
|
|
20
|
-
tableName?: string;
|
|
21
|
-
});
|
|
22
|
-
initialize(): Promise<void>;
|
|
23
|
-
upsert(records: KnowledgeRecord[], vectors: Float32Array[]): Promise<void>;
|
|
24
|
-
upsertInteractive(records: KnowledgeRecord[], vectors: Float32Array[]): Promise<void>;
|
|
25
|
-
private _upsertImpl;
|
|
26
|
-
search(queryVector: Float32Array, options?: SearchOptions): Promise<SearchResult[]>;
|
|
27
|
-
createFtsIndex(): Promise<void>;
|
|
28
|
-
private _createFtsIndexImpl;
|
|
29
|
-
ftsSearch(query: string, options?: SearchOptions): Promise<SearchResult[]>;
|
|
30
|
-
getById(id: string): Promise<KnowledgeRecord | null>;
|
|
31
|
-
deleteBySourcePath(sourcePath: string): Promise<number>;
|
|
32
|
-
private _deleteBySourcePathImpl;
|
|
33
|
-
deleteById(id: string): Promise<boolean>;
|
|
34
|
-
deleteByIdInteractive(id: string): Promise<boolean>;
|
|
35
|
-
private _deleteByIdImpl;
|
|
36
|
-
getBySourcePath(sourcePath: string): Promise<KnowledgeRecord[]>;
|
|
37
|
-
getStats(): Promise<IndexStats>;
|
|
38
|
-
listSourcePaths(): Promise<string[]>;
|
|
39
|
-
dropTable(): Promise<void>;
|
|
40
|
-
private _dropTableImpl;
|
|
41
|
-
close(): Promise<void>;
|
|
42
|
-
private buildFilterString;
|
|
43
|
-
private fromLanceRecord;
|
|
44
|
-
}
|
|
45
|
-
//#endregion
|
|
46
|
-
export { LanceStore };
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{EMBEDDING_DEFAULTS as e,SEARCH_DEFAULTS as t,STORE_DEFAULTS as n,createLogger as r,serializeError as i,sourceTypeContentTypes as a}from"../../core/dist/index.js";import{Index as o,connect as s}from"@lancedb/lancedb";function c(e){if(!e)return[];try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}const l=/^[\w.\-/ ]+$/,u=r(`store`);function d(e,t){if(!l.test(e))throw Error(`Invalid ${t} filter value: contains disallowed characters`);return e.replace(/'/g,`''`)}var f=class r{db=null;table=null;dbPath;tableName;_draining=!1;_priorityQueue=[];_normalQueue=[];_ftsReady=!1;_ftsRecoveryAttemptAt=0;static FTS_RECOVERY_COOLDOWN_MS=300*1e3;enqueueWrite(e,t=!1){return new Promise((n,r)=>{let i=async()=>{try{n(await e())}catch(e){r(e)}};t?this._priorityQueue.push(i):this._normalQueue.push(i),this._drain()})}async _drain(){if(!this._draining){this._draining=!0;try{for(;this._priorityQueue.length>0||this._normalQueue.length>0;){let e=this._priorityQueue.shift()??this._normalQueue.shift();e&&await e()}}finally{this._draining=!1}}}constructor(e){this.dbPath=e?.path??n.path,this.tableName=e?.tableName??n.tableName}async initialize(){this.db=await s(this.dbPath),(await this.db.tableNames()).includes(this.tableName)&&(this.table=await this.db.openTable(this.tableName),await this.createFtsIndex())}async upsert(e,t){if(e.length!==0){if(e.length!==t.length)throw Error(`Record count (${e.length}) does not match vector count (${t.length})`);return this.enqueueWrite(()=>this._upsertImpl(e,t))}}async upsertInteractive(e,t){if(e.length!==0){if(e.length!==t.length)throw Error(`Record count (${e.length}) does not match vector count (${t.length})`);return this.enqueueWrite(()=>this._upsertImpl(e,t),!0)}}async _upsertImpl(e,t){let n=e.map((e,n)=>({id:e.id,vector:Array.from(t[n]),content:e.content,sourcePath:e.sourcePath,contentType:e.contentType,headingPath:e.headingPath??``,chunkIndex:e.chunkIndex,totalChunks:e.totalChunks,startLine:e.startLine,endLine:e.endLine,fileHash:e.fileHash,indexedAt:e.indexedAt,origin:e.origin,tags:JSON.stringify(e.tags),category:e.category??``,version:e.version}));if(this.table){let t=[...new Set(e.map(e=>e.sourcePath))];for(let e of t)try{await this.table.delete(`sourcePath = '${d(e,`sourcePath`)}'`)}catch{}await this.table.add(n)}else try{this.table=await this.db?.createTable(this.tableName,n)??null}catch(e){if(String(e).includes(`already exists`)&&this.db)this.table=await this.db.openTable(this.tableName),await this.table.add(n);else throw e}}async search(e,n){if(!this.table)return[];let r=n?.limit??t.maxResults,i=n?.minScore??t.minScore,a=this.table.search(e).limit(r*2),o=this.buildFilterString(n);return o&&(a=a.where(o)),(await a.toArray()).map(e=>({record:this.fromLanceRecord(e),score:1-(e._distance??1)})).filter(e=>e.score>=i).slice(0,r)}async createFtsIndex(){return this.enqueueWrite(()=>this._createFtsIndexImpl())}async _createFtsIndexImpl(){if(this.table)try{await this.table.createIndex(`content`,{config:o.fts({withPosition:!0}),replace:!0}),this._ftsReady=!0,this._ftsRecoveryAttemptAt=0,u.info(`FTS index created/updated`,{column:`content`})}catch(e){u.warn(`FTS index creation failed`,i(e))}}async ftsSearch(e,n){if(!this.table)return[];if(!this._ftsReady){let e=Date.now();if(e-this._ftsRecoveryAttemptAt<r.FTS_RECOVERY_COOLDOWN_MS)return[];this._ftsRecoveryAttemptAt=e;try{await this.createFtsIndex()}catch{return[]}if(!this._ftsReady)return[]}let a=n?.limit??t.maxResults;try{let t=this.table.search(e).limit(a*2),r=this.buildFilterString(n);return r&&(t=t.where(r)),(await t.toArray()).map(e=>({record:this.fromLanceRecord(e),score:e._score??e._relevance_score??0}))}catch(e){return(e instanceof Error?e.message:String(e)).includes(`INVERTED index`)?(u.debug(`FTS search skipped — index not yet available`),this._ftsReady=!1):u.warn(`FTS search failed`,i(e)),[]}}async getById(e){if(!this.table)return null;let t=await this.table.query().where(`id = '${d(e,`id`)}'`).limit(1).toArray();return t.length===0?null:this.fromLanceRecord(t[0])}async deleteBySourcePath(e){return this.enqueueWrite(()=>this._deleteBySourcePathImpl(e))}async _deleteBySourcePathImpl(e){if(!this.table)return 0;let t=await this.getBySourcePath(e);return t.length===0?0:(await this.table.delete(`sourcePath = '${d(e,`sourcePath`)}'`),t.length)}async deleteById(e){return this.enqueueWrite(()=>this._deleteByIdImpl(e))}async deleteByIdInteractive(e){return this.enqueueWrite(()=>this._deleteByIdImpl(e),!0)}async _deleteByIdImpl(e){return!this.table||!await this.getById(e)?!1:(await this.table.delete(`id = '${d(e,`id`)}'`),!0)}async getBySourcePath(e){return this.table?(await this.table.query().where(`sourcePath = '${d(e,`sourcePath`)}'`).limit(1e3).toArray()).map(e=>this.fromLanceRecord(e)):[]}async getStats(){if(!this.table)return{totalRecords:0,totalFiles:0,contentTypeBreakdown:{},lastIndexedAt:null,storeBackend:`lancedb`,embeddingModel:e.model};let t=await this.table.countRows(),n=await this.table.query().select([`sourcePath`,`contentType`,`indexedAt`]).limit(1e5).toArray(),r={},i=new Set,a=null;for(let e of n){let t=e;r[t.contentType]=(r[t.contentType]??0)+1,i.add(t.sourcePath),(!a||t.indexedAt>a)&&(a=t.indexedAt)}return{totalRecords:t,totalFiles:i.size,contentTypeBreakdown:r,lastIndexedAt:a,storeBackend:`lancedb`,embeddingModel:e.model}}async listSourcePaths(){if(!this.table)return[];let e=await this.table.query().select([`sourcePath`]).limit(1e5).toArray();return[...new Set(e.map(e=>e.sourcePath))]}async dropTable(){return this.enqueueWrite(()=>this._dropTableImpl())}async _dropTableImpl(){if(this.db&&(await this.db.tableNames()).includes(this.tableName))for(let e=1;e<=3;e++)try{await this.db.dropTable(this.tableName);break}catch(t){if(e===3)throw t;let n=e*500;u.warn(`dropTable attempt failed, retrying`,{attempt:e,delayMs:n}),await new Promise(e=>setTimeout(e,n))}this.table=null}async close(){try{this.db&&typeof this.db.close==`function`&&await this.db.close()}catch{}this.table=null,this.db=null}buildFilterString(e){let t=[];if(e?.contentType&&t.push(`contentType = '${d(e.contentType,`contentType`)}'`),e?.sourceType){let n=a(e.sourceType);if(n.length>0){let e=n.map(e=>`'${d(e,`sourceType`)}'`).join(`, `);t.push(`contentType IN (${e})`)}}if(e?.origin&&t.push(`origin = '${d(e.origin,`origin`)}'`),e?.category&&t.push(`category = '${d(e.category,`category`)}'`),e?.tags&&e.tags.length>0){let n=e.tags.map(e=>`tags LIKE '%${d(e,`tag`)}%'`);t.push(`(${n.join(` OR `)})`)}return t.length>0?t.join(` AND `):null}fromLanceRecord(e){return{id:e.id,content:e.content,sourcePath:e.sourcePath,contentType:e.contentType,headingPath:e.headingPath||void 0,chunkIndex:e.chunkIndex,totalChunks:e.totalChunks,startLine:e.startLine,endLine:e.endLine,fileHash:e.fileHash,indexedAt:e.indexedAt,origin:e.origin,tags:c(e.tags),category:e.category||void 0,version:e.version}}};export{f as LanceStore};
|
|
@@ -1,57 +0,0 @@
|
|
|
1
|
-
import { DepthGroupedResult, GraphEdge, GraphNode, GraphStats, GraphTraversalOptions, GraphTraversalResult, GraphValidationResult, IGraphStore, ProcessInfo, Symbol360 } from "./graph-store.interface.js";
|
|
2
|
-
|
|
3
|
-
//#region packages/store/src/sqlite-graph-store.d.ts
|
|
4
|
-
declare class SqliteGraphStore implements IGraphStore {
|
|
5
|
-
private db;
|
|
6
|
-
private readonly dbPath;
|
|
7
|
-
private sqlFactory;
|
|
8
|
-
private dirty;
|
|
9
|
-
constructor(options?: {
|
|
10
|
-
path?: string;
|
|
11
|
-
});
|
|
12
|
-
initialize(): Promise<void>;
|
|
13
|
-
private configureDb;
|
|
14
|
-
private createTables;
|
|
15
|
-
private migrateSchema;
|
|
16
|
-
private ensureDb;
|
|
17
|
-
private persist;
|
|
18
|
-
private markDirty;
|
|
19
|
-
private flushIfDirty;
|
|
20
|
-
private query;
|
|
21
|
-
private run;
|
|
22
|
-
upsertNode(node: GraphNode): Promise<void>;
|
|
23
|
-
upsertEdge(edge: GraphEdge): Promise<void>;
|
|
24
|
-
upsertNodes(nodes: GraphNode[]): Promise<void>;
|
|
25
|
-
upsertEdges(edges: GraphEdge[]): Promise<void>;
|
|
26
|
-
getNode(id: string): Promise<GraphNode | null>;
|
|
27
|
-
getNeighbors(nodeId: string, options?: GraphTraversalOptions): Promise<GraphTraversalResult>;
|
|
28
|
-
traverse(startId: string, options?: GraphTraversalOptions): Promise<GraphTraversalResult>;
|
|
29
|
-
findNodes(filter: {
|
|
30
|
-
type?: string;
|
|
31
|
-
namePattern?: string;
|
|
32
|
-
sourcePath?: string;
|
|
33
|
-
limit?: number;
|
|
34
|
-
}): Promise<GraphNode[]>;
|
|
35
|
-
findEdges(filter: {
|
|
36
|
-
type?: string;
|
|
37
|
-
fromId?: string;
|
|
38
|
-
toId?: string;
|
|
39
|
-
limit?: number;
|
|
40
|
-
}): Promise<GraphEdge[]>;
|
|
41
|
-
deleteNode(id: string): Promise<void>;
|
|
42
|
-
deleteBySourcePath(sourcePath: string): Promise<number>;
|
|
43
|
-
clear(): Promise<void>;
|
|
44
|
-
getStats(): Promise<GraphStats>;
|
|
45
|
-
validate(): Promise<GraphValidationResult>;
|
|
46
|
-
setNodeCommunity(nodeId: string, community: string): Promise<void>;
|
|
47
|
-
detectCommunities(): Promise<Record<string, string[]>>;
|
|
48
|
-
traceProcess(entryNodeId: string, label: string): Promise<ProcessInfo>;
|
|
49
|
-
getProcesses(nodeId?: string): Promise<ProcessInfo[]>;
|
|
50
|
-
deleteProcess(processId: string): Promise<void>;
|
|
51
|
-
depthGroupedTraversal(startId: string, maxDepth?: number, options?: GraphTraversalOptions): Promise<DepthGroupedResult>;
|
|
52
|
-
getCohesionScore(community: string): Promise<number>;
|
|
53
|
-
getSymbol360(nodeId: string): Promise<Symbol360>;
|
|
54
|
-
close(): Promise<void>;
|
|
55
|
-
}
|
|
56
|
-
//#endregion
|
|
57
|
-
export { SqliteGraphStore };
|
|
@@ -1,90 +0,0 @@
|
|
|
1
|
-
import{AIKIT_PATHS as e}from"../../core/dist/index.js";import{existsSync as t,mkdirSync as n,readFileSync as r,writeFileSync as i}from"node:fs";import{dirname as a,join as o}from"node:path";var s=class{db=null;dbPath;sqlFactory=null;dirty=!1;constructor(t){let n=t?.path??e.data;this.dbPath=o(n,`graph.db`)}async initialize(){let e=a(this.dbPath);t(e)||n(e,{recursive:!0});let i=(await import(`sql.js`)).default,o=await i();if(this.sqlFactory=o,t(this.dbPath)){let e=r(this.dbPath);this.db=new o.Database(e)}else this.db=new o.Database;this.configureDb(this.db),this.createTables(this.db),this.migrateSchema(this.db),this.persist()}configureDb(e){e.run(`PRAGMA journal_mode = WAL`),e.exec(`PRAGMA foreign_keys = ON;`)}createTables(e){e.run(`
|
|
2
|
-
CREATE TABLE IF NOT EXISTS nodes (
|
|
3
|
-
id TEXT PRIMARY KEY,
|
|
4
|
-
type TEXT NOT NULL,
|
|
5
|
-
name TEXT NOT NULL,
|
|
6
|
-
properties TEXT NOT NULL DEFAULT '{}',
|
|
7
|
-
source_record_id TEXT,
|
|
8
|
-
source_path TEXT,
|
|
9
|
-
created_at TEXT NOT NULL DEFAULT (datetime('now')),
|
|
10
|
-
community TEXT
|
|
11
|
-
)
|
|
12
|
-
`),e.run(`
|
|
13
|
-
CREATE TABLE IF NOT EXISTS edges (
|
|
14
|
-
id TEXT PRIMARY KEY,
|
|
15
|
-
from_id TEXT NOT NULL,
|
|
16
|
-
to_id TEXT NOT NULL,
|
|
17
|
-
type TEXT NOT NULL,
|
|
18
|
-
weight REAL DEFAULT 1.0,
|
|
19
|
-
confidence REAL DEFAULT 1.0,
|
|
20
|
-
properties TEXT NOT NULL DEFAULT '{}',
|
|
21
|
-
FOREIGN KEY (from_id) REFERENCES nodes(id) ON DELETE CASCADE,
|
|
22
|
-
FOREIGN KEY (to_id) REFERENCES nodes(id) ON DELETE CASCADE
|
|
23
|
-
)
|
|
24
|
-
`),e.run(`CREATE INDEX IF NOT EXISTS idx_nodes_type ON nodes(type)`),e.run(`CREATE INDEX IF NOT EXISTS idx_nodes_name ON nodes(name)`),e.run(`CREATE INDEX IF NOT EXISTS idx_nodes_source_path ON nodes(source_path)`),e.run(`CREATE INDEX IF NOT EXISTS idx_edges_from ON edges(from_id)`),e.run(`CREATE INDEX IF NOT EXISTS idx_edges_to ON edges(to_id)`),e.run(`CREATE INDEX IF NOT EXISTS idx_edges_type ON edges(type)`),e.run(`
|
|
25
|
-
CREATE TABLE IF NOT EXISTS processes (
|
|
26
|
-
id TEXT PRIMARY KEY,
|
|
27
|
-
entry_node_id TEXT NOT NULL,
|
|
28
|
-
label TEXT NOT NULL,
|
|
29
|
-
properties TEXT NOT NULL DEFAULT '{}',
|
|
30
|
-
created_at TEXT NOT NULL DEFAULT (datetime('now')),
|
|
31
|
-
FOREIGN KEY (entry_node_id) REFERENCES nodes(id) ON DELETE CASCADE
|
|
32
|
-
)
|
|
33
|
-
`),e.run(`
|
|
34
|
-
CREATE TABLE IF NOT EXISTS process_steps (
|
|
35
|
-
process_id TEXT NOT NULL,
|
|
36
|
-
node_id TEXT NOT NULL,
|
|
37
|
-
step_order INTEGER NOT NULL,
|
|
38
|
-
PRIMARY KEY (process_id, node_id),
|
|
39
|
-
FOREIGN KEY (process_id) REFERENCES processes(id) ON DELETE CASCADE,
|
|
40
|
-
FOREIGN KEY (node_id) REFERENCES nodes(id) ON DELETE CASCADE
|
|
41
|
-
)
|
|
42
|
-
`),e.run(`CREATE INDEX IF NOT EXISTS idx_process_steps_node ON process_steps(node_id)`)}migrateSchema(e){for(let t of[`ALTER TABLE edges ADD COLUMN confidence REAL DEFAULT 1.0`,`ALTER TABLE nodes ADD COLUMN community TEXT`])try{e.run(t)}catch{}e.run(`CREATE INDEX IF NOT EXISTS idx_nodes_community ON nodes(community)`)}ensureDb(){if(!this.db){if(!this.sqlFactory)throw Error(`Graph store not initialized — call initialize() first`);this.db=t(this.dbPath)?new this.sqlFactory.Database(r(this.dbPath)):new this.sqlFactory.Database,this.configureDb(this.db),this.createTables(this.db),this.migrateSchema(this.db)}return this.db}persist(){if(!this.db)return;let e=this.db.export();try{i(this.dbPath,Buffer.from(e))}finally{this.db.exec(`PRAGMA foreign_keys = ON;`)}this.dirty=!1}markDirty(){this.dirty=!0}flushIfDirty(){this.dirty&&this.persist()}query(e,t=[]){let n=this.ensureDb().prepare(e);n.bind(t);let r=[];try{for(;n.step();)r.push(n.getAsObject())}finally{n.free()}return r}run(e,t=[]){this.ensureDb().run(e,t)}async upsertNode(e){this.run(`INSERT INTO nodes (id, type, name, properties, source_record_id, source_path, created_at, community)
|
|
43
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
|
44
|
-
ON CONFLICT(id) DO UPDATE SET
|
|
45
|
-
type = excluded.type, name = excluded.name, properties = excluded.properties,
|
|
46
|
-
source_record_id = excluded.source_record_id, source_path = excluded.source_path,
|
|
47
|
-
community = excluded.community`,[e.id,e.type,e.name,JSON.stringify(e.properties),e.sourceRecordId??null,e.sourcePath??null,e.createdAt??new Date().toISOString(),e.community??null]),this.markDirty(),this.flushIfDirty()}async upsertEdge(e){this.run(`INSERT INTO edges (id, from_id, to_id, type, weight, confidence, properties)
|
|
48
|
-
VALUES (?, ?, ?, ?, ?, ?, ?)
|
|
49
|
-
ON CONFLICT(id) DO UPDATE SET
|
|
50
|
-
from_id = excluded.from_id, to_id = excluded.to_id,
|
|
51
|
-
type = excluded.type, weight = excluded.weight, confidence = excluded.confidence, properties = excluded.properties`,[e.id,e.fromId,e.toId,e.type,e.weight??1,e.confidence??1,JSON.stringify(e.properties??{})]),this.markDirty(),this.flushIfDirty()}async upsertNodes(e){if(e.length===0)return;let t=this.ensureDb();t.run(`BEGIN TRANSACTION`);try{for(let t of e)this.run(`INSERT INTO nodes (id, type, name, properties, source_record_id, source_path, created_at, community)
|
|
52
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
|
53
|
-
ON CONFLICT(id) DO UPDATE SET
|
|
54
|
-
type = excluded.type, name = excluded.name, properties = excluded.properties,
|
|
55
|
-
source_record_id = excluded.source_record_id, source_path = excluded.source_path,
|
|
56
|
-
community = excluded.community`,[t.id,t.type,t.name,JSON.stringify(t.properties),t.sourceRecordId??null,t.sourcePath??null,t.createdAt??new Date().toISOString(),t.community??null]);t.run(`COMMIT`)}catch(e){throw t.run(`ROLLBACK`),e}this.markDirty(),this.flushIfDirty()}async upsertEdges(e){if(e.length===0)return;let t=this.ensureDb();t.run(`PRAGMA foreign_keys = OFF`),t.run(`BEGIN TRANSACTION`);try{for(let t of e)this.run(`INSERT INTO edges (id, from_id, to_id, type, weight, confidence, properties)
|
|
57
|
-
VALUES (?, ?, ?, ?, ?, ?, ?)
|
|
58
|
-
ON CONFLICT(id) DO UPDATE SET
|
|
59
|
-
from_id = excluded.from_id, to_id = excluded.to_id,
|
|
60
|
-
type = excluded.type, weight = excluded.weight, confidence = excluded.confidence, properties = excluded.properties`,[t.id,t.fromId,t.toId,t.type,t.weight??1,t.confidence??1,JSON.stringify(t.properties??{})]);t.run(`COMMIT`)}catch(e){throw t.run(`ROLLBACK`),e}finally{t.run(`PRAGMA foreign_keys = ON`)}this.markDirty(),this.flushIfDirty()}async getNode(e){let t=this.query(`SELECT * FROM nodes WHERE id = ?`,[e]);return t.length>0?l(t[0]):null}async getNeighbors(e,t){let n=t?.direction??`both`,r=t?.edgeType,i=t?.limit??50,a=[],o=[],s=new Set;if(n===`outgoing`||n===`both`){let t=`
|
|
61
|
-
SELECT e.id AS edge_id, e.from_id, e.to_id, e.type AS edge_type, e.weight,
|
|
62
|
-
e.confidence AS edge_confidence, e.properties AS edge_props,
|
|
63
|
-
n.id AS node_id, n.type AS node_type, n.name AS node_name, n.properties AS node_props,
|
|
64
|
-
n.source_record_id AS node_src_rec, n.source_path AS node_src_path,
|
|
65
|
-
n.created_at AS node_created, n.community AS node_community
|
|
66
|
-
FROM edges e JOIN nodes n ON e.to_id = n.id WHERE e.from_id = ?`,n=[e];r&&(t+=` AND e.type = ?`,n.push(r)),t+=` LIMIT ?`,n.push(i);let c=this.query(t,n);for(let e of c)o.push(d(e)),s.has(e.node_id)||(s.add(e.node_id),a.push(f(e)))}if(n===`incoming`||n===`both`){let t=`
|
|
67
|
-
SELECT e.id AS edge_id, e.from_id, e.to_id, e.type AS edge_type, e.weight,
|
|
68
|
-
e.confidence AS edge_confidence, e.properties AS edge_props,
|
|
69
|
-
n.id AS node_id, n.type AS node_type, n.name AS node_name, n.properties AS node_props,
|
|
70
|
-
n.source_record_id AS node_src_rec, n.source_path AS node_src_path,
|
|
71
|
-
n.created_at AS node_created, n.community AS node_community
|
|
72
|
-
FROM edges e JOIN nodes n ON e.from_id = n.id WHERE e.to_id = ?`,n=[e];r&&(t+=` AND e.type = ?`,n.push(r)),t+=` LIMIT ?`,n.push(i);let c=this.query(t,n);for(let e of c)o.push(d(e)),s.has(e.node_id)||(s.add(e.node_id),a.push(f(e)))}return{nodes:a,edges:o}}async traverse(e,t){let n=t?.maxDepth??2,r=t?.direction??`both`,i=t?.edgeType,a=t?.limit??50,o=new Map,s=new Map,c=new Set,l=[{nodeId:e,depth:0}];for(;l.length>0&&o.size<a;){let e=l.shift();if(!e||c.has(e.nodeId)||e.depth>n)continue;c.add(e.nodeId);let t=await this.getNeighbors(e.nodeId,{direction:r,edgeType:i,limit:a-o.size});for(let r of t.nodes)o.has(r.id)||(o.set(r.id,r),e.depth+1<n&&l.push({nodeId:r.id,depth:e.depth+1}));for(let e of t.edges)s.set(e.id,e)}return{nodes:[...o.values()],edges:[...s.values()]}}async findNodes(e){let t=[],n=[];e.type&&(t.push(`type = ?`),n.push(e.type)),e.namePattern&&(t.push(`name LIKE ?`),n.push(`%${e.namePattern}%`)),e.sourcePath&&(t.push(`source_path = ?`),n.push(e.sourcePath));let r=t.length>0?`WHERE ${t.join(` AND `)}`:``,i=e.limit??100;return this.query(`SELECT * FROM nodes ${r} LIMIT ?`,[...n,i]).map(e=>l(e))}async findEdges(e){let t=[],n=[];e.type&&(t.push(`type = ?`),n.push(e.type)),e.fromId&&(t.push(`from_id = ?`),n.push(e.fromId)),e.toId&&(t.push(`to_id = ?`),n.push(e.toId));let r=t.length>0?`WHERE ${t.join(` AND `)}`:``,i=e.limit??100;return this.query(`SELECT * FROM edges ${r} LIMIT ?`,[...n,i]).map(e=>u(e))}async deleteNode(e){let t=this.ensureDb();t.run(`BEGIN TRANSACTION`);try{this.run(`DELETE FROM edges WHERE from_id = ? OR to_id = ?`,[e,e]),this.run(`DELETE FROM nodes WHERE id = ?`,[e]),t.run(`COMMIT`)}catch(e){throw t.run(`ROLLBACK`),e}this.markDirty(),this.flushIfDirty()}async deleteBySourcePath(e){let t=this.query(`SELECT id FROM nodes WHERE source_path = ?`,[e]);if(t.length===0)return 0;let n=this.ensureDb();n.run(`BEGIN TRANSACTION`);try{for(let e of t)this.run(`DELETE FROM edges WHERE from_id = ? OR to_id = ?`,[e.id,e.id]);this.run(`DELETE FROM nodes WHERE source_path = ?`,[e]),n.run(`COMMIT`)}catch(e){throw n.run(`ROLLBACK`),e}return this.markDirty(),this.flushIfDirty(),t.length}async clear(){this.run(`DELETE FROM process_steps`),this.run(`DELETE FROM processes`),this.run(`DELETE FROM edges`),this.run(`DELETE FROM nodes`),this.markDirty(),this.flushIfDirty()}async getStats(){let e=this.query(`SELECT COUNT(*) as count FROM nodes`)[0]?.count??0,t=this.query(`SELECT COUNT(*) as count FROM edges`)[0]?.count??0,n=this.query(`SELECT type, COUNT(*) as count FROM nodes GROUP BY type`),r={};for(let e of n)r[e.type]=e.count;let i=this.query(`SELECT type, COUNT(*) as count FROM edges GROUP BY type`),a={};for(let e of i)a[e.type]=e.count;return{nodeCount:e,edgeCount:t,nodeTypes:r,edgeTypes:a}}async validate(){let e=await this.getStats(),t=this.query(`SELECT e.id AS edgeId,
|
|
73
|
-
CASE
|
|
74
|
-
WHEN n1.id IS NULL THEN e.from_id
|
|
75
|
-
WHEN n2.id IS NULL THEN e.to_id
|
|
76
|
-
END AS missingNodeId
|
|
77
|
-
FROM edges e
|
|
78
|
-
LEFT JOIN nodes n1 ON e.from_id = n1.id
|
|
79
|
-
LEFT JOIN nodes n2 ON e.to_id = n2.id
|
|
80
|
-
WHERE n1.id IS NULL OR n2.id IS NULL`),n=this.query(`SELECT n.id AS id
|
|
81
|
-
FROM nodes n
|
|
82
|
-
LEFT JOIN edges e1 ON n.id = e1.from_id
|
|
83
|
-
LEFT JOIN edges e2 ON n.id = e2.to_id
|
|
84
|
-
WHERE e1.id IS NULL AND e2.id IS NULL`).map(e=>e.id);return{valid:t.length===0,orphanNodes:n,danglingEdges:t,stats:e}}async setNodeCommunity(e,t){this.run(`UPDATE nodes SET community = ? WHERE id = ?`,[t,e]),this.markDirty(),this.flushIfDirty()}async detectCommunities(){let e=this.query(`SELECT id FROM nodes`),t=new Map;for(let n of e)t.set(n.id,n.id);for(let n=0;n<10;n++){let n=!1,r=new Map(t);for(let i of e){let e=this.query(`SELECT to_id AS neighbor_id FROM edges WHERE from_id = ?
|
|
85
|
-
UNION
|
|
86
|
-
SELECT from_id AS neighbor_id FROM edges WHERE to_id = ?`,[i.id,i.id]),a=new Map,o=t.get(i.id)??i.id;a.set(o,1);for(let n of e){let e=t.get(n.neighbor_id)??n.neighbor_id;a.set(e,(a.get(e)??0)+1)}let s=o,c=0;for(let[e,t]of a)(t>c||t===c&&e<s)&&(c=t,s=e);o!==s&&(r.set(i.id,s),n=!0)}t.clear();for(let[e,n]of r)t.set(e,n);if(!n)break}let n=this.ensureDb();n.run(`BEGIN TRANSACTION`);try{for(let[e,n]of t)this.run(`UPDATE nodes SET community = ? WHERE id = ?`,[n,e]);n.run(`COMMIT`)}catch(e){throw n.run(`ROLLBACK`),e}this.markDirty(),this.flushIfDirty();let r={};for(let[e,n]of t)r[n]||(r[n]=[]),r[n].push(e);return r}async traceProcess(e,t){let n=[],r=new Set,i=[e];for(;i.length>0;){let e=i.shift();if(!e||r.has(e))continue;r.add(e),n.push(e);let t=this.query(`SELECT to_id FROM edges WHERE from_id = ? AND type = 'calls'`,[e]);for(let e of t)r.has(e.to_id)||i.push(e.to_id)}let a=`proc_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,o=new Date().toISOString(),s=this.ensureDb();s.run(`BEGIN TRANSACTION`);try{this.run(`INSERT INTO processes (id, entry_node_id, label, properties, created_at)
|
|
87
|
-
VALUES (?, ?, ?, '{}', ?)`,[a,e,t,o]);for(let e=0;e<n.length;e++)this.run(`INSERT INTO process_steps (process_id, node_id, step_order) VALUES (?, ?, ?)`,[a,n[e],e]);s.run(`COMMIT`)}catch(e){throw s.run(`ROLLBACK`),e}return this.markDirty(),this.flushIfDirty(),{id:a,entryNodeId:e,label:t,properties:{},steps:n,createdAt:o}}async getProcesses(e){let t;t=e?this.query(`SELECT DISTINCT p.id, p.entry_node_id, p.label, p.properties, p.created_at
|
|
88
|
-
FROM processes p
|
|
89
|
-
JOIN process_steps ps ON p.id = ps.process_id
|
|
90
|
-
WHERE ps.node_id = ?`,[e]):this.query(`SELECT * FROM processes`);let n=[];for(let e of t){let t=this.query(`SELECT node_id FROM process_steps WHERE process_id = ? ORDER BY step_order`,[e.id]);n.push({id:e.id,entryNodeId:e.entry_node_id,label:e.label,properties:c(e.properties),steps:t.map(e=>e.node_id),createdAt:e.created_at})}return n}async deleteProcess(e){let t=this.ensureDb();t.run(`BEGIN TRANSACTION`);try{this.run(`DELETE FROM process_steps WHERE process_id = ?`,[e]),this.run(`DELETE FROM processes WHERE id = ?`,[e]),t.run(`COMMIT`)}catch(e){throw t.run(`ROLLBACK`),e}this.markDirty(),this.flushIfDirty()}async depthGroupedTraversal(e,t=3,n){let r=n?.direction??`both`,i=n?.edgeType,a=n?.limit??100,o={},s=new Set;s.add(e);let c=[e];for(let e=1;e<=t;e++){let t=[],n=[];for(let e of c){let o=await this.getNeighbors(e,{direction:r,edgeType:i,limit:a});for(let e of o.nodes)s.has(e.id)||(s.add(e.id),t.push(e.id),n.push(e))}if(n.length>0&&(o[e]=n),c=t,c.length===0||s.size>=a)break}return o}async getCohesionScore(e){let t=this.query(`SELECT id FROM nodes WHERE community = ?`,[e]);if(t.length===0)return 0;let n=new Set(t.map(e=>e.id)),r=t.map(()=>`?`).join(`,`),i=t.map(e=>e.id),a=this.query(`SELECT from_id, to_id FROM edges WHERE from_id IN (${r}) OR to_id IN (${r})`,[...i,...i]);if(a.length===0)return 0;let o=0;for(let e of a)n.has(e.from_id)&&n.has(e.to_id)&&o++;return o/a.length}async getSymbol360(e){let t=await this.getNode(e);if(!t)throw Error(`Node '${e}' not found`);let n=await this.findEdges({toId:e}),r=await this.findEdges({fromId:e}),i=await this.getProcesses(e);return{node:t,incoming:n,outgoing:r,community:t.community??null,processes:i}}async close(){this.db&&=(this.flushIfDirty(),this.db.close(),null)}};function c(e){if(!e)return{};try{return JSON.parse(e)}catch{return{}}}function l(e){return{id:e.id,type:e.type,name:e.name,properties:c(e.properties),sourceRecordId:e.source_record_id??void 0,sourcePath:e.source_path??void 0,createdAt:e.created_at,community:e.community??void 0}}function u(e){return{id:e.id,fromId:e.from_id,toId:e.to_id,type:e.type,weight:e.weight??1,confidence:e.confidence??1,properties:c(e.properties)}}function d(e){return{id:e.edge_id,fromId:e.from_id,toId:e.to_id,type:e.edge_type,weight:e.weight??1,confidence:e.edge_confidence??1,properties:c(e.edge_props??`{}`)}}function f(e){return{id:e.node_id,type:e.node_type,name:e.node_name,properties:c(e.node_props??`{}`),sourceRecordId:e.node_src_rec??void 0,sourcePath:e.node_src_path??void 0,createdAt:e.node_created,community:e.node_community??void 0}}export{s as SqliteGraphStore};
|
|
@@ -1,12 +0,0 @@
|
|
|
1
|
-
import { IKnowledgeStore } from "./store.interface.js";
|
|
2
|
-
|
|
3
|
-
//#region packages/store/src/store-factory.d.ts
|
|
4
|
-
type StoreBackend = 'lancedb' | 'sqlite-vec';
|
|
5
|
-
interface StoreConfig {
|
|
6
|
-
backend: StoreBackend;
|
|
7
|
-
path: string;
|
|
8
|
-
options?: Record<string, unknown>;
|
|
9
|
-
}
|
|
10
|
-
declare function createStore(config: StoreConfig): Promise<IKnowledgeStore>;
|
|
11
|
-
//#endregion
|
|
12
|
-
export { StoreBackend, StoreConfig, createStore };
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
async function e(e){switch(e.backend){case`lancedb`:{let{LanceStore:t}=await import(`./lance-store.js`);return new t({path:e.path})}default:throw Error(`Unknown store backend: "${e.backend}". Supported: lancedb`)}}export{e as createStore};
|