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,202 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* G5 T1 — Central error sanitizer for HTTP responses.
|
|
3
|
+
*
|
|
4
|
+
* Threat-model ref: docs/security/THREAT-MODEL.md §6.2 T-A3-1 + Appendix Gap G5.
|
|
5
|
+
*
|
|
6
|
+
* Problem: Wave B HTTP handlers (P1 answer, A2 export, L3 mark, P5 viewer
|
|
7
|
+
* SSE, L2 conflict, P2 hooks) each implement their own catch-block. Several
|
|
8
|
+
* leak `error.stack` or internal paths (`/Users/lab/...`, `/root/...`) via
|
|
9
|
+
* `JSON.stringify(err)` or `err.message` containing fs paths.
|
|
10
|
+
*
|
|
11
|
+
* Solution: one function. All handlers pipe their errors through
|
|
12
|
+
* `sanitizeErrorForHttp()` to produce a fixed shape:
|
|
13
|
+
*
|
|
14
|
+
* { error: string, code: string, requestId: string, details?: unknown }
|
|
15
|
+
*
|
|
16
|
+
* Always emits requestId so users can quote one to support. Never emits stack
|
|
17
|
+
* (unless `exposeStack: true` AND NODE_ENV=development AND the dev flag is
|
|
18
|
+
* explicitly opted into via the caller).
|
|
19
|
+
*
|
|
20
|
+
* Status-code policy: maps a small allowlist of known error classes. Unknown
|
|
21
|
+
* → 500 + generic message. The status code is the only signal the client
|
|
22
|
+
* needs to differentiate "your input was bad" from "we crashed".
|
|
23
|
+
*
|
|
24
|
+
* Code values are CAPITAL_SNAKE per HTTP-convention; matches both the error's
|
|
25
|
+
* `.name` and a stable string per error class.
|
|
26
|
+
*/
|
|
27
|
+
import { randomUUID } from "node:crypto";
|
|
28
|
+
// ─── Known error → status mapping ────────────────────────────────────────
|
|
29
|
+
//
|
|
30
|
+
// Add entries here (and to the tests) when a new throwable becomes part of
|
|
31
|
+
// the public HTTP surface. Anything not listed → 500.
|
|
32
|
+
const ERROR_STATUS_MAP = new Map([
|
|
33
|
+
// Validation / client input — 4xx
|
|
34
|
+
["ValidationError", { status: 400, code: "VALIDATION_ERROR" }],
|
|
35
|
+
["InvalidBodyError", { status: 400, code: "INVALID_BODY" }],
|
|
36
|
+
["BadRequestError", { status: 400, code: "BAD_REQUEST" }],
|
|
37
|
+
["WeakPassphraseError", { status: 400, code: "WEAK_PASSPHRASE" }],
|
|
38
|
+
["UnauthorizedError", { status: 401, code: "UNAUTHORIZED", safeMsg: "missing or invalid auth token" }],
|
|
39
|
+
["ForbiddenError", { status: 403, code: "FORBIDDEN", safeMsg: "forbidden" }],
|
|
40
|
+
["NotFoundError", { status: 404, code: "NOT_FOUND", safeMsg: "resource not found" }],
|
|
41
|
+
["ConflictError", { status: 409, code: "CONFLICT" }],
|
|
42
|
+
["PayloadTooLargeError", { status: 413, code: "PAYLOAD_TOO_LARGE" }],
|
|
43
|
+
// Archive / encryption — 422 (semantically processable but failed)
|
|
44
|
+
["BadPassphraseError", { status: 422, code: "BAD_PASSPHRASE", safeMsg: "bad passphrase or wrong key" }],
|
|
45
|
+
["TamperedArchiveError", { status: 422, code: "TAMPERED_ARCHIVE", safeMsg: "archive integrity check failed" }],
|
|
46
|
+
["MissingAADError", { status: 422, code: "MISSING_AAD" }],
|
|
47
|
+
["SchemaVersionError", { status: 422, code: "SCHEMA_VERSION_MISMATCH" }],
|
|
48
|
+
["ManifestError", { status: 422, code: "MANIFEST_ERROR" }],
|
|
49
|
+
["ArchiveFormatError", { status: 422, code: "ARCHIVE_FORMAT_ERROR" }],
|
|
50
|
+
// Rate limit / overload — 429
|
|
51
|
+
["RateLimitError", { status: 429, code: "RATE_LIMITED", safeMsg: "rate limit exceeded" }],
|
|
52
|
+
["CostCapExceededError", { status: 429, code: "COST_CAP_EXCEEDED" }],
|
|
53
|
+
// Server-side — 5xx
|
|
54
|
+
["LLMTimeoutError", { status: 504, code: "LLM_TIMEOUT", safeMsg: "upstream LLM timed out" }],
|
|
55
|
+
["LLMUnreachableError", { status: 502, code: "LLM_UNREACHABLE", safeMsg: "upstream LLM unreachable" }],
|
|
56
|
+
["RetrievalEmptyError", { status: 503, code: "RETRIEVAL_EMPTY" }],
|
|
57
|
+
["HallucinationError", { status: 422, code: "HALLUCINATION_AFTER_RETRY" }],
|
|
58
|
+
]);
|
|
59
|
+
// ─── Internal-path patterns (drop on sight) ──────────────────────────────
|
|
60
|
+
/**
|
|
61
|
+
* Patterns that indicate an internal filesystem path or runtime detail leaked
|
|
62
|
+
* into the message. If detected, the message is replaced with a generic
|
|
63
|
+
* "internal_error: <code>" string.
|
|
64
|
+
*/
|
|
65
|
+
const INTERNAL_PATH_PATTERNS = [
|
|
66
|
+
/\/Users\/[^\s'"`]+/, // macOS dev path
|
|
67
|
+
/\/home\/[^\s'"`]+/, // linux user homedir
|
|
68
|
+
/\/root\/[^\s'"`]+/, // root path (very common in VPS)
|
|
69
|
+
/\/var\/[^\s'"`]+/,
|
|
70
|
+
/\/etc\/[^\s'"`]+/,
|
|
71
|
+
/\/tmp\/[^\s'"`]+/,
|
|
72
|
+
/\/opt\/[^\s'"`]+/,
|
|
73
|
+
/C:\\[^\s'"`]+/i, // windows paths just in case
|
|
74
|
+
/\(node:\d+\)/, // node debug line markers leak pid
|
|
75
|
+
/[A-Za-z]:\\Users\\[^\s'"`]+/, // windows user homedir variants
|
|
76
|
+
];
|
|
77
|
+
/** Token-shaped secrets — never appear in body */
|
|
78
|
+
const SECRET_PATTERNS = [
|
|
79
|
+
/AIza[0-9A-Za-z_-]{20,}/g, // Google API keys
|
|
80
|
+
/sk-[A-Za-z0-9]{20,}/g, // OpenAI / Stripe-style
|
|
81
|
+
/Bearer\s+[A-Za-z0-9._-]{20,}/gi,
|
|
82
|
+
/eyJ[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}/g, // JWTs
|
|
83
|
+
/xox[bps]-[A-Za-z0-9-]{20,}/g, // Slack
|
|
84
|
+
/ghp_[A-Za-z0-9]{20,}/g, // GitHub PAT
|
|
85
|
+
/key=[A-Za-z0-9_-]{16,}/g,
|
|
86
|
+
/token=[A-Za-z0-9_-]{16,}/g,
|
|
87
|
+
/password=[^\s&]+/gi,
|
|
88
|
+
/passphrase=[^\s&]+/gi,
|
|
89
|
+
];
|
|
90
|
+
/** Env-shaped indicators — never appear in body */
|
|
91
|
+
const ENV_PATTERNS = [
|
|
92
|
+
/\bNOX_[A-Z_]+=[^\s]+/g,
|
|
93
|
+
/\bGEMINI_API_KEY=[^\s]+/gi,
|
|
94
|
+
/\bANTHROPIC_API_KEY=[^\s]+/gi,
|
|
95
|
+
/\bAWS_[A-Z_]+=[^\s]+/g,
|
|
96
|
+
];
|
|
97
|
+
const MAX_MSG_LEN = 200;
|
|
98
|
+
// ─── Core ────────────────────────────────────────────────────────────────
|
|
99
|
+
export function sanitizeErrorForHttp(err, opts = {}) {
|
|
100
|
+
const requestId = typeof opts.requestId === "string" && opts.requestId.length > 0
|
|
101
|
+
? opts.requestId
|
|
102
|
+
: randomUUID();
|
|
103
|
+
const nodeEnv = opts.nodeEnv ?? process.env.NODE_ENV ?? "production";
|
|
104
|
+
const isProd = nodeEnv === "production";
|
|
105
|
+
// Coerce to Error.
|
|
106
|
+
const errObj = err instanceof Error
|
|
107
|
+
? err
|
|
108
|
+
: new Error(typeof err === "string" ? err : "unknown error");
|
|
109
|
+
const name = errObj.name || "Error";
|
|
110
|
+
const known = ERROR_STATUS_MAP.get(name);
|
|
111
|
+
const status = known?.status ?? 500;
|
|
112
|
+
const code = known?.code ?? "INTERNAL_ERROR";
|
|
113
|
+
// Build a safe message.
|
|
114
|
+
let safeMsg;
|
|
115
|
+
if (known?.safeMsg) {
|
|
116
|
+
safeMsg = known.safeMsg;
|
|
117
|
+
}
|
|
118
|
+
else if (status >= 500) {
|
|
119
|
+
// Server-side: NEVER echo the raw message (might contain SQL fragments,
|
|
120
|
+
// stack lines, internal paths). Use a fixed phrase.
|
|
121
|
+
safeMsg = "internal error";
|
|
122
|
+
}
|
|
123
|
+
else {
|
|
124
|
+
safeMsg = scrubMessage(errObj.message ?? "");
|
|
125
|
+
}
|
|
126
|
+
// Optional details — sanitizer drops it if it smells like a leak.
|
|
127
|
+
const details = sanitizeDetails(errObj.details);
|
|
128
|
+
const body = {
|
|
129
|
+
error: safeMsg,
|
|
130
|
+
code,
|
|
131
|
+
requestId,
|
|
132
|
+
};
|
|
133
|
+
if (details !== undefined) {
|
|
134
|
+
body.details = details;
|
|
135
|
+
}
|
|
136
|
+
// Stack: dev-only AND opt-in. Production NEVER leaks.
|
|
137
|
+
if (opts.exposeStack === true && !isProd && typeof errObj.stack === "string") {
|
|
138
|
+
body.stack = errObj.stack;
|
|
139
|
+
}
|
|
140
|
+
// Log a redacted line for observability (caller can wire to pino/winston).
|
|
141
|
+
if (opts.log) {
|
|
142
|
+
opts.log(`[error-sanitizer] requestId=${requestId} status=${status} code=${code} name=${name}`);
|
|
143
|
+
}
|
|
144
|
+
return { status, body };
|
|
145
|
+
}
|
|
146
|
+
/** Strip secrets/paths/env from a message; trim to MAX_MSG_LEN. */
|
|
147
|
+
function scrubMessage(raw) {
|
|
148
|
+
if (typeof raw !== "string" || raw.length === 0)
|
|
149
|
+
return "request failed";
|
|
150
|
+
let s = raw;
|
|
151
|
+
for (const re of SECRET_PATTERNS)
|
|
152
|
+
s = s.replace(re, "[REDACTED]");
|
|
153
|
+
for (const re of ENV_PATTERNS)
|
|
154
|
+
s = s.replace(re, "[REDACTED]");
|
|
155
|
+
// If any internal path remains, replace the whole message — too risky to partially redact.
|
|
156
|
+
for (const re of INTERNAL_PATH_PATTERNS) {
|
|
157
|
+
if (re.test(s))
|
|
158
|
+
return "request failed (details redacted)";
|
|
159
|
+
}
|
|
160
|
+
// Drop newlines (stack-like content).
|
|
161
|
+
s = s.replace(/[\r\n]+/g, " ");
|
|
162
|
+
if (s.length > MAX_MSG_LEN)
|
|
163
|
+
s = s.slice(0, MAX_MSG_LEN) + "…";
|
|
164
|
+
return s;
|
|
165
|
+
}
|
|
166
|
+
/** Best-effort scrub for an arbitrary `details` payload. */
|
|
167
|
+
function sanitizeDetails(d) {
|
|
168
|
+
if (d == null)
|
|
169
|
+
return undefined;
|
|
170
|
+
if (typeof d === "string") {
|
|
171
|
+
const cleaned = scrubMessage(d);
|
|
172
|
+
return cleaned === "request failed (details redacted)" ? undefined : cleaned;
|
|
173
|
+
}
|
|
174
|
+
if (typeof d === "number" || typeof d === "boolean")
|
|
175
|
+
return d;
|
|
176
|
+
if (Array.isArray(d)) {
|
|
177
|
+
const arr = d.map(sanitizeDetails).filter((v) => v !== undefined);
|
|
178
|
+
return arr.length > 0 ? arr : undefined;
|
|
179
|
+
}
|
|
180
|
+
if (typeof d === "object") {
|
|
181
|
+
const out = {};
|
|
182
|
+
let kept = 0;
|
|
183
|
+
for (const [k, v] of Object.entries(d)) {
|
|
184
|
+
// Drop top-level forbidden keys
|
|
185
|
+
if (/^(stack|cause|env|process|__proto__)$/i.test(k))
|
|
186
|
+
continue;
|
|
187
|
+
const cv = sanitizeDetails(v);
|
|
188
|
+
if (cv !== undefined) {
|
|
189
|
+
out[k] = cv;
|
|
190
|
+
kept++;
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
return kept > 0 ? out : undefined;
|
|
194
|
+
}
|
|
195
|
+
return undefined;
|
|
196
|
+
}
|
|
197
|
+
/** Convenience: generate a fresh requestId (callable from middleware). */
|
|
198
|
+
export function newRequestId() {
|
|
199
|
+
return randomUUID();
|
|
200
|
+
}
|
|
201
|
+
/** Re-export so callers can `import { sanitizeErrorForHttp, ... }`. */
|
|
202
|
+
export { ERROR_STATUS_MAP };
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { type EvalVariant } from "./eval.js";
|
|
2
|
+
export interface BatchMetricStats {
|
|
3
|
+
mean: number;
|
|
4
|
+
std: number;
|
|
5
|
+
min: number;
|
|
6
|
+
max: number;
|
|
7
|
+
values: number[];
|
|
8
|
+
}
|
|
9
|
+
export interface BatchSummary {
|
|
10
|
+
variant: EvalVariant;
|
|
11
|
+
runs: number;
|
|
12
|
+
query_count: number;
|
|
13
|
+
total_duration_ms: number;
|
|
14
|
+
individual_runs: Array<{
|
|
15
|
+
run_id: number;
|
|
16
|
+
nDCG: number;
|
|
17
|
+
MRR: number;
|
|
18
|
+
Recall: number;
|
|
19
|
+
Precision: number;
|
|
20
|
+
duration_ms: number;
|
|
21
|
+
}>;
|
|
22
|
+
stats: {
|
|
23
|
+
nDCG: BatchMetricStats;
|
|
24
|
+
MRR: BatchMetricStats;
|
|
25
|
+
Recall: BatchMetricStats;
|
|
26
|
+
Precision: BatchMetricStats;
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
export declare function runBatch(opts: {
|
|
30
|
+
variant?: EvalVariant;
|
|
31
|
+
runs?: number;
|
|
32
|
+
notes?: string;
|
|
33
|
+
}): Promise<BatchSummary>;
|
|
34
|
+
export declare function formatBatchSummary(b: BatchSummary, mode?: 'json' | 'text'): string;
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
// R02 replication (2026-05-03): N-run batch para mean ± std variance estimate.
|
|
2
|
+
// Wraps runEval N vezes + agrega métricas por iteração.
|
|
3
|
+
import { runEval } from "./eval.js";
|
|
4
|
+
function statsFor(values) {
|
|
5
|
+
const n = values.length;
|
|
6
|
+
const mean = values.reduce((s, v) => s + v, 0) / n;
|
|
7
|
+
// CODE-FIX MEDIUM: Bessel's correction (n-1) for sample variance — paper R02 reports uncertainty
|
|
8
|
+
// from sample, not population. Falls back to population variance only if n=1 (degenerate).
|
|
9
|
+
const denom = n > 1 ? n - 1 : 1;
|
|
10
|
+
const variance = values.reduce((s, v) => s + (v - mean) ** 2, 0) / denom;
|
|
11
|
+
const std = Math.sqrt(variance);
|
|
12
|
+
// CODE-FIX MEDIUM: reduce-based min/max evita stack blowup com large N (Math.min/max(...values) crash ~100k)
|
|
13
|
+
const min = values.reduce((a, b) => (a < b ? a : b));
|
|
14
|
+
const max = values.reduce((a, b) => (a > b ? a : b));
|
|
15
|
+
return {
|
|
16
|
+
mean: Math.round(mean * 10000) / 10000,
|
|
17
|
+
std: Math.round(std * 10000) / 10000,
|
|
18
|
+
min: Math.round(min * 10000) / 10000,
|
|
19
|
+
max: Math.round(max * 10000) / 10000,
|
|
20
|
+
values: values.map((v) => Math.round(v * 10000) / 10000),
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
|
+
export async function runBatch(opts) {
|
|
24
|
+
const variant = opts.variant || "hybrid";
|
|
25
|
+
const runs = opts.runs ?? 3;
|
|
26
|
+
if (runs < 2)
|
|
27
|
+
throw new Error("--runs must be ≥ 2 for variance estimate");
|
|
28
|
+
const t0 = Date.now();
|
|
29
|
+
const summaries = [];
|
|
30
|
+
const ndcgs = [];
|
|
31
|
+
const mrrs = [];
|
|
32
|
+
const recalls = [];
|
|
33
|
+
const precs = [];
|
|
34
|
+
const errors = [];
|
|
35
|
+
for (let i = 0; i < runs; i++) {
|
|
36
|
+
// CODE-FIX MEDIUM: try/catch per iteration — não perde N-1 successful runs em 1 falha
|
|
37
|
+
try {
|
|
38
|
+
const s = await runEval({
|
|
39
|
+
variant,
|
|
40
|
+
notes: `${opts.notes || 'batch'} (iter ${i + 1}/${runs})`,
|
|
41
|
+
});
|
|
42
|
+
summaries.push(s);
|
|
43
|
+
ndcgs.push(s.aggregate.ndcg_at_10);
|
|
44
|
+
mrrs.push(s.aggregate.mrr);
|
|
45
|
+
recalls.push(s.aggregate.recall_at_10);
|
|
46
|
+
precs.push(s.aggregate.precision_at_5);
|
|
47
|
+
}
|
|
48
|
+
catch (e) {
|
|
49
|
+
errors.push({ iter: i + 1, error: e.message?.substring(0, 200) || String(e) });
|
|
50
|
+
console.error(`[eval-batch] iter ${i + 1}/${runs} failed: ${errors[errors.length - 1].error}`);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
if (summaries.length < 2) {
|
|
54
|
+
throw new Error(`eval-batch: ${summaries.length}/${runs} runs succeeded — need ≥2 for variance estimate. Errors: ${errors.map((e) => `iter${e.iter}=${e.error}`).join("; ")}`);
|
|
55
|
+
}
|
|
56
|
+
// CODE-FIX MEDIUM: assert query_count uniformity (golden set may mutate mid-batch via concurrent ingest)
|
|
57
|
+
const qCounts = summaries.map((s) => s.query_count);
|
|
58
|
+
const qCountsUniform = qCounts.every((c) => c === qCounts[0]);
|
|
59
|
+
if (!qCountsUniform) {
|
|
60
|
+
console.warn(`[eval-batch] WARN: query_count varies across runs ${JSON.stringify(qCounts)} — golden set mutated mid-batch?`);
|
|
61
|
+
}
|
|
62
|
+
return {
|
|
63
|
+
variant,
|
|
64
|
+
runs,
|
|
65
|
+
query_count: qCountsUniform ? summaries[0].query_count : Math.max(...qCounts),
|
|
66
|
+
total_duration_ms: Date.now() - t0,
|
|
67
|
+
individual_runs: summaries.map((s) => ({
|
|
68
|
+
run_id: s.run_id,
|
|
69
|
+
nDCG: s.aggregate.ndcg_at_10,
|
|
70
|
+
MRR: s.aggregate.mrr,
|
|
71
|
+
Recall: s.aggregate.recall_at_10,
|
|
72
|
+
Precision: s.aggregate.precision_at_5,
|
|
73
|
+
duration_ms: s.total_duration_ms,
|
|
74
|
+
})),
|
|
75
|
+
stats: {
|
|
76
|
+
nDCG: statsFor(ndcgs),
|
|
77
|
+
MRR: statsFor(mrrs),
|
|
78
|
+
Recall: statsFor(recalls),
|
|
79
|
+
Precision: statsFor(precs),
|
|
80
|
+
},
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
export function formatBatchSummary(b, mode = 'text') {
|
|
84
|
+
if (mode === 'json')
|
|
85
|
+
return JSON.stringify(b, null, 2);
|
|
86
|
+
const lines = [];
|
|
87
|
+
lines.push(`## Eval Batch (variant=${b.variant}) — ${b.runs} runs over ${b.query_count} queries`);
|
|
88
|
+
lines.push(`Total duration: ${(b.total_duration_ms / 1000).toFixed(1)}s`);
|
|
89
|
+
lines.push(``);
|
|
90
|
+
lines.push(`| Run | nDCG@10 | MRR | Recall@10 | Prec@5 | Duration |`);
|
|
91
|
+
lines.push(`|-----|---------|-----|-----------|--------|----------|`);
|
|
92
|
+
for (const r of b.individual_runs) {
|
|
93
|
+
lines.push(`| #${r.run_id} | ${r.nDCG.toFixed(4)} | ${r.MRR.toFixed(4)} | ${r.Recall.toFixed(4)} | ${r.Precision.toFixed(4)} | ${(r.duration_ms / 1000).toFixed(1)}s |`);
|
|
94
|
+
}
|
|
95
|
+
lines.push(``);
|
|
96
|
+
lines.push(`### Aggregate (mean ± std)`);
|
|
97
|
+
lines.push(`| Metric | Mean | Std | Min | Max | Values |`);
|
|
98
|
+
lines.push(`|--------|------|-----|-----|-----|--------|`);
|
|
99
|
+
for (const [name, s] of Object.entries(b.stats)) {
|
|
100
|
+
lines.push(`| ${name.padEnd(8)} | ${s.mean.toFixed(4)} | ±${s.std.toFixed(4)} | ${s.min.toFixed(4)} | ${s.max.toFixed(4)} | ${s.values.map(v => v.toFixed(3)).join(", ")} |`);
|
|
101
|
+
}
|
|
102
|
+
return lines.join("\n");
|
|
103
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* nDCG@K — Normalized Discounted Cumulative Gain.
|
|
3
|
+
* Binary relevance (1 if chunk ∈ gold, else 0).
|
|
4
|
+
*
|
|
5
|
+
* DCG@K = Σ (i=1..K) [ rel(ri) / log2(i+1) ]
|
|
6
|
+
* IDCG@K = Σ (i=1..min(|G|, K)) [ 1 / log2(i+1) ]
|
|
7
|
+
* nDCG@K = DCG@K / IDCG@K (clamped to [0, 1])
|
|
8
|
+
*
|
|
9
|
+
* Returns 0 if gold standard is empty (no positives = undefined; convention 0).
|
|
10
|
+
*/
|
|
11
|
+
export declare function ndcgAtK(retrieved: number[], gold: Set<number>, k: number): number;
|
|
12
|
+
/**
|
|
13
|
+
* MRR — Mean Reciprocal Rank (per-query; aggregate is mean of these).
|
|
14
|
+
* Returns 1/rank of first gold hit, else 0.
|
|
15
|
+
*/
|
|
16
|
+
export declare function reciprocalRank(retrieved: number[], gold: Set<number>): number;
|
|
17
|
+
/**
|
|
18
|
+
* Recall@K — fraction of gold present in top-K retrieved.
|
|
19
|
+
*/
|
|
20
|
+
export declare function recallAtK(retrieved: number[], gold: Set<number>, k: number): number;
|
|
21
|
+
/**
|
|
22
|
+
* Precision@K — fraction of top-K that is gold.
|
|
23
|
+
* Denominator is always K (not min(K, retrieved.length)) — convention.
|
|
24
|
+
*/
|
|
25
|
+
export declare function precisionAtK(retrieved: number[], gold: Set<number>, k: number): number;
|
|
26
|
+
/**
|
|
27
|
+
* Aggregate mean across queries. Skips NaN (gold-empty queries with conventions).
|
|
28
|
+
*/
|
|
29
|
+
export declare function mean(values: number[]): number;
|
|
30
|
+
export interface PerQueryMetrics {
|
|
31
|
+
ndcg_at_10: number;
|
|
32
|
+
mrr: number;
|
|
33
|
+
recall_at_10: number;
|
|
34
|
+
precision_at_5: number;
|
|
35
|
+
}
|
|
36
|
+
export declare function computePerQuery(retrieved: number[], gold: Set<number>): PerQueryMetrics;
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
// R01a — Eval metrics pure functions.
|
|
2
|
+
// Spec: specs/2026-04-27-R01a-eval-harness.md (formulações exatas)
|
|
3
|
+
//
|
|
4
|
+
// All functions are pure (no DB, no I/O). Take retrieved chunk IDs ranked +
|
|
5
|
+
// gold standard (expected chunk IDs as Set). Return [0, 1] scores.
|
|
6
|
+
/**
|
|
7
|
+
* nDCG@K — Normalized Discounted Cumulative Gain.
|
|
8
|
+
* Binary relevance (1 if chunk ∈ gold, else 0).
|
|
9
|
+
*
|
|
10
|
+
* DCG@K = Σ (i=1..K) [ rel(ri) / log2(i+1) ]
|
|
11
|
+
* IDCG@K = Σ (i=1..min(|G|, K)) [ 1 / log2(i+1) ]
|
|
12
|
+
* nDCG@K = DCG@K / IDCG@K (clamped to [0, 1])
|
|
13
|
+
*
|
|
14
|
+
* Returns 0 if gold standard is empty (no positives = undefined; convention 0).
|
|
15
|
+
*/
|
|
16
|
+
export function ndcgAtK(retrieved, gold, k) {
|
|
17
|
+
if (gold.size === 0)
|
|
18
|
+
return 0;
|
|
19
|
+
const cutoff = Math.min(k, retrieved.length);
|
|
20
|
+
let dcg = 0;
|
|
21
|
+
for (let i = 0; i < cutoff; i++) {
|
|
22
|
+
const rel = gold.has(retrieved[i]) ? 1 : 0;
|
|
23
|
+
if (rel === 0)
|
|
24
|
+
continue;
|
|
25
|
+
// i is 0-indexed; rank is (i+1); discount log2(rank+1) = log2(i+2)
|
|
26
|
+
dcg += rel / Math.log2(i + 2);
|
|
27
|
+
}
|
|
28
|
+
let idcg = 0;
|
|
29
|
+
const idealCount = Math.min(gold.size, k);
|
|
30
|
+
for (let i = 0; i < idealCount; i++) {
|
|
31
|
+
idcg += 1 / Math.log2(i + 2);
|
|
32
|
+
}
|
|
33
|
+
if (idcg === 0)
|
|
34
|
+
return 0;
|
|
35
|
+
return Math.max(0, Math.min(1, dcg / idcg));
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* MRR — Mean Reciprocal Rank (per-query; aggregate is mean of these).
|
|
39
|
+
* Returns 1/rank of first gold hit, else 0.
|
|
40
|
+
*/
|
|
41
|
+
export function reciprocalRank(retrieved, gold) {
|
|
42
|
+
if (gold.size === 0)
|
|
43
|
+
return 0;
|
|
44
|
+
for (let i = 0; i < retrieved.length; i++) {
|
|
45
|
+
if (gold.has(retrieved[i]))
|
|
46
|
+
return 1 / (i + 1);
|
|
47
|
+
}
|
|
48
|
+
return 0;
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* Recall@K — fraction of gold present in top-K retrieved.
|
|
52
|
+
*/
|
|
53
|
+
export function recallAtK(retrieved, gold, k) {
|
|
54
|
+
if (gold.size === 0)
|
|
55
|
+
return 0;
|
|
56
|
+
const cutoff = Math.min(k, retrieved.length);
|
|
57
|
+
let hits = 0;
|
|
58
|
+
for (let i = 0; i < cutoff; i++) {
|
|
59
|
+
if (gold.has(retrieved[i]))
|
|
60
|
+
hits++;
|
|
61
|
+
}
|
|
62
|
+
return hits / gold.size;
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* Precision@K — fraction of top-K that is gold.
|
|
66
|
+
* Denominator is always K (not min(K, retrieved.length)) — convention.
|
|
67
|
+
*/
|
|
68
|
+
export function precisionAtK(retrieved, gold, k) {
|
|
69
|
+
if (k === 0)
|
|
70
|
+
return 0;
|
|
71
|
+
const cutoff = Math.min(k, retrieved.length);
|
|
72
|
+
let hits = 0;
|
|
73
|
+
for (let i = 0; i < cutoff; i++) {
|
|
74
|
+
if (gold.has(retrieved[i]))
|
|
75
|
+
hits++;
|
|
76
|
+
}
|
|
77
|
+
return hits / k;
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* Aggregate mean across queries. Skips NaN (gold-empty queries with conventions).
|
|
81
|
+
*/
|
|
82
|
+
export function mean(values) {
|
|
83
|
+
const valid = values.filter((v) => !Number.isNaN(v));
|
|
84
|
+
if (valid.length === 0)
|
|
85
|
+
return 0;
|
|
86
|
+
return valid.reduce((a, b) => a + b, 0) / valid.length;
|
|
87
|
+
}
|
|
88
|
+
export function computePerQuery(retrieved, gold) {
|
|
89
|
+
return {
|
|
90
|
+
ndcg_at_10: ndcgAtK(retrieved, gold, 10),
|
|
91
|
+
mrr: reciprocalRank(retrieved, gold),
|
|
92
|
+
recall_at_10: recallAtK(retrieved, gold, 10),
|
|
93
|
+
precision_at_5: precisionAtK(retrieved, gold, 5),
|
|
94
|
+
};
|
|
95
|
+
}
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
import Database from "better-sqlite3";
|
|
2
|
+
export type EvalVariant = "hybrid" | "fts" | "vector" | "rrf-only" | "custom" | "rerank";
|
|
3
|
+
export interface GoldenQuery {
|
|
4
|
+
id?: number;
|
|
5
|
+
query: string;
|
|
6
|
+
expected_chunk_ids: number[];
|
|
7
|
+
difficulty?: "easy" | "medium" | "hard";
|
|
8
|
+
category?: string;
|
|
9
|
+
added_by?: string;
|
|
10
|
+
notes?: string;
|
|
11
|
+
}
|
|
12
|
+
export interface EvalRunRow {
|
|
13
|
+
id: number;
|
|
14
|
+
variant: EvalVariant;
|
|
15
|
+
ran_at: string;
|
|
16
|
+
git_sha: string | null;
|
|
17
|
+
schema_version: number | null;
|
|
18
|
+
query_count: number;
|
|
19
|
+
total_duration_ms: number | null;
|
|
20
|
+
notes: string | null;
|
|
21
|
+
}
|
|
22
|
+
export interface EvalAggregate {
|
|
23
|
+
ndcg_at_10: number;
|
|
24
|
+
mrr: number;
|
|
25
|
+
recall_at_10: number;
|
|
26
|
+
precision_at_5: number;
|
|
27
|
+
}
|
|
28
|
+
export declare function getGitSha(): string | null;
|
|
29
|
+
export declare function getSchemaVersion(db: Database.Database): number;
|
|
30
|
+
/**
|
|
31
|
+
* Import golden queries from JSONL file. INSERT OR IGNORE on UNIQUE(query).
|
|
32
|
+
* Returns { imported, skipped, total_in_db }.
|
|
33
|
+
*/
|
|
34
|
+
export declare function importGolden(file: string, addedBy?: string): {
|
|
35
|
+
imported: number;
|
|
36
|
+
skipped: number;
|
|
37
|
+
total: number;
|
|
38
|
+
};
|
|
39
|
+
/**
|
|
40
|
+
* List all golden queries in DB.
|
|
41
|
+
*/
|
|
42
|
+
export declare function listGolden(): GoldenQuery[];
|
|
43
|
+
export interface RunOptions {
|
|
44
|
+
variant?: EvalVariant;
|
|
45
|
+
notes?: string;
|
|
46
|
+
gitSha?: string;
|
|
47
|
+
reportsDir?: string;
|
|
48
|
+
}
|
|
49
|
+
export interface RunSummary {
|
|
50
|
+
run_id: number;
|
|
51
|
+
variant: EvalVariant;
|
|
52
|
+
ran_at: string;
|
|
53
|
+
git_sha: string | null;
|
|
54
|
+
query_count: number;
|
|
55
|
+
total_duration_ms: number;
|
|
56
|
+
aggregate: EvalAggregate;
|
|
57
|
+
byDifficulty: Record<string, EvalAggregate & {
|
|
58
|
+
n: number;
|
|
59
|
+
}>;
|
|
60
|
+
byCategory: Record<string, EvalAggregate & {
|
|
61
|
+
n: number;
|
|
62
|
+
}>;
|
|
63
|
+
jsonlPath: string;
|
|
64
|
+
prevRunId: number | null;
|
|
65
|
+
delta: EvalAggregate | null;
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* Run eval over all golden queries with given variant.
|
|
69
|
+
* Persists eval_runs + eval_results, exports JSONL, returns summary.
|
|
70
|
+
*/
|
|
71
|
+
export declare function runEval(opts?: RunOptions): Promise<RunSummary>;
|
|
72
|
+
/**
|
|
73
|
+
* Compute aggregate for a given run from eval_results table.
|
|
74
|
+
*/
|
|
75
|
+
export declare function aggregateForRun(runId: number): EvalAggregate | null;
|
|
76
|
+
/**
|
|
77
|
+
* List recent runs, optionally filtered by variant.
|
|
78
|
+
*/
|
|
79
|
+
export declare function listRuns(variant?: EvalVariant, limit?: number): EvalRunRow[];
|
|
80
|
+
export interface CompareRow {
|
|
81
|
+
query_id: number;
|
|
82
|
+
query: string;
|
|
83
|
+
a_ndcg: number;
|
|
84
|
+
b_ndcg: number;
|
|
85
|
+
delta: number;
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* Compare two runs query-by-query. Returns sorted by delta (regressions first).
|
|
89
|
+
*/
|
|
90
|
+
export declare function compareRuns(runIdA: number, runIdB: number): {
|
|
91
|
+
regressions: CompareRow[];
|
|
92
|
+
improvements: CompareRow[];
|
|
93
|
+
aggregate_a: EvalAggregate | null;
|
|
94
|
+
aggregate_b: EvalAggregate | null;
|
|
95
|
+
};
|
|
96
|
+
/**
|
|
97
|
+
* Get latest run per variant for /api/health.evalMetrics surface.
|
|
98
|
+
*/
|
|
99
|
+
export declare function getEvalMetricsSnapshot(): {
|
|
100
|
+
lastRun: (EvalRunRow & EvalAggregate) | null;
|
|
101
|
+
byVariant: Record<string, {
|
|
102
|
+
ndcg_at_10: number;
|
|
103
|
+
ran_at: string;
|
|
104
|
+
run_id: number;
|
|
105
|
+
}>;
|
|
106
|
+
};
|