@vpxa/kb 0.1.15 → 0.1.16
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 +62 -15
- package/package.json +5 -1
- package/packages/analyzers/dist/blast-radius-analyzer.d.ts +1 -2
- package/packages/analyzers/dist/blast-radius-analyzer.js +1 -2
- package/packages/analyzers/dist/dependency-analyzer.d.ts +2 -3
- package/packages/analyzers/dist/dependency-analyzer.js +3 -4
- package/packages/analyzers/dist/diagram-generator.d.ts +1 -2
- package/packages/analyzers/dist/diagram-generator.js +1 -2
- package/packages/analyzers/dist/entry-point-analyzer.d.ts +1 -2
- package/packages/analyzers/dist/entry-point-analyzer.js +3 -4
- package/packages/analyzers/dist/knowledge-producer.d.ts +6 -2
- package/packages/analyzers/dist/knowledge-producer.js +4 -3
- package/packages/analyzers/dist/pattern-analyzer.d.ts +1 -2
- package/packages/analyzers/dist/pattern-analyzer.js +2 -3
- package/packages/analyzers/dist/regex-call-graph.d.ts +1 -2
- package/packages/analyzers/dist/regex-call-graph.js +1 -2
- package/packages/analyzers/dist/structure-analyzer.d.ts +1 -2
- package/packages/analyzers/dist/structure-analyzer.js +1 -2
- package/packages/analyzers/dist/symbol-analyzer.d.ts +3 -3
- package/packages/analyzers/dist/symbol-analyzer.js +8 -7
- package/packages/analyzers/dist/ts-call-graph.d.ts +1 -2
- package/packages/analyzers/dist/ts-call-graph.js +1 -2
- package/packages/analyzers/dist/types.d.ts +1 -2
- package/packages/chunker/dist/call-graph-extractor.d.ts +3 -3
- package/packages/chunker/dist/call-graph-extractor.js +1 -2
- package/packages/chunker/dist/chunker-factory.d.ts +12 -4
- package/packages/chunker/dist/chunker-factory.js +1 -2
- package/packages/chunker/dist/chunker.interface.d.ts +1 -2
- package/packages/chunker/dist/code-chunker.d.ts +1 -2
- package/packages/chunker/dist/code-chunker.js +1 -2
- package/packages/chunker/dist/extractors/call-extractor.d.ts +24 -0
- package/packages/chunker/dist/extractors/call-extractor.js +1 -0
- package/packages/chunker/dist/extractors/entry-point-detector.d.ts +14 -0
- package/packages/chunker/dist/extractors/entry-point-detector.js +1 -0
- package/packages/chunker/dist/extractors/import-extractor.d.ts +14 -0
- package/packages/chunker/dist/extractors/import-extractor.js +1 -0
- package/packages/chunker/dist/extractors/pattern-detector.d.ts +14 -0
- package/packages/chunker/dist/extractors/pattern-detector.js +1 -0
- package/packages/chunker/dist/extractors/scope-resolver.d.ts +26 -0
- package/packages/chunker/dist/extractors/scope-resolver.js +1 -0
- package/packages/chunker/dist/extractors/symbol-extractor.d.ts +14 -0
- package/packages/chunker/dist/extractors/symbol-extractor.js +1 -0
- package/packages/chunker/dist/extractors/types.d.ts +36 -0
- package/packages/chunker/dist/extractors/types.js +1 -0
- package/packages/chunker/dist/generic-chunker.d.ts +1 -2
- package/packages/chunker/dist/generic-chunker.js +1 -2
- package/packages/chunker/dist/index.d.ts +15 -4
- package/packages/chunker/dist/index.js +1 -1
- package/packages/chunker/dist/markdown-chunker.d.ts +1 -2
- package/packages/chunker/dist/markdown-chunker.js +1 -2
- package/packages/chunker/dist/wasm/languages.d.ts +18 -0
- package/packages/chunker/dist/wasm/languages.js +1 -0
- package/packages/chunker/dist/wasm/query-executor.d.ts +70 -0
- package/packages/chunker/dist/wasm/query-executor.js +1 -0
- package/packages/chunker/dist/wasm/runtime.d.ts +44 -0
- package/packages/chunker/dist/wasm/runtime.js +1 -0
- package/packages/chunker/dist/wasm/types.d.ts +84 -0
- package/packages/chunker/dist/wasm/types.js +1 -0
- package/packages/chunker/dist/wasm-chunker.d.ts +23 -0
- package/packages/chunker/dist/wasm-chunker.js +6 -0
- package/packages/chunker/src/queries/go/calls.scm +11 -0
- package/packages/chunker/src/queries/go/entry-points.scm +20 -0
- package/packages/chunker/src/queries/go/imports.scm +6 -0
- package/packages/chunker/src/queries/go/patterns.scm +25 -0
- package/packages/chunker/src/queries/go/symbols.scm +26 -0
- package/packages/chunker/src/queries/java/calls.scm +10 -0
- package/packages/chunker/src/queries/java/entry-points.scm +27 -0
- package/packages/chunker/src/queries/java/imports.scm +11 -0
- package/packages/chunker/src/queries/java/patterns.scm +27 -0
- package/packages/chunker/src/queries/java/symbols.scm +28 -0
- package/packages/chunker/src/queries/javascript/calls.scm +21 -0
- package/packages/chunker/src/queries/javascript/entry-points.scm +31 -0
- package/packages/chunker/src/queries/javascript/imports.scm +32 -0
- package/packages/chunker/src/queries/javascript/patterns.scm +28 -0
- package/packages/chunker/src/queries/javascript/symbols.scm +52 -0
- package/packages/chunker/src/queries/python/calls.scm +11 -0
- package/packages/chunker/src/queries/python/entry-points.scm +21 -0
- package/packages/chunker/src/queries/python/imports.scm +14 -0
- package/packages/chunker/src/queries/python/patterns.scm +25 -0
- package/packages/chunker/src/queries/python/symbols.scm +17 -0
- package/packages/chunker/src/queries/rust/calls.scm +20 -0
- package/packages/chunker/src/queries/rust/entry-points.scm +7 -0
- package/packages/chunker/src/queries/rust/imports.scm +26 -0
- package/packages/chunker/src/queries/rust/patterns.scm +18 -0
- package/packages/chunker/src/queries/rust/symbols.scm +73 -0
- package/packages/chunker/src/queries/typescript/calls.scm +21 -0
- package/packages/chunker/src/queries/typescript/entry-points.scm +48 -0
- package/packages/chunker/src/queries/typescript/imports.scm +35 -0
- package/packages/chunker/src/queries/typescript/patterns.scm +47 -0
- package/packages/chunker/src/queries/typescript/symbols.scm +79 -0
- package/packages/chunker/wasm/tree-sitter-go.wasm +0 -0
- package/packages/chunker/wasm/tree-sitter-java.wasm +0 -0
- package/packages/chunker/wasm/tree-sitter-javascript.wasm +0 -0
- package/packages/chunker/wasm/tree-sitter-python.wasm +0 -0
- package/packages/chunker/wasm/tree-sitter-rust.wasm +0 -0
- package/packages/chunker/wasm/tree-sitter-typescript.wasm +0 -0
- package/packages/chunker/wasm/tree-sitter.wasm +0 -0
- package/packages/cli/dist/commands/analyze.d.ts +1 -2
- package/packages/cli/dist/commands/analyze.js +1 -2
- package/packages/cli/dist/commands/context-cmds.d.ts +1 -2
- package/packages/cli/dist/commands/context-cmds.js +1 -2
- package/packages/cli/dist/commands/environment.d.ts +1 -2
- package/packages/cli/dist/commands/environment.js +1 -2
- package/packages/cli/dist/commands/execution.d.ts +1 -2
- package/packages/cli/dist/commands/execution.js +1 -2
- package/packages/cli/dist/commands/graph.d.ts +1 -2
- package/packages/cli/dist/commands/graph.js +1 -2
- package/packages/cli/dist/commands/init/adapters.d.ts +4 -3
- package/packages/cli/dist/commands/init/adapters.js +1 -2
- package/packages/cli/dist/commands/init/config.d.ts +1 -2
- package/packages/cli/dist/commands/init/config.js +3 -4
- package/packages/cli/dist/commands/init/constants.d.ts +18 -0
- package/packages/cli/dist/commands/init/constants.js +1 -0
- package/packages/cli/dist/commands/init/curated.d.ts +1 -2
- package/packages/cli/dist/commands/init/curated.js +1 -2
- package/packages/cli/dist/commands/init/global.d.ts +34 -0
- package/packages/cli/dist/commands/init/global.js +5 -0
- package/packages/cli/dist/commands/init/index.d.ts +7 -2
- package/packages/cli/dist/commands/init/index.js +5 -3
- package/packages/cli/dist/commands/init/scaffold.d.ts +1 -2
- package/packages/cli/dist/commands/init/scaffold.js +1 -2
- package/packages/cli/dist/commands/init/templates.d.ts +3 -4
- package/packages/cli/dist/commands/init/templates.js +106 -243
- package/packages/cli/dist/commands/knowledge.d.ts +1 -2
- package/packages/cli/dist/commands/knowledge.js +1 -2
- package/packages/cli/dist/commands/search.d.ts +1 -2
- package/packages/cli/dist/commands/search.js +1 -2
- package/packages/cli/dist/commands/system.d.ts +1 -2
- package/packages/cli/dist/commands/system.js +3 -4
- package/packages/cli/dist/commands/workspace.d.ts +1 -2
- package/packages/cli/dist/commands/workspace.js +1 -2
- package/packages/cli/dist/context.d.ts +1 -2
- package/packages/cli/dist/context.js +1 -2
- package/packages/cli/dist/helpers.d.ts +1 -2
- package/packages/cli/dist/helpers.js +1 -2
- package/packages/cli/dist/index.d.ts +1 -2
- package/packages/cli/dist/index.js +1 -2
- package/packages/cli/dist/kb-init.d.ts +1 -2
- package/packages/cli/dist/kb-init.js +1 -2
- package/packages/cli/dist/types.d.ts +1 -2
- package/packages/core/dist/constants.d.ts +23 -2
- package/packages/core/dist/constants.js +1 -2
- package/packages/core/dist/content-detector.d.ts +1 -2
- package/packages/core/dist/content-detector.js +1 -2
- package/packages/core/dist/errors.d.ts +1 -2
- package/packages/core/dist/errors.js +1 -2
- package/packages/core/dist/global-registry.d.ts +62 -0
- package/packages/core/dist/global-registry.js +1 -0
- package/packages/core/dist/index.d.ts +4 -3
- package/packages/core/dist/index.js +1 -1
- package/packages/core/dist/logger.d.ts +4 -2
- package/packages/core/dist/logger.js +1 -2
- package/packages/core/dist/types.d.ts +1 -2
- package/packages/core/dist/types.js +1 -2
- package/packages/embeddings/dist/embedder.interface.d.ts +1 -2
- package/packages/embeddings/dist/onnx-embedder.d.ts +1 -2
- package/packages/embeddings/dist/onnx-embedder.js +1 -2
- package/packages/enterprise-bridge/dist/cache.d.ts +1 -2
- package/packages/enterprise-bridge/dist/cache.js +1 -2
- package/packages/enterprise-bridge/dist/er-client.d.ts +1 -2
- package/packages/enterprise-bridge/dist/er-client.js +1 -2
- package/packages/enterprise-bridge/dist/evolution-collector.d.ts +1 -2
- package/packages/enterprise-bridge/dist/evolution-collector.js +1 -2
- package/packages/enterprise-bridge/dist/policy-store.d.ts +1 -2
- package/packages/enterprise-bridge/dist/policy-store.js +1 -2
- package/packages/enterprise-bridge/dist/push-adapter.d.ts +1 -2
- package/packages/enterprise-bridge/dist/push-adapter.js +1 -2
- package/packages/enterprise-bridge/dist/result-merger.d.ts +1 -2
- package/packages/enterprise-bridge/dist/result-merger.js +1 -2
- package/packages/enterprise-bridge/dist/types.d.ts +1 -2
- package/packages/enterprise-bridge/dist/types.js +1 -2
- package/packages/indexer/dist/file-hasher.d.ts +1 -2
- package/packages/indexer/dist/file-hasher.js +1 -2
- package/packages/indexer/dist/filesystem-crawler.d.ts +1 -2
- package/packages/indexer/dist/filesystem-crawler.js +1 -2
- package/packages/indexer/dist/graph-extractor.d.ts +1 -2
- package/packages/indexer/dist/graph-extractor.js +1 -2
- package/packages/indexer/dist/incremental-indexer.d.ts +1 -2
- package/packages/indexer/dist/incremental-indexer.js +1 -2
- package/packages/server/dist/config.d.ts +1 -2
- package/packages/server/dist/config.js +1 -2
- package/packages/server/dist/cross-workspace.d.ts +43 -0
- package/packages/server/dist/cross-workspace.js +1 -0
- package/packages/server/dist/curated-manager.d.ts +2 -3
- package/packages/server/dist/curated-manager.js +4 -5
- package/packages/server/dist/index.js +1 -2
- package/packages/server/dist/replay-interceptor.d.ts +1 -2
- package/packages/server/dist/replay-interceptor.js +1 -2
- package/packages/server/dist/resources/resources.d.ts +1 -2
- package/packages/server/dist/resources/resources.js +1 -2
- package/packages/server/dist/server.d.ts +4 -2
- package/packages/server/dist/server.js +1 -2
- package/packages/server/dist/tools/analyze.tools.d.ts +1 -2
- package/packages/server/dist/tools/analyze.tools.js +1 -2
- package/packages/server/dist/tools/audit.tool.d.ts +1 -2
- package/packages/server/dist/tools/audit.tool.js +1 -2
- package/packages/server/dist/tools/bridge.tools.d.ts +1 -2
- package/packages/server/dist/tools/bridge.tools.js +1 -2
- package/packages/server/dist/tools/evolution.tools.d.ts +1 -2
- package/packages/server/dist/tools/evolution.tools.js +1 -2
- package/packages/server/dist/tools/forge.tools.d.ts +1 -2
- package/packages/server/dist/tools/forge.tools.js +5 -6
- package/packages/server/dist/tools/forget.tool.d.ts +1 -2
- package/packages/server/dist/tools/forget.tool.js +1 -2
- package/packages/server/dist/tools/graph.tool.d.ts +1 -2
- package/packages/server/dist/tools/graph.tool.js +1 -2
- package/packages/server/dist/tools/list.tool.d.ts +1 -2
- package/packages/server/dist/tools/list.tool.js +1 -2
- package/packages/server/dist/tools/lookup.tool.d.ts +1 -2
- package/packages/server/dist/tools/lookup.tool.js +1 -2
- package/packages/server/dist/tools/onboard.tool.d.ts +1 -2
- package/packages/server/dist/tools/onboard.tool.js +1 -2
- package/packages/server/dist/tools/policy.tools.d.ts +1 -2
- package/packages/server/dist/tools/policy.tools.js +1 -2
- package/packages/server/dist/tools/produce.tool.d.ts +1 -2
- package/packages/server/dist/tools/produce.tool.js +1 -2
- package/packages/server/dist/tools/read.tool.d.ts +1 -2
- package/packages/server/dist/tools/read.tool.js +2 -3
- package/packages/server/dist/tools/reindex.tool.d.ts +1 -2
- package/packages/server/dist/tools/reindex.tool.js +3 -3
- package/packages/server/dist/tools/remember.tool.d.ts +1 -2
- package/packages/server/dist/tools/remember.tool.js +1 -2
- package/packages/server/dist/tools/replay.tool.d.ts +1 -2
- package/packages/server/dist/tools/replay.tool.js +1 -2
- package/packages/server/dist/tools/search.tool.d.ts +1 -2
- package/packages/server/dist/tools/search.tool.js +4 -5
- package/packages/server/dist/tools/status.tool.d.ts +7 -3
- package/packages/server/dist/tools/status.tool.js +2 -3
- package/packages/server/dist/tools/toolkit.tools.d.ts +1 -2
- package/packages/server/dist/tools/toolkit.tools.js +19 -19
- package/packages/server/dist/tools/update.tool.d.ts +1 -2
- package/packages/server/dist/tools/update.tool.js +1 -2
- package/packages/server/dist/tools/utility.tools.d.ts +1 -2
- package/packages/server/dist/tools/utility.tools.js +2 -3
- package/packages/server/dist/version-check.d.ts +1 -2
- package/packages/server/dist/version-check.js +1 -2
- package/packages/store/dist/graph-store.interface.d.ts +1 -2
- package/packages/store/dist/lance-store.d.ts +1 -2
- package/packages/store/dist/lance-store.js +1 -2
- package/packages/store/dist/sqlite-graph-store.d.ts +1 -2
- package/packages/store/dist/sqlite-graph-store.js +6 -7
- package/packages/store/dist/store-factory.d.ts +1 -2
- package/packages/store/dist/store-factory.js +1 -2
- package/packages/store/dist/store.interface.d.ts +1 -2
- package/packages/tools/dist/audit.d.ts +1 -2
- package/packages/tools/dist/audit.js +1 -2
- package/packages/tools/dist/batch.d.ts +1 -2
- package/packages/tools/dist/batch.js +1 -2
- package/packages/tools/dist/changelog.d.ts +1 -2
- package/packages/tools/dist/changelog.js +2 -3
- package/packages/tools/dist/check.d.ts +1 -2
- package/packages/tools/dist/check.js +2 -3
- package/packages/tools/dist/checkpoint.d.ts +1 -2
- package/packages/tools/dist/checkpoint.js +1 -2
- package/packages/tools/dist/codemod.d.ts +1 -2
- package/packages/tools/dist/codemod.js +1 -2
- package/packages/tools/dist/compact.d.ts +1 -2
- package/packages/tools/dist/compact.js +1 -2
- package/packages/tools/dist/data-transform.d.ts +1 -2
- package/packages/tools/dist/data-transform.js +1 -2
- package/packages/tools/dist/dead-symbols.d.ts +1 -2
- package/packages/tools/dist/dead-symbols.js +2 -3
- package/packages/tools/dist/delegate.d.ts +1 -2
- package/packages/tools/dist/delegate.js +1 -2
- package/packages/tools/dist/diff-parse.d.ts +1 -2
- package/packages/tools/dist/diff-parse.js +1 -2
- package/packages/tools/dist/digest.d.ts +1 -2
- package/packages/tools/dist/digest.js +1 -2
- package/packages/tools/dist/dogfood-log.d.ts +49 -0
- package/packages/tools/dist/dogfood-log.js +2 -0
- package/packages/tools/dist/encode.d.ts +1 -2
- package/packages/tools/dist/encode.js +1 -2
- package/packages/tools/dist/env-info.d.ts +1 -2
- package/packages/tools/dist/env-info.js +1 -2
- package/packages/tools/dist/eval.d.ts +1 -2
- package/packages/tools/dist/eval.js +1 -2
- package/packages/tools/dist/evidence-map.d.ts +1 -2
- package/packages/tools/dist/evidence-map.js +2 -3
- package/packages/tools/dist/file-cache.d.ts +1 -2
- package/packages/tools/dist/file-cache.js +1 -2
- package/packages/tools/dist/file-summary.d.ts +17 -2
- package/packages/tools/dist/file-summary.js +2 -3
- package/packages/tools/dist/file-walk.d.ts +1 -2
- package/packages/tools/dist/file-walk.js +1 -2
- package/packages/tools/dist/find-examples.d.ts +1 -2
- package/packages/tools/dist/find-examples.js +1 -2
- package/packages/tools/dist/find.d.ts +1 -2
- package/packages/tools/dist/find.js +1 -2
- package/packages/tools/dist/forge-classify.d.ts +1 -2
- package/packages/tools/dist/forge-classify.js +2 -3
- package/packages/tools/dist/forge-ground.d.ts +1 -2
- package/packages/tools/dist/forge-ground.js +1 -2
- package/packages/tools/dist/git-context.d.ts +1 -2
- package/packages/tools/dist/git-context.js +1 -2
- package/packages/tools/dist/graph-query.d.ts +1 -2
- package/packages/tools/dist/graph-query.js +1 -2
- package/packages/tools/dist/guide.d.ts +1 -2
- package/packages/tools/dist/guide.js +1 -2
- package/packages/tools/dist/health.d.ts +1 -2
- package/packages/tools/dist/health.js +1 -2
- package/packages/tools/dist/http-request.d.ts +1 -2
- package/packages/tools/dist/http-request.js +1 -2
- package/packages/tools/dist/index.d.ts +2 -1
- package/packages/tools/dist/index.js +1 -1
- package/packages/tools/dist/lane.d.ts +1 -2
- package/packages/tools/dist/lane.js +3 -4
- package/packages/tools/dist/measure.d.ts +4 -3
- package/packages/tools/dist/measure.js +2 -3
- package/packages/tools/dist/onboard.d.ts +1 -2
- package/packages/tools/dist/onboard.js +14 -15
- package/packages/tools/dist/parse-output.d.ts +1 -2
- package/packages/tools/dist/parse-output.js +2 -3
- package/packages/tools/dist/path-resolver.d.ts +1 -2
- package/packages/tools/dist/path-resolver.js +1 -2
- package/packages/tools/dist/process-manager.d.ts +1 -2
- package/packages/tools/dist/process-manager.js +1 -2
- package/packages/tools/dist/queue.d.ts +1 -2
- package/packages/tools/dist/queue.js +1 -2
- package/packages/tools/dist/regex-test.d.ts +1 -2
- package/packages/tools/dist/regex-test.js +1 -2
- package/packages/tools/dist/rename.d.ts +1 -2
- package/packages/tools/dist/rename.js +1 -2
- package/packages/tools/dist/replay.d.ts +2 -3
- package/packages/tools/dist/replay.js +4 -5
- package/packages/tools/dist/response-envelope.d.ts +1 -2
- package/packages/tools/dist/response-envelope.js +1 -2
- package/packages/tools/dist/schema-validate.d.ts +1 -2
- package/packages/tools/dist/schema-validate.js +1 -2
- package/packages/tools/dist/scope-map.d.ts +1 -2
- package/packages/tools/dist/scope-map.js +1 -2
- package/packages/tools/dist/snippet.d.ts +1 -2
- package/packages/tools/dist/snippet.js +1 -2
- package/packages/tools/dist/stash.d.ts +1 -2
- package/packages/tools/dist/stash.js +1 -2
- package/packages/tools/dist/stratum-card.d.ts +1 -2
- package/packages/tools/dist/stratum-card.js +1 -2
- package/packages/tools/dist/symbol.d.ts +3 -2
- package/packages/tools/dist/symbol.js +3 -4
- package/packages/tools/dist/test-run.d.ts +1 -2
- package/packages/tools/dist/test-run.js +2 -3
- package/packages/tools/dist/text-utils.d.ts +1 -2
- package/packages/tools/dist/text-utils.js +1 -2
- package/packages/tools/dist/time-utils.d.ts +1 -2
- package/packages/tools/dist/time-utils.js +1 -2
- package/packages/tools/dist/trace.d.ts +3 -2
- package/packages/tools/dist/trace.js +2 -3
- package/packages/tools/dist/truncation.d.ts +1 -2
- package/packages/tools/dist/truncation.js +1 -2
- package/packages/tools/dist/watch.d.ts +1 -2
- package/packages/tools/dist/watch.js +1 -2
- package/packages/tools/dist/web-fetch.d.ts +1 -2
- package/packages/tools/dist/web-fetch.js +1 -2
- package/packages/tools/dist/web-search.d.ts +1 -2
- package/packages/tools/dist/web-search.js +1 -2
- package/packages/tools/dist/workset.d.ts +1 -2
- package/packages/tools/dist/workset.js +1 -2
- package/packages/tui/dist/{App-BAlmxCCw.js → App-CYLNJLr6.js} +1 -2
- package/packages/tui/dist/App.d.ts +1 -2
- package/packages/tui/dist/App.js +1 -1
- package/packages/tui/dist/CuratedPanel-sYdZAICX.js +1 -2
- package/packages/tui/dist/LogPanel-DtMnoyXT.js +3 -0
- package/packages/tui/dist/SearchPanel-DREo6zgt.js +1 -2
- package/packages/tui/dist/StatusPanel-2ex8fLOO.js +1 -2
- package/packages/tui/dist/devtools-DUyj952l.js +1 -2
- package/packages/tui/dist/embedder.interface-D4ew0HPW.d.ts +1 -2
- package/packages/tui/dist/index-B9VpfVPP.d.ts +1 -2
- package/packages/tui/dist/index.js +1 -2
- package/packages/tui/dist/jsx-runtime-Cof-kwFn.js +1 -2
- package/packages/tui/dist/panels/CuratedPanel.d.ts +1 -2
- package/packages/tui/dist/panels/LogPanel.d.ts +1 -2
- package/packages/tui/dist/panels/LogPanel.js +1 -1
- package/packages/tui/dist/panels/SearchPanel.d.ts +1 -2
- package/packages/tui/dist/panels/StatusPanel.d.ts +1 -2
- package/packages/tui/dist/store.interface-CnY6SPOH.d.ts +1 -2
- package/scaffold/copilot/agents/Architect-Reviewer-Alpha.agent.md +7 -0
- package/scaffold/copilot/agents/Architect-Reviewer-Beta.agent.md +7 -0
- package/scaffold/copilot/agents/Documenter.agent.md +7 -0
- package/scaffold/copilot/agents/Orchestrator.agent.md +8 -0
- package/scaffold/copilot/agents/Planner.agent.md +9 -0
- package/scaffold/copilot/agents/Refactor.agent.md +6 -0
- package/scaffold/copilot/agents/Researcher-Alpha.agent.md +8 -0
- package/scaffold/copilot/agents/Researcher-Beta.agent.md +8 -0
- package/scaffold/copilot/agents/Researcher-Delta.agent.md +8 -0
- package/scaffold/copilot/agents/Researcher-Gamma.agent.md +8 -0
- package/scaffold/general/agents/Architect-Reviewer-Alpha.agent.md +21 -0
- package/scaffold/general/agents/Architect-Reviewer-Beta.agent.md +21 -0
- package/scaffold/general/agents/Documenter.agent.md +42 -0
- package/scaffold/general/agents/Orchestrator.agent.md +104 -0
- package/scaffold/general/agents/Planner.agent.md +55 -0
- package/scaffold/general/agents/Refactor.agent.md +36 -0
- package/scaffold/general/agents/Researcher-Alpha.agent.md +20 -0
- package/scaffold/general/agents/Researcher-Beta.agent.md +20 -0
- package/scaffold/general/agents/Researcher-Delta.agent.md +20 -0
- package/scaffold/general/agents/Researcher-Gamma.agent.md +20 -0
- package/scaffold/{copilot → general}/agents/_shared/code-agent-base.md +18 -0
- package/skills/adr-skill/SKILL.md +329 -0
- package/skills/adr-skill/assets/templates/adr-madr.md +89 -0
- package/skills/adr-skill/assets/templates/adr-readme.md +20 -0
- package/skills/adr-skill/assets/templates/adr-simple.md +46 -0
- package/skills/adr-skill/references/adr-conventions.md +95 -0
- package/skills/adr-skill/references/examples.md +193 -0
- package/skills/adr-skill/references/review-checklist.md +77 -0
- package/skills/adr-skill/references/template-variants.md +52 -0
- package/skills/adr-skill/scripts/bootstrap_adr.js +259 -0
- package/skills/adr-skill/scripts/new_adr.js +391 -0
- package/skills/adr-skill/scripts/set_adr_status.js +169 -0
- package/skills/c4-architecture/SKILL.md +295 -0
- package/skills/c4-architecture/references/advanced-patterns.md +552 -0
- package/skills/c4-architecture/references/c4-syntax.md +492 -0
- package/skills/c4-architecture/references/common-mistakes.md +437 -0
- package/skills/knowledge-base/SKILL.md +78 -1
- package/skills/lesson-learned/SKILL.md +105 -0
- package/skills/lesson-learned/references/anti-patterns.md +55 -0
- package/skills/lesson-learned/references/se-principles.md +109 -0
- package/skills/requirements-clarity/SKILL.md +324 -0
- package/skills/session-handoff/SKILL.md +189 -0
- package/skills/session-handoff/references/handoff-template.md +139 -0
- package/skills/session-handoff/references/resume-checklist.md +80 -0
- package/skills/session-handoff/scripts/check_staleness.js +269 -0
- package/skills/session-handoff/scripts/create_handoff.js +299 -0
- package/skills/session-handoff/scripts/list_handoffs.js +113 -0
- package/skills/session-handoff/scripts/validate_handoff.js +241 -0
- package/packages/chunker/dist/treesitter-chunker.d.ts +0 -44
- package/packages/chunker/dist/treesitter-chunker.js +0 -7
- package/packages/cli/dist/commands/init.d.ts +0 -15
- package/packages/cli/dist/commands/init.js +0 -305
- package/packages/tui/dist/LogPanel-DVB8Sv46.js +0 -4
- /package/scaffold/{copilot → general}/agents/Code-Reviewer-Alpha.agent.md +0 -0
- /package/scaffold/{copilot → general}/agents/Code-Reviewer-Beta.agent.md +0 -0
- /package/scaffold/{copilot → general}/agents/Debugger.agent.md +0 -0
- /package/scaffold/{copilot → general}/agents/Explorer.agent.md +0 -0
- /package/scaffold/{copilot → general}/agents/Frontend.agent.md +0 -0
- /package/scaffold/{copilot → general}/agents/Implementer.agent.md +0 -0
- /package/scaffold/{copilot → general}/agents/README.md +0 -0
- /package/scaffold/{copilot → general}/agents/Security.agent.md +0 -0
- /package/scaffold/{copilot → general}/agents/_shared/adr-protocol.md +0 -0
- /package/scaffold/{copilot → general}/agents/_shared/architect-reviewer-base.md +0 -0
- /package/scaffold/{copilot → general}/agents/_shared/code-reviewer-base.md +0 -0
- /package/scaffold/{copilot → general}/agents/_shared/decision-protocol.md +0 -0
- /package/scaffold/{copilot → general}/agents/_shared/forge-protocol.md +0 -0
- /package/scaffold/{copilot → general}/agents/_shared/researcher-base.md +0 -0
- /package/scaffold/{copilot → general}/agents/templates/adr-template.md +0 -0
- /package/scaffold/{copilot → general}/agents/templates/execution-state.md +0 -0
- /package/scaffold/{copilot → general}/prompts/ask.prompt.md +0 -0
- /package/scaffold/{copilot → general}/prompts/debug.prompt.md +0 -0
- /package/scaffold/{copilot → general}/prompts/design.prompt.md +0 -0
- /package/scaffold/{copilot → general}/prompts/implement.prompt.md +0 -0
- /package/scaffold/{copilot → general}/prompts/plan.prompt.md +0 -0
- /package/scaffold/{copilot → general}/prompts/review.prompt.md +0 -0
|
@@ -2,5 +2,4 @@ import{resolve as e}from"node:path";import{readFile as t}from"node:fs/promises";
|
|
|
2
2
|
`))console.log(` ${e}`)}}function x(e){console.log(e.id),console.log(` Command: ${e.command}${e.args.length>0?` ${e.args.join(` `)}`:``}`),console.log(` PID: ${e.pid??`unknown`}`),console.log(` Status: ${e.status}`),console.log(` Started: ${e.startedAt}`),e.exitCode!==void 0&&console.log(` Exit code: ${e.exitCode}`),console.log(` Logs: ${e.logs.length}`)}function S(e){if(console.log(`Exports scanned: ${e.totalExports}`),console.log(`Dead in source: ${e.totalDeadSource} (actionable)`),console.log(`Dead in docs: ${e.totalDeadDocs} (informational)`),e.totalDeadSource===0&&e.totalDeadDocs===0){console.log(`No dead symbols found.`);return}if(e.deadInSource.length>0){console.log(`
|
|
3
3
|
Dead in source (actionable):`);for(let t of e.deadInSource)console.log(` - ${t.path}:${t.line} ${t.kind} ${t.name}`)}if(e.deadInDocs.length>0){console.log(`
|
|
4
4
|
Dead in docs (informational):`);for(let t of e.deadInDocs)console.log(` - ${t.path}:${t.line} ${t.kind} ${t.name}`)}}function C(e){console.log(e.path),console.log(` Language: ${e.language}`),console.log(` Lines: ${e.lines}`),console.log(` Estimated tokens: ~${e.estimatedTokens}`),console.log(``),D(`Imports`,e.imports),D(`Exports`,e.exports),D(`Functions`,e.functions.map(e=>`${e.name} @ line ${e.line}${e.exported?` [exported]`:``}`)),D(`Classes`,e.classes.map(e=>`${e.name} @ line ${e.line}${e.exported?` [exported]`:``}`)),D(`Interfaces`,e.interfaces.map(e=>`${e.name} @ line ${e.line}`)),D(`Types`,e.types.map(e=>`${e.name} @ line ${e.line}`))}function w(e){if(console.log(`Symbol: ${e.name}`),e.definedIn?console.log(`Defined in: ${e.definedIn.path}:${e.definedIn.line} (${e.definedIn.kind})`):console.log(`Defined in: not found`),console.log(``),console.log(`Imported by:`),e.importedBy.length===0)console.log(` none`);else for(let t of e.importedBy)console.log(` - ${t.path}:${t.line} ${t.importStatement}`);if(console.log(``),console.log(`Referenced in:`),e.referencedIn.length===0)console.log(` none`);else for(let t of e.referencedIn)console.log(` - ${t.path}:${t.line} ${t.context}`)}function T(e){console.log(e.name),console.log(` Files: ${e.files.length}`),console.log(` Updated: ${e.updated}`),e.description&&console.log(` Description: ${e.description}`);for(let t of e.files)console.log(` - ${t}`)}function E(e){if(console.log(e.id),console.log(` Label: ${e.label}`),console.log(` Created: ${e.createdAt}`),e.notes&&console.log(` Notes: ${e.notes}`),e.files?.length){console.log(` Files: ${e.files.length}`);for(let t of e.files)console.log(` - ${t}`)}console.log(` Data:`);for(let t of JSON.stringify(e.data,null,2).split(`
|
|
5
|
-
`))console.log(` ${t}`)}function D(e,t){if(console.log(`${e}:`),t.length===0){console.log(` none`),console.log(``);return}for(let e of t)console.log(` - ${e}`);console.log(``)}function O(e){let t=e.trim();if(!t)return``;try{return JSON.parse(t)}catch{return e}}function k(e){let t=e.trim();if(!t)return{};let n=JSON.parse(t);if(!n||typeof n!=`object`||Array.isArray(n))throw Error(`Checkpoint data must be a JSON object.`);return n}function A(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)}async function j(e,t){switch(e.type){case`search`:{if(!t)throw Error(`search operation requires knowledge base context`);let n=typeof e.args.query==`string`?e.args.query.trim():``;if(!n)throw Error(`search operation requires a query`);let r=typeof e.args.limit==`number`?e.args.limit:5,i=e.args.search_mode===`semantic`||e.args.search_mode===`keyword`?e.args.search_mode:`hybrid`,a=typeof e.args.content_type==`string`?e.args.content_type:void 0,o=typeof e.args.min_score==`number`?e.args.min_score:.25;if(i===`keyword`)return(await t.store.ftsSearch(n,{limit:r,contentType:a,minScore:o})).slice(0,r);let s=await t.embedder.embedQuery(n);if(i===`semantic`)return t.store.search(s,{limit:r,contentType:a,minScore:o});let[c,l]=await Promise.all([t.store.search(s,{limit:r*2,contentType:a,minScore:o}),t.store.ftsSearch(n,{limit:r*2,contentType:a,minScore:o}).catch(()=>[])]);return A(c,l).slice(0,r)}case`find`:{if(!t)throw Error(`find operation requires knowledge base context`);let n=typeof e.args.query==`string`?e.args.query:void 0,i=typeof e.args.glob==`string`?e.args.glob:void 0,a=typeof e.args.pattern==`string`?e.args.pattern:void 0,o=typeof e.args.limit==`number`?e.args.limit:10,s=typeof e.args.content_type==`string`?e.args.content_type:void 0,c=typeof e.args.cwd==`string`?e.args.cwd:void 0;if(!n&&!i&&!a)throw Error(`find operation requires query, glob, or pattern`);return r(t.embedder,t.store,{query:n,glob:i,pattern:a,limit:o,contentType:s,cwd:c})}case`check`:return n({files:Array.isArray(e.args.files)?e.args.files.filter(e=>typeof e==`string`):void 0,cwd:typeof e.args.cwd==`string`?e.args.cwd:void 0,skipTypes:e.args.skip_types===!0,skipLint:e.args.skip_lint===!0});default:throw Error(`Unsupported batch operation type: ${e.type}`)}}export{j as executeCliBatchOperation,o as extractBoolFlag,i as extractNumFlag,a as extractStrFlag,f as formatFocusRanges,u as parseBatchPayload,O as parseMaybeJsonString,k as parseRecordString,m as printCheckResult,h as printCheckSection,E as printCheckpoint,S as printDeadSymbolsResult,v as printDiffFiles,b as printExamplesResult,C as printFileSummary,_ as printGitContext,x as printManagedProcess,p as printParsedOutput,D as printSection,w as printSymbolInfo,g as printTestRunResult,y as printTraceResult,T as printWorkset,c as readInput,s as readStdin,A as rrf,l as splitCsv,d as validateBatchOperations};
|
|
6
|
-
//# sourceMappingURL=helpers.js.map
|
|
5
|
+
`))console.log(` ${t}`)}function D(e,t){if(console.log(`${e}:`),t.length===0){console.log(` none`),console.log(``);return}for(let e of t)console.log(` - ${e}`);console.log(``)}function O(e){let t=e.trim();if(!t)return``;try{return JSON.parse(t)}catch{return e}}function k(e){let t=e.trim();if(!t)return{};let n=JSON.parse(t);if(!n||typeof n!=`object`||Array.isArray(n))throw Error(`Checkpoint data must be a JSON object.`);return n}function A(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)}async function j(e,t){switch(e.type){case`search`:{if(!t)throw Error(`search operation requires knowledge base context`);let n=typeof e.args.query==`string`?e.args.query.trim():``;if(!n)throw Error(`search operation requires a query`);let r=typeof e.args.limit==`number`?e.args.limit:5,i=e.args.search_mode===`semantic`||e.args.search_mode===`keyword`?e.args.search_mode:`hybrid`,a=typeof e.args.content_type==`string`?e.args.content_type:void 0,o=typeof e.args.min_score==`number`?e.args.min_score:.25;if(i===`keyword`)return(await t.store.ftsSearch(n,{limit:r,contentType:a,minScore:o})).slice(0,r);let s=await t.embedder.embedQuery(n);if(i===`semantic`)return t.store.search(s,{limit:r,contentType:a,minScore:o});let[c,l]=await Promise.all([t.store.search(s,{limit:r*2,contentType:a,minScore:o}),t.store.ftsSearch(n,{limit:r*2,contentType:a,minScore:o}).catch(()=>[])]);return A(c,l).slice(0,r)}case`find`:{if(!t)throw Error(`find operation requires knowledge base context`);let n=typeof e.args.query==`string`?e.args.query:void 0,i=typeof e.args.glob==`string`?e.args.glob:void 0,a=typeof e.args.pattern==`string`?e.args.pattern:void 0,o=typeof e.args.limit==`number`?e.args.limit:10,s=typeof e.args.content_type==`string`?e.args.content_type:void 0,c=typeof e.args.cwd==`string`?e.args.cwd:void 0;if(!n&&!i&&!a)throw Error(`find operation requires query, glob, or pattern`);return r(t.embedder,t.store,{query:n,glob:i,pattern:a,limit:o,contentType:s,cwd:c})}case`check`:return n({files:Array.isArray(e.args.files)?e.args.files.filter(e=>typeof e==`string`):void 0,cwd:typeof e.args.cwd==`string`?e.args.cwd:void 0,skipTypes:e.args.skip_types===!0,skipLint:e.args.skip_lint===!0});default:throw Error(`Unsupported batch operation type: ${e.type}`)}}export{j as executeCliBatchOperation,o as extractBoolFlag,i as extractNumFlag,a as extractStrFlag,f as formatFocusRanges,u as parseBatchPayload,O as parseMaybeJsonString,k as parseRecordString,m as printCheckResult,h as printCheckSection,E as printCheckpoint,S as printDeadSymbolsResult,v as printDiffFiles,b as printExamplesResult,C as printFileSummary,_ as printGitContext,x as printManagedProcess,p as printParsedOutput,D as printSection,w as printSymbolInfo,g as printTestRunResult,y as printTraceResult,T as printWorkset,c as readInput,s as readStdin,A as rrf,l as splitCsv,d as validateBatchOperations};
|
|
@@ -1,4 +1,3 @@
|
|
|
1
1
|
import{getCtx as e}from"./context.js";import{analyzeCommands as t}from"./commands/analyze.js";import{contextCommands as n}from"./commands/context-cmds.js";import{environmentCommands as r}from"./commands/environment.js";import{executionCommands as i}from"./commands/execution.js";import{graphCommands as a}from"./commands/graph.js";import{knowledgeCommands as o}from"./commands/knowledge.js";import{searchCommands as s}from"./commands/search.js";import{systemCommands as c}from"./commands/system.js";import{workspaceCommands as l}from"./commands/workspace.js";import{readFileSync as u}from"node:fs";import{dirname as d,resolve as f}from"node:path";import{fileURLToPath as p}from"node:url";const m=[...s,...o,...t,...a,...c,...i,...n,...l,...r];m.push({name:`help`,description:`Show available commands`,run:async()=>{g()}});async function h(t){let n=[...t],r=n.shift();if(!r||r===`--help`||r===`-h`){g();return}if(r===`--version`||r===`-v`){let e=f(d(p(import.meta.url)),`..`,`..`,`..`,`package.json`),t=JSON.parse(u(e,`utf-8`));console.log(t.version);return}let i=m.find(e=>e.name===r);i||(console.error(`Unknown command: ${r}`),g(),process.exit(1));try{await i.run(n)}finally{let t=e();t&&await t.store.close()}}function g(){console.log(`@vpxa/kb — Local-first AI developer toolkit
|
|
2
2
|
`),console.log(`Usage: kb <command> [options]
|
|
3
|
-
`),console.log(`Commands:`);let e=Math.max(...m.map(e=>e.name.length));for(let t of m)console.log(` ${t.name.padEnd(e+2)}${t.description}`);console.log(``),console.log(`Options:`),console.log(` --help, -h Show this help`),console.log(` --version, -v Show version`)}export{h as run};
|
|
4
|
-
//# sourceMappingURL=index.js.map
|
|
3
|
+
`),console.log(`Commands:`);let e=Math.max(...m.map(e=>e.name.length));for(let t of m)console.log(` ${t.name.padEnd(e+2)}${t.description}`);console.log(``),console.log(`Options:`),console.log(` --help, -h Show this help`),console.log(` --version, -v Show version`)}export{h as run};
|
|
@@ -1,2 +1 @@
|
|
|
1
|
-
import{existsSync as e,readFileSync as t}from"node:fs";import{dirname as n,resolve as r}from"node:path";import{
|
|
2
|
-
//# sourceMappingURL=kb-init.js.map
|
|
1
|
+
import{existsSync as e,readFileSync as t}from"node:fs";import{dirname as n,resolve as r}from"node:path";import{initializeWasm as i}from"../../chunker/dist/index.js";import{OnnxEmbedder as a}from"../../embeddings/dist/index.js";import{IncrementalIndexer as o}from"../../indexer/dist/index.js";import{SqliteGraphStore as s,createStore as c}from"../../store/dist/index.js";function l(){let i=process.env.KB_CONFIG_PATH??(e(r(process.cwd(),`kb.config.json`))?r(process.cwd(),`kb.config.json`):null);i||(console.error(`No kb.config.json found in current directory.`),console.error("Run `kb init` to create one, or set KB_CONFIG_PATH."),process.exit(1));let a=t(i,`utf-8`),o;try{o=JSON.parse(a)}catch{console.error(`Failed to parse ${i} as JSON. Ensure the file contains valid JSON.`),process.exit(1)}let s=n(i);return o.sources=o.sources.map(e=>({...e,path:r(s,e.path)})),o.store.path=r(s,o.store.path),o.curated=o.curated??{path:`curated`},o.curated.path=r(s,o.curated.path),o}async function u(){let e=l(),t=new a({model:e.embedding.model,dimensions:e.embedding.dimensions});await t.initialize();let n=await c({backend:e.store.backend,path:e.store.path});await n.initialize();let r=new o(t,n),{CuratedKnowledgeManager:u}=await import(`../../server/dist/curated-manager.js`),d=new u(e.curated.path,n,t),f;try{let t=new s({path:e.store.path});await t.initialize(),f=t,r.setGraphStore(f)}catch(e){console.error(`[kb] Graph store init failed (non-fatal): ${e.message}`),f={initialize:async()=>{},upsertNode:async()=>{},upsertEdge:async()=>{},upsertNodes:async()=>{},upsertEdges:async()=>{},getNode:async()=>null,getNeighbors:async()=>({nodes:[],edges:[]}),traverse:async()=>({nodes:[],edges:[]}),findNodes:async()=>[],findEdges:async()=>[],deleteNode:async()=>{},deleteBySourcePath:async()=>0,clear:async()=>{},getStats:async()=>({nodeCount:0,edgeCount:0,nodeTypes:{},edgeTypes:{}}),close:async()=>{}}}return await i().catch(()=>{}),{config:e,embedder:t,store:n,graphStore:f,indexer:r,curated:d}}export{u as initKB};
|
|
@@ -2,6 +2,28 @@
|
|
|
2
2
|
/**
|
|
3
3
|
* Default constants for the Knowledge Base system.
|
|
4
4
|
*/
|
|
5
|
+
/**
|
|
6
|
+
* Centralized directory paths for all KB artifacts.
|
|
7
|
+
* Single source of truth — change here to update everywhere.
|
|
8
|
+
*/
|
|
9
|
+
declare const KB_PATHS: {
|
|
10
|
+
/** AI artifacts root directory */readonly ai: ".ai"; /** Onboard / produce_knowledge output directory */
|
|
11
|
+
readonly aiKb: ".ai/kb"; /** Curated knowledge directory */
|
|
12
|
+
readonly aiCurated: ".ai/curated"; /** Vector store + graph data */
|
|
13
|
+
readonly data: ".kb-data"; /** Session state (stash, lanes, checkpoints, worksets, queues, replay, evidence-maps, snippets) */
|
|
14
|
+
readonly state: ".kb-state"; /** Persistent warn/error logs for dogfooding review */
|
|
15
|
+
readonly logs: ".kb-state/logs"; /** Brainstorming sessions */
|
|
16
|
+
readonly brainstorm: ".brainstorm"; /** Session handoff documents */
|
|
17
|
+
readonly handoffs: ".handoffs";
|
|
18
|
+
};
|
|
19
|
+
/**
|
|
20
|
+
* Global-mode directory paths (under ~/.kb-data/).
|
|
21
|
+
* Used when KB is installed at user level rather than per-workspace.
|
|
22
|
+
*/
|
|
23
|
+
declare const KB_GLOBAL_PATHS: {
|
|
24
|
+
/** Root directory name for global data store */readonly root: ".kb-data"; /** Registry file tracking all enrolled workspaces */
|
|
25
|
+
readonly registry: "registry.json";
|
|
26
|
+
};
|
|
5
27
|
/** Default chunk sizes by content type */
|
|
6
28
|
declare const CHUNK_SIZES: {
|
|
7
29
|
readonly markdown: {
|
|
@@ -48,5 +70,4 @@ declare const CATEGORY_PATTERN: RegExp;
|
|
|
48
70
|
/** Default knowledge categories */
|
|
49
71
|
declare const DEFAULT_CATEGORIES: readonly ["decisions", "patterns", "troubleshooting", "conventions", "architecture"];
|
|
50
72
|
//#endregion
|
|
51
|
-
export { CATEGORY_PATTERN, CHUNK_SIZES, DEFAULT_CATEGORIES, EMBEDDING_DEFAULTS, FILE_LIMITS, SEARCH_DEFAULTS, STORE_DEFAULTS };
|
|
52
|
-
//# sourceMappingURL=constants.d.ts.map
|
|
73
|
+
export { CATEGORY_PATTERN, CHUNK_SIZES, DEFAULT_CATEGORIES, EMBEDDING_DEFAULTS, FILE_LIMITS, KB_GLOBAL_PATHS, KB_PATHS, SEARCH_DEFAULTS, STORE_DEFAULTS };
|
|
@@ -1,2 +1 @@
|
|
|
1
|
-
const e={markdown:{max:1500,min:100},code:{max:2e3,min:50},config:{max:3e3,min:50},default:{max:1500,min:100,overlap:200}},
|
|
2
|
-
//# sourceMappingURL=constants.js.map
|
|
1
|
+
const e={ai:`.ai`,aiKb:`.ai/kb`,aiCurated:`.ai/curated`,data:`.kb-data`,state:`.kb-state`,logs:`.kb-state/logs`,brainstorm:`.brainstorm`,handoffs:`.handoffs`},t={root:`.kb-data`,registry:`registry.json`},n={markdown:{max:1500,min:100},code:{max:2e3,min:50},config:{max:3e3,min:50},default:{max:1500,min:100,overlap:200}},r={model:`mixedbread-ai/mxbai-embed-large-v1`,dimensions:1024},i={backend:`lancedb`,path:e.data,tableName:`knowledge`},a={maxFileSizeBytes:1e6,maxCuratedFileSizeBytes:5e4},o={maxResults:10,minScore:.25},s=/^[a-z][a-z0-9-]*$/,c=[`decisions`,`patterns`,`troubleshooting`,`conventions`,`architecture`];export{s as CATEGORY_PATTERN,n as CHUNK_SIZES,c as DEFAULT_CATEGORIES,r as EMBEDDING_DEFAULTS,a as FILE_LIMITS,t as KB_GLOBAL_PATHS,e as KB_PATHS,o as SEARCH_DEFAULTS,i as STORE_DEFAULTS};
|
|
@@ -10,5 +10,4 @@ declare function contentTypeToSourceType(ct: ContentType): SourceType;
|
|
|
10
10
|
/** Get all ContentTypes that belong to a given SourceType. */
|
|
11
11
|
declare function sourceTypeContentTypes(st: SourceType): ContentType[];
|
|
12
12
|
//#endregion
|
|
13
|
-
export { contentTypeToSourceType, detectContentType, sourceTypeContentTypes };
|
|
14
|
-
//# sourceMappingURL=content-detector.d.ts.map
|
|
13
|
+
export { contentTypeToSourceType, detectContentType, sourceTypeContentTypes };
|
|
@@ -1,2 +1 @@
|
|
|
1
|
-
import{basename as
|
|
2
|
-
//# sourceMappingURL=content-detector.js.map
|
|
1
|
+
import{KB_PATHS as e}from"./constants.js";import{basename as t,extname as n}from"node:path";const r={".ts":`code-typescript`,".tsx":`code-typescript`,".mts":`code-typescript`,".cts":`code-typescript`,".js":`code-javascript`,".jsx":`code-javascript`,".mjs":`code-javascript`,".cjs":`code-javascript`,".py":`code-python`,".json":`config-json`,".yaml":`config-yaml`,".yml":`config-yaml`,".toml":`config-toml`,".env":`config-env`,".md":`markdown`,".mdx":`markdown`},i=[/\.test\.[jt]sx?$/,/\.spec\.[jt]sx?$/,/(^|\/)__tests__\//,/(^|\/)test\//,/(^|\/)tests\//,/(^|\/)spec\//,/(^|\/)fixtures\//],a=[/\.stack\.[jt]s$/,/(^|\/)stacks\//,/(^|\/)constructs\//,/cdk\.json$/];function o(o){let s=n(o).toLowerCase(),c=t(o).toLowerCase();return o.includes(`${e.aiKb}/`)?`produced-knowledge`:o.includes(`${e.aiCurated}/`)?`curated-knowledge`:i.some(e=>e.test(o))?`test-code`:a.some(e=>e.test(o))?`cdk-stack`:s in r?r[s]:c.startsWith(`.env`)?`config-env`:[`.go`,`.rs`,`.java`,`.rb`,`.php`,`.sh`,`.ps1`,`.sql`,`.graphql`,`.proto`,`.css`,`.scss`,`.less`,`.html`,`.htm`,`.vue`,`.svelte`,`.astro`,`.hbs`,`.ejs`,`.svg`].includes(s)?`code-other`:`unknown`}const s={"code-typescript":`source`,"code-javascript":`source`,"code-python":`source`,"code-other":`source`,"cdk-stack":`source`,"test-code":`test`,markdown:`documentation`,documentation:`documentation`,"curated-knowledge":`documentation`,"produced-knowledge":`documentation`,"config-json":`config`,"config-yaml":`config`,"config-toml":`config`,"config-env":`config`,unknown:`source`};function c(e){return s[e]??`source`}function l(e){return Object.entries(s).filter(([,t])=>t===e).map(([e])=>e)}export{c as contentTypeToSourceType,o as detectContentType,l as sourceTypeContentTypes};
|
|
@@ -17,5 +17,4 @@ declare class ConfigError extends KBError {
|
|
|
17
17
|
constructor(message: string, cause?: unknown);
|
|
18
18
|
}
|
|
19
19
|
//#endregion
|
|
20
|
-
export { ConfigError, EmbeddingError, IndexError, KBError, StoreError };
|
|
21
|
-
//# sourceMappingURL=errors.d.ts.map
|
|
20
|
+
export { ConfigError, EmbeddingError, IndexError, KBError, StoreError };
|
|
@@ -1,2 +1 @@
|
|
|
1
|
-
var e=class extends Error{constructor(e,t,n){super(e),this.code=t,this.cause=n,this.name=`KBError`}},t=class extends e{constructor(e,t){super(e,`EMBEDDING_ERROR`,t),this.name=`EmbeddingError`}},n=class extends e{constructor(e,t){super(e,`STORE_ERROR`,t),this.name=`StoreError`}},r=class extends e{constructor(e,t){super(e,`INDEX_ERROR`,t),this.name=`IndexError`}},i=class extends e{constructor(e,t){super(e,`CONFIG_ERROR`,t),this.name=`ConfigError`}};export{i as ConfigError,t as EmbeddingError,r as IndexError,e as KBError,n as StoreError};
|
|
2
|
-
//# sourceMappingURL=errors.js.map
|
|
1
|
+
var e=class extends Error{constructor(e,t,n){super(e),this.code=t,this.cause=n,this.name=`KBError`}},t=class extends e{constructor(e,t){super(e,`EMBEDDING_ERROR`,t),this.name=`EmbeddingError`}},n=class extends e{constructor(e,t){super(e,`STORE_ERROR`,t),this.name=`StoreError`}},r=class extends e{constructor(e,t){super(e,`INDEX_ERROR`,t),this.name=`IndexError`}},i=class extends e{constructor(e,t){super(e,`CONFIG_ERROR`,t),this.name=`ConfigError`}};export{i as ConfigError,t as EmbeddingError,r as IndexError,e as KBError,n as StoreError};
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
//#region packages/core/src/global-registry.d.ts
|
|
2
|
+
/**
|
|
3
|
+
* Global registry for tracking workspaces enrolled in global MCP install mode.
|
|
4
|
+
* Registry lives at ~/.kb-data/registry.json alongside per-workspace partition directories.
|
|
5
|
+
*/
|
|
6
|
+
/** A single workspace entry in the global registry. */
|
|
7
|
+
interface RegistryEntry {
|
|
8
|
+
/** Partition key: <folder-name>-<sha256-8chars> */
|
|
9
|
+
partition: string;
|
|
10
|
+
/** Absolute path to workspace root */
|
|
11
|
+
workspacePath: string;
|
|
12
|
+
/** ISO timestamp of first registration */
|
|
13
|
+
registeredAt: string;
|
|
14
|
+
/** ISO timestamp of last server start */
|
|
15
|
+
lastAccessedAt: string;
|
|
16
|
+
}
|
|
17
|
+
/** Schema for ~/.kb-data/registry.json */
|
|
18
|
+
interface GlobalRegistry {
|
|
19
|
+
version: 1;
|
|
20
|
+
workspaces: Record<string, RegistryEntry>;
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Get the global data directory root.
|
|
24
|
+
* Override with `KB_GLOBAL_DATA_DIR` env var for testing.
|
|
25
|
+
*/
|
|
26
|
+
declare function getGlobalDataDir(): string;
|
|
27
|
+
/**
|
|
28
|
+
* Compute a deterministic partition key from a workspace path.
|
|
29
|
+
* Format: <folder-basename>-<sha256(absolutePath)-first8hex>
|
|
30
|
+
*/
|
|
31
|
+
declare function computePartitionKey(cwd: string): string;
|
|
32
|
+
/**
|
|
33
|
+
* Load the global registry. Returns empty registry if file doesn't exist.
|
|
34
|
+
*/
|
|
35
|
+
declare function loadRegistry(): GlobalRegistry;
|
|
36
|
+
/**
|
|
37
|
+
* Save the global registry atomically (write to .tmp then rename).
|
|
38
|
+
*/
|
|
39
|
+
declare function saveRegistry(registry: GlobalRegistry): void;
|
|
40
|
+
/**
|
|
41
|
+
* Register a workspace in the global registry. Creates partition directory.
|
|
42
|
+
* If already registered, updates lastAccessedAt.
|
|
43
|
+
*/
|
|
44
|
+
declare function registerWorkspace(cwd: string): RegistryEntry;
|
|
45
|
+
/**
|
|
46
|
+
* Look up a workspace in the registry by cwd.
|
|
47
|
+
*/
|
|
48
|
+
declare function lookupWorkspace(cwd: string): RegistryEntry | undefined;
|
|
49
|
+
/**
|
|
50
|
+
* List all registered workspaces.
|
|
51
|
+
*/
|
|
52
|
+
declare function listWorkspaces(): RegistryEntry[];
|
|
53
|
+
/**
|
|
54
|
+
* Get the absolute path to a partition's data directory.
|
|
55
|
+
*/
|
|
56
|
+
declare function getPartitionDir(partition: string): string;
|
|
57
|
+
/**
|
|
58
|
+
* Check whether global mode is installed (registry.json exists in ~/.kb-data/).
|
|
59
|
+
*/
|
|
60
|
+
declare function isGlobalInstalled(): boolean;
|
|
61
|
+
//#endregion
|
|
62
|
+
export { GlobalRegistry, RegistryEntry, computePartitionKey, getGlobalDataDir, getPartitionDir, isGlobalInstalled, listWorkspaces, loadRegistry, lookupWorkspace, registerWorkspace, saveRegistry };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{KB_GLOBAL_PATHS as e}from"./constants.js";import{basename as t,resolve as n}from"node:path";import{createHash as r}from"node:crypto";import{existsSync as i,mkdirSync as a,readFileSync as o,renameSync as s,writeFileSync as c}from"node:fs";import{homedir as l}from"node:os";function u(){return process.env.KB_GLOBAL_DATA_DIR??n(l(),e.root)}function d(e){let i=n(e);return`${t(i).toLowerCase().replace(/[^a-z0-9-]/g,`-`)||`workspace`}-${r(`sha256`).update(i).digest(`hex`).slice(0,8)}`}function f(){let t=n(u(),e.registry);if(!i(t))return{version:1,workspaces:{}};let r=o(t,`utf-8`);return JSON.parse(r)}function p(t){let r=u();a(r,{recursive:!0});let i=n(r,e.registry),o=`${i}.tmp`;c(o,JSON.stringify(t,null,2),`utf-8`),s(o,i)}function m(e){let t=f(),r=d(e),i=new Date().toISOString();return t.workspaces[r]?t.workspaces[r].lastAccessedAt=i:t.workspaces[r]={partition:r,workspacePath:n(e),registeredAt:i,lastAccessedAt:i},a(_(r),{recursive:!0}),p(t),t.workspaces[r]}function h(e){let t=f(),n=d(e);return t.workspaces[n]}function g(){let e=f();return Object.values(e.workspaces)}function _(e){return n(u(),e)}function v(){return i(n(u(),e.registry))}export{d as computePartitionKey,u as getGlobalDataDir,_ as getPartitionDir,v as isGlobalInstalled,g as listWorkspaces,f as loadRegistry,h as lookupWorkspace,m as registerWorkspace,p as saveRegistry};
|
|
@@ -1,6 +1,7 @@
|
|
|
1
|
-
import { CATEGORY_PATTERN, CHUNK_SIZES, DEFAULT_CATEGORIES, EMBEDDING_DEFAULTS, FILE_LIMITS, SEARCH_DEFAULTS, STORE_DEFAULTS } from "./constants.js";
|
|
1
|
+
import { CATEGORY_PATTERN, CHUNK_SIZES, DEFAULT_CATEGORIES, EMBEDDING_DEFAULTS, FILE_LIMITS, KB_GLOBAL_PATHS, KB_PATHS, SEARCH_DEFAULTS, STORE_DEFAULTS } from "./constants.js";
|
|
2
2
|
import { CONTENT_TYPES, ChunkMetadata, ContentType, IndexStats, KBConfig, KNOWLEDGE_ORIGINS, KnowledgeOrigin, KnowledgeRecord, RawChunk, SOURCE_TYPES, SearchResult, SourceType } from "./types.js";
|
|
3
3
|
import { contentTypeToSourceType, detectContentType, sourceTypeContentTypes } from "./content-detector.js";
|
|
4
4
|
import { ConfigError, EmbeddingError, IndexError, KBError, StoreError } from "./errors.js";
|
|
5
|
-
import {
|
|
6
|
-
|
|
5
|
+
import { GlobalRegistry, RegistryEntry, computePartitionKey, getGlobalDataDir, getPartitionDir, isGlobalInstalled, listWorkspaces, loadRegistry, lookupWorkspace, registerWorkspace, saveRegistry } from "./global-registry.js";
|
|
6
|
+
import { LogLevel, createLogger, getLogLevel, resetLogDir, serializeError, setFileSinkEnabled, setLogLevel } from "./logger.js";
|
|
7
|
+
export { CATEGORY_PATTERN, CHUNK_SIZES, CONTENT_TYPES, ChunkMetadata, ConfigError, ContentType, DEFAULT_CATEGORIES, EMBEDDING_DEFAULTS, EmbeddingError, FILE_LIMITS, GlobalRegistry, IndexError, IndexStats, KBConfig, KBError, KB_GLOBAL_PATHS, KB_PATHS, KNOWLEDGE_ORIGINS, KnowledgeOrigin, KnowledgeRecord, LogLevel, RawChunk, RegistryEntry, SEARCH_DEFAULTS, SOURCE_TYPES, STORE_DEFAULTS, SearchResult, SourceType, StoreError, computePartitionKey, contentTypeToSourceType, createLogger, detectContentType, getGlobalDataDir, getLogLevel, getPartitionDir, isGlobalInstalled, listWorkspaces, loadRegistry, lookupWorkspace, registerWorkspace, resetLogDir, saveRegistry, serializeError, setFileSinkEnabled, setLogLevel, sourceTypeContentTypes };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{CATEGORY_PATTERN as e,CHUNK_SIZES as t,DEFAULT_CATEGORIES as n,EMBEDDING_DEFAULTS as r,FILE_LIMITS as i,
|
|
1
|
+
import{CATEGORY_PATTERN as e,CHUNK_SIZES as t,DEFAULT_CATEGORIES as n,EMBEDDING_DEFAULTS as r,FILE_LIMITS as i,KB_GLOBAL_PATHS as a,KB_PATHS as o,SEARCH_DEFAULTS as s,STORE_DEFAULTS as c}from"./constants.js";import{contentTypeToSourceType as l,detectContentType as u,sourceTypeContentTypes as d}from"./content-detector.js";import{ConfigError as f,EmbeddingError as p,IndexError as m,KBError as h,StoreError as g}from"./errors.js";import{computePartitionKey as _,getGlobalDataDir as v,getPartitionDir as y,isGlobalInstalled as b,listWorkspaces as x,loadRegistry as S,lookupWorkspace as C,registerWorkspace as w,saveRegistry as T}from"./global-registry.js";import{createLogger as E,getLogLevel as D,resetLogDir as O,serializeError as k,setFileSinkEnabled as A,setLogLevel as j}from"./logger.js";import{CONTENT_TYPES as M,KNOWLEDGE_ORIGINS as N,SOURCE_TYPES as P}from"./types.js";export{e as CATEGORY_PATTERN,t as CHUNK_SIZES,M as CONTENT_TYPES,f as ConfigError,n as DEFAULT_CATEGORIES,r as EMBEDDING_DEFAULTS,p as EmbeddingError,i as FILE_LIMITS,m as IndexError,h as KBError,a as KB_GLOBAL_PATHS,o as KB_PATHS,N as KNOWLEDGE_ORIGINS,s as SEARCH_DEFAULTS,P as SOURCE_TYPES,c as STORE_DEFAULTS,g as StoreError,_ as computePartitionKey,l as contentTypeToSourceType,E as createLogger,u as detectContentType,v as getGlobalDataDir,D as getLogLevel,y as getPartitionDir,b as isGlobalInstalled,x as listWorkspaces,S as loadRegistry,C as lookupWorkspace,w as registerWorkspace,O as resetLogDir,T as saveRegistry,k as serializeError,A as setFileSinkEnabled,j as setLogLevel,d as sourceTypeContentTypes};
|
|
@@ -2,6 +2,9 @@
|
|
|
2
2
|
type LogLevel = 'debug' | 'info' | 'warn' | 'error';
|
|
3
3
|
declare function setLogLevel(level: LogLevel): void;
|
|
4
4
|
declare function getLogLevel(): LogLevel;
|
|
5
|
+
declare function setFileSinkEnabled(enabled: boolean): void;
|
|
6
|
+
/** Reset resolved log directory (for testing). */
|
|
7
|
+
declare function resetLogDir(): void;
|
|
5
8
|
/**
|
|
6
9
|
* Serialize an unknown error into a structured record suitable for JSON logging.
|
|
7
10
|
* Includes stack traces only at debug level to keep production logs concise.
|
|
@@ -14,5 +17,4 @@ declare function createLogger(component: string): {
|
|
|
14
17
|
error: (msg: string, data?: Record<string, unknown>) => void;
|
|
15
18
|
};
|
|
16
19
|
//#endregion
|
|
17
|
-
export { LogLevel, createLogger, getLogLevel, serializeError, setLogLevel };
|
|
18
|
-
//# sourceMappingURL=logger.d.ts.map
|
|
20
|
+
export { LogLevel, createLogger, getLogLevel, resetLogDir, serializeError, setFileSinkEnabled, setLogLevel };
|
|
@@ -1,2 +1 @@
|
|
|
1
|
-
const
|
|
2
|
-
//# sourceMappingURL=logger.js.map
|
|
1
|
+
import{KB_PATHS as e}from"./constants.js";import{join as t,resolve as n}from"node:path";import{appendFileSync as r,mkdirSync as i,readdirSync as a,unlinkSync as o}from"node:fs";const s={debug:0,info:1,warn:2,error:3};let c=process.env.KB_LOG_LEVEL??`info`,l=process.env.KB_LOG_FILE_SINK===`true`||process.env.KB_LOG_FILE_SINK!==`false`&&!process.env.VITEST&&process.env.NODE_ENV!==`test`;function u(){return l?process.env.VITEST||process.env.NODE_ENV===`test`?process.env.KB_LOG_FILE_SINK===`true`:!0:!1}let d;function f(){return d||=n(process.cwd(),e.logs),d}function p(e){let n=e.toISOString().slice(0,10);return t(f(),`${n}.jsonl`)}let m=0;function h(){let e=Date.now();if(!(e-m<36e5)){m=e;try{let n=f(),r=new Date(e-30*864e5).toISOString().slice(0,10);for(let e of a(n))if(e.endsWith(`.jsonl`)&&e.slice(0,10)<r)try{o(t(n,e))}catch{}}catch{}}}function g(e,t){try{i(f(),{recursive:!0}),r(p(t),`${e}\n`),h()}catch{}}function _(e){c=e}function v(){return c}function y(e){l=e}function b(){d=void 0}function x(e){if(e instanceof Error){let t={error:e.message};return c===`debug`&&e.stack&&(t.stack=e.stack),t}return{error:String(e)}}function S(e){function t(t,n,r){if(s[t]<s[c])return;let i=new Date,a={ts:i.toISOString(),level:t,component:e,msg:n,...r},o=JSON.stringify(a);console.error(o),u()&&(t===`warn`||t===`error`)&&g(o,i)}return{debug:(e,n)=>t(`debug`,e,n),info:(e,n)=>t(`info`,e,n),warn:(e,n)=>t(`warn`,e,n),error:(e,n)=>t(`error`,e,n)}}export{S as createLogger,v as getLogLevel,b as resetLogDir,x as serializeError,y as setFileSinkEnabled,_ as setLogLevel};
|
|
@@ -122,5 +122,4 @@ interface IndexStats {
|
|
|
122
122
|
embeddingModel: string;
|
|
123
123
|
}
|
|
124
124
|
//#endregion
|
|
125
|
-
export { CONTENT_TYPES, ChunkMetadata, ContentType, IndexStats, KBConfig, KNOWLEDGE_ORIGINS, KnowledgeOrigin, KnowledgeRecord, RawChunk, SOURCE_TYPES, SearchResult, SourceType };
|
|
126
|
-
//# sourceMappingURL=types.d.ts.map
|
|
125
|
+
export { CONTENT_TYPES, ChunkMetadata, ContentType, IndexStats, KBConfig, KNOWLEDGE_ORIGINS, KnowledgeOrigin, KnowledgeRecord, RawChunk, SOURCE_TYPES, SearchResult, SourceType };
|
|
@@ -1,2 +1 @@
|
|
|
1
|
-
const e=[`indexed`,`curated`,`produced`],t=[`source`,`documentation`,`test`,`config`,`generated`],n=[`documentation`,`code-typescript`,`code-javascript`,`code-python`,`code-other`,`config-json`,`config-yaml`,`config-toml`,`config-env`,`test-code`,`cdk-stack`,`markdown`,`curated-knowledge`,`produced-knowledge`,`unknown`];export{n as CONTENT_TYPES,e as KNOWLEDGE_ORIGINS,t as SOURCE_TYPES};
|
|
2
|
-
//# sourceMappingURL=types.js.map
|
|
1
|
+
const e=[`indexed`,`curated`,`produced`],t=[`source`,`documentation`,`test`,`config`,`generated`],n=[`documentation`,`code-typescript`,`code-javascript`,`code-python`,`code-other`,`config-json`,`config-yaml`,`config-toml`,`config-env`,`test-code`,`cdk-stack`,`markdown`,`curated-knowledge`,`produced-knowledge`,`unknown`];export{n as CONTENT_TYPES,e as KNOWLEDGE_ORIGINS,t as SOURCE_TYPES};
|
|
@@ -1,2 +1 @@
|
|
|
1
|
-
import{homedir as e}from"node:os";import{join as t}from"node:path";import{env as n,pipeline as r}from"@huggingface/transformers";import{EMBEDDING_DEFAULTS as i}from"../../core/dist/index.js";n.cacheDir=t(e(),`.cache`,`huggingface`,`transformers-js`);var a=class{pipe=null;dimensions;modelId;queryPrefix;constructor(e){this.modelId=e?.model??i.model,this.dimensions=e?.dimensions??i.dimensions,this.queryPrefix=e?.queryPrefix??this.detectQueryPrefix(this.modelId)}detectQueryPrefix(e){let t=e.toLowerCase();return t.includes(`bge`)||t.includes(`mxbai-embed`)?`Represent this sentence for searching relevant passages: `:t.includes(`/e5-`)||t.includes(`multilingual-e5`)?`query: `:``}async initialize(){if(!this.pipe)try{this.pipe=await r(`feature-extraction`,this.modelId,{dtype:`fp32`})}catch(e){throw Error(`Failed to initialize embedding model "${this.modelId}": ${e.message}`)}}async shutdown(){this.pipe=null}async embed(e){this.pipe||await this.initialize();let t=await this.pipe?.(e,{pooling:`mean`,normalize:!0});if(!t)throw Error(`Embedding pipeline returned no output`);return new Float32Array(t.data)}async embedQuery(e){return this.embed(this.queryPrefix+e)}async embedBatch(e){if(e.length===0)return[];this.pipe||await this.initialize();let t=[];for(let n=0;n<e.length;n+=32){let r=e.slice(n,n+32),i=await this.pipe?.(r,{pooling:`mean`,normalize:!0});if(!i)throw Error(`Embedding pipeline returned no output`);if(r.length===1)t.push(new Float32Array(i.data));else for(let e=0;e<r.length;e++){let n=e*this.dimensions,r=i.data.slice(n,n+this.dimensions);t.push(new Float32Array(r))}}return t}};export{a as OnnxEmbedder};
|
|
2
|
-
//# sourceMappingURL=onnx-embedder.js.map
|
|
1
|
+
import{homedir as e}from"node:os";import{join as t}from"node:path";import{env as n,pipeline as r}from"@huggingface/transformers";import{EMBEDDING_DEFAULTS as i}from"../../core/dist/index.js";n.cacheDir=t(e(),`.cache`,`huggingface`,`transformers-js`);var a=class{pipe=null;dimensions;modelId;queryPrefix;constructor(e){this.modelId=e?.model??i.model,this.dimensions=e?.dimensions??i.dimensions,this.queryPrefix=e?.queryPrefix??this.detectQueryPrefix(this.modelId)}detectQueryPrefix(e){let t=e.toLowerCase();return t.includes(`bge`)||t.includes(`mxbai-embed`)?`Represent this sentence for searching relevant passages: `:t.includes(`/e5-`)||t.includes(`multilingual-e5`)?`query: `:``}async initialize(){if(!this.pipe)try{this.pipe=await r(`feature-extraction`,this.modelId,{dtype:`fp32`})}catch(e){throw Error(`Failed to initialize embedding model "${this.modelId}": ${e.message}`)}}async shutdown(){this.pipe=null}async embed(e){this.pipe||await this.initialize();let t=await this.pipe?.(e,{pooling:`mean`,normalize:!0});if(!t)throw Error(`Embedding pipeline returned no output`);return new Float32Array(t.data)}async embedQuery(e){return this.embed(this.queryPrefix+e)}async embedBatch(e){if(e.length===0)return[];this.pipe||await this.initialize();let t=[];for(let n=0;n<e.length;n+=32){let r=e.slice(n,n+32),i=await this.pipe?.(r,{pooling:`mean`,normalize:!0});if(!i)throw Error(`Embedding pipeline returned no output`);if(r.length===1)t.push(new Float32Array(i.data));else for(let e=0;e<r.length;e++){let n=e*this.dimensions,r=i.data.slice(n,n+this.dimensions);t.push(new Float32Array(r))}}return t}};export{a as OnnxEmbedder};
|
|
@@ -1,2 +1 @@
|
|
|
1
|
-
var e=class e{cache=new Map;maxEntries;defaultTtl;constructor(e){this.maxEntries=e?.maxEntries??100,this.defaultTtl=e?.defaultTtl??216e5}static normalizeKey(e){return e.toLowerCase().trim().replace(/\s+/g,` `)}get(t){let n=e.normalizeKey(t),r=this.cache.get(n);if(r){if(Date.now()-r.cachedAt>r.ttl){this.cache.delete(n);return}return this.cache.delete(n),this.cache.set(n,r),r.results}}set(t,n,r){let i=e.normalizeKey(t);if(this.cache.size>=this.maxEntries&&!this.cache.has(i)){let e=this.cache.keys().next().value;e!==void 0&&this.cache.delete(e)}this.cache.set(i,{results:n,query:i,cachedAt:Date.now(),ttl:r??this.defaultTtl})}invalidate(t){let n=e.normalizeKey(t);return this.cache.delete(n)}clear(){this.cache.clear()}get size(){return this.cache.size}stats(){return{size:this.cache.size,maxEntries:this.maxEntries,defaultTtlMs:this.defaultTtl}}};export{e as ERCache};
|
|
2
|
-
//# sourceMappingURL=cache.js.map
|
|
1
|
+
var e=class e{cache=new Map;maxEntries;defaultTtl;constructor(e){this.maxEntries=e?.maxEntries??100,this.defaultTtl=e?.defaultTtl??216e5}static normalizeKey(e){return e.toLowerCase().trim().replace(/\s+/g,` `)}get(t){let n=e.normalizeKey(t),r=this.cache.get(n);if(r){if(Date.now()-r.cachedAt>r.ttl){this.cache.delete(n);return}return this.cache.delete(n),this.cache.set(n,r),r.results}}set(t,n,r){let i=e.normalizeKey(t);if(this.cache.size>=this.maxEntries&&!this.cache.has(i)){let e=this.cache.keys().next().value;e!==void 0&&this.cache.delete(e)}this.cache.set(i,{results:n,query:i,cachedAt:Date.now(),ttl:r??this.defaultTtl})}invalidate(t){let n=e.normalizeKey(t);return this.cache.delete(n)}clear(){this.cache.clear()}get size(){return this.cache.size}stats(){return{size:this.cache.size,maxEntries:this.maxEntries,defaultTtlMs:this.defaultTtl}}};export{e as ERCache};
|
|
@@ -1,2 +1 @@
|
|
|
1
|
-
import{ERTransientError as e}from"./types.js";var t=class t{baseUrl;apiKey;timeoutMs;circuitState=`closed`;consecutiveFailures=0;openUntil=0;halfOpenProbeInFlight=!1;static FAILURE_THRESHOLD=3;static RESET_TIMEOUT_MS=6e4;constructor(e){let t=new URL(e.baseUrl);if(t.protocol!==`http:`&&t.protocol!==`https:`)throw Error(`Unsupported protocol: ${t.protocol} — only http/https allowed`);let n=t.hostname===`localhost`||t.hostname===`127.0.0.1`||t.hostname===`::1`;if(t.protocol===`http:`&&!n)throw Error(`Non-TLS (http://) ER endpoints are only allowed for localhost. Use https:// to avoid leaking API keys.`);this.baseUrl=e.baseUrl.replace(/\/+$/,``),this.apiKey=e.apiKey,this.timeoutMs=e.timeoutMs}async search(e,t=5){let n=await this.fetch(`/api/v1/search`,{method:`POST`,body:JSON.stringify({query:e,maxResults:t,generateResponse:!1})});if(!n.ok)throw Error(`ER search failed: ${n.status} ${n.statusText}`);return((await n.json()).sources??[]).map(e=>{let t=typeof e.score==`number`?e.score:void 0,n=typeof e.confidence==`number`?e.confidence:void 0;return{content:e.content,sourcePath:e.metadata?.sourceUri??`unknown`,score:t??n??0,metadata:e.metadata}})}async push(e){let t=await this.fetch(`/mcp/tools`,{method:`POST`,body:JSON.stringify({name:`curated_remember`,arguments:{title:e.title,content:e.content,category:e.category??`conventions`,tags:[...e.tags??[],`pushed-from-kb`]}})});if(!t.ok)return{pushed:!1,status:`failed`,timestamp:new Date().toISOString(),error:`ER push failed: ${t.status} ${t.statusText}`};let n=await t.json();return{pushed:!0,status:`stored`,remotePath:typeof n.path==`string`?n.path:void 0,timestamp:new Date().toISOString()}}async pull(e,t=10){return this.search(e,t)}async health(){try{let e=await this.fetch(`/api/v1/health`,{method:`GET`});return{healthy:e.ok,status:e.status}}catch{return{healthy:!1}}}async listTools(){try{let e=await this.fetch(`/mcp/tools`,{method:`GET`});return e.ok?((await e.json()).tools??[]).map(e=>e.name):[]}catch{return[]}}async fetch(e,t){this.checkCircuit();let n;for(let r=0;r<=2;r++){let i=new AbortController,a=setTimeout(()=>i.abort(),this.timeoutMs);try{let n=await fetch(`${this.baseUrl}${e}`,{...t,headers:{"Content-Type":`application/json`,"X-Api-Key":this.apiKey,"User-Agent":`kb-enterprise-bridge/1.0`,...t.headers},signal:i.signal});if(n.ok||n.status>=400&&n.status<500&&n.status!==429)return this.recordSuccess(),n;if(r<2){let e=this.parseRetryAfter(n)??this.backoffMs(r);await this.sleep(e);continue}return this.recordFailure(),n}catch(e){n=e,r<2&&await this.sleep(this.backoffMs(r))}finally{clearTimeout(a)}}throw this.recordFailure(),n??Error(`Fetch failed after retries`)}checkCircuit(){if(this.circuitState===`open`)if(Date.now()>=this.openUntil){if(this.halfOpenProbeInFlight)throw new e(`ER circuit breaker is half-open — probe in progress`);this.circuitState=`half-open`,this.halfOpenProbeInFlight=!0}else throw new e(`ER circuit breaker is open — skipping request`)}recordSuccess(){this.consecutiveFailures=0,this.circuitState=`closed`,this.halfOpenProbeInFlight=!1}recordFailure(){this.consecutiveFailures++,this.halfOpenProbeInFlight=!1,this.consecutiveFailures>=t.FAILURE_THRESHOLD&&(this.circuitState=`open`,this.openUntil=Date.now()+t.RESET_TIMEOUT_MS)}backoffMs(e){let t=500*3**e,n=t*.25*(Math.random()*2-1);return Math.round(t+n)}parseRetryAfter(e){let t=e.headers.get(`Retry-After`);if(!t)return;let n=Number(t);if(!Number.isNaN(n)&&n>=0)return Math.min(n*1e3,3e4)}sleep(e){return new Promise(t=>setTimeout(t,e))}};export{t as ERClient};
|
|
2
|
-
//# sourceMappingURL=er-client.js.map
|
|
1
|
+
import{ERTransientError as e}from"./types.js";var t=class t{baseUrl;apiKey;timeoutMs;circuitState=`closed`;consecutiveFailures=0;openUntil=0;halfOpenProbeInFlight=!1;static FAILURE_THRESHOLD=3;static RESET_TIMEOUT_MS=6e4;constructor(e){let t=new URL(e.baseUrl);if(t.protocol!==`http:`&&t.protocol!==`https:`)throw Error(`Unsupported protocol: ${t.protocol} — only http/https allowed`);let n=t.hostname===`localhost`||t.hostname===`127.0.0.1`||t.hostname===`::1`;if(t.protocol===`http:`&&!n)throw Error(`Non-TLS (http://) ER endpoints are only allowed for localhost. Use https:// to avoid leaking API keys.`);this.baseUrl=e.baseUrl.replace(/\/+$/,``),this.apiKey=e.apiKey,this.timeoutMs=e.timeoutMs}async search(e,t=5){let n=await this.fetch(`/api/v1/search`,{method:`POST`,body:JSON.stringify({query:e,maxResults:t,generateResponse:!1})});if(!n.ok)throw Error(`ER search failed: ${n.status} ${n.statusText}`);return((await n.json()).sources??[]).map(e=>{let t=typeof e.score==`number`?e.score:void 0,n=typeof e.confidence==`number`?e.confidence:void 0;return{content:e.content,sourcePath:e.metadata?.sourceUri??`unknown`,score:t??n??0,metadata:e.metadata}})}async push(e){let t=await this.fetch(`/mcp/tools`,{method:`POST`,body:JSON.stringify({name:`curated_remember`,arguments:{title:e.title,content:e.content,category:e.category??`conventions`,tags:[...e.tags??[],`pushed-from-kb`]}})});if(!t.ok)return{pushed:!1,status:`failed`,timestamp:new Date().toISOString(),error:`ER push failed: ${t.status} ${t.statusText}`};let n=await t.json();return{pushed:!0,status:`stored`,remotePath:typeof n.path==`string`?n.path:void 0,timestamp:new Date().toISOString()}}async pull(e,t=10){return this.search(e,t)}async health(){try{let e=await this.fetch(`/api/v1/health`,{method:`GET`});return{healthy:e.ok,status:e.status}}catch{return{healthy:!1}}}async listTools(){try{let e=await this.fetch(`/mcp/tools`,{method:`GET`});return e.ok?((await e.json()).tools??[]).map(e=>e.name):[]}catch{return[]}}async fetch(e,t){this.checkCircuit();let n;for(let r=0;r<=2;r++){let i=new AbortController,a=setTimeout(()=>i.abort(),this.timeoutMs);try{let n=await fetch(`${this.baseUrl}${e}`,{...t,headers:{"Content-Type":`application/json`,"X-Api-Key":this.apiKey,"User-Agent":`kb-enterprise-bridge/1.0`,...t.headers},signal:i.signal});if(n.ok||n.status>=400&&n.status<500&&n.status!==429)return this.recordSuccess(),n;if(r<2){let e=this.parseRetryAfter(n)??this.backoffMs(r);await this.sleep(e);continue}return this.recordFailure(),n}catch(e){n=e,r<2&&await this.sleep(this.backoffMs(r))}finally{clearTimeout(a)}}throw this.recordFailure(),n??Error(`Fetch failed after retries`)}checkCircuit(){if(this.circuitState===`open`)if(Date.now()>=this.openUntil){if(this.halfOpenProbeInFlight)throw new e(`ER circuit breaker is half-open — probe in progress`);this.circuitState=`half-open`,this.halfOpenProbeInFlight=!0}else throw new e(`ER circuit breaker is open — skipping request`)}recordSuccess(){this.consecutiveFailures=0,this.circuitState=`closed`,this.halfOpenProbeInFlight=!1}recordFailure(){this.consecutiveFailures++,this.halfOpenProbeInFlight=!1,this.consecutiveFailures>=t.FAILURE_THRESHOLD&&(this.circuitState=`open`,this.openUntil=Date.now()+t.RESET_TIMEOUT_MS)}backoffMs(e){let t=500*3**e,n=t*.25*(Math.random()*2-1);return Math.round(t+n)}parseRetryAfter(e){let t=e.headers.get(`Retry-After`);if(!t)return;let n=Number(t);if(!Number.isNaN(n)&&n>=0)return Math.min(n*1e3,3e4)}sleep(e){return new Promise(t=>setTimeout(t,e))}};export{t as ERClient};
|
|
@@ -1,2 +1 @@
|
|
|
1
|
-
var e=class{searchEvents=[];classificationEvents=[];pushEvents=[];startedAt;constructor(){this.startedAt=new Date().toISOString()}recordSearch(e,t,n){this.searchEvents.push({query:e.toLowerCase().trim(),erFallbackTriggered:t,erCacheHit:n,timestamp:Date.now()}),this.trimEvents()}recordClassification(e,t,n){this.classificationEvents.push({entryTitle:e,matchingRuleIds:t,pushRecommended:n,timestamp:Date.now()}),this.trimEvents()}recordPush(e,t,n){this.pushEvents.push({entryId:e,ruleId:n,success:t,timestamp:Date.now()}),this.trimEvents()}getMetrics(){let e=this.searchEvents.length,t=this.searchEvents.filter(e=>e.erFallbackTriggered).length,n=this.searchEvents.filter(e=>e.erCacheHit).length,r=new Map;for(let e of this.searchEvents)e.erFallbackTriggered&&r.set(e.query,(r.get(e.query)??0)+1);let i=[...r.entries()].sort((e,t)=>t[1]-e[1]).slice(0,20).map(([e,t])=>({query:e,count:t})),a=this.pushEvents.length,o=this.pushEvents.filter(e=>e.success).length,s=this.classificationEvents.length,c=this.classificationEvents.filter(e=>e.pushRecommended).length,l={},u={};for(let e of this.classificationEvents)for(let t of e.matchingRuleIds)l[t]=(l[t]??0)+1;for(let e of this.pushEvents)e.ruleId&&(u[e.ruleId]=(u[e.ruleId]??0)+1);let d=Object.entries(l).map(([e,t])=>{let n=u[e]??0;return{ruleId:e,matchCount:t,pushCount:n,conversionRate:t>0?n/t:0}}).filter(e=>e.matchCount>=3&&e.conversionRate<.3).sort((e,t)=>e.conversionRate-t.conversionRate);return{search:{totalSearches:e,erFallbackCount:t,erFallbackRate:e>0?t/e:0,erCacheHitCount:n,erCacheHitRate:t>0?n/t:0,topMissedQueries:i},push:{totalPushes:a,successCount:o,failCount:a-o,pushRate:s>0?a/s:0,classificationMatchRate:s>0?c/s:0,pushAcceptanceRate:c>0?a/c:0},rules:{matchCounts:l,pushCounts:u,lowConversionRules:d},period:{startedAt:this.startedAt,queriedAt:new Date().toISOString(),totalEvents:this.searchEvents.length+this.classificationEvents.length+this.pushEvents.length}}}reset(){this.searchEvents=[],this.classificationEvents=[],this.pushEvents=[]}trimEvents(){this.searchEvents.length>500&&(this.searchEvents=this.searchEvents.slice(-500)),this.classificationEvents.length>500&&(this.classificationEvents=this.classificationEvents.slice(-500)),this.pushEvents.length>500&&(this.pushEvents=this.pushEvents.slice(-500))}};export{e as EvolutionCollector};
|
|
2
|
-
//# sourceMappingURL=evolution-collector.js.map
|
|
1
|
+
var e=class{searchEvents=[];classificationEvents=[];pushEvents=[];startedAt;constructor(){this.startedAt=new Date().toISOString()}recordSearch(e,t,n){this.searchEvents.push({query:e.toLowerCase().trim(),erFallbackTriggered:t,erCacheHit:n,timestamp:Date.now()}),this.trimEvents()}recordClassification(e,t,n){this.classificationEvents.push({entryTitle:e,matchingRuleIds:t,pushRecommended:n,timestamp:Date.now()}),this.trimEvents()}recordPush(e,t,n){this.pushEvents.push({entryId:e,ruleId:n,success:t,timestamp:Date.now()}),this.trimEvents()}getMetrics(){let e=this.searchEvents.length,t=this.searchEvents.filter(e=>e.erFallbackTriggered).length,n=this.searchEvents.filter(e=>e.erCacheHit).length,r=new Map;for(let e of this.searchEvents)e.erFallbackTriggered&&r.set(e.query,(r.get(e.query)??0)+1);let i=[...r.entries()].sort((e,t)=>t[1]-e[1]).slice(0,20).map(([e,t])=>({query:e,count:t})),a=this.pushEvents.length,o=this.pushEvents.filter(e=>e.success).length,s=this.classificationEvents.length,c=this.classificationEvents.filter(e=>e.pushRecommended).length,l={},u={};for(let e of this.classificationEvents)for(let t of e.matchingRuleIds)l[t]=(l[t]??0)+1;for(let e of this.pushEvents)e.ruleId&&(u[e.ruleId]=(u[e.ruleId]??0)+1);let d=Object.entries(l).map(([e,t])=>{let n=u[e]??0;return{ruleId:e,matchCount:t,pushCount:n,conversionRate:t>0?n/t:0}}).filter(e=>e.matchCount>=3&&e.conversionRate<.3).sort((e,t)=>e.conversionRate-t.conversionRate);return{search:{totalSearches:e,erFallbackCount:t,erFallbackRate:e>0?t/e:0,erCacheHitCount:n,erCacheHitRate:t>0?n/t:0,topMissedQueries:i},push:{totalPushes:a,successCount:o,failCount:a-o,pushRate:s>0?a/s:0,classificationMatchRate:s>0?c/s:0,pushAcceptanceRate:c>0?a/c:0},rules:{matchCounts:l,pushCounts:u,lowConversionRules:d},period:{startedAt:this.startedAt,queriedAt:new Date().toISOString(),totalEvents:this.searchEvents.length+this.classificationEvents.length+this.pushEvents.length}}}reset(){this.searchEvents=[],this.classificationEvents=[],this.pushEvents=[]}trimEvents(){this.searchEvents.length>500&&(this.searchEvents=this.searchEvents.slice(-500)),this.classificationEvents.length>500&&(this.classificationEvents=this.classificationEvents.slice(-500)),this.pushEvents.length>500&&(this.pushEvents=this.pushEvents.slice(-500))}};export{e as EvolutionCollector};
|
|
@@ -1,2 +1 @@
|
|
|
1
|
-
import{existsSync as e,mkdirSync as t,readFileSync as n,writeFileSync as r}from"node:fs";import{join as i}from"node:path";import{createLogger as a}from"../../core/dist/index.js";const o=a(`bridge`),s=()=>new Date().toISOString(),c=[{id:`cross-repo-contract`,patterns:[`contract`,`interface`,`api`,`event schema`,`publishes`,`subscribes`],category:`contract`,pushWeight:.8,description:`Knowledge describing cross-service interfaces`,examples:[`Service X publishes OrderCreated event with fields...`],autoPush:!1,enabled:!0,createdAt:s(),updatedAt:s()},{id:`architecture-decision`,patterns:[`decided`,`chose`,`tradeoff`,`adr`,`because we need`],category:`decision`,pushWeight:.7,description:`Architecture decisions that affect the ecosystem`,examples:[`We decided to use event sourcing because...`],autoPush:!1,enabled:!0,createdAt:s(),updatedAt:s()},{id:`shared-pattern`,patterns:[`pattern`,`convention`,`standard`,`guideline`,`always use`],category:`pattern`,pushWeight:.6,description:`Patterns and conventions that maintain consistency across repos`,examples:[`Always use the Result type for error handling...`],autoPush:!1,enabled:!0,createdAt:s(),updatedAt:s()},{id:`company-term`,patterns:[`means`,`defined as`,`acronym`,`refers to`],category:`glossary`,pushWeight:.7,description:`Shared vocabulary and terminology definitions`,examples:[`DDD means Domain-Driven Design in our context...`],autoPush:!1,enabled:!0,createdAt:s(),updatedAt:s()},{id:`implementation-detail`,patterns:[`private`,`internal`,`helper`,`todo`,`hack`,`workaround`],category:`local-only`,pushWeight:0,description:`Local-only implementation details — never push`,examples:[`TODO: refactor this helper`,`Internal workaround for...`],autoPush:!1,enabled:!0,createdAt:s(),updatedAt:s()}];var l=class{rules=[];rulesPath;constructor(r){let a=i(r,`_policy`);if(this.rulesPath=i(a,`rules.json`),e(a)||t(a,{recursive:!0}),e(this.rulesPath))try{let e=n(this.rulesPath,`utf-8`),t=JSON.parse(e);if(!Array.isArray(t))throw Error(`rules.json must be an array`);for(let e of t)if(typeof e!=`object`||!e||typeof e.id!=`string`||!Array.isArray(e.patterns)||typeof e.category!=`string`||typeof e.pushWeight!=`number`)throw Error(`Invalid rule: ${JSON.stringify(e).slice(0,100)}`);this.rules=t}catch{o.warn(`Failed to parse policy rules, resetting to starter set`),this.rules=[...c],this.save()}else this.rules=[...c],this.save()}classify(e,t,n){let r=`${e} ${t} ${n.join(` `)}`.toLowerCase(),i=[];for(let e of this.rules){if(!e.enabled)continue;let t=e.patterns.filter(e=>r.includes(e.toLowerCase()));t.length>0&&i.push({ruleId:e.id,category:e.category,pushWeight:e.pushWeight,matchedPatterns:t})}let a=i.length>0?Math.max(...i.map(e=>e.pushWeight)):0;return{matchingRules:i,pushRecommended:a>=.5,maxPushWeight:a}}getRules(){return[...this.rules]}getRule(e){return this.rules.find(t=>t.id===e)}updateRule(e,t){let n=this.rules.find(t=>t.id===e);if(n)return Object.assign(n,t,{updatedAt:new Date().toISOString(),autoPush:!1}),this.save(),n}addRule(e){if(this.rules.find(t=>t.id===e.id))throw Error(`Rule with id '${e.id}' already exists`);let t=new Date().toISOString(),n={...e,autoPush:!1,createdAt:t,updatedAt:t};return this.rules.push(n),this.save(),n}deleteRule(e){let t=this.rules.findIndex(t=>t.id===e);return t===-1?!1:(this.rules.splice(t,1),this.save(),!0)}save(){r(this.rulesPath,JSON.stringify(this.rules,null,2),`utf-8`)}};export{l as PolicyStore};
|
|
2
|
-
//# sourceMappingURL=policy-store.js.map
|
|
1
|
+
import{existsSync as e,mkdirSync as t,readFileSync as n,writeFileSync as r}from"node:fs";import{join as i}from"node:path";import{createLogger as a}from"../../core/dist/index.js";const o=a(`bridge`),s=()=>new Date().toISOString(),c=[{id:`cross-repo-contract`,patterns:[`contract`,`interface`,`api`,`event schema`,`publishes`,`subscribes`],category:`contract`,pushWeight:.8,description:`Knowledge describing cross-service interfaces`,examples:[`Service X publishes OrderCreated event with fields...`],autoPush:!1,enabled:!0,createdAt:s(),updatedAt:s()},{id:`architecture-decision`,patterns:[`decided`,`chose`,`tradeoff`,`adr`,`because we need`],category:`decision`,pushWeight:.7,description:`Architecture decisions that affect the ecosystem`,examples:[`We decided to use event sourcing because...`],autoPush:!1,enabled:!0,createdAt:s(),updatedAt:s()},{id:`shared-pattern`,patterns:[`pattern`,`convention`,`standard`,`guideline`,`always use`],category:`pattern`,pushWeight:.6,description:`Patterns and conventions that maintain consistency across repos`,examples:[`Always use the Result type for error handling...`],autoPush:!1,enabled:!0,createdAt:s(),updatedAt:s()},{id:`company-term`,patterns:[`means`,`defined as`,`acronym`,`refers to`],category:`glossary`,pushWeight:.7,description:`Shared vocabulary and terminology definitions`,examples:[`DDD means Domain-Driven Design in our context...`],autoPush:!1,enabled:!0,createdAt:s(),updatedAt:s()},{id:`implementation-detail`,patterns:[`private`,`internal`,`helper`,`todo`,`hack`,`workaround`],category:`local-only`,pushWeight:0,description:`Local-only implementation details — never push`,examples:[`TODO: refactor this helper`,`Internal workaround for...`],autoPush:!1,enabled:!0,createdAt:s(),updatedAt:s()}];var l=class{rules=[];rulesPath;constructor(r){let a=i(r,`_policy`);if(this.rulesPath=i(a,`rules.json`),e(a)||t(a,{recursive:!0}),e(this.rulesPath))try{let e=n(this.rulesPath,`utf-8`),t=JSON.parse(e);if(!Array.isArray(t))throw Error(`rules.json must be an array`);for(let e of t)if(typeof e!=`object`||!e||typeof e.id!=`string`||!Array.isArray(e.patterns)||typeof e.category!=`string`||typeof e.pushWeight!=`number`)throw Error(`Invalid rule: ${JSON.stringify(e).slice(0,100)}`);this.rules=t}catch{o.warn(`Failed to parse policy rules, resetting to starter set`),this.rules=[...c],this.save()}else this.rules=[...c],this.save()}classify(e,t,n){let r=`${e} ${t} ${n.join(` `)}`.toLowerCase(),i=[];for(let e of this.rules){if(!e.enabled)continue;let t=e.patterns.filter(e=>r.includes(e.toLowerCase()));t.length>0&&i.push({ruleId:e.id,category:e.category,pushWeight:e.pushWeight,matchedPatterns:t})}let a=i.length>0?Math.max(...i.map(e=>e.pushWeight)):0;return{matchingRules:i,pushRecommended:a>=.5,maxPushWeight:a}}getRules(){return[...this.rules]}getRule(e){return this.rules.find(t=>t.id===e)}updateRule(e,t){let n=this.rules.find(t=>t.id===e);if(n)return Object.assign(n,t,{updatedAt:new Date().toISOString(),autoPush:!1}),this.save(),n}addRule(e){if(this.rules.find(t=>t.id===e.id))throw Error(`Rule with id '${e.id}' already exists`);let t=new Date().toISOString(),n={...e,autoPush:!1,createdAt:t,updatedAt:t};return this.rules.push(n),this.save(),n}deleteRule(e){let t=this.rules.findIndex(t=>t.id===e);return t===-1?!1:(this.rules.splice(t,1),this.save(),!0)}save(){r(this.rulesPath,JSON.stringify(this.rules,null,2),`utf-8`)}};export{l as PolicyStore};
|
|
@@ -1,2 +1 @@
|
|
|
1
|
-
var e=class e{client;syncHistory=[];static MAX_HISTORY=100;constructor(e){this.client=e}async push(t,n){let r=await this.client.push(n);for(this.syncHistory.push({entryId:t,title:n.title,pushedAt:r.timestamp,status:r.status,remotePath:r.remotePath});this.syncHistory.length>e.MAX_HISTORY;)this.syncHistory.shift();return r}getHistory(){return[...this.syncHistory]}getStatus(){let e=this.syncHistory.filter(e=>e.status===`stored`).length;return{totalPushed:this.syncHistory.length,successCount:e,failCount:this.syncHistory.length-e,lastPush:this.syncHistory.at(-1)}}};export{e as PushAdapter};
|
|
2
|
-
//# sourceMappingURL=push-adapter.js.map
|
|
1
|
+
var e=class e{client;syncHistory=[];static MAX_HISTORY=100;constructor(e){this.client=e}async push(t,n){let r=await this.client.push(n);for(this.syncHistory.push({entryId:t,title:n.title,pushedAt:r.timestamp,status:r.status,remotePath:r.remotePath});this.syncHistory.length>e.MAX_HISTORY;)this.syncHistory.shift();return r}getHistory(){return[...this.syncHistory]}getStatus(){let e=this.syncHistory.filter(e=>e.status===`stored`).length;return{totalPushed:this.syncHistory.length,successCount:e,failCount:this.syncHistory.length-e,lastPush:this.syncHistory.at(-1)}}};export{e as PushAdapter};
|
|
@@ -11,5 +11,4 @@ import { SearchResult } from "@kb/core";
|
|
|
11
11
|
*/
|
|
12
12
|
declare function mergeResults(localResults: SearchResult[], erResults: ERSearchResult[], limit: number): MergedSearchResult[];
|
|
13
13
|
//#endregion
|
|
14
|
-
export { mergeResults };
|
|
15
|
-
//# sourceMappingURL=result-merger.d.ts.map
|
|
14
|
+
export { mergeResults };
|
|
@@ -1,2 +1 @@
|
|
|
1
|
-
function e(e){return{content:e.record.content,sourcePath:e.record.sourcePath,score:e.score,source:`local`,startLine:e.record.startLine,endLine:e.record.endLine,contentType:e.record.contentType,headingPath:e.record.headingPath,origin:e.record.origin,category:e.record.category,tags:e.record.tags}}function t(e){return{content:e.content,sourcePath:e.sourcePath,score:e.score,source:`er`,metadata:e.metadata}}function n(e){return`${e.slice(0,200).replace(/\s+/g,` `)}:${e.length}`}function r(r,i,a){let o=new Set,s=[];for(let t of r){let r=n(t.record.content);o.has(r)||(o.add(r),s.push(e(t)))}let c=[...i].sort((e,t)=>t.score-e.score);for(let e of c){let r=n(e.content);o.has(r)||(o.add(r),s.push(t(e)))}return s.slice(0,a)}export{r as mergeResults};
|
|
2
|
-
//# sourceMappingURL=result-merger.js.map
|
|
1
|
+
function e(e){return{content:e.record.content,sourcePath:e.record.sourcePath,score:e.score,source:`local`,startLine:e.record.startLine,endLine:e.record.endLine,contentType:e.record.contentType,headingPath:e.record.headingPath,origin:e.record.origin,category:e.record.category,tags:e.record.tags}}function t(e){return{content:e.content,sourcePath:e.sourcePath,score:e.score,source:`er`,metadata:e.metadata}}function n(e){return`${e.slice(0,200).replace(/\s+/g,` `)}:${e.length}`}function r(r,i,a){let o=new Set,s=[];for(let t of r){let r=n(t.record.content);o.has(r)||(o.add(r),s.push(e(t)))}let c=[...i].sort((e,t)=>t.score-e.score);for(let e of c){let r=n(e.content);o.has(r)||(o.add(r),s.push(t(e)))}return s.slice(0,a)}export{r as mergeResults};
|
|
@@ -78,5 +78,4 @@ interface MergedSearchResult {
|
|
|
78
78
|
metadata?: Record<string, unknown>;
|
|
79
79
|
}
|
|
80
80
|
//#endregion
|
|
81
|
-
export { ERBridgeConfig, ERCacheEntry, ERPushRequest, ERPushResponse, ERSearchResponse, ERSearchResult, ERSyncEntry, ERTransientError, MergedSearchResult };
|
|
82
|
-
//# sourceMappingURL=types.d.ts.map
|
|
81
|
+
export { ERBridgeConfig, ERCacheEntry, ERPushRequest, ERPushResponse, ERSearchResponse, ERSearchResult, ERSyncEntry, ERTransientError, MergedSearchResult };
|
|
@@ -1,2 +1 @@
|
|
|
1
|
-
var e=class extends Error{constructor(e,t){super(e),this.statusCode=t,this.name=`ERTransientError`}};export{e as ERTransientError};
|
|
2
|
-
//# sourceMappingURL=types.js.map
|
|
1
|
+
var e=class extends Error{constructor(e,t){super(e),this.statusCode=t,this.name=`ERTransientError`}};export{e as ERTransientError};
|
|
@@ -10,5 +10,4 @@ declare function hashContent(content: string): string;
|
|
|
10
10
|
*/
|
|
11
11
|
declare function generateRecordId(sourcePath: string, chunkIndex: number): string;
|
|
12
12
|
//#endregion
|
|
13
|
-
export { generateRecordId, hashContent };
|
|
14
|
-
//# sourceMappingURL=file-hasher.d.ts.map
|
|
13
|
+
export { generateRecordId, hashContent };
|
|
@@ -1,2 +1 @@
|
|
|
1
|
-
import{createHash as e}from"node:crypto";function t(t){return e(`sha256`).update(t).digest(`hex`).slice(0,16)}function n(t,n){let r=`${t}:${n}`;return e(`sha256`).update(r).digest(`hex`).slice(0,16)}export{n as generateRecordId,t as hashContent};
|
|
2
|
-
//# sourceMappingURL=file-hasher.js.map
|
|
1
|
+
import{createHash as e}from"node:crypto";function t(t){return e(`sha256`).update(t).digest(`hex`).slice(0,16)}function n(t,n){let r=`${t}:${n}`;return e(`sha256`).update(r).digest(`hex`).slice(0,16)}export{n as generateRecordId,t as hashContent};
|
|
@@ -1,2 +1 @@
|
|
|
1
|
-
import{lstat as e,readFile as t,readdir as n,stat as r}from"node:fs/promises";import{extname as i,join as a,relative as o}from"node:path";import{FILE_LIMITS as s,createLogger as
|
|
2
|
-
//# sourceMappingURL=filesystem-crawler.js.map
|
|
1
|
+
import{lstat as e,readFile as t,readdir as n,stat as r}from"node:fs/promises";import{extname as i,join as a,relative as o}from"node:path";import{FILE_LIMITS as s,KB_PATHS as c,createLogger as l}from"../../core/dist/index.js";import{minimatch as u}from"minimatch";const d=l(`indexer`);var f=class l{static BINARY_EXTENSIONS=new Set(`.node,.so,.dylib,.dll,.wasm,.bin,.exe,.png,.jpg,.jpeg,.gif,.bmp,.ico,.webp,.svg,.mp3,.mp4,.wav,.avi,.mov,.flac,.zip,.gz,.tar,.bz2,.7z,.rar,.pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.ttf,.otf,.woff,.woff2,.eot,.pyc,.class,.o,.obj,.a,.lib`.split(`,`));async crawl(e){let t=[],n=new Set;return await this.walkDir(e.rootDir,e.rootDir,e.excludePatterns,t,n),t}async walkDir(u,f,p,m,h){let g;try{g=await n(u,{withFileTypes:!0})}catch(e){let t=e.code;(t===`EACCES`||t===`EPERM`)&&d.warn(`Permission denied, skipping directory`,{dir:u});return}for(let n of g){let d=a(u,n.name),g=o(f,d).replace(/\\/g,`/`);if(!this.isExcluded(g,p)){if(n.isDirectory()){if(n.name.startsWith(`.`)&&!(n.name===c.ai.slice(1)&&g.startsWith(c.ai)))continue;try{if((await e(d)).isSymbolicLink())continue}catch{continue}let t=d;if(h.has(t))continue;h.add(t),await this.walkDir(d,f,p,m,h)}else if(n.isFile()){let e=i(n.name).toLowerCase();if(l.BINARY_EXTENSIONS.has(e))continue;try{if((await r(d)).size>s.maxFileSizeBytes)continue;let n=await t(d,`utf-8`);if(n.includes(`\0`))continue;m.push({relativePath:g,absolutePath:d,content:n,extension:e})}catch{}}}}}isExcluded(e,t){return t.some(t=>u(e,t,{dot:!0}))}};export{f as FilesystemCrawler};
|
|
@@ -15,5 +15,4 @@ interface ExtractedGraph {
|
|
|
15
15
|
*/
|
|
16
16
|
declare function extractGraph(content: string, sourcePath: string): ExtractedGraph;
|
|
17
17
|
//#endregion
|
|
18
|
-
export { ExtractedGraph, extractGraph };
|
|
19
|
-
//# sourceMappingURL=graph-extractor.d.ts.map
|
|
18
|
+
export { ExtractedGraph, extractGraph };
|
|
@@ -1,2 +1 @@
|
|
|
1
|
-
import{createHash as e}from"node:crypto";import{dirname as t,extname as n,join as r}from"node:path";const i=new Set([`.ts`,`.tsx`,`.js`,`.jsx`,`.mjs`,`.cjs`]),a=[{pattern:/^export\s+(?:async\s+)?function\s+(\w+)/gm,kind:`function`,exported:!0},{pattern:/^export\s+(?:default\s+)?class\s+(\w+)/gm,kind:`class`,exported:!0},{pattern:/^export\s+interface\s+(\w+)/gm,kind:`interface`,exported:!0},{pattern:/^export\s+type\s+(\w+)/gm,kind:`type`,exported:!0},{pattern:/^export\s+(?:const|let)\s+(\w+)/gm,kind:`const`,exported:!0},{pattern:/^export\s+enum\s+(\w+)/gm,kind:`enum`,exported:!0},{pattern:/^(?:async\s+)?function\s+(\w+)/gm,kind:`function`,exported:!1},{pattern:/^class\s+(\w+)/gm,kind:`class`,exported:!1},{pattern:/^interface\s+(\w+)/gm,kind:`interface`,exported:!1},{pattern:/^type\s+(\w+)/gm,kind:`type`,exported:!1},{pattern:/^enum\s+(\w+)/gm,kind:`enum`,exported:!1}],o=[/import\s+(?:(?:type\s+)?(?:(?:\{[^}]*\}|[\w*]+)\s+from\s+)?)['"]([^'"]+)['"]/g,/import\(\s*['"]([^'"]+)['"]\s*\)/g,/require\(\s*['"]([^'"]+)['"]\s*\)/g];function s(t,n,r){return e(`sha256`).update(`${t}:${n}:${r}`).digest(`hex`).slice(0,16)}function c(t,n,r){return e(`sha256`).update(`${t}-${r}-${n}`).digest(`hex`).slice(0,16)}function l(e,n){return r(t(n),e).replace(/\\/g,`/`).replace(/\.(js|jsx|ts|tsx|mjs|cjs)$/,``)}function u(e){return e.replace(/\.(js|jsx|ts|tsx|mjs|cjs)$/,``)}function d(e,t){let r=n(t).toLowerCase();if(!i.has(r))return{nodes:[],edges:[]};let d=[],f=[],p=new Date().toISOString(),m=new Set,h=u(t),g=s(`module`,h,h);d.push({id:g,type:`module`,name:t,properties:{ext:r},sourcePath:t,createdAt:p});for(let{pattern:n,kind:r,exported:i}of a){let a=new RegExp(n.source,n.flags),o;for(;(o=a.exec(e))!==null;){let e=o[1],n=`${r}:${e}`;if(m.has(n))continue;m.add(n);let a=s(r,e,t);d.push({id:a,type:r,name:e,properties:{exported:i},sourcePath:t,createdAt:p}),f.push({id:c(g,a,`defines`),fromId:g,toId:a,type:`defines`,weight:i?1:.5})}}let _=new Set;for(let n of o){let r=new RegExp(n.source,n.flags),i;for(;(i=r.exec(e))!==null;){let e=i[1];if(!e.startsWith(`.`)||_.has(e))continue;_.add(e);let n=l(e,t),r=s(`module`,n,n);f.push({id:c(g,r,`imports`),fromId:g,toId:r,type:`imports`,properties:{source:e}})}}return{nodes:d,edges:f}}export{d as extractGraph};
|
|
2
|
-
//# sourceMappingURL=graph-extractor.js.map
|
|
1
|
+
import{createHash as e}from"node:crypto";import{dirname as t,extname as n,join as r}from"node:path";const i=new Set([`.ts`,`.tsx`,`.js`,`.jsx`,`.mjs`,`.cjs`]),a=[{pattern:/^export\s+(?:async\s+)?function\s+(\w+)/gm,kind:`function`,exported:!0},{pattern:/^export\s+(?:default\s+)?class\s+(\w+)/gm,kind:`class`,exported:!0},{pattern:/^export\s+interface\s+(\w+)/gm,kind:`interface`,exported:!0},{pattern:/^export\s+type\s+(\w+)/gm,kind:`type`,exported:!0},{pattern:/^export\s+(?:const|let)\s+(\w+)/gm,kind:`const`,exported:!0},{pattern:/^export\s+enum\s+(\w+)/gm,kind:`enum`,exported:!0},{pattern:/^(?:async\s+)?function\s+(\w+)/gm,kind:`function`,exported:!1},{pattern:/^class\s+(\w+)/gm,kind:`class`,exported:!1},{pattern:/^interface\s+(\w+)/gm,kind:`interface`,exported:!1},{pattern:/^type\s+(\w+)/gm,kind:`type`,exported:!1},{pattern:/^enum\s+(\w+)/gm,kind:`enum`,exported:!1}],o=[/import\s+(?:(?:type\s+)?(?:(?:\{[^}]*\}|[\w*]+)\s+from\s+)?)['"]([^'"]+)['"]/g,/import\(\s*['"]([^'"]+)['"]\s*\)/g,/require\(\s*['"]([^'"]+)['"]\s*\)/g];function s(t,n,r){return e(`sha256`).update(`${t}:${n}:${r}`).digest(`hex`).slice(0,16)}function c(t,n,r){return e(`sha256`).update(`${t}-${r}-${n}`).digest(`hex`).slice(0,16)}function l(e,n){return r(t(n),e).replace(/\\/g,`/`).replace(/\.(js|jsx|ts|tsx|mjs|cjs)$/,``)}function u(e){return e.replace(/\.(js|jsx|ts|tsx|mjs|cjs)$/,``)}function d(e,t){let r=n(t).toLowerCase();if(!i.has(r))return{nodes:[],edges:[]};let d=[],f=[],p=new Date().toISOString(),m=new Set,h=u(t),g=s(`module`,h,h);d.push({id:g,type:`module`,name:t,properties:{ext:r},sourcePath:t,createdAt:p});for(let{pattern:n,kind:r,exported:i}of a){let a=new RegExp(n.source,n.flags),o;for(;(o=a.exec(e))!==null;){let e=o[1],n=`${r}:${e}`;if(m.has(n))continue;m.add(n);let a=s(r,e,t);d.push({id:a,type:r,name:e,properties:{exported:i},sourcePath:t,createdAt:p}),f.push({id:c(g,a,`defines`),fromId:g,toId:a,type:`defines`,weight:i?1:.5})}}let _=new Set;for(let n of o){let r=new RegExp(n.source,n.flags),i;for(;(i=r.exec(e))!==null;){let e=i[1];if(!e.startsWith(`.`)||_.has(e))continue;_.add(e);let n=l(e,t),r=s(`module`,n,n);f.push({id:c(g,r,`imports`),fromId:g,toId:r,type:`imports`,properties:{source:e}})}}return{nodes:d,edges:f}}export{d as extractGraph};
|
|
@@ -49,5 +49,4 @@ declare class IncrementalIndexer {
|
|
|
49
49
|
getStats(): Promise<IndexStats>;
|
|
50
50
|
}
|
|
51
51
|
//#endregion
|
|
52
|
-
export { IncrementalIndexer, IndexProgress, IndexResult, ProgressCallback };
|
|
53
|
-
//# sourceMappingURL=incremental-indexer.d.ts.map
|
|
52
|
+
export { IncrementalIndexer, IndexProgress, IndexResult, ProgressCallback };
|
|
@@ -1,2 +1 @@
|
|
|
1
|
-
import{generateRecordId as e,hashContent as t}from"./file-hasher.js";import{FilesystemCrawler as n}from"./filesystem-crawler.js";import{extractGraph as r}from"./graph-extractor.js";import{
|
|
2
|
-
//# sourceMappingURL=incremental-indexer.js.map
|
|
1
|
+
import{generateRecordId as e,hashContent as t}from"./file-hasher.js";import{FilesystemCrawler as n}from"./filesystem-crawler.js";import{extractGraph as r}from"./graph-extractor.js";import{KB_PATHS as i,createLogger as a,detectContentType as o,serializeError as s}from"../../core/dist/index.js";import{availableParallelism as c}from"node:os";import{createChunkerSync as l}from"../../chunker/dist/index.js";const u=a(`indexer`);async function d(e,t,n,r){let i=0;async function a(){for(;i<e.length;){let n=i++;try{await t(e[n])}catch(t){r?.(e[n],t)}}}await Promise.all(Array.from({length:Math.min(n,e.length)},()=>a()))}const f=Math.max(1,Math.floor(c()/2));var p=class{crawler;indexing=!1;graphStore;get isIndexing(){return this.indexing}constructor(e,t){this.embedder=e,this.store=t,this.crawler=new n}setGraphStore(e){this.graphStore=e}async index(e,t){if(this.indexing)throw Error(`Indexing is already in progress`);this.indexing=!0;try{return await this.doIndex(e,t,{})}finally{this.indexing=!1}}async doIndex(n,a,c={}){let p=Date.now(),m=0,h=0,g=0,_=0,v=n.indexing.concurrency??f;a?.({phase:`crawling`,filesTotal:0,filesProcessed:0,chunksTotal:0,chunksProcessed:0});let y=(await Promise.all(n.sources.map(e=>this.crawler.crawl({rootDir:e.path,excludePatterns:e.excludePatterns})))).flat(),b,x;if(c.skipHashCheck)b=y,x=[];else{let e=await this.store.listSourcePaths(),n=new Set(y.map(e=>e.relativePath));x=e.filter(e=>!n.has(e)&&!e.startsWith(`${i.aiCurated}/`)),b=[],await d(y,async e=>{let n=t(e.content),r=await this.store.getBySourcePath(e.relativePath);if(r.length>0&&r[0].fileHash===n){h++;return}b.push(e)},v,(e,t)=>u.error(`Hash check failed`,{sourcePath:e.relativePath,...s(t)}))}let S=b.length,C=[],w=[],T=0,E=async()=>{if(this.graphStore){try{C.length>0&&await this.graphStore.upsertNodes(C),w.length>0&&await this.graphStore.upsertEdges(w)}catch(e){u.warn(`Graph batch flush failed`,s(e))}C=[],w=[],T=0}};return await d(b,async n=>{a?.({phase:`chunking`,filesTotal:S,filesProcessed:m,chunksTotal:g,chunksProcessed:g,currentFile:n.relativePath});let i=o(n.relativePath),d=l(n.extension).chunk(n.content,{sourcePath:n.relativePath,contentType:i});if(d.length===0)return;a?.({phase:`embedding`,filesTotal:S,filesProcessed:m,chunksTotal:g+d.length,chunksProcessed:g,currentFile:n.relativePath});let f=await this.embedder.embedBatch(d.map(e=>e.text)),p=t(n.content),h=d.map((t,r)=>({id:e(n.relativePath,r),content:t.text,sourcePath:t.sourcePath,contentType:t.contentType,headingPath:t.headingPath,chunkIndex:t.chunkIndex,totalChunks:t.totalChunks,startLine:t.startLine,endLine:t.endLine,fileHash:p,indexedAt:new Date().toISOString(),origin:`indexed`,tags:[],version:1}));if(a?.({phase:`storing`,filesTotal:S,filesProcessed:m,chunksTotal:g+d.length,chunksProcessed:g,currentFile:n.relativePath}),await this.store.upsert(h,f),this.graphStore)try{c.graphCleared||await this.graphStore.deleteBySourcePath(n.relativePath);let e=r(n.content,n.relativePath);e.nodes.length>0&&C.push(...e.nodes),e.edges.length>0&&w.push(...e.edges),T++,T>=50&&await E()}catch(e){u.warn(`Graph extraction failed`,{sourcePath:n.relativePath,...s(e)})}m++,g+=d.length},v,(e,t)=>u.error(`Processing failed`,{sourcePath:e.relativePath,...s(t)})),await E(),x.length>0&&(a?.({phase:`cleanup`,filesTotal:S,filesProcessed:m,chunksTotal:g,chunksProcessed:g}),await d(x,async e=>{await this.store.deleteBySourcePath(e),this.graphStore&&await this.graphStore.deleteBySourcePath(e).catch(t=>u.warn(`Graph cleanup failed`,{sourcePath:e,...s(t)})),_++},v,(e,t)=>u.error(`Cleanup failed`,{sourcePath:e,...s(t)}))),a?.({phase:`done`,filesTotal:S,filesProcessed:m,chunksTotal:g,chunksProcessed:g}),{filesProcessed:m,filesSkipped:h,chunksCreated:g,filesRemoved:_,durationMs:Date.now()-p}}async reindexAll(e,t){if(this.indexing)throw Error(`Indexing is already in progress`);this.indexing=!0;try{if(await this.store.dropTable(),this.graphStore)try{let e=await this.graphStore.getStats();e.nodeCount>0&&(await this.graphStore.clear(),u.info(`Graph store cleared`,{nodeCount:e.nodeCount,edgeCount:e.edgeCount}))}catch(e){u.warn(`Graph store clear failed`,s(e))}return await this.doReindex(e,t)}catch(e){throw this.indexing=!1,e}}async doReindex(e,t){try{return await this.doIndex(e,t,{skipHashCheck:!0,graphCleared:!0})}finally{this.indexing=!1}}async getStats(){return this.store.getStats()}};export{p as IncrementalIndexer};
|
|
@@ -1,2 +1 @@
|
|
|
1
|
-
import{existsSync as e,readFileSync as t}from"node:fs";import{dirname as n,resolve as r}from"node:path";import{fileURLToPath as i}from"node:url";import{
|
|
2
|
-
//# sourceMappingURL=config.js.map
|
|
1
|
+
import{existsSync as e,readFileSync as t}from"node:fs";import{dirname as n,resolve as r}from"node:path";import{fileURLToPath as i}from"node:url";import{KB_PATHS as a,createLogger as o,getPartitionDir as s,isGlobalInstalled as c,registerWorkspace as l,serializeError as u}from"../../core/dist/index.js";const d=n(i(import.meta.url)),f=o(`server`);function p(e,t,n){let i=r(e),a=r(t);if(!i.startsWith(a))throw Error(`Config ${n} path escapes workspace root: ${e} is not under ${t}`);return i}function m(){let i=process.env.KB_CONFIG_PATH??(e(r(process.cwd(),`kb.config.json`))?r(process.cwd(),`kb.config.json`):r(d,`..`,`..`,`..`,`kb.config.json`));try{let e=t(i,`utf-8`),o=JSON.parse(e);if(!o.sources||!Array.isArray(o.sources)||o.sources.length===0)throw Error(`Config must have at least one source`);if(!o.store?.path)throw Error(`Config must specify store.path`);let s=n(i);return o.sources=o.sources.map(e=>({...e,path:p(r(s,e.path),s,`source`)})),o.store.path=p(r(s,o.store.path),s,`store`),o.curated=o.curated??{path:a.aiCurated},o.curated.path=p(r(s,o.curated.path),s,`curated`),g(o,s),o}catch(e){return f.error(`Failed to load config`,{configPath:i,...u(e)}),f.warn(`Falling back to default configuration`,{configPath:i}),h()}}function h(){let e=process.env.KB_WORKSPACE_ROOT??process.cwd(),t={sources:[{path:e,excludePatterns:[`node_modules/**`,`dist/**`,`.git/**`,`coverage/**`,`*.lock`,`pnpm-lock.yaml`]}],serverName:`knowledge-base`,indexing:{chunkSize:1500,chunkOverlap:200,minChunkSize:100},embedding:{model:`mixedbread-ai/mxbai-embed-large-v1`,dimensions:1024},store:{backend:`lancedb`,path:r(e,a.data)},curated:{path:r(e,a.aiCurated)}};return g(t,e),t}function g(e,t){if(!c())return;let n=t,i=l(n);e.store.path=r(s(i.partition)),e.curated||={path:r(n,a.aiCurated)}}export{m as loadConfig};
|