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,59 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* src/providers/types.ts — Shared types + errors (T1).
|
|
3
|
+
*
|
|
4
|
+
* `HealthStatus` shape is consumed by both EmbeddingProvider.healthCheck()
|
|
5
|
+
* and LLMProvider.healthCheck() — same contract on both sides keeps the
|
|
6
|
+
* registry-level boot probe (T8) uniform.
|
|
7
|
+
*
|
|
8
|
+
* Errors are typed so the registry (T2) can surface clear messages and so
|
|
9
|
+
* callers can distinguish "user config bug" from "transient backend issue"
|
|
10
|
+
* without parsing error strings.
|
|
11
|
+
*/
|
|
12
|
+
/** Thrown when an env API key is missing for the selected provider. */
|
|
13
|
+
export class MissingKeyError extends Error {
|
|
14
|
+
providerName;
|
|
15
|
+
envVar;
|
|
16
|
+
constructor(providerName, envVar) {
|
|
17
|
+
super(`MissingKeyError: provider "${providerName}" requires env var ${envVar} ` +
|
|
18
|
+
`(currently unset or empty). Refusing to construct provider without credentials.`);
|
|
19
|
+
this.name = "MissingKeyError";
|
|
20
|
+
this.providerName = providerName;
|
|
21
|
+
this.envVar = envVar;
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
/** Thrown when an unknown provider name is requested via env or factory arg. */
|
|
25
|
+
export class UnknownProviderError extends Error {
|
|
26
|
+
requested;
|
|
27
|
+
known;
|
|
28
|
+
constructor(requested, known) {
|
|
29
|
+
super(`UnknownProviderError: provider "${requested}" not in known set ` +
|
|
30
|
+
`[${known.join(", ")}]. Check NOX_*_PROVIDER env var.`);
|
|
31
|
+
this.name = "UnknownProviderError";
|
|
32
|
+
this.requested = requested;
|
|
33
|
+
this.known = known;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
/** Thrown by stub providers when actual work is invoked (vs healthCheck). */
|
|
37
|
+
export class NotImplementedError extends Error {
|
|
38
|
+
providerName;
|
|
39
|
+
constructor(providerName, op) {
|
|
40
|
+
super(`NotImplementedError: provider "${providerName}" is a stub. ` +
|
|
41
|
+
`Operation "${op}" is not implemented — interface conformance only. ` +
|
|
42
|
+
`Implement when first user activates this provider (A3.1 follow-up).`);
|
|
43
|
+
this.name = "NotImplementedError";
|
|
44
|
+
this.providerName = providerName;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
/** Thrown when a provider's healthCheck fails at boot AND fail-fast is enabled. */
|
|
48
|
+
export class ProviderHealthError extends Error {
|
|
49
|
+
providerName;
|
|
50
|
+
cause;
|
|
51
|
+
constructor(providerName, cause) {
|
|
52
|
+
super(`ProviderHealthError: provider "${providerName}" failed health check at boot` +
|
|
53
|
+
(cause ? ` (${cause})` : "") +
|
|
54
|
+
`. Set NOX_PROVIDER_HEALTH_FAIL_FAST=0 to soft-warn instead.`);
|
|
55
|
+
this.name = "ProviderHealthError";
|
|
56
|
+
this.providerName = providerName;
|
|
57
|
+
this.cause = cause;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* query-entity-count.ts — G10d: Conditional Hard Mutex entity detection
|
|
3
|
+
*
|
|
4
|
+
* Counts named entities mentioned in a query by matching against the
|
|
5
|
+
* `kg_entities` table (Option B — KG lookup, recommended in spec).
|
|
6
|
+
*
|
|
7
|
+
* Design constraints:
|
|
8
|
+
* - Zero LLM calls — pure DB lookup, p95 <1ms on hot cache
|
|
9
|
+
* - Cache TTL 5min — amortises cold-start overhead (~12KB index, ~5ms)
|
|
10
|
+
* - Greedy longest-match — "Acme Corp" counts as 1, not 2
|
|
11
|
+
* - Fallback: if DB unavailable or KG empty → returns 0 (mutex stays active,
|
|
12
|
+
* same as current G10 hard mutex behaviour — no regression possible)
|
|
13
|
+
* - PascalCase regex fallback when KG returns 0 rows
|
|
14
|
+
*
|
|
15
|
+
* Env flags used (evaluated at call time, NOT at module load):
|
|
16
|
+
* (none — count is stateless data, flags live in search.ts)
|
|
17
|
+
*
|
|
18
|
+
* Cross-links:
|
|
19
|
+
* - specs/2026-05-21-G10d-conditional-mutex-by-query-entities.md §3 Option B
|
|
20
|
+
* - staged-1.7a/edits/search.ts — consumer of countQueryEntities()
|
|
21
|
+
*/
|
|
22
|
+
import type Database from "better-sqlite3";
|
|
23
|
+
export interface QueryEntityCountResult {
|
|
24
|
+
count: number;
|
|
25
|
+
matchedEntities: string[];
|
|
26
|
+
method: "kg_lookup" | "fallback_regex";
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Returns the number of distinct KG entities mentioned in `query`.
|
|
30
|
+
*
|
|
31
|
+
* Algorithm:
|
|
32
|
+
* 1. Check per-query cache (LRU, max 1000 entries).
|
|
33
|
+
* 2. Load entity index from `kg_entities` (cached 5min).
|
|
34
|
+
* 3. Greedy longest-match scan of lowercased query.
|
|
35
|
+
* 4. If index is empty, fall back to PascalCase regex.
|
|
36
|
+
* 5. Cache and return result.
|
|
37
|
+
*
|
|
38
|
+
* The `cacheable` option (default: true) allows callers to suppress caching
|
|
39
|
+
* for eval harnesses that reuse query strings across different DB fixtures.
|
|
40
|
+
*
|
|
41
|
+
* @param query The raw search query string.
|
|
42
|
+
* @param db The open better-sqlite3 database connection.
|
|
43
|
+
* @param options.cacheable Whether to use per-query result cache (default true).
|
|
44
|
+
*/
|
|
45
|
+
export declare function countQueryEntities(query: string, db: Database.Database, options?: {
|
|
46
|
+
cacheable?: boolean;
|
|
47
|
+
}): QueryEntityCountResult;
|
|
48
|
+
/** Resets entity index AND query cache. Call in beforeEach for test isolation. */
|
|
49
|
+
export declare function clearQueryEntityCache(): void;
|
|
50
|
+
/**
|
|
51
|
+
* @deprecated Use clearQueryEntityCache() — resets both caches.
|
|
52
|
+
* Kept for backward compat with spec examples.
|
|
53
|
+
*/
|
|
54
|
+
export declare function _resetEntityIndexCache(): void;
|
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* query-entity-count.ts — G10d: Conditional Hard Mutex entity detection
|
|
3
|
+
*
|
|
4
|
+
* Counts named entities mentioned in a query by matching against the
|
|
5
|
+
* `kg_entities` table (Option B — KG lookup, recommended in spec).
|
|
6
|
+
*
|
|
7
|
+
* Design constraints:
|
|
8
|
+
* - Zero LLM calls — pure DB lookup, p95 <1ms on hot cache
|
|
9
|
+
* - Cache TTL 5min — amortises cold-start overhead (~12KB index, ~5ms)
|
|
10
|
+
* - Greedy longest-match — "Acme Corp" counts as 1, not 2
|
|
11
|
+
* - Fallback: if DB unavailable or KG empty → returns 0 (mutex stays active,
|
|
12
|
+
* same as current G10 hard mutex behaviour — no regression possible)
|
|
13
|
+
* - PascalCase regex fallback when KG returns 0 rows
|
|
14
|
+
*
|
|
15
|
+
* Env flags used (evaluated at call time, NOT at module load):
|
|
16
|
+
* (none — count is stateless data, flags live in search.ts)
|
|
17
|
+
*
|
|
18
|
+
* Cross-links:
|
|
19
|
+
* - specs/2026-05-21-G10d-conditional-mutex-by-query-entities.md §3 Option B
|
|
20
|
+
* - staged-1.7a/edits/search.ts — consumer of countQueryEntities()
|
|
21
|
+
*/
|
|
22
|
+
// ── In-memory entity index (module-scope, amortised across queries) ───────────
|
|
23
|
+
/** Lowercased name → set of entity_types (for diagnostic use). */
|
|
24
|
+
let _entityIndex = null;
|
|
25
|
+
let _entityIndexLoadedAt = 0;
|
|
26
|
+
const ENTITY_INDEX_TTL_MS = 5 * 60 * 1000; // 5 min — covers >>99% of queries
|
|
27
|
+
/**
|
|
28
|
+
* Per-query LRU cache (string → count result).
|
|
29
|
+
* Bounded at CACHE_MAX_SIZE to avoid unbounded growth in long-running daemons.
|
|
30
|
+
* Eviction: oldest-insert (Map insertion-order property).
|
|
31
|
+
*/
|
|
32
|
+
const _queryCache = new Map();
|
|
33
|
+
const CACHE_MAX_SIZE = 1_000;
|
|
34
|
+
function loadEntityIndex(db) {
|
|
35
|
+
const now = Date.now();
|
|
36
|
+
if (_entityIndex !== null && now - _entityIndexLoadedAt < ENTITY_INDEX_TTL_MS) {
|
|
37
|
+
return _entityIndex;
|
|
38
|
+
}
|
|
39
|
+
try {
|
|
40
|
+
const rows = db
|
|
41
|
+
.prepare("SELECT name, entity_type FROM kg_entities WHERE name IS NOT NULL")
|
|
42
|
+
.all();
|
|
43
|
+
const idx = new Map();
|
|
44
|
+
for (const row of rows) {
|
|
45
|
+
const key = row.name.toLowerCase().trim();
|
|
46
|
+
if (!key)
|
|
47
|
+
continue;
|
|
48
|
+
if (!idx.has(key))
|
|
49
|
+
idx.set(key, new Set());
|
|
50
|
+
idx.get(key).add(row.entity_type ?? "unknown");
|
|
51
|
+
}
|
|
52
|
+
_entityIndex = idx;
|
|
53
|
+
_entityIndexLoadedAt = now;
|
|
54
|
+
return idx;
|
|
55
|
+
}
|
|
56
|
+
catch {
|
|
57
|
+
// DB unavailable or table missing — return empty, triggering fallback
|
|
58
|
+
return new Map();
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
// ── Greedy longest-match scan ─────────────────────────────────────────────────
|
|
62
|
+
/**
|
|
63
|
+
* Scans `lower` for entity names from `idx`, using greedy longest-match:
|
|
64
|
+
* entities are tested in descending length order so "Acme Corp" is
|
|
65
|
+
* consumed before a hypothetical standalone "Fundo" entry.
|
|
66
|
+
* Returns an array of canonical (lowercased) matched entity names.
|
|
67
|
+
*/
|
|
68
|
+
function greedyMatch(lower, idx) {
|
|
69
|
+
// Sort once per idx reference — in practice this is cached alongside the index.
|
|
70
|
+
const sorted = [...idx.keys()].sort((a, b) => b.length - a.length);
|
|
71
|
+
const matched = [];
|
|
72
|
+
let remaining = lower;
|
|
73
|
+
for (const name of sorted) {
|
|
74
|
+
if (remaining.includes(name)) {
|
|
75
|
+
matched.push(name);
|
|
76
|
+
// Replace matched span with spaces so overlapping shorter names don't
|
|
77
|
+
// re-match the same span (e.g. "Fundo" inside "Acme Corp").
|
|
78
|
+
remaining = remaining.split(name).join(" ");
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
return matched;
|
|
82
|
+
}
|
|
83
|
+
// ── PascalCase fallback ───────────────────────────────────────────────────────
|
|
84
|
+
/**
|
|
85
|
+
* Lightweight regex fallback used when KG is empty (cold start before
|
|
86
|
+
* kg-extract has run, or evaluation harness with minimal fixture DB).
|
|
87
|
+
*
|
|
88
|
+
* Detects PascalCase tokens and quoted strings. Intentionally conservative —
|
|
89
|
+
* false positives are preferable to false negatives in this fallback path
|
|
90
|
+
* (mutex defaults to active on undercount, which is the safe direction).
|
|
91
|
+
*/
|
|
92
|
+
function countPascalCaseFallback(query) {
|
|
93
|
+
// Multi-word PascalCase: e.g. "Fundo X", "Project Capital", "PersonName"
|
|
94
|
+
const pascalMatches = query.match(/\b[A-ZÀ-Ý][a-zà-ÿ]+(?:\s+[A-ZÀ-Ý][a-zà-ÿ]+)*/gu) ?? [];
|
|
95
|
+
// Quoted entities: "nox-mem", 'openclaw'
|
|
96
|
+
const quotedMatches = query.match(/"[^"]+"|'[^']+'/g) ?? [];
|
|
97
|
+
const deduped = new Set([
|
|
98
|
+
...pascalMatches,
|
|
99
|
+
...quotedMatches.map((q) => q.slice(1, -1)),
|
|
100
|
+
]);
|
|
101
|
+
const matchedEntities = [...deduped];
|
|
102
|
+
return {
|
|
103
|
+
count: matchedEntities.length,
|
|
104
|
+
matchedEntities,
|
|
105
|
+
method: "fallback_regex",
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
// ── Public API ────────────────────────────────────────────────────────────────
|
|
109
|
+
/**
|
|
110
|
+
* Returns the number of distinct KG entities mentioned in `query`.
|
|
111
|
+
*
|
|
112
|
+
* Algorithm:
|
|
113
|
+
* 1. Check per-query cache (LRU, max 1000 entries).
|
|
114
|
+
* 2. Load entity index from `kg_entities` (cached 5min).
|
|
115
|
+
* 3. Greedy longest-match scan of lowercased query.
|
|
116
|
+
* 4. If index is empty, fall back to PascalCase regex.
|
|
117
|
+
* 5. Cache and return result.
|
|
118
|
+
*
|
|
119
|
+
* The `cacheable` option (default: true) allows callers to suppress caching
|
|
120
|
+
* for eval harnesses that reuse query strings across different DB fixtures.
|
|
121
|
+
*
|
|
122
|
+
* @param query The raw search query string.
|
|
123
|
+
* @param db The open better-sqlite3 database connection.
|
|
124
|
+
* @param options.cacheable Whether to use per-query result cache (default true).
|
|
125
|
+
*/
|
|
126
|
+
export function countQueryEntities(query, db, options = {}) {
|
|
127
|
+
const { cacheable = true } = options;
|
|
128
|
+
// Cache check
|
|
129
|
+
if (cacheable && _queryCache.has(query)) {
|
|
130
|
+
return _queryCache.get(query);
|
|
131
|
+
}
|
|
132
|
+
const idx = loadEntityIndex(db);
|
|
133
|
+
let result;
|
|
134
|
+
if (idx.size === 0) {
|
|
135
|
+
// KG unavailable or not yet populated — use regex fallback
|
|
136
|
+
result = countPascalCaseFallback(query);
|
|
137
|
+
}
|
|
138
|
+
else {
|
|
139
|
+
const lower = query.toLowerCase();
|
|
140
|
+
const matched = greedyMatch(lower, idx);
|
|
141
|
+
result = {
|
|
142
|
+
count: matched.length,
|
|
143
|
+
matchedEntities: matched,
|
|
144
|
+
method: "kg_lookup",
|
|
145
|
+
};
|
|
146
|
+
}
|
|
147
|
+
// Evict oldest entry if cache is full (Map preserves insertion order)
|
|
148
|
+
if (cacheable) {
|
|
149
|
+
if (_queryCache.size >= CACHE_MAX_SIZE) {
|
|
150
|
+
const oldest = _queryCache.keys().next().value;
|
|
151
|
+
if (oldest !== undefined)
|
|
152
|
+
_queryCache.delete(oldest);
|
|
153
|
+
}
|
|
154
|
+
_queryCache.set(query, result);
|
|
155
|
+
}
|
|
156
|
+
return result;
|
|
157
|
+
}
|
|
158
|
+
// ── Test hooks ────────────────────────────────────────────────────────────────
|
|
159
|
+
/** Resets entity index AND query cache. Call in beforeEach for test isolation. */
|
|
160
|
+
export function clearQueryEntityCache() {
|
|
161
|
+
_queryCache.clear();
|
|
162
|
+
_entityIndex = null;
|
|
163
|
+
_entityIndexLoadedAt = 0;
|
|
164
|
+
}
|
|
165
|
+
/**
|
|
166
|
+
* @deprecated Use clearQueryEntityCache() — resets both caches.
|
|
167
|
+
* Kept for backward compat with spec examples.
|
|
168
|
+
*/
|
|
169
|
+
export function _resetEntityIndexCache() {
|
|
170
|
+
clearQueryEntityCache();
|
|
171
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
export declare function ensureReflectCache(): void;
|
|
2
|
+
export declare function getReflectCacheStats(): {
|
|
3
|
+
entries: number;
|
|
4
|
+
total_hits: number;
|
|
5
|
+
top_queries: Array<{
|
|
6
|
+
query: string;
|
|
7
|
+
hits: number;
|
|
8
|
+
last_hit_at: string | null;
|
|
9
|
+
}>;
|
|
10
|
+
};
|
|
11
|
+
export declare function reflect(question: string, options?: {
|
|
12
|
+
noCache?: boolean;
|
|
13
|
+
}): Promise<{
|
|
14
|
+
answer: string;
|
|
15
|
+
evidence_count: number;
|
|
16
|
+
cached: boolean;
|
|
17
|
+
sources: string[];
|
|
18
|
+
cache_kind?: 'exact' | 'semantic';
|
|
19
|
+
}>;
|
|
20
|
+
export declare function formatReflect(result: {
|
|
21
|
+
answer: string;
|
|
22
|
+
evidence_count: number;
|
|
23
|
+
cached: boolean;
|
|
24
|
+
sources: string[];
|
|
25
|
+
cache_kind?: 'exact' | 'semantic';
|
|
26
|
+
}): string;
|
package/dist/reflect.js
ADDED
|
@@ -0,0 +1,290 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* reflect.ts — Deep KG synthesis: gather evidence + synthesize with Gemini
|
|
3
|
+
*/
|
|
4
|
+
import { getDb } from "./db.js";
|
|
5
|
+
import { search, searchHybrid } from "./search.js";
|
|
6
|
+
import { queryEntity, listDecisions } from "./knowledge-graph.js";
|
|
7
|
+
import { findPath } from "./cross-agent-v2.js";
|
|
8
|
+
import { embedText } from "./embed.js";
|
|
9
|
+
const GEMINI_API_KEY = process.env.GEMINI_API_KEY || "";
|
|
10
|
+
const GEMINI_MODEL = "gemini-2.5-flash-lite";
|
|
11
|
+
const API_BASE = "https://generativelanguage.googleapis.com/v1beta";
|
|
12
|
+
const MAX_EVIDENCE_CHARS = 2000;
|
|
13
|
+
const CACHE_TTL_HOURS = 24;
|
|
14
|
+
// E11 (2026-05-03): semantic key cache
|
|
15
|
+
const SEMANTIC_CACHE_THRESHOLD = parseFloat(process.env.NOX_REFLECT_SEMANTIC_THRESHOLD || "0.88");
|
|
16
|
+
const SEMANTIC_CACHE_ENABLED = process.env.NOX_REFLECT_SEMANTIC_CACHE !== "0"; // opt-out
|
|
17
|
+
const SEMANTIC_CACHE_LOG = process.env.NOX_REFLECT_SEMANTIC_LOG === "1";
|
|
18
|
+
function cosineSim(a, b) {
|
|
19
|
+
let dot = 0, magA = 0, magB = 0;
|
|
20
|
+
const len = Math.min(a.length, b.length);
|
|
21
|
+
for (let i = 0; i < len; i++) {
|
|
22
|
+
dot += a[i] * b[i];
|
|
23
|
+
magA += a[i] * a[i];
|
|
24
|
+
magB += b[i] * b[i];
|
|
25
|
+
}
|
|
26
|
+
if (magA === 0 || magB === 0)
|
|
27
|
+
return 0;
|
|
28
|
+
return dot / (Math.sqrt(magA) * Math.sqrt(magB));
|
|
29
|
+
}
|
|
30
|
+
// CODE-FIX CRITICAL #2: Buffer aliasing — Node Buffer pool memory could be overwritten
|
|
31
|
+
// between read and cosine compute. Copy bytes into fresh ArrayBuffer to detach from pool.
|
|
32
|
+
// Also handles unaligned offsets (byteOffset % 4 !== 0).
|
|
33
|
+
function blobToFloat32(blob) {
|
|
34
|
+
const copy = new Uint8Array(blob.byteLength);
|
|
35
|
+
copy.set(blob);
|
|
36
|
+
return new Float32Array(copy.buffer, 0, blob.byteLength / 4);
|
|
37
|
+
}
|
|
38
|
+
function float32ToBlob(arr) {
|
|
39
|
+
return Buffer.from(arr.buffer.slice(arr.byteOffset, arr.byteOffset + arr.byteLength));
|
|
40
|
+
}
|
|
41
|
+
export function ensureReflectCache() {
|
|
42
|
+
const db = getDb();
|
|
43
|
+
db.exec(`
|
|
44
|
+
CREATE TABLE IF NOT EXISTS reflect_cache (
|
|
45
|
+
query_hash TEXT PRIMARY KEY,
|
|
46
|
+
query TEXT NOT NULL,
|
|
47
|
+
response TEXT NOT NULL,
|
|
48
|
+
evidence_sources TEXT,
|
|
49
|
+
model TEXT DEFAULT 'gemini-2.5-flash-lite',
|
|
50
|
+
created_at TEXT DEFAULT (datetime('now')),
|
|
51
|
+
ttl_hours INTEGER DEFAULT 24
|
|
52
|
+
)
|
|
53
|
+
`);
|
|
54
|
+
// Additive migration: hit tracking (idempotent — ALTER fails if already added)
|
|
55
|
+
for (const stmt of [
|
|
56
|
+
"ALTER TABLE reflect_cache ADD COLUMN hit_count INTEGER DEFAULT 0",
|
|
57
|
+
"ALTER TABLE reflect_cache ADD COLUMN last_hit_at TEXT",
|
|
58
|
+
// E11: semantic cache
|
|
59
|
+
"ALTER TABLE reflect_cache ADD COLUMN query_embedding BLOB",
|
|
60
|
+
"ALTER TABLE reflect_cache ADD COLUMN semantic_hit_count INTEGER DEFAULT 0",
|
|
61
|
+
]) {
|
|
62
|
+
try {
|
|
63
|
+
db.exec(stmt);
|
|
64
|
+
}
|
|
65
|
+
catch { /* column exists */ }
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
export function getReflectCacheStats() {
|
|
69
|
+
ensureReflectCache();
|
|
70
|
+
const db = getDb();
|
|
71
|
+
const entries = db.prepare("SELECT COUNT(*) as c FROM reflect_cache").get().c;
|
|
72
|
+
const total_hits = db.prepare("SELECT COALESCE(SUM(hit_count),0) as s FROM reflect_cache").get().s;
|
|
73
|
+
const top_queries = db.prepare("SELECT query, hit_count as hits, last_hit_at FROM reflect_cache WHERE hit_count > 0 ORDER BY hit_count DESC LIMIT 5").all();
|
|
74
|
+
return { entries, total_hits, top_queries };
|
|
75
|
+
}
|
|
76
|
+
function hashQuery(q) {
|
|
77
|
+
let hash = 0;
|
|
78
|
+
for (let i = 0; i < q.length; i++) {
|
|
79
|
+
hash = ((hash << 5) - hash) + q.charCodeAt(i);
|
|
80
|
+
hash |= 0;
|
|
81
|
+
}
|
|
82
|
+
return "r" + Math.abs(hash).toString(36);
|
|
83
|
+
}
|
|
84
|
+
async function gatherEvidence(question) {
|
|
85
|
+
// 1. Hybrid search top 10 (async because semantic is async)
|
|
86
|
+
let searchResults;
|
|
87
|
+
try {
|
|
88
|
+
searchResults = await searchHybrid(question, 10);
|
|
89
|
+
}
|
|
90
|
+
catch {
|
|
91
|
+
searchResults = search(question, 10); // fallback to FTS only
|
|
92
|
+
}
|
|
93
|
+
const chunks = searchResults.map(r => ({
|
|
94
|
+
text: r.chunk_text.substring(0, 300),
|
|
95
|
+
source: r.source_file,
|
|
96
|
+
score: r.score,
|
|
97
|
+
}));
|
|
98
|
+
// 2. Extract entity names
|
|
99
|
+
const entityNames = [];
|
|
100
|
+
const words = question.split(/\s+/);
|
|
101
|
+
for (const w of words) {
|
|
102
|
+
if (w.length > 2 && w[0] === w[0].toUpperCase()) {
|
|
103
|
+
const clean = w.replace(/[^a-zA-Z\u00C0-\u024F-]/g, "");
|
|
104
|
+
if (clean && !entityNames.includes(clean))
|
|
105
|
+
entityNames.push(clean);
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
// 3. Query KG for entities
|
|
109
|
+
const entities = [];
|
|
110
|
+
for (const name of entityNames.slice(0, 5)) {
|
|
111
|
+
const result = queryEntity(name);
|
|
112
|
+
if (result.entity) {
|
|
113
|
+
entities.push({
|
|
114
|
+
name: result.entity.name,
|
|
115
|
+
type: result.entity.entityType,
|
|
116
|
+
relations: result.relations.slice(0, 5).map((r) => `${r.relation} -> ${r.target}`),
|
|
117
|
+
});
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
// 4. Find paths between top 2 entities
|
|
121
|
+
const paths = [];
|
|
122
|
+
const entNames = entities.map(e => e.name);
|
|
123
|
+
if (entNames.length >= 2) {
|
|
124
|
+
try {
|
|
125
|
+
const pathResult = findPath(entNames[0], entNames[1]);
|
|
126
|
+
if (pathResult && pathResult.length > 0) {
|
|
127
|
+
paths.push(pathResult.map(n => n.entity).join(" -> "));
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
catch { }
|
|
131
|
+
}
|
|
132
|
+
// 5. Related decisions
|
|
133
|
+
const allDecisions = listDecisions();
|
|
134
|
+
const questionLower = question.toLowerCase();
|
|
135
|
+
const decisions = allDecisions
|
|
136
|
+
.filter(d => {
|
|
137
|
+
const kl = d.decision_key.toLowerCase();
|
|
138
|
+
const cl = d.content.toLowerCase();
|
|
139
|
+
return words.some(w => w.length > 3 && (kl.includes(w.toLowerCase()) || cl.includes(w.toLowerCase())));
|
|
140
|
+
})
|
|
141
|
+
.slice(0, 3)
|
|
142
|
+
.map(d => ({ key: d.decision_key, content: d.content.substring(0, 200) }));
|
|
143
|
+
return { chunks, entities, decisions, paths };
|
|
144
|
+
}
|
|
145
|
+
function formatEvidence(evidence) {
|
|
146
|
+
const parts = [];
|
|
147
|
+
if (evidence.chunks.length > 0) {
|
|
148
|
+
parts.push("MEMORY CHUNKS:");
|
|
149
|
+
for (const c of evidence.chunks.slice(0, 5)) {
|
|
150
|
+
parts.push(`- [score:${c.score.toFixed(2)}] ${c.text}`);
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
if (evidence.entities.length > 0) {
|
|
154
|
+
parts.push("\nKG ENTITIES:");
|
|
155
|
+
for (const e of evidence.entities.slice(0, 5)) {
|
|
156
|
+
parts.push(`- ${e.name} (${e.type}) rels: ${e.relations.join(", ") || "none"}`);
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
if (evidence.decisions.length > 0) {
|
|
160
|
+
parts.push("\nDECISIONS:");
|
|
161
|
+
for (const d of evidence.decisions) {
|
|
162
|
+
parts.push(`- [${d.key}] ${d.content}`);
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
if (evidence.paths.length > 0) {
|
|
166
|
+
parts.push("\nGRAPH PATHS:");
|
|
167
|
+
for (const p of evidence.paths)
|
|
168
|
+
parts.push(`- ${p}`);
|
|
169
|
+
}
|
|
170
|
+
let result = parts.join("\n");
|
|
171
|
+
if (result.length > MAX_EVIDENCE_CHARS)
|
|
172
|
+
result = result.substring(0, MAX_EVIDENCE_CHARS) + "\n[truncated]";
|
|
173
|
+
return result;
|
|
174
|
+
}
|
|
175
|
+
async function synthesize(question, evidence) {
|
|
176
|
+
if (!GEMINI_API_KEY)
|
|
177
|
+
return "[reflect error: GEMINI_API_KEY not set]";
|
|
178
|
+
const url = `${API_BASE}/models/${GEMINI_MODEL}:generateContent?key=${GEMINI_API_KEY}`;
|
|
179
|
+
const prompt = `You are a memory synthesis agent. Given the evidence below, answer the question concisely.
|
|
180
|
+
Cite sources when possible. If the evidence is insufficient, say so.
|
|
181
|
+
Answer in the same language as the question. Max 500 characters.
|
|
182
|
+
|
|
183
|
+
QUESTION: ${question}
|
|
184
|
+
|
|
185
|
+
EVIDENCE:
|
|
186
|
+
${evidence}
|
|
187
|
+
|
|
188
|
+
SYNTHESIZED ANSWER:`;
|
|
189
|
+
const resp = await fetch(url, {
|
|
190
|
+
method: "POST",
|
|
191
|
+
headers: { "Content-Type": "application/json" },
|
|
192
|
+
body: JSON.stringify({
|
|
193
|
+
contents: [{ parts: [{ text: prompt }] }],
|
|
194
|
+
generationConfig: { maxOutputTokens: 256, temperature: 0.3 },
|
|
195
|
+
}),
|
|
196
|
+
});
|
|
197
|
+
if (!resp.ok) {
|
|
198
|
+
const errText = await resp.text();
|
|
199
|
+
return `[reflect error: Gemini ${resp.status}: ${errText.substring(0, 100)}]`;
|
|
200
|
+
}
|
|
201
|
+
const data = await resp.json();
|
|
202
|
+
return data?.candidates?.[0]?.content?.parts?.[0]?.text?.trim() || "[reflect: empty response]";
|
|
203
|
+
}
|
|
204
|
+
export async function reflect(question, options = {}) {
|
|
205
|
+
ensureReflectCache();
|
|
206
|
+
const db = getDb();
|
|
207
|
+
if (!options.noCache) {
|
|
208
|
+
// Path 1: exact hash hit (zero embedding cost)
|
|
209
|
+
const qHash = hashQuery(question);
|
|
210
|
+
const cached = db.prepare("SELECT response, evidence_sources FROM reflect_cache WHERE query_hash = ? AND datetime(created_at, '+' || ttl_hours || ' hours') > datetime('now')").get(qHash);
|
|
211
|
+
if (cached) {
|
|
212
|
+
db.prepare("UPDATE reflect_cache SET hit_count = hit_count + 1, last_hit_at = datetime('now') WHERE query_hash = ?").run(qHash);
|
|
213
|
+
return { answer: cached.response, evidence_count: 0, cached: true, sources: JSON.parse(cached.evidence_sources || "[]"), cache_kind: 'exact' };
|
|
214
|
+
}
|
|
215
|
+
// Path 2 (E11): semantic cache lookup
|
|
216
|
+
// CODE-FIX CRITICAL #1 (perf): COUNT short-circuit + LIMIT recent (avoid embed call + N×3072d alloc on empty cache)
|
|
217
|
+
if (SEMANTIC_CACHE_ENABLED) {
|
|
218
|
+
const haveEmbeds = db.prepare("SELECT COUNT(*) AS c FROM reflect_cache WHERE query_embedding IS NOT NULL AND datetime(created_at, '+' || ttl_hours || ' hours') > datetime('now')").get().c;
|
|
219
|
+
if (haveEmbeds > 0)
|
|
220
|
+
try {
|
|
221
|
+
const queryEmbed = await embedText(question);
|
|
222
|
+
// LIMIT 500 ORDER BY most recent — bounds scan; semantic_hit_count desc keeps hot entries
|
|
223
|
+
const candidates = db.prepare(`SELECT query_hash, query, response, evidence_sources, query_embedding
|
|
224
|
+
FROM reflect_cache
|
|
225
|
+
WHERE query_embedding IS NOT NULL AND datetime(created_at, '+' || ttl_hours || ' hours') > datetime('now')
|
|
226
|
+
ORDER BY (hit_count + semantic_hit_count) DESC, created_at DESC LIMIT 500`).all();
|
|
227
|
+
let bestSim = 0;
|
|
228
|
+
let bestRow;
|
|
229
|
+
for (const c of candidates) {
|
|
230
|
+
const sim = cosineSim(queryEmbed, blobToFloat32(c.query_embedding));
|
|
231
|
+
if (sim > bestSim) {
|
|
232
|
+
bestSim = sim;
|
|
233
|
+
bestRow = c;
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
if (SEMANTIC_CACHE_LOG && bestRow) {
|
|
237
|
+
console.log(`[reflect-semantic] query="${question.substring(0, 60)}" best_match="${bestRow.query.substring(0, 60)}" sim=${bestSim.toFixed(3)} threshold=${SEMANTIC_CACHE_THRESHOLD}`);
|
|
238
|
+
}
|
|
239
|
+
if (bestRow && bestSim >= SEMANTIC_CACHE_THRESHOLD) {
|
|
240
|
+
db.prepare("UPDATE reflect_cache SET semantic_hit_count = semantic_hit_count + 1, last_hit_at = datetime('now') WHERE query_hash = ?").run(bestRow.query_hash);
|
|
241
|
+
return {
|
|
242
|
+
answer: bestRow.response,
|
|
243
|
+
evidence_count: 0,
|
|
244
|
+
cached: true,
|
|
245
|
+
sources: JSON.parse(bestRow.evidence_sources || "[]"),
|
|
246
|
+
cache_kind: 'semantic',
|
|
247
|
+
};
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
catch (e) {
|
|
251
|
+
if (SEMANTIC_CACHE_LOG)
|
|
252
|
+
console.error(`[reflect-semantic] embed failed, falling back to fresh: ${e.message?.substring(0, 80)}`);
|
|
253
|
+
// Fail-open: continue to fresh synthesis
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
const evidence = await gatherEvidence(question);
|
|
258
|
+
const evidenceText = formatEvidence(evidence);
|
|
259
|
+
const sources = evidence.chunks.slice(0, 5).map(c => c.source);
|
|
260
|
+
const answer = await synthesize(question, evidenceText);
|
|
261
|
+
const qHash = hashQuery(question);
|
|
262
|
+
// CODE-FIX MEDIUM: write fresh entry sync (without embedding); fire-and-forget embedding update
|
|
263
|
+
// CODE-FIX MEDIUM: ON CONFLICT DO UPDATE preserva hit_count/semantic_hit_count vs INSERT OR REPLACE que zera
|
|
264
|
+
db.prepare(`
|
|
265
|
+
INSERT INTO reflect_cache (query_hash, query, response, evidence_sources, model, ttl_hours)
|
|
266
|
+
VALUES (?, ?, ?, ?, ?, ?)
|
|
267
|
+
ON CONFLICT(query_hash) DO UPDATE SET
|
|
268
|
+
response=excluded.response, evidence_sources=excluded.evidence_sources,
|
|
269
|
+
model=excluded.model, ttl_hours=excluded.ttl_hours, created_at=datetime('now')
|
|
270
|
+
`).run(qHash, question, answer, JSON.stringify(sources), GEMINI_MODEL, CACHE_TTL_HOURS);
|
|
271
|
+
// CODE-FIX MEDIUM: embedding capture deferred (don't block user response)
|
|
272
|
+
if (SEMANTIC_CACHE_ENABLED) {
|
|
273
|
+
embedText(question).then((emb) => {
|
|
274
|
+
try {
|
|
275
|
+
getDb().prepare("UPDATE reflect_cache SET query_embedding = ? WHERE query_hash = ?")
|
|
276
|
+
.run(float32ToBlob(emb), qHash);
|
|
277
|
+
}
|
|
278
|
+
catch { /* db closed mid-flight, OK */ }
|
|
279
|
+
}).catch(() => { });
|
|
280
|
+
}
|
|
281
|
+
return { answer, evidence_count: evidence.chunks.length + evidence.entities.length + evidence.decisions.length, cached: false, sources };
|
|
282
|
+
}
|
|
283
|
+
export function formatReflect(result) {
|
|
284
|
+
const lines = [result.answer];
|
|
285
|
+
if (result.sources.length > 0)
|
|
286
|
+
lines.push("", `Sources: ${result.sources.join(", ")}`);
|
|
287
|
+
const cacheLabel = result.cached ? `cached:${result.cache_kind || 'exact'}` : "fresh";
|
|
288
|
+
lines.push(`[${cacheLabel}, ${result.evidence_count} evidence items]`);
|
|
289
|
+
return lines.join("\n");
|
|
290
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
export declare const MIN_RETENTION_RATIO: number;
|
|
2
|
+
export declare class ReindexWipeDetectedError extends Error {
|
|
3
|
+
readonly preCount: number;
|
|
4
|
+
readonly postCount: number;
|
|
5
|
+
readonly ratio: number;
|
|
6
|
+
constructor(preCount: number, postCount: number, ratio: number);
|
|
7
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
// reindex-errors.ts — error classes for reindex.ts, extracted so the canary
|
|
2
|
+
// test can import them without pulling getDb / op-audit / ingest-router deps.
|
|
3
|
+
export const MIN_RETENTION_RATIO = Number(process.env.NOX_REINDEX_MIN_RETENTION_RATIO ?? "0.90");
|
|
4
|
+
export class ReindexWipeDetectedError extends Error {
|
|
5
|
+
preCount;
|
|
6
|
+
postCount;
|
|
7
|
+
ratio;
|
|
8
|
+
constructor(preCount, postCount, ratio) {
|
|
9
|
+
super(`[reindex] WIPE DETECTED: post-reindex chunks=${postCount} < ${(ratio * 100).toFixed(1)}% of pre=${preCount} ` +
|
|
10
|
+
`(threshold=${(ratio * 100).toFixed(1)}%). ` +
|
|
11
|
+
`Aborting via thrown error so withOpAudit() runs the failure path and preserves the pre-op snapshot. ` +
|
|
12
|
+
`Recover via safeRestore() from your configured snapshot dir ` +
|
|
13
|
+
`($NOX_PRE_OP_SNAPSHOT_DIR; default /var/backups/nox-mem/pre-op on origin, ` +
|
|
14
|
+
`<NOX_MEM_DIR|DB dir>/.nox-snapshots standalone)/reindex-<src>-<ts>-*.db. ` +
|
|
15
|
+
`Set NOX_REINDEX_ALLOW_WIPE=1 ONLY if intentional content removal is expected.`);
|
|
16
|
+
this.name = "ReindexWipeDetectedError";
|
|
17
|
+
this.preCount = preCount;
|
|
18
|
+
this.postCount = postCount;
|
|
19
|
+
this.ratio = ratio;
|
|
20
|
+
}
|
|
21
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
export { ReindexWipeDetectedError } from "./reindex-errors.js";
|
|
2
|
+
interface ReindexResult {
|
|
3
|
+
files: number;
|
|
4
|
+
chunks: number;
|
|
5
|
+
affected_rows?: number;
|
|
6
|
+
notes?: string;
|
|
7
|
+
dryRun?: boolean;
|
|
8
|
+
preCount?: number;
|
|
9
|
+
postCount?: number;
|
|
10
|
+
upserted?: number;
|
|
11
|
+
inserted?: number;
|
|
12
|
+
orphaned?: number;
|
|
13
|
+
}
|
|
14
|
+
export declare function reindex(opts?: {
|
|
15
|
+
dryRun?: boolean;
|
|
16
|
+
}): Promise<ReindexResult>;
|