nox-mem 3.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +179 -0
- package/dist/api/answer.d.ts +116 -0
- package/dist/api/answer.js +274 -0
- package/dist/api/answer.validate-patch.d.ts +72 -0
- package/dist/api/answer.validate-patch.js +52 -0
- package/dist/api/brief-diversity.d.ts +64 -0
- package/dist/api/brief-diversity.js +91 -0
- package/dist/api/brief.d.ts +114 -0
- package/dist/api/brief.js +524 -0
- package/dist/api/conflict.d.ts +33 -0
- package/dist/api/conflict.js +143 -0
- package/dist/api/cors.d.ts +73 -0
- package/dist/api/cors.js +124 -0
- package/dist/api/events-stream-limited.d.ts +133 -0
- package/dist/api/events-stream-limited.js +217 -0
- package/dist/api/events-stream.d.ts +53 -0
- package/dist/api/events-stream.js +125 -0
- package/dist/api/export.d.ts +42 -0
- package/dist/api/export.js +85 -0
- package/dist/api/health-confidence-adapter.d.ts +29 -0
- package/dist/api/health-confidence-adapter.js +73 -0
- package/dist/api/health-confidence.d.ts +36 -0
- package/dist/api/health-confidence.js +141 -0
- package/dist/api/hooks.d.ts +50 -0
- package/dist/api/hooks.js +115 -0
- package/dist/api/import.d.ts +38 -0
- package/dist/api/import.js +87 -0
- package/dist/api/ingest-event.d.ts +65 -0
- package/dist/api/ingest-event.js +153 -0
- package/dist/api/mark.d.ts +42 -0
- package/dist/api/mark.js +127 -0
- package/dist/api/server-deps-a2.d.ts +55 -0
- package/dist/api/server-deps-a2.js +138 -0
- package/dist/api/server-deps-l2-l3.d.ts +68 -0
- package/dist/api/server-deps-l2-l3.js +123 -0
- package/dist/api/server-deps-p1.d.ts +84 -0
- package/dist/api/server-deps-p1.js +156 -0
- package/dist/api/server-deps-p2.d.ts +32 -0
- package/dist/api/server-deps-p2.js +84 -0
- package/dist/api/server-deps-p5.d.ts +66 -0
- package/dist/api/server-deps-p5.js +139 -0
- package/dist/api/viewer-static.d.ts +30 -0
- package/dist/api/viewer-static.js +102 -0
- package/dist/api/wire-up.d.ts +54 -0
- package/dist/api/wire-up.js +521 -0
- package/dist/api-impact.d.ts +30 -0
- package/dist/api-impact.js +196 -0
- package/dist/api-server.d.ts +2 -0
- package/dist/api-server.js +614 -0
- package/dist/backfill-fts-anchor.d.ts +15 -0
- package/dist/backfill-fts-anchor.js +97 -0
- package/dist/backfill-source-type.d.ts +20 -0
- package/dist/backfill-source-type.js +182 -0
- package/dist/churn.d.ts +31 -0
- package/dist/churn.js +98 -0
- package/dist/cli/answer.d.ts +66 -0
- package/dist/cli/answer.js +287 -0
- package/dist/cli/conflict.d.ts +38 -0
- package/dist/cli/conflict.js +282 -0
- package/dist/cli/export.d.ts +51 -0
- package/dist/cli/export.js +280 -0
- package/dist/cli/hooks.d.ts +54 -0
- package/dist/cli/hooks.js +133 -0
- package/dist/cli/import.d.ts +52 -0
- package/dist/cli/import.js +274 -0
- package/dist/cli/mark.d.ts +33 -0
- package/dist/cli/mark.js +130 -0
- package/dist/cli/ocr-batch.d.ts +12 -0
- package/dist/cli/ocr-batch.js +411 -0
- package/dist/cli/snapshot-main.d.ts +30 -0
- package/dist/cli/snapshot-main.js +47 -0
- package/dist/cli/viewer.d.ts +35 -0
- package/dist/cli/viewer.js +71 -0
- package/dist/cli-telemetry.d.ts +36 -0
- package/dist/cli-telemetry.js +150 -0
- package/dist/compact.d.ts +7 -0
- package/dist/compact.js +147 -0
- package/dist/consolidate.d.ts +18 -0
- package/dist/consolidate.js +475 -0
- package/dist/consolidation.d.ts +32 -0
- package/dist/consolidation.js +212 -0
- package/dist/cross-agent-v2.d.ts +45 -0
- package/dist/cross-agent-v2.js +271 -0
- package/dist/cross-search.d.ts +11 -0
- package/dist/cross-search.js +119 -0
- package/dist/crystallize.d.ts +43 -0
- package/dist/crystallize.js +111 -0
- package/dist/db.d.ts +11 -0
- package/dist/db.js +388 -0
- package/dist/dedup.d.ts +1 -0
- package/dist/dedup.js +106 -0
- package/dist/detect-changes.d.ts +29 -0
- package/dist/detect-changes.js +236 -0
- package/dist/digest.d.ts +1 -0
- package/dist/digest.js +205 -0
- package/dist/doctor.d.ts +1 -0
- package/dist/doctor.js +71 -0
- package/dist/embed.d.ts +45 -0
- package/dist/embed.js +257 -0
- package/dist/evals.d.ts +176 -0
- package/dist/evals.js +351 -0
- package/dist/generate-user-profile.d.ts +18 -0
- package/dist/generate-user-profile.js +163 -0
- package/dist/graphify-ingest.d.ts +18 -0
- package/dist/graphify-ingest.js +158 -0
- package/dist/impact.d.ts +39 -0
- package/dist/impact.js +143 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +689 -0
- package/dist/ingest-entity.d.ts +44 -0
- package/dist/ingest-entity.js +197 -0
- package/dist/ingest.d.ts +13 -0
- package/dist/ingest.js +210 -0
- package/dist/kg-llm.d.ts +39 -0
- package/dist/kg-llm.js +295 -0
- package/dist/knowledge-graph.d.ts +72 -0
- package/dist/knowledge-graph.js +507 -0
- package/dist/lib/answer/config.d.ts +41 -0
- package/dist/lib/answer/config.js +70 -0
- package/dist/lib/answer/index.d.ts +47 -0
- package/dist/lib/answer/index.js +221 -0
- package/dist/lib/answer/prompt.d.ts +37 -0
- package/dist/lib/answer/prompt.js +88 -0
- package/dist/lib/answer/provider.d.ts +47 -0
- package/dist/lib/answer/provider.js +101 -0
- package/dist/lib/answer/retrieval.d.ts +36 -0
- package/dist/lib/answer/retrieval.js +92 -0
- package/dist/lib/answer/telemetry.d.ts +99 -0
- package/dist/lib/answer/telemetry.js +154 -0
- package/dist/lib/answer/types.d.ts +108 -0
- package/dist/lib/answer/types.js +1 -0
- package/dist/lib/api/error-leak-fix.d.ts +54 -0
- package/dist/lib/api/error-leak-fix.js +55 -0
- package/dist/lib/api/safe-error-message.d.ts +70 -0
- package/dist/lib/api/safe-error-message.js +122 -0
- package/dist/lib/archive/common-passwords.d.ts +37 -0
- package/dist/lib/archive/common-passwords.js +753 -0
- package/dist/lib/archive/encryption.d.ts +81 -0
- package/dist/lib/archive/encryption.js +236 -0
- package/dist/lib/archive/enforce-strength.d.ts +54 -0
- package/dist/lib/archive/enforce-strength.js +70 -0
- package/dist/lib/archive/entropy.d.ts +34 -0
- package/dist/lib/archive/entropy.js +180 -0
- package/dist/lib/archive/export-locking.d.ts +102 -0
- package/dist/lib/archive/export-locking.js +202 -0
- package/dist/lib/archive/format.d.ts +20 -0
- package/dist/lib/archive/format.js +174 -0
- package/dist/lib/archive/index.d.ts +23 -0
- package/dist/lib/archive/index.js +17 -0
- package/dist/lib/archive/manifest.d.ts +53 -0
- package/dist/lib/archive/manifest.js +183 -0
- package/dist/lib/archive/migration.d.ts +36 -0
- package/dist/lib/archive/migration.js +100 -0
- package/dist/lib/archive/migrations/v18_to_v19.d.ts +16 -0
- package/dist/lib/archive/migrations/v18_to_v19.js +18 -0
- package/dist/lib/archive/orchestrator.d.ts +166 -0
- package/dist/lib/archive/orchestrator.js +428 -0
- package/dist/lib/archive/serializers/chunks.d.ts +30 -0
- package/dist/lib/archive/serializers/chunks.js +113 -0
- package/dist/lib/archive/serializers/embeddings.d.ts +36 -0
- package/dist/lib/archive/serializers/embeddings.js +115 -0
- package/dist/lib/archive/serializers/kg.d.ts +28 -0
- package/dist/lib/archive/serializers/kg.js +184 -0
- package/dist/lib/archive/serializers/ops_audit.d.ts +21 -0
- package/dist/lib/archive/serializers/ops_audit.js +97 -0
- package/dist/lib/archive/server-deps.d.ts +131 -0
- package/dist/lib/archive/server-deps.js +232 -0
- package/dist/lib/archive/strength.d.ts +50 -0
- package/dist/lib/archive/strength.js +77 -0
- package/dist/lib/archive/types.d.ts +159 -0
- package/dist/lib/archive/types.js +45 -0
- package/dist/lib/archive/unpack-streaming.d.ts +70 -0
- package/dist/lib/archive/unpack-streaming.js +255 -0
- package/dist/lib/auth/localhost-guard.d.ts +106 -0
- package/dist/lib/auth/localhost-guard.js +164 -0
- package/dist/lib/confidence/config.d.ts +37 -0
- package/dist/lib/confidence/config.js +107 -0
- package/dist/lib/confidence/db-shim-singleton.d.ts +20 -0
- package/dist/lib/confidence/db-shim-singleton.js +41 -0
- package/dist/lib/confidence/db-shim.d.ts +47 -0
- package/dist/lib/confidence/db-shim.js +141 -0
- package/dist/lib/confidence/mark.d.ts +58 -0
- package/dist/lib/confidence/mark.js +168 -0
- package/dist/lib/confidence/ranking.d.ts +69 -0
- package/dist/lib/confidence/ranking.js +101 -0
- package/dist/lib/confidence/search-filter.d.ts +44 -0
- package/dist/lib/confidence/search-filter.js +103 -0
- package/dist/lib/confidence/types.d.ts +146 -0
- package/dist/lib/confidence/types.js +20 -0
- package/dist/lib/confidence/write-hooks.d.ts +50 -0
- package/dist/lib/confidence/write-hooks.js +159 -0
- package/dist/lib/conflict/audit-fk-check.d.ts +72 -0
- package/dist/lib/conflict/audit-fk-check.js +131 -0
- package/dist/lib/conflict/audit-writer.d.ts +39 -0
- package/dist/lib/conflict/audit-writer.js +133 -0
- package/dist/lib/conflict/db-singleton.d.ts +28 -0
- package/dist/lib/conflict/db-singleton.js +61 -0
- package/dist/lib/conflict/db.d.ts +27 -0
- package/dist/lib/conflict/db.js +20 -0
- package/dist/lib/conflict/detector-direct.d.ts +21 -0
- package/dist/lib/conflict/detector-direct.js +105 -0
- package/dist/lib/conflict/evidence.d.ts +24 -0
- package/dist/lib/conflict/evidence.js +76 -0
- package/dist/lib/conflict/index.d.ts +14 -0
- package/dist/lib/conflict/index.js +12 -0
- package/dist/lib/conflict/scheduler.d.ts +78 -0
- package/dist/lib/conflict/scheduler.js +111 -0
- package/dist/lib/conflict/shadow.d.ts +75 -0
- package/dist/lib/conflict/shadow.js +161 -0
- package/dist/lib/conflict/types.d.ts +133 -0
- package/dist/lib/conflict/types.js +19 -0
- package/dist/lib/cost-cap.d.ts +94 -0
- package/dist/lib/cost-cap.js +129 -0
- package/dist/lib/deps/deps-registry.d.ts +111 -0
- package/dist/lib/deps/deps-registry.js +209 -0
- package/dist/lib/error-sanitizer/middleware.d.ts +43 -0
- package/dist/lib/error-sanitizer/middleware.js +100 -0
- package/dist/lib/error-sanitizer/sanitize.d.ts +78 -0
- package/dist/lib/error-sanitizer/sanitize.js +202 -0
- package/dist/lib/eval-batch.d.ts +34 -0
- package/dist/lib/eval-batch.js +103 -0
- package/dist/lib/eval-metrics.d.ts +36 -0
- package/dist/lib/eval-metrics.js +95 -0
- package/dist/lib/eval.d.ts +106 -0
- package/dist/lib/eval.js +343 -0
- package/dist/lib/events/bus.d.ts +135 -0
- package/dist/lib/events/bus.js +95 -0
- package/dist/lib/fts-anchor.d.ts +1 -0
- package/dist/lib/fts-anchor.js +131 -0
- package/dist/lib/hooks/classifier.d.ts +47 -0
- package/dist/lib/hooks/classifier.js +129 -0
- package/dist/lib/hooks/config.d.ts +49 -0
- package/dist/lib/hooks/config.js +106 -0
- package/dist/lib/hooks/decorators.d.ts +35 -0
- package/dist/lib/hooks/decorators.js +59 -0
- package/dist/lib/hooks/pipeline.d.ts +76 -0
- package/dist/lib/hooks/pipeline.js +213 -0
- package/dist/lib/hooks/privacy-filter-adapter.d.ts +55 -0
- package/dist/lib/hooks/privacy-filter-adapter.js +84 -0
- package/dist/lib/hooks/rate-limit-constant-time.d.ts +57 -0
- package/dist/lib/hooks/rate-limit-constant-time.js +69 -0
- package/dist/lib/hooks/rate-limit-dryrun-fix.d.ts +71 -0
- package/dist/lib/hooks/rate-limit-dryrun-fix.js +110 -0
- package/dist/lib/hooks/rate-limit.d.ts +54 -0
- package/dist/lib/hooks/rate-limit.js +122 -0
- package/dist/lib/hooks/server-deps.d.ts +61 -0
- package/dist/lib/hooks/server-deps.js +92 -0
- package/dist/lib/hooks/source-allowlist.d.ts +26 -0
- package/dist/lib/hooks/source-allowlist.js +53 -0
- package/dist/lib/hooks/types.d.ts +129 -0
- package/dist/lib/hooks/types.js +24 -0
- package/dist/lib/hooks/worker.d.ts +56 -0
- package/dist/lib/hooks/worker.js +150 -0
- package/dist/lib/ingest-router.d.ts +25 -0
- package/dist/lib/ingest-router.js +103 -0
- package/dist/lib/ocr-detector.d.ts +61 -0
- package/dist/lib/ocr-detector.js +138 -0
- package/dist/lib/ocr-engine-stub.d.ts +48 -0
- package/dist/lib/ocr-engine-stub.js +190 -0
- package/dist/lib/ocr-engines/google-doc-ai.d.ts +36 -0
- package/dist/lib/ocr-engines/google-doc-ai.js +164 -0
- package/dist/lib/ocr-jobs.d.ts +67 -0
- package/dist/lib/ocr-jobs.js +129 -0
- package/dist/lib/op-audit-extension/ran-at-guard.d.ts +86 -0
- package/dist/lib/op-audit-extension/ran-at-guard.js +110 -0
- package/dist/lib/op-audit.d.ts +71 -0
- package/dist/lib/op-audit.js +777 -0
- package/dist/lib/privacy-br/detector.d.ts +42 -0
- package/dist/lib/privacy-br/detector.js +130 -0
- package/dist/lib/privacy-br/index.d.ts +20 -0
- package/dist/lib/privacy-br/index.js +20 -0
- package/dist/lib/privacy-br/integration.d.ts +71 -0
- package/dist/lib/privacy-br/integration.js +74 -0
- package/dist/lib/privacy-br/patterns.d.ts +117 -0
- package/dist/lib/privacy-br/patterns.js +434 -0
- package/dist/lib/privacy-br/redact.d.ts +42 -0
- package/dist/lib/privacy-br/redact.js +103 -0
- package/dist/lib/privacy-br/types.d.ts +55 -0
- package/dist/lib/privacy-br/types.js +25 -0
- package/dist/lib/regex-extract/extractor.d.ts +30 -0
- package/dist/lib/regex-extract/extractor.js +91 -0
- package/dist/lib/regex-extract/frontmatter.d.ts +44 -0
- package/dist/lib/regex-extract/frontmatter.js +169 -0
- package/dist/lib/regex-extract/index.d.ts +14 -0
- package/dist/lib/regex-extract/index.js +14 -0
- package/dist/lib/regex-extract/ingest-router-l4.d.ts +76 -0
- package/dist/lib/regex-extract/ingest-router-l4.js +102 -0
- package/dist/lib/regex-extract/patterns.d.ts +61 -0
- package/dist/lib/regex-extract/patterns.js +91 -0
- package/dist/lib/regex-extract/production-wire.d.ts +128 -0
- package/dist/lib/regex-extract/production-wire.js +202 -0
- package/dist/lib/regex-extract/reconcile.d.ts +162 -0
- package/dist/lib/regex-extract/reconcile.js +210 -0
- package/dist/lib/regex-extract/strip-code.d.ts +24 -0
- package/dist/lib/regex-extract/strip-code.js +52 -0
- package/dist/lib/regex-extract/types.d.ts +48 -0
- package/dist/lib/regex-extract/types.js +25 -0
- package/dist/lib/reranker.d.ts +80 -0
- package/dist/lib/reranker.js +324 -0
- package/dist/lib/shadow-tracker.d.ts +191 -0
- package/dist/lib/shadow-tracker.js +384 -0
- package/dist/lib/spo-injection.d.ts +52 -0
- package/dist/lib/spo-injection.js +166 -0
- package/dist/lib/telemetry-collector.d.ts +158 -0
- package/dist/lib/telemetry-collector.js +249 -0
- package/dist/lib/temporal-detector.d.ts +27 -0
- package/dist/lib/temporal-detector.js +81 -0
- package/dist/lib/viewer/auth.d.ts +37 -0
- package/dist/lib/viewer/auth.js +70 -0
- package/dist/lib/viewer/backpressure.d.ts +59 -0
- package/dist/lib/viewer/backpressure.js +100 -0
- package/dist/lib/viewer/broadcast-singleton.d.ts +34 -0
- package/dist/lib/viewer/broadcast-singleton.js +49 -0
- package/dist/lib/viewer/broadcast.d.ts +66 -0
- package/dist/lib/viewer/broadcast.js +96 -0
- package/dist/lib/viewer/event-types.d.ts +132 -0
- package/dist/lib/viewer/event-types.js +74 -0
- package/dist/lib/viewer/instrumentation.d.ts +106 -0
- package/dist/lib/viewer/instrumentation.js +224 -0
- package/dist/lib/viewer/migration.d.ts +23 -0
- package/dist/lib/viewer/migration.js +56 -0
- package/dist/lib/viewer/redaction.d.ts +44 -0
- package/dist/lib/viewer/redaction.js +139 -0
- package/dist/lib/viewer/session.d.ts +51 -0
- package/dist/lib/viewer/session.js +87 -0
- package/dist/mcp/tools/answer.d.ts +94 -0
- package/dist/mcp/tools/answer.js +213 -0
- package/dist/mcp/tools/archive.d.ts +152 -0
- package/dist/mcp/tools/archive.js +170 -0
- package/dist/mcp/tools/conflict.d.ts +44 -0
- package/dist/mcp/tools/conflict.js +130 -0
- package/dist/mcp/tools/hooks.d.ts +29 -0
- package/dist/mcp/tools/hooks.js +78 -0
- package/dist/mcp/tools/mark.d.ts +38 -0
- package/dist/mcp/tools/mark.js +82 -0
- package/dist/mcp/tools/viewer.d.ts +58 -0
- package/dist/mcp/tools/viewer.js +64 -0
- package/dist/mcp-server.d.ts +2 -0
- package/dist/mcp-server.js +395 -0
- package/dist/metrics.d.ts +3 -0
- package/dist/metrics.js +59 -0
- package/dist/noise-filter.d.ts +18 -0
- package/dist/noise-filter.js +142 -0
- package/dist/notion-sync.d.ts +7 -0
- package/dist/notion-sync.js +97 -0
- package/dist/observability/adapters/a3-adapter.d.ts +63 -0
- package/dist/observability/adapters/a3-adapter.js +83 -0
- package/dist/observability/adapters/p1-adapter.d.ts +49 -0
- package/dist/observability/adapters/p1-adapter.js +63 -0
- package/dist/observability/adapters/p5-adapter.d.ts +36 -0
- package/dist/observability/adapters/p5-adapter.js +71 -0
- package/dist/observability/cardinality.d.ts +61 -0
- package/dist/observability/cardinality.js +300 -0
- package/dist/observability/collectors/db-stats.collector.d.ts +9 -0
- package/dist/observability/collectors/db-stats.collector.js +88 -0
- package/dist/observability/collectors/eventbus.collector.d.ts +6 -0
- package/dist/observability/collectors/eventbus.collector.js +50 -0
- package/dist/observability/collectors/process.collector.d.ts +7 -0
- package/dist/observability/collectors/process.collector.js +93 -0
- package/dist/observability/collectors/provider-telemetry.collector.d.ts +11 -0
- package/dist/observability/collectors/provider-telemetry.collector.js +112 -0
- package/dist/observability/collectors/search-telemetry.collector.d.ts +12 -0
- package/dist/observability/collectors/search-telemetry.collector.js +76 -0
- package/dist/observability/exporter.d.ts +30 -0
- package/dist/observability/exporter.js +182 -0
- package/dist/observability/index.d.ts +22 -0
- package/dist/observability/index.js +21 -0
- package/dist/observability/metrics.d.ts +53 -0
- package/dist/observability/metrics.js +213 -0
- package/dist/observability/privacy-guard.d.ts +32 -0
- package/dist/observability/privacy-guard.js +116 -0
- package/dist/observability/record.d.ts +83 -0
- package/dist/observability/record.js +217 -0
- package/dist/observability/registry.d.ts +60 -0
- package/dist/observability/registry.js +93 -0
- package/dist/observability/types.d.ts +115 -0
- package/dist/observability/types.js +235 -0
- package/dist/observability.d.ts +131 -0
- package/dist/observability.js +234 -0
- package/dist/plugins/nox-hooks/index.d.ts +61 -0
- package/dist/plugins/nox-hooks/index.js +99 -0
- package/dist/primer.d.ts +1 -0
- package/dist/primer.js +100 -0
- package/dist/privacy/filter.d.ts +27 -0
- package/dist/privacy/filter.js +74 -0
- package/dist/privacy/patterns.d.ts +29 -0
- package/dist/privacy/patterns.js +178 -0
- package/dist/privacy/tag-parser.d.ts +24 -0
- package/dist/privacy/tag-parser.js +29 -0
- package/dist/project-context-gen.d.ts +10 -0
- package/dist/project-context-gen.js +106 -0
- package/dist/providers/embedding/gemini.d.ts +73 -0
- package/dist/providers/embedding/gemini.js +118 -0
- package/dist/providers/embedding/openai.d.ts +76 -0
- package/dist/providers/embedding/openai.js +123 -0
- package/dist/providers/embedding/types.d.ts +39 -0
- package/dist/providers/embedding/types.js +1 -0
- package/dist/providers/embedding/voyage.d.ts +36 -0
- package/dist/providers/embedding/voyage.js +29 -0
- package/dist/providers/index.d.ts +116 -0
- package/dist/providers/index.js +158 -0
- package/dist/providers/llm/anthropic.d.ts +29 -0
- package/dist/providers/llm/anthropic.js +28 -0
- package/dist/providers/llm/chain.d.ts +99 -0
- package/dist/providers/llm/chain.js +213 -0
- package/dist/providers/llm/gemini.d.ts +48 -0
- package/dist/providers/llm/gemini.js +96 -0
- package/dist/providers/llm/openai.d.ts +64 -0
- package/dist/providers/llm/openai.js +109 -0
- package/dist/providers/llm/types.d.ts +47 -0
- package/dist/providers/llm/types.js +1 -0
- package/dist/providers/telemetry.d.ts +87 -0
- package/dist/providers/telemetry.js +156 -0
- package/dist/providers/types.d.ts +42 -0
- package/dist/providers/types.js +59 -0
- package/dist/query-entity-count.d.ts +54 -0
- package/dist/query-entity-count.js +171 -0
- package/dist/reflect.d.ts +26 -0
- package/dist/reflect.js +290 -0
- package/dist/reindex-errors.d.ts +7 -0
- package/dist/reindex-errors.js +21 -0
- package/dist/reindex.d.ts +16 -0
- package/dist/reindex.js +293 -0
- package/dist/retention.d.ts +40 -0
- package/dist/retention.js +86 -0
- package/dist/salience.d.ts +85 -0
- package/dist/salience.js +245 -0
- package/dist/scripts/migrate-v17-ops-audit.d.ts +17 -0
- package/dist/scripts/migrate-v17-ops-audit.js +70 -0
- package/dist/search-dedup.d.ts +44 -0
- package/dist/search-dedup.js +137 -0
- package/dist/search-expansion.d.ts +20 -0
- package/dist/search-expansion.js +99 -0
- package/dist/search.d.ts +62 -0
- package/dist/search.js +582 -0
- package/dist/seh-detector.d.ts +31 -0
- package/dist/seh-detector.js +201 -0
- package/dist/self-improve.d.ts +1 -0
- package/dist/self-improve.js +189 -0
- package/dist/session-distill.d.ts +29 -0
- package/dist/session-distill.js +325 -0
- package/dist/session-update.d.ts +1 -0
- package/dist/session-update.js +54 -0
- package/dist/shared-memory.d.ts +24 -0
- package/dist/shared-memory.js +104 -0
- package/dist/stats.d.ts +1 -0
- package/dist/stats.js +44 -0
- package/dist/temporal-retrieval.d.ts +132 -0
- package/dist/temporal-retrieval.js +495 -0
- package/dist/tier-manager.d.ts +69 -0
- package/dist/tier-manager.js +225 -0
- package/dist/vectorize.d.ts +16 -0
- package/dist/vectorize.js +91 -0
- package/dist/watch.d.ts +8 -0
- package/dist/watch.js +124 -0
- package/package.json +74 -0
|
@@ -0,0 +1,384 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* shadow-tracker.ts — F10 Phase D shadow tracker
|
|
3
|
+
*
|
|
4
|
+
* Records side-by-side comparisons between a baseline ranker and a shadow
|
|
5
|
+
* (candidate) ranker for the same query. Used to validate ranking changes
|
|
6
|
+
* BEFORE flipping the active path (per memory [[shadow-mode-for-ranking-changes]]).
|
|
7
|
+
*
|
|
8
|
+
* Data flow:
|
|
9
|
+
* 1. `recordShadowComparison(feature, query, baseline, shadow, metrics)` is
|
|
10
|
+
* called from the search hot-path (post-result, before response write).
|
|
11
|
+
* 2. The collector computes a delta_pct from the supplied scalar metric
|
|
12
|
+
* (or, when result-sets are passed without scalar metrics, from a
|
|
13
|
+
* rank-difference fallback).
|
|
14
|
+
* 3. The event is stored in BOTH:
|
|
15
|
+
* a) an in-memory 24h × 1h ring buffer keyed by feature, used by the
|
|
16
|
+
* dashboard endpoint for fast aggregation.
|
|
17
|
+
* b) the `shadow_runs` SQLite table for long-tail audit (append-only).
|
|
18
|
+
*
|
|
19
|
+
* Design principles:
|
|
20
|
+
* - Pattern mirrors `telemetry-collector.ts` from Phase C: synchronous, no
|
|
21
|
+
* external deps, ring-buffer eviction lazy on record().
|
|
22
|
+
* - Persistence is best-effort: a DB write failure logs to stderr but does
|
|
23
|
+
* NOT throw, so the search hot-path is never broken by observability.
|
|
24
|
+
* - SQLite handle is injected (not import-time singleton), so tests use
|
|
25
|
+
* in-memory DBs and prod uses the shared connection from db.ts.
|
|
26
|
+
*
|
|
27
|
+
* Spec: docs/ROADMAP.md F10 Phase D
|
|
28
|
+
* Cross-link: src/lib/shadow-tracker-schema.sql, api-server.shadow-wire-up.md
|
|
29
|
+
*/
|
|
30
|
+
import { createHash } from "node:crypto";
|
|
31
|
+
// ── Constants ─────────────────────────────────────────────────────────────────
|
|
32
|
+
const BUCKET_SIZE_MS = 60 * 60 * 1000; // 1h
|
|
33
|
+
const MAX_BUCKETS = 24;
|
|
34
|
+
/** Latest N rows kept per feature in memory for drill-down. */
|
|
35
|
+
const MAX_LATEST_PER_FEATURE = 10;
|
|
36
|
+
// ── Hashing ───────────────────────────────────────────────────────────────────
|
|
37
|
+
/** Stable SHA-256 (truncated) of the query string. Privacy-preserving (no
|
|
38
|
+
* way to recover the query text from the hash). */
|
|
39
|
+
export function hashQuery(query) {
|
|
40
|
+
return createHash("sha256").update(query).digest("hex").slice(0, 16);
|
|
41
|
+
}
|
|
42
|
+
// ── Delta helpers ─────────────────────────────────────────────────────────────
|
|
43
|
+
function hourFloor(ts) {
|
|
44
|
+
return Math.floor(ts / BUCKET_SIZE_MS) * BUCKET_SIZE_MS;
|
|
45
|
+
}
|
|
46
|
+
function hourLabel(ts) {
|
|
47
|
+
return new Date(ts).toISOString().slice(0, 13) + ":00Z";
|
|
48
|
+
}
|
|
49
|
+
function emptyBucket(hour_ts) {
|
|
50
|
+
return {
|
|
51
|
+
hour_ts,
|
|
52
|
+
label: hourLabel(hour_ts),
|
|
53
|
+
count: 0,
|
|
54
|
+
sum_delta_pct: 0,
|
|
55
|
+
sum_delta_sq: 0,
|
|
56
|
+
win_count: 0,
|
|
57
|
+
regression_count: 0,
|
|
58
|
+
neutral_count: 0,
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
/** Compute (shadow - baseline) / baseline * 100. Returns null when baseline is
|
|
62
|
+
* zero, null, or undefined. */
|
|
63
|
+
export function computeDeltaPct(baseline, shadow) {
|
|
64
|
+
if (baseline === null || baseline === undefined)
|
|
65
|
+
return null;
|
|
66
|
+
if (shadow === null || shadow === undefined)
|
|
67
|
+
return null;
|
|
68
|
+
if (baseline === 0)
|
|
69
|
+
return null;
|
|
70
|
+
return ((shadow - baseline) / baseline) * 100;
|
|
71
|
+
}
|
|
72
|
+
/** Fallback delta when the caller did not supply a scalar metric: compute
|
|
73
|
+
* Kendall-style rank-difference normalised to [-100, +100] where positive
|
|
74
|
+
* means shadow promoted more of the baseline's top results. */
|
|
75
|
+
export function rankDifferenceDelta(baseline, shadow) {
|
|
76
|
+
if (baseline.length === 0 && shadow.length === 0)
|
|
77
|
+
return 0;
|
|
78
|
+
if (baseline.length === 0)
|
|
79
|
+
return 100; // any result is an improvement over nothing
|
|
80
|
+
if (shadow.length === 0)
|
|
81
|
+
return -100;
|
|
82
|
+
const baselineIds = baseline.map((r) => String(r.id));
|
|
83
|
+
const shadowIds = shadow.map((r) => String(r.id));
|
|
84
|
+
const baselineRank = new Map();
|
|
85
|
+
baselineIds.forEach((id, i) => baselineRank.set(id, i));
|
|
86
|
+
// For each item in the shadow's top-K, find how much it moved up vs baseline
|
|
87
|
+
let totalDelta = 0;
|
|
88
|
+
let counted = 0;
|
|
89
|
+
const K = Math.min(baselineIds.length, shadowIds.length, 10);
|
|
90
|
+
for (let i = 0; i < K; i++) {
|
|
91
|
+
const id = shadowIds[i];
|
|
92
|
+
if (id === undefined)
|
|
93
|
+
continue;
|
|
94
|
+
const baselineIdx = baselineRank.get(id);
|
|
95
|
+
if (baselineIdx === undefined) {
|
|
96
|
+
// New item — count as a positive move (capped at +K)
|
|
97
|
+
totalDelta += K;
|
|
98
|
+
}
|
|
99
|
+
else {
|
|
100
|
+
totalDelta += baselineIdx - i; // baseline at pos 5, shadow at pos 0 → +5
|
|
101
|
+
}
|
|
102
|
+
counted++;
|
|
103
|
+
}
|
|
104
|
+
if (counted === 0)
|
|
105
|
+
return 0;
|
|
106
|
+
// Normalise: max possible per-item delta is K (item went from worst to best).
|
|
107
|
+
return Math.max(-100, Math.min(100, (totalDelta / (counted * K)) * 100));
|
|
108
|
+
}
|
|
109
|
+
// ── ShadowTracker class ───────────────────────────────────────────────────────
|
|
110
|
+
export class ShadowTracker {
|
|
111
|
+
/** Ring buffer: Map<feature, Map<hour_ts, ShadowFeatureBucket>> */
|
|
112
|
+
buckets = new Map();
|
|
113
|
+
/** Per-feature ring of latest comparisons for drill-down. */
|
|
114
|
+
latest = new Map();
|
|
115
|
+
/** Optional DB handle for append-only persistence. */
|
|
116
|
+
db = null;
|
|
117
|
+
/** Cumulative count of skipped DB writes (failure or no-handle). Exposed for ops visibility. */
|
|
118
|
+
skippedPersist = 0;
|
|
119
|
+
constructor(db) {
|
|
120
|
+
this.db = db ?? null;
|
|
121
|
+
}
|
|
122
|
+
/** Inject or replace the DB handle (used by tests + lazy wire-up). */
|
|
123
|
+
setDB(db) {
|
|
124
|
+
this.db = db;
|
|
125
|
+
}
|
|
126
|
+
/**
|
|
127
|
+
* Record a shadow comparison.
|
|
128
|
+
*
|
|
129
|
+
* @param feature Feature name. Required, non-empty.
|
|
130
|
+
* @param query Query text (will be hashed, not stored verbatim).
|
|
131
|
+
* @param baseline Baseline result-set (used for rank-diff fallback).
|
|
132
|
+
* @param shadow Shadow result-set (used for rank-diff fallback).
|
|
133
|
+
* @param metrics Optional scalar metrics. If `metric_name` is set, the
|
|
134
|
+
* corresponding `baseline`/`shadow` keys drive delta_pct.
|
|
135
|
+
* Otherwise delta_pct falls back to rank-difference.
|
|
136
|
+
* @param nowMs Override of `Date.now()` for tests.
|
|
137
|
+
*/
|
|
138
|
+
recordShadowComparison(feature, query, baseline, shadow, metrics = {}, nowMs) {
|
|
139
|
+
if (!feature || feature.length === 0) {
|
|
140
|
+
throw new Error("shadow-tracker: feature must be a non-empty string");
|
|
141
|
+
}
|
|
142
|
+
const ts = nowMs ?? Date.now();
|
|
143
|
+
const query_hash = hashQuery(query);
|
|
144
|
+
let baseline_value = null;
|
|
145
|
+
let shadow_value = null;
|
|
146
|
+
let delta_pct = null;
|
|
147
|
+
const baselineMetric = metrics["baseline"];
|
|
148
|
+
const shadowMetric = metrics["shadow"];
|
|
149
|
+
if (typeof baselineMetric === "number" &&
|
|
150
|
+
typeof shadowMetric === "number" &&
|
|
151
|
+
Number.isFinite(baselineMetric) &&
|
|
152
|
+
Number.isFinite(shadowMetric)) {
|
|
153
|
+
baseline_value = baselineMetric;
|
|
154
|
+
shadow_value = shadowMetric;
|
|
155
|
+
delta_pct = computeDeltaPct(baseline_value, shadow_value);
|
|
156
|
+
}
|
|
157
|
+
else {
|
|
158
|
+
// Fallback: use rank-difference scaled to delta_pct semantics.
|
|
159
|
+
delta_pct = rankDifferenceDelta(baseline, shadow);
|
|
160
|
+
}
|
|
161
|
+
const metadata = {
|
|
162
|
+
...metrics,
|
|
163
|
+
baseline_size: baseline.length,
|
|
164
|
+
shadow_size: shadow.length,
|
|
165
|
+
baseline_top_ids: baseline.slice(0, 5).map((r) => r.id),
|
|
166
|
+
shadow_top_ids: shadow.slice(0, 5).map((r) => r.id),
|
|
167
|
+
};
|
|
168
|
+
const comparison = {
|
|
169
|
+
ts,
|
|
170
|
+
feature,
|
|
171
|
+
query_hash,
|
|
172
|
+
baseline_value,
|
|
173
|
+
shadow_value,
|
|
174
|
+
delta_pct,
|
|
175
|
+
metadata,
|
|
176
|
+
};
|
|
177
|
+
this._updateRingBuffer(comparison);
|
|
178
|
+
this._updateLatestRing(comparison);
|
|
179
|
+
this._persist(comparison);
|
|
180
|
+
return comparison;
|
|
181
|
+
}
|
|
182
|
+
/** Update the per-feature ring buffer + roll old buckets. */
|
|
183
|
+
_updateRingBuffer(c) {
|
|
184
|
+
const hour_ts = hourFloor(c.ts);
|
|
185
|
+
let featureMap = this.buckets.get(c.feature);
|
|
186
|
+
if (!featureMap) {
|
|
187
|
+
featureMap = new Map();
|
|
188
|
+
this.buckets.set(c.feature, featureMap);
|
|
189
|
+
}
|
|
190
|
+
this._evict(featureMap, hour_ts);
|
|
191
|
+
let bucket = featureMap.get(hour_ts);
|
|
192
|
+
if (!bucket) {
|
|
193
|
+
bucket = emptyBucket(hour_ts);
|
|
194
|
+
featureMap.set(hour_ts, bucket);
|
|
195
|
+
}
|
|
196
|
+
bucket.count++;
|
|
197
|
+
const d = c.delta_pct;
|
|
198
|
+
if (d === null) {
|
|
199
|
+
bucket.neutral_count++;
|
|
200
|
+
}
|
|
201
|
+
else {
|
|
202
|
+
bucket.sum_delta_pct += d;
|
|
203
|
+
bucket.sum_delta_sq += d * d;
|
|
204
|
+
if (d > 0)
|
|
205
|
+
bucket.win_count++;
|
|
206
|
+
else if (d < 0)
|
|
207
|
+
bucket.regression_count++;
|
|
208
|
+
else
|
|
209
|
+
bucket.neutral_count++;
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
_updateLatestRing(c) {
|
|
213
|
+
let ring = this.latest.get(c.feature);
|
|
214
|
+
if (!ring) {
|
|
215
|
+
ring = [];
|
|
216
|
+
this.latest.set(c.feature, ring);
|
|
217
|
+
}
|
|
218
|
+
ring.push(c);
|
|
219
|
+
while (ring.length > MAX_LATEST_PER_FEATURE)
|
|
220
|
+
ring.shift();
|
|
221
|
+
}
|
|
222
|
+
_evict(featureMap, currentHour) {
|
|
223
|
+
const oldestKept = currentHour - (MAX_BUCKETS - 1) * BUCKET_SIZE_MS;
|
|
224
|
+
for (const [ts] of featureMap) {
|
|
225
|
+
if (ts < oldestKept)
|
|
226
|
+
featureMap.delete(ts);
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
/** Best-effort SQLite persistence. Never throws — failures bump skippedPersist. */
|
|
230
|
+
_persist(c) {
|
|
231
|
+
if (!this.db) {
|
|
232
|
+
this.skippedPersist++;
|
|
233
|
+
return;
|
|
234
|
+
}
|
|
235
|
+
try {
|
|
236
|
+
const stmt = this.db.prepare(`INSERT INTO shadow_runs (ts, feature, query_hash, baseline_value, shadow_value, delta_pct, metadata)
|
|
237
|
+
VALUES (?, ?, ?, ?, ?, ?, ?)`);
|
|
238
|
+
stmt.run(c.ts, c.feature, c.query_hash, c.baseline_value, c.shadow_value, c.delta_pct, JSON.stringify(c.metadata));
|
|
239
|
+
}
|
|
240
|
+
catch (err) {
|
|
241
|
+
this.skippedPersist++;
|
|
242
|
+
// Mirror telemetry-collector silence policy: stderr only, do not throw.
|
|
243
|
+
process.stderr.write(`[shadow-tracker] persist failed for feature=${c.feature}: ${err.message}\n`);
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
/**
|
|
247
|
+
* Aggregate shadow stats for the dashboard endpoint.
|
|
248
|
+
*
|
|
249
|
+
* @param featureFilter When set, returns only that feature (+ latest_runs).
|
|
250
|
+
* @param windowHours 1..24
|
|
251
|
+
* @param nowMs Override "now" for tests.
|
|
252
|
+
*/
|
|
253
|
+
query(featureFilter = null, windowHours = 24, nowMs) {
|
|
254
|
+
const now = nowMs ?? Date.now();
|
|
255
|
+
const window_hours = Math.max(1, Math.min(MAX_BUCKETS, Math.floor(windowHours)));
|
|
256
|
+
const to_ts = hourFloor(now) + BUCKET_SIZE_MS;
|
|
257
|
+
const from_ts = to_ts - window_hours * BUCKET_SIZE_MS;
|
|
258
|
+
const features = [];
|
|
259
|
+
const featureNames = featureFilter
|
|
260
|
+
? [featureFilter]
|
|
261
|
+
: Array.from(this.buckets.keys()).sort();
|
|
262
|
+
for (const featureName of featureNames) {
|
|
263
|
+
const featureMap = this.buckets.get(featureName);
|
|
264
|
+
const buckets = [];
|
|
265
|
+
let count = 0;
|
|
266
|
+
let win = 0;
|
|
267
|
+
let regression = 0;
|
|
268
|
+
let neutral = 0;
|
|
269
|
+
let sumDelta = 0;
|
|
270
|
+
let sumDeltaSq = 0;
|
|
271
|
+
for (let ts = from_ts; ts < to_ts; ts += BUCKET_SIZE_MS) {
|
|
272
|
+
const bucket = featureMap?.get(ts) ?? emptyBucket(ts);
|
|
273
|
+
buckets.push(bucket);
|
|
274
|
+
count += bucket.count;
|
|
275
|
+
win += bucket.win_count;
|
|
276
|
+
regression += bucket.regression_count;
|
|
277
|
+
neutral += bucket.neutral_count;
|
|
278
|
+
sumDelta += bucket.sum_delta_pct;
|
|
279
|
+
sumDeltaSq += bucket.sum_delta_sq;
|
|
280
|
+
}
|
|
281
|
+
const measured = count - neutral;
|
|
282
|
+
const mean_delta_pct = measured > 0 ? sumDelta / measured : null;
|
|
283
|
+
// Sample standard deviation requires ≥2 measured points.
|
|
284
|
+
let std_dev = null;
|
|
285
|
+
if (measured >= 2 && mean_delta_pct !== null) {
|
|
286
|
+
const variance = sumDeltaSq / measured - mean_delta_pct * mean_delta_pct;
|
|
287
|
+
std_dev = variance > 0 ? Math.sqrt(variance) : 0;
|
|
288
|
+
}
|
|
289
|
+
features.push({
|
|
290
|
+
feature: featureName,
|
|
291
|
+
count,
|
|
292
|
+
win_count: win,
|
|
293
|
+
regression_count: regression,
|
|
294
|
+
neutral_count: neutral,
|
|
295
|
+
mean_delta_pct,
|
|
296
|
+
std_dev,
|
|
297
|
+
buckets,
|
|
298
|
+
});
|
|
299
|
+
}
|
|
300
|
+
// Drill-down: latest N runs for the filtered feature only.
|
|
301
|
+
let latest_runs = [];
|
|
302
|
+
if (featureFilter) {
|
|
303
|
+
const ring = this.latest.get(featureFilter) ?? [];
|
|
304
|
+
latest_runs = ring
|
|
305
|
+
.filter((c) => c.ts >= from_ts)
|
|
306
|
+
.slice(-MAX_LATEST_PER_FEATURE)
|
|
307
|
+
.reverse(); // newest first
|
|
308
|
+
}
|
|
309
|
+
return {
|
|
310
|
+
window: {
|
|
311
|
+
hours: window_hours,
|
|
312
|
+
bucket_size_hours: 1,
|
|
313
|
+
from_ts,
|
|
314
|
+
to_ts,
|
|
315
|
+
},
|
|
316
|
+
features,
|
|
317
|
+
latest_runs,
|
|
318
|
+
generated_at_ms: now,
|
|
319
|
+
};
|
|
320
|
+
}
|
|
321
|
+
/** Exposed for tests. */
|
|
322
|
+
_reset() {
|
|
323
|
+
this.buckets.clear();
|
|
324
|
+
this.latest.clear();
|
|
325
|
+
this.skippedPersist = 0;
|
|
326
|
+
}
|
|
327
|
+
/** Exposed for ops visibility. */
|
|
328
|
+
getSkippedPersistCount() {
|
|
329
|
+
return this.skippedPersist;
|
|
330
|
+
}
|
|
331
|
+
/** Exposed for tests — number of features currently held. */
|
|
332
|
+
_featureCount() {
|
|
333
|
+
return this.buckets.size;
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
// ── Singleton + wire-up helpers ───────────────────────────────────────────────
|
|
337
|
+
/** Module-scope singleton consumed by api-server.ts wire-up. Tests use
|
|
338
|
+
* fresh instances or call `_reset()` between cases. */
|
|
339
|
+
export const tracker = new ShadowTracker();
|
|
340
|
+
/**
|
|
341
|
+
* Hot-path API: record one shadow comparison. Mirrors `recordRequest` shape
|
|
342
|
+
* from the Phase C telemetry collector.
|
|
343
|
+
*
|
|
344
|
+
* @param feature Feature name (required).
|
|
345
|
+
* @param query Query text (will be hashed).
|
|
346
|
+
* @param baseline Baseline result-set.
|
|
347
|
+
* @param shadow Shadow result-set.
|
|
348
|
+
* @param metrics Optional scalar metrics: pass `{ baseline, shadow }` to use
|
|
349
|
+
* scalar delta; omit to fall back to rank-diff.
|
|
350
|
+
*/
|
|
351
|
+
export function recordShadowComparison(feature, query, baseline, shadow, metrics = {}) {
|
|
352
|
+
return tracker.recordShadowComparison(feature, query, baseline, shadow, metrics);
|
|
353
|
+
}
|
|
354
|
+
/**
|
|
355
|
+
* Handler for GET /api/observability/shadow.
|
|
356
|
+
* Query params:
|
|
357
|
+
* feature (optional) Filter to a single feature name.
|
|
358
|
+
* window (default 24h) Hours to include (1..24).
|
|
359
|
+
* bucket (default 1h) Reserved for future sub-hour buckets.
|
|
360
|
+
*/
|
|
361
|
+
export function handleObsShadow(params) {
|
|
362
|
+
const feature = params["feature"]?.trim() || null;
|
|
363
|
+
const windowHours = parseWindowParam(params["window"] ?? "24h");
|
|
364
|
+
return tracker.query(feature, windowHours);
|
|
365
|
+
}
|
|
366
|
+
/** Parse "24h"/"6h"/"12" → integer hours clamped to [1, 24]. */
|
|
367
|
+
export function parseWindowParam(raw) {
|
|
368
|
+
const m = /^(\d+)h?$/i.exec(raw.trim());
|
|
369
|
+
if (!m || !m[1])
|
|
370
|
+
return 24;
|
|
371
|
+
const n = parseInt(m[1], 10);
|
|
372
|
+
if (!Number.isFinite(n) || n < 1)
|
|
373
|
+
return 24;
|
|
374
|
+
return Math.min(MAX_BUCKETS, n);
|
|
375
|
+
}
|
|
376
|
+
// ── Internals for tests ───────────────────────────────────────────────────────
|
|
377
|
+
export const _internals = {
|
|
378
|
+
BUCKET_SIZE_MS,
|
|
379
|
+
MAX_BUCKETS,
|
|
380
|
+
MAX_LATEST_PER_FEATURE,
|
|
381
|
+
hourFloor,
|
|
382
|
+
hourLabel,
|
|
383
|
+
emptyBucket,
|
|
384
|
+
};
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import Database from "better-sqlite3";
|
|
2
|
+
export type VaultFactsMode = "off" | "shadow" | "active";
|
|
3
|
+
export interface VaultTriple {
|
|
4
|
+
subject: string;
|
|
5
|
+
relation: string;
|
|
6
|
+
object: string;
|
|
7
|
+
confidence: number | null;
|
|
8
|
+
reason?: string | null;
|
|
9
|
+
}
|
|
10
|
+
export declare function getMode(): VaultFactsMode;
|
|
11
|
+
export declare function getK(): number;
|
|
12
|
+
export declare function pickBudget(query: string): number;
|
|
13
|
+
/**
|
|
14
|
+
* Match query tokens against kg_entities.name (case-insensitive exact match).
|
|
15
|
+
* v1 minimal: no NER, no fuzzy. Returns deduped list of matched entity names.
|
|
16
|
+
*/
|
|
17
|
+
export declare function extractCandidateEntities(query: string, db: Database.Database): string[];
|
|
18
|
+
/**
|
|
19
|
+
* Lookup top-K SPO triples touching given entity names.
|
|
20
|
+
* JOIN with kg_entities to resolve FK ids → names.
|
|
21
|
+
* ORDER BY confidence DESC NULLS LAST, then created_at DESC.
|
|
22
|
+
*/
|
|
23
|
+
export declare function lookupTopK(entityNames: string[], db: Database.Database, k: number): VaultTriple[];
|
|
24
|
+
/**
|
|
25
|
+
* Format triples as <vault-facts> XML-like block.
|
|
26
|
+
* Returns null if no triples (avoid empty block).
|
|
27
|
+
* Truncates each field to 80 chars to bound token usage.
|
|
28
|
+
*/
|
|
29
|
+
export declare function formatVaultFacts(triples: VaultTriple[]): string | null;
|
|
30
|
+
/**
|
|
31
|
+
* Estimate token usage roughly (chars/4 heuristic).
|
|
32
|
+
* Used to enforce budget cap.
|
|
33
|
+
*/
|
|
34
|
+
export declare function estimateTokens(s: string): number;
|
|
35
|
+
/**
|
|
36
|
+
* Trim triples list to fit token budget.
|
|
37
|
+
*/
|
|
38
|
+
export declare function applyBudget(triples: VaultTriple[], budget: number): VaultTriple[];
|
|
39
|
+
/**
|
|
40
|
+
* Top-level orchestrator. Returns VaultFacts result or null if disabled/empty.
|
|
41
|
+
* Logs telemetry when enabled (shadow or active).
|
|
42
|
+
*/
|
|
43
|
+
export interface VaultFactsResult {
|
|
44
|
+
block: string | null;
|
|
45
|
+
mode: VaultFactsMode;
|
|
46
|
+
surface: boolean;
|
|
47
|
+
entities: number;
|
|
48
|
+
triples: number;
|
|
49
|
+
tokens: number;
|
|
50
|
+
budget: number;
|
|
51
|
+
}
|
|
52
|
+
export declare function getVaultFacts(query: string, db: Database.Database): VaultFactsResult;
|
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
// E03a — Entity-Facts SPO Injection (`<vault-facts>` block)
|
|
2
|
+
// 2026-05-02 impl. Spec: specs/2026-05-01-E03a-spo-injection.md
|
|
3
|
+
//
|
|
4
|
+
// Read-only KG → context surface. Top-K SPO triples surfaced as XML-like
|
|
5
|
+
// block, injected as `vaultFacts` field in /api/search response (envelope).
|
|
6
|
+
//
|
|
7
|
+
// Schema reality: kg_relations uses FK ids (source_entity_id, target_entity_id,
|
|
8
|
+
// relation_type) — NOT inline strings as spec assumed. JOIN with kg_entities
|
|
9
|
+
// resolves names.
|
|
10
|
+
//
|
|
11
|
+
// Modes (env NOX_VAULT_FACTS_MODE):
|
|
12
|
+
// off — disabled, no compute, no surface
|
|
13
|
+
// shadow — compute + log telemetry, but DO NOT surface in response (default v1)
|
|
14
|
+
// active — compute + log + surface in response (E03b activate after 7d)
|
|
15
|
+
const TOKEN_BUDGET = {
|
|
16
|
+
balanced: 200,
|
|
17
|
+
deep: 250,
|
|
18
|
+
};
|
|
19
|
+
const DEEP_MARKER = /(?<=^|\s)(explicar?|como funciona|por qu[eê]|deep dive|detalh)(?=\s|[.,?!]|$)/i;
|
|
20
|
+
const APPROX_TOKENS_PER_TRIPLE = 25;
|
|
21
|
+
export function getMode() {
|
|
22
|
+
const v = (process.env.NOX_VAULT_FACTS_MODE || "shadow").toLowerCase();
|
|
23
|
+
if (v === "off" || v === "shadow" || v === "active")
|
|
24
|
+
return v;
|
|
25
|
+
return "shadow";
|
|
26
|
+
}
|
|
27
|
+
export function getK() {
|
|
28
|
+
const v = parseInt(process.env.NOX_VAULT_FACTS_K || "8", 10);
|
|
29
|
+
if (Number.isNaN(v) || v < 1 || v > 32)
|
|
30
|
+
return 8;
|
|
31
|
+
return v;
|
|
32
|
+
}
|
|
33
|
+
export function pickBudget(query) {
|
|
34
|
+
return DEEP_MARKER.test(query) ? TOKEN_BUDGET.deep : TOKEN_BUDGET.balanced;
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Match query tokens against kg_entities.name (case-insensitive exact match).
|
|
38
|
+
* v1 minimal: no NER, no fuzzy. Returns deduped list of matched entity names.
|
|
39
|
+
*/
|
|
40
|
+
export function extractCandidateEntities(query, db) {
|
|
41
|
+
const tokens = query
|
|
42
|
+
.toLowerCase()
|
|
43
|
+
.split(/[\s,;.!?()[\]{}'"]+/)
|
|
44
|
+
.filter((t) => t.length >= 2)
|
|
45
|
+
.slice(0, 32); // hard limit to bound query size
|
|
46
|
+
if (tokens.length === 0)
|
|
47
|
+
return [];
|
|
48
|
+
const placeholders = tokens.map(() => "?").join(",");
|
|
49
|
+
const stmt = db.prepare(`SELECT DISTINCT name FROM kg_entities WHERE LOWER(name) IN (${placeholders})`);
|
|
50
|
+
const rows = stmt.all(...tokens);
|
|
51
|
+
return rows.map((r) => r.name);
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* Lookup top-K SPO triples touching given entity names.
|
|
55
|
+
* JOIN with kg_entities to resolve FK ids → names.
|
|
56
|
+
* ORDER BY confidence DESC NULLS LAST, then created_at DESC.
|
|
57
|
+
*/
|
|
58
|
+
export function lookupTopK(entityNames, db, k) {
|
|
59
|
+
if (entityNames.length === 0)
|
|
60
|
+
return [];
|
|
61
|
+
const placeholders = entityNames.map(() => "?").join(",");
|
|
62
|
+
const sql = `
|
|
63
|
+
SELECT
|
|
64
|
+
src.name AS subject,
|
|
65
|
+
r.relation_type AS relation,
|
|
66
|
+
tgt.name AS object,
|
|
67
|
+
r.confidence AS confidence,
|
|
68
|
+
r.relation_reason AS reason
|
|
69
|
+
FROM kg_relations r
|
|
70
|
+
JOIN kg_entities src ON r.source_entity_id = src.id
|
|
71
|
+
JOIN kg_entities tgt ON r.target_entity_id = tgt.id
|
|
72
|
+
WHERE src.name IN (${placeholders}) OR tgt.name IN (${placeholders})
|
|
73
|
+
ORDER BY
|
|
74
|
+
CASE WHEN r.relation_reason = 'unknown' OR r.relation_reason IS NULL THEN 1 ELSE 0 END,
|
|
75
|
+
CASE WHEN r.confidence IS NULL THEN 1 ELSE 0 END,
|
|
76
|
+
r.confidence DESC,
|
|
77
|
+
r.created_at DESC
|
|
78
|
+
LIMIT ?
|
|
79
|
+
`;
|
|
80
|
+
const stmt = db.prepare(sql);
|
|
81
|
+
const rows = stmt.all(...entityNames, ...entityNames, k);
|
|
82
|
+
return rows;
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* Format triples as <vault-facts> XML-like block.
|
|
86
|
+
* Returns null if no triples (avoid empty block).
|
|
87
|
+
* Truncates each field to 80 chars to bound token usage.
|
|
88
|
+
*/
|
|
89
|
+
export function formatVaultFacts(triples) {
|
|
90
|
+
if (triples.length === 0)
|
|
91
|
+
return null;
|
|
92
|
+
const lines = triples.map((t) => {
|
|
93
|
+
const subject = sanitize(t.subject).slice(0, 80);
|
|
94
|
+
const relation = sanitize(t.relation).slice(0, 40);
|
|
95
|
+
const object = sanitize(t.object).slice(0, 80);
|
|
96
|
+
// E05: append reason annotation when classified (omit 'unknown' to keep output clean)
|
|
97
|
+
const reason = t.reason && t.reason !== 'unknown' ? ` [${sanitize(t.reason).slice(0, 20)}]` : '';
|
|
98
|
+
return `${subject} ${relation} ${object}${reason}`;
|
|
99
|
+
});
|
|
100
|
+
return `<vault-facts>\n${lines.join("\n")}\n</vault-facts>`;
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* Sanitize a KG field — collapse whitespace, strip newlines and angle brackets.
|
|
104
|
+
* Prevents prompt injection via second-order data (e.g. KG value containing
|
|
105
|
+
* `</vault-facts>` to escape the block). Security review M1 (2026-05-02).
|
|
106
|
+
*/
|
|
107
|
+
function sanitize(s) {
|
|
108
|
+
return s.replace(/[<>\n\r]/g, " ").replace(/\s+/g, " ").trim();
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* Estimate token usage roughly (chars/4 heuristic).
|
|
112
|
+
* Used to enforce budget cap.
|
|
113
|
+
*/
|
|
114
|
+
export function estimateTokens(s) {
|
|
115
|
+
return Math.ceil(s.length / 4);
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* Trim triples list to fit token budget.
|
|
119
|
+
*/
|
|
120
|
+
export function applyBudget(triples, budget) {
|
|
121
|
+
const trimmed = [];
|
|
122
|
+
let totalTokens = 20; // wrapper overhead (<vault-facts>...</vault-facts>)
|
|
123
|
+
for (const t of triples) {
|
|
124
|
+
const tripleTokens = APPROX_TOKENS_PER_TRIPLE;
|
|
125
|
+
if (totalTokens + tripleTokens > budget)
|
|
126
|
+
break;
|
|
127
|
+
trimmed.push(t);
|
|
128
|
+
totalTokens += tripleTokens;
|
|
129
|
+
}
|
|
130
|
+
return trimmed;
|
|
131
|
+
}
|
|
132
|
+
export function getVaultFacts(query, db) {
|
|
133
|
+
const mode = getMode();
|
|
134
|
+
const budget = pickBudget(query);
|
|
135
|
+
if (mode === "off") {
|
|
136
|
+
return { block: null, mode, surface: false, entities: 0, triples: 0, tokens: 0, budget };
|
|
137
|
+
}
|
|
138
|
+
const entities = extractCandidateEntities(query, db);
|
|
139
|
+
if (entities.length === 0) {
|
|
140
|
+
logTelemetry(query, mode, 0, 0, 0, budget);
|
|
141
|
+
return { block: null, mode, surface: false, entities: 0, triples: 0, tokens: 0, budget };
|
|
142
|
+
}
|
|
143
|
+
const k = getK();
|
|
144
|
+
const triples = lookupTopK(entities, db, k);
|
|
145
|
+
const trimmed = applyBudget(triples, budget);
|
|
146
|
+
const block = formatVaultFacts(trimmed);
|
|
147
|
+
const tokens = block ? estimateTokens(block) : 0;
|
|
148
|
+
logTelemetry(query, mode, entities.length, trimmed.length, tokens, budget);
|
|
149
|
+
const surface = mode === "active" && block !== null;
|
|
150
|
+
return {
|
|
151
|
+
block,
|
|
152
|
+
mode,
|
|
153
|
+
surface,
|
|
154
|
+
entities: entities.length,
|
|
155
|
+
triples: trimmed.length,
|
|
156
|
+
tokens,
|
|
157
|
+
budget,
|
|
158
|
+
};
|
|
159
|
+
}
|
|
160
|
+
function logTelemetry(query, mode, entities, triples, tokens, budget) {
|
|
161
|
+
if (process.env.NOX_VAULT_FACTS_LOG !== "1")
|
|
162
|
+
return;
|
|
163
|
+
const safeQuery = query.replace(/[\r\n"]/g, " ").slice(0, 100);
|
|
164
|
+
// eslint-disable-next-line no-console
|
|
165
|
+
console.log(`[vault-facts] mode=${mode} query="${safeQuery}" entities=${entities} triples=${triples} tokens=${tokens} budget=${budget}`);
|
|
166
|
+
}
|