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
package/dist/salience.js
ADDED
|
@@ -0,0 +1,245 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* staged-1.7a/edits/salience.ts
|
|
3
|
+
*
|
|
4
|
+
* Salience computation helper for nox-mem hybrid search.
|
|
5
|
+
*
|
|
6
|
+
* Implements the canonical formula documented in the paper (§3.2) and CLAUDE.md:
|
|
7
|
+
*
|
|
8
|
+
* salience = recency × pain × importance
|
|
9
|
+
*
|
|
10
|
+
* Where:
|
|
11
|
+
* - recency ∈ [0,1] — half-life decay over `retention_days` window
|
|
12
|
+
* - pain ∈ [0,1] — severity field on chunks (0.1 trivial → 1.0 outage)
|
|
13
|
+
* - importance ∈ [0,1] — chunk_type / source_type / tier signal (manual mapping)
|
|
14
|
+
*
|
|
15
|
+
* Mode gating (per architectural constraint, paper §4 — "shadow discipline"):
|
|
16
|
+
*
|
|
17
|
+
* NOX_SALIENCE_MODE=shadow (DEFAULT) — compute but DO NOT apply to retrieval
|
|
18
|
+
* NOX_SALIENCE_MODE=active — apply as additive delta in [-0.5, +0.5]
|
|
19
|
+
* NOX_SALIENCE_MODE=off — short-circuit to 0 (ablation experiments)
|
|
20
|
+
*
|
|
21
|
+
* The 7-day shadow gate is enforced operationally by /api/health.salience telemetry
|
|
22
|
+
* and `withOpAudit` activation logging — this module just honors whatever value
|
|
23
|
+
* is set in the env at module-load (re-export getter for tests).
|
|
24
|
+
*
|
|
25
|
+
* Mirror module on the VPS lives at `src/lib/salience.ts` (per CLAUDE.md §"Schema v10").
|
|
26
|
+
* This staged copy is the patch shipped via Wave A boost-stack-wiring.
|
|
27
|
+
*/
|
|
28
|
+
export function getSalienceMode() {
|
|
29
|
+
const raw = (process.env.NOX_SALIENCE_MODE ?? "shadow").toLowerCase();
|
|
30
|
+
if (raw === "active" || raw === "off")
|
|
31
|
+
return raw;
|
|
32
|
+
return "shadow";
|
|
33
|
+
}
|
|
34
|
+
// ─── Recency component ────────────────────────────────────────────────────────
|
|
35
|
+
//
|
|
36
|
+
// half-life-style decay: a chunk that's `retention_days` old has recency=0.5;
|
|
37
|
+
// fresh today = 1.0; ancient (10× retention_days) ≈ 0.001.
|
|
38
|
+
// retention_days defaults follow the V8 typed-retention table (see CLAUDE.md).
|
|
39
|
+
const DEFAULT_RETENTION_BY_TYPE = {
|
|
40
|
+
feedback: 0, // never-decay (treated as retention=Infinity → recency=1.0)
|
|
41
|
+
person: 0, // never-decay
|
|
42
|
+
lesson: 180,
|
|
43
|
+
decision: 365,
|
|
44
|
+
project: 365,
|
|
45
|
+
team: 120,
|
|
46
|
+
daily: 90,
|
|
47
|
+
pending: 30,
|
|
48
|
+
graph_node: 60,
|
|
49
|
+
};
|
|
50
|
+
const FALLBACK_RETENTION = 90;
|
|
51
|
+
export function resolveRetentionDays(retention_days, chunk_type) {
|
|
52
|
+
if (retention_days !== null && retention_days !== undefined && Number.isFinite(retention_days)) {
|
|
53
|
+
return retention_days;
|
|
54
|
+
}
|
|
55
|
+
if (chunk_type && chunk_type in DEFAULT_RETENTION_BY_TYPE) {
|
|
56
|
+
return DEFAULT_RETENTION_BY_TYPE[chunk_type];
|
|
57
|
+
}
|
|
58
|
+
return FALLBACK_RETENTION;
|
|
59
|
+
}
|
|
60
|
+
export function recencyComponent(source_date, last_accessed_at, retention_days, nowMs = Date.now()) {
|
|
61
|
+
// never-decay path: retention_days == 0 (per V8 spec, NULL retention === never)
|
|
62
|
+
if (retention_days <= 0)
|
|
63
|
+
return 1.0;
|
|
64
|
+
const refStr = last_accessed_at ?? source_date;
|
|
65
|
+
if (!refStr)
|
|
66
|
+
return 0.5; // unknown age → neutral
|
|
67
|
+
const refMs = Date.parse(refStr);
|
|
68
|
+
if (!Number.isFinite(refMs))
|
|
69
|
+
return 0.5;
|
|
70
|
+
const ageDays = (nowMs - refMs) / (1000 * 60 * 60 * 24);
|
|
71
|
+
if (ageDays <= 0)
|
|
72
|
+
return 1.0;
|
|
73
|
+
// half-life decay: at age == retention_days, recency = 0.5
|
|
74
|
+
return Math.pow(2, -ageDays / retention_days);
|
|
75
|
+
}
|
|
76
|
+
// ─── Importance component ─────────────────────────────────────────────────────
|
|
77
|
+
//
|
|
78
|
+
// Type-priors. These mirror the section_boost / chunk_type weighting documented
|
|
79
|
+
// in the paper and CLAUDE.md. They produce a number in (0, 1].
|
|
80
|
+
const IMPORTANCE_BY_TYPE = {
|
|
81
|
+
decision: 0.95,
|
|
82
|
+
lesson: 0.90,
|
|
83
|
+
person: 0.85,
|
|
84
|
+
project: 0.80,
|
|
85
|
+
pending: 0.75,
|
|
86
|
+
feedback: 0.70,
|
|
87
|
+
team: 0.60,
|
|
88
|
+
daily: 0.50,
|
|
89
|
+
graph_node: 0.45,
|
|
90
|
+
};
|
|
91
|
+
const FALLBACK_IMPORTANCE = 0.40;
|
|
92
|
+
export function importanceComponent(chunk_type, explicitImportance) {
|
|
93
|
+
// explicit column wins if present and finite
|
|
94
|
+
if (explicitImportance !== null &&
|
|
95
|
+
explicitImportance !== undefined &&
|
|
96
|
+
Number.isFinite(explicitImportance)) {
|
|
97
|
+
return clamp01(explicitImportance);
|
|
98
|
+
}
|
|
99
|
+
if (chunk_type && chunk_type in IMPORTANCE_BY_TYPE) {
|
|
100
|
+
return IMPORTANCE_BY_TYPE[chunk_type];
|
|
101
|
+
}
|
|
102
|
+
return FALLBACK_IMPORTANCE;
|
|
103
|
+
}
|
|
104
|
+
// ─── Pain component ───────────────────────────────────────────────────────────
|
|
105
|
+
export function painComponent(pain) {
|
|
106
|
+
if (pain === null || pain === undefined || !Number.isFinite(pain))
|
|
107
|
+
return 0.2; // V9 schema default
|
|
108
|
+
return clamp01(pain);
|
|
109
|
+
}
|
|
110
|
+
// ─── Backwards-compat helpers (used by ingest-entity.ts) ──────────────────────
|
|
111
|
+
//
|
|
112
|
+
// These helpers existed in the pre-Wave-A salience.ts and are still imported by
|
|
113
|
+
// src/ingest-entity.ts. Keeping them here preserves the existing ingest pipeline
|
|
114
|
+
// behaviour (chunk_type → importance prior + keyword-based pain inference).
|
|
115
|
+
//
|
|
116
|
+
// `inferImportance(chunk_type)` is a thin wrapper around `importanceComponent`.
|
|
117
|
+
// `inferPain(chunk_type, content)` is keyword-heuristic on incident/outage terms.
|
|
118
|
+
//
|
|
119
|
+
// Without these exports, src/ingest-entity.ts fails at module-load with
|
|
120
|
+
// "Module './salience.js' has no exported member 'inferPain'" — the "import
|
|
121
|
+
// mismatch" repair commit (080407f8) in VPS git history.
|
|
122
|
+
const PAIN_BY_TYPE = {
|
|
123
|
+
feedback: 0.3,
|
|
124
|
+
lesson: 0.4,
|
|
125
|
+
pending: 0.5,
|
|
126
|
+
decision: 0.3,
|
|
127
|
+
project: 0.3,
|
|
128
|
+
daily: 0.2,
|
|
129
|
+
team: 0.2,
|
|
130
|
+
graph_node: 0.2,
|
|
131
|
+
person: 0.2,
|
|
132
|
+
};
|
|
133
|
+
const FALLBACK_PAIN = 0.2;
|
|
134
|
+
// Heuristic: incident/outage/breach/severity keywords elevate pain.
|
|
135
|
+
// Conservative pattern — matches PT-BR + EN incident-flavored vocabulary.
|
|
136
|
+
const HIGH_PAIN_PATTERN = /\b(incident|incidente|outage|breach|critical|cr[íi]tic[ao]|emergency|emerg[êe]ncia|prod[\.\s]?down|sev[\s\-]?[0-2]|p0\b|severity[\s\-]?(high|critical))\b/i;
|
|
137
|
+
export function inferPain(chunk_type, content) {
|
|
138
|
+
const base = chunk_type
|
|
139
|
+
? (PAIN_BY_TYPE[chunk_type] ?? FALLBACK_PAIN)
|
|
140
|
+
: FALLBACK_PAIN;
|
|
141
|
+
if (content && HIGH_PAIN_PATTERN.test(content)) {
|
|
142
|
+
return clamp01(base + 0.5);
|
|
143
|
+
}
|
|
144
|
+
return base;
|
|
145
|
+
}
|
|
146
|
+
export function inferImportance(chunk_type) {
|
|
147
|
+
return importanceComponent(chunk_type, null);
|
|
148
|
+
}
|
|
149
|
+
// ─── Additive weights (evidence-based, audit 2026-05-19) ──────────────────────
|
|
150
|
+
//
|
|
151
|
+
// Multiplicative formula `recency × pain × importance` concentrated 99.7% chunks
|
|
152
|
+
// in the [0.05-0.40] band. Audit (docs/audits/2026-05-19-salience-distribution-audit.md)
|
|
153
|
+
// revealed pain (90.67% = default 0.2) and recency (99.76% in [7-30d] post-restore)
|
|
154
|
+
// are CONSTANT signals — multiplying by a constant just rescales without
|
|
155
|
+
// information gain. Only `importance` (bimodal 74% low / 17% high) is alive
|
|
156
|
+
// as a continuous signal; `access_count` (87% zero / 13% accessed) is a strong
|
|
157
|
+
// binary signal that the previous formula ignored entirely.
|
|
158
|
+
//
|
|
159
|
+
// Additive formulation captures live signals proportionally and never
|
|
160
|
+
// zero-outs when any single field is NULL/default.
|
|
161
|
+
//
|
|
162
|
+
// Weights tuned to mirror tier-manager threshold semantics (0.7 / 0.4 / 0.15)
|
|
163
|
+
// so `classifySalience` still partitions chunks meaningfully.
|
|
164
|
+
const W_IMPORTANCE = 0.55; // PRIMARY live signal
|
|
165
|
+
const W_RECENCY = 0.15; // dampened (homogeneous corpus age post-restore)
|
|
166
|
+
const W_PAIN = 0.10; // dampened (90% default value)
|
|
167
|
+
const W_ACCESS = 0.20; // binary used/unused signal
|
|
168
|
+
/**
|
|
169
|
+
* Access-count component. Maps 0 → 0, log-saturating toward 1.0 at ~1000 accesses.
|
|
170
|
+
*/
|
|
171
|
+
export function accessCountComponent(access_count) {
|
|
172
|
+
if (access_count === null || access_count === undefined || !Number.isFinite(access_count)) {
|
|
173
|
+
return 0;
|
|
174
|
+
}
|
|
175
|
+
if (access_count <= 0)
|
|
176
|
+
return 0;
|
|
177
|
+
return clamp01(Math.log1p(access_count) / Math.log(1000));
|
|
178
|
+
}
|
|
179
|
+
/**
|
|
180
|
+
* Pure salience computation. Returns a number in [0, 1].
|
|
181
|
+
* Does NOT consult NOX_SALIENCE_MODE — that gating lives in the caller (search.ts),
|
|
182
|
+
* so this function stays pure and testable.
|
|
183
|
+
*
|
|
184
|
+
* v2 (2026-05-19): additive evidence-weighted formula.
|
|
185
|
+
* See docs/audits/2026-05-19-salience-distribution-audit.md for rationale.
|
|
186
|
+
* Previous multiplicative formula is preserved at `calculateSalienceLegacy`
|
|
187
|
+
* for ablation comparison and shadow-discipline regression detection.
|
|
188
|
+
*/
|
|
189
|
+
export function calculateSalience(chunk, nowMs = Date.now()) {
|
|
190
|
+
const retention = resolveRetentionDays(chunk.retention_days, chunk.chunk_type);
|
|
191
|
+
const recency = recencyComponent(chunk.source_date ?? chunk.created_at, chunk.last_accessed_at, retention, nowMs);
|
|
192
|
+
const pain = painComponent(chunk.pain);
|
|
193
|
+
const importance = importanceComponent(chunk.chunk_type, chunk.importance);
|
|
194
|
+
const access = accessCountComponent(chunk.access_count);
|
|
195
|
+
return clamp01(W_IMPORTANCE * importance +
|
|
196
|
+
W_RECENCY * recency +
|
|
197
|
+
W_PAIN * pain +
|
|
198
|
+
W_ACCESS * access);
|
|
199
|
+
}
|
|
200
|
+
/**
|
|
201
|
+
* Legacy multiplicative formula. Retained for ablation comparison only.
|
|
202
|
+
* DO NOT USE in production scoring paths — proven to concentrate 99.7%
|
|
203
|
+
* of chunks in a narrow dead-range (G4 ablation 2026-05-19).
|
|
204
|
+
*/
|
|
205
|
+
export function calculateSalienceLegacy(chunk, nowMs = Date.now()) {
|
|
206
|
+
const retention = resolveRetentionDays(chunk.retention_days, chunk.chunk_type);
|
|
207
|
+
const recency = recencyComponent(chunk.source_date ?? chunk.created_at, chunk.last_accessed_at, retention, nowMs);
|
|
208
|
+
const pain = painComponent(chunk.pain);
|
|
209
|
+
const importance = importanceComponent(chunk.chunk_type, chunk.importance);
|
|
210
|
+
return clamp01(recency * pain * importance);
|
|
211
|
+
}
|
|
212
|
+
/**
|
|
213
|
+
* Mirror of `src/lib/salience.ts:computeSalience` on the VPS — kept as an alias
|
|
214
|
+
* so existing call-sites (e.g. /api/health.salience) keep working when the
|
|
215
|
+
* staged patch lands on top of the VPS module graph.
|
|
216
|
+
*/
|
|
217
|
+
export const computeSalience = calculateSalience;
|
|
218
|
+
/**
|
|
219
|
+
* Classify salience score into a tier action (for /api/health.sectionDistribution).
|
|
220
|
+
* Reconstructed from tier-manager.ts usage 2026-05-19 hotfix — pre-A `classifySalience`
|
|
221
|
+
* was not preserved in PR #148 salience.ts rewrite; this restores backwards-compat.
|
|
222
|
+
* promote: score >= 0.7 (candidate for tier promotion if not core)
|
|
223
|
+
* retain: 0.4 <= score < 0.7
|
|
224
|
+
* review: 0.15 <= score < 0.4
|
|
225
|
+
* archive: score < 0.15
|
|
226
|
+
*/
|
|
227
|
+
export function classifySalience(score) {
|
|
228
|
+
if (score >= 0.7)
|
|
229
|
+
return "promote";
|
|
230
|
+
if (score >= 0.4)
|
|
231
|
+
return "retain";
|
|
232
|
+
if (score >= 0.15)
|
|
233
|
+
return "review";
|
|
234
|
+
return "archive";
|
|
235
|
+
}
|
|
236
|
+
// ─── Utils ────────────────────────────────────────────────────────────────────
|
|
237
|
+
function clamp01(x) {
|
|
238
|
+
if (!Number.isFinite(x))
|
|
239
|
+
return 0;
|
|
240
|
+
if (x < 0)
|
|
241
|
+
return 0;
|
|
242
|
+
if (x > 1)
|
|
243
|
+
return 1;
|
|
244
|
+
return x;
|
|
245
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Schema migration v.17 — ops_audit visibility columns.
|
|
3
|
+
*
|
|
4
|
+
* Wrapper standalone para aplicar migration v.17 com snapshot atômico pré-op
|
|
5
|
+
* via withOpAudit, antes de restart da nox-mem-api (que aplicaria a mesma
|
|
6
|
+
* migration via ensureSchema no boot, mas sem snapshot do main DB de 1.2GB).
|
|
7
|
+
*
|
|
8
|
+
* Pattern: withOpAudit('schema-v17-migration', ...) → VACUUM INTO atômico do
|
|
9
|
+
* main DB → aplica ALTER TABLE → ops_audit row registrada com status='success'.
|
|
10
|
+
*
|
|
11
|
+
* Fase 2 / Gap C-migration (2026-05-15) — plans/2026-05-15-op-audit-gaps-review.md §10.6
|
|
12
|
+
*
|
|
13
|
+
* Uso na VPS:
|
|
14
|
+
* cd /root/.openclaw/workspace/tools/nox-mem
|
|
15
|
+
* NOX_DB_SOURCE=main node dist/scripts/migrate-v17-ops-audit.js
|
|
16
|
+
*/
|
|
17
|
+
export {};
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Schema migration v.17 — ops_audit visibility columns.
|
|
3
|
+
*
|
|
4
|
+
* Wrapper standalone para aplicar migration v.17 com snapshot atômico pré-op
|
|
5
|
+
* via withOpAudit, antes de restart da nox-mem-api (que aplicaria a mesma
|
|
6
|
+
* migration via ensureSchema no boot, mas sem snapshot do main DB de 1.2GB).
|
|
7
|
+
*
|
|
8
|
+
* Pattern: withOpAudit('schema-v17-migration', ...) → VACUUM INTO atômico do
|
|
9
|
+
* main DB → aplica ALTER TABLE → ops_audit row registrada com status='success'.
|
|
10
|
+
*
|
|
11
|
+
* Fase 2 / Gap C-migration (2026-05-15) — plans/2026-05-15-op-audit-gaps-review.md §10.6
|
|
12
|
+
*
|
|
13
|
+
* Uso na VPS:
|
|
14
|
+
* cd /root/.openclaw/workspace/tools/nox-mem
|
|
15
|
+
* NOX_DB_SOURCE=main node dist/scripts/migrate-v17-ops-audit.js
|
|
16
|
+
*/
|
|
17
|
+
import { withOpAudit } from "../lib/op-audit.js";
|
|
18
|
+
import { getDb } from "../db.js";
|
|
19
|
+
async function main() {
|
|
20
|
+
console.log("[migrate-v17] starting schema v.17 migration with pre-op snapshot");
|
|
21
|
+
const result = await withOpAudit("schema-v17-migration", async () => {
|
|
22
|
+
const db = getDb();
|
|
23
|
+
const before = db
|
|
24
|
+
.prepare("SELECT value FROM meta WHERE key = 'schema_version'")
|
|
25
|
+
.get();
|
|
26
|
+
console.log(`[migrate-v17] schema_version before: ${before?.value ?? "unset"}`);
|
|
27
|
+
// Idempotent ALTER TABLE — duplicate column é OK (re-run safe)
|
|
28
|
+
const statements = [
|
|
29
|
+
"ALTER TABLE ops_audit ADD COLUMN db_source TEXT DEFAULT 'unknown'",
|
|
30
|
+
"ALTER TABLE ops_audit ADD COLUMN db_path TEXT DEFAULT 'unknown'",
|
|
31
|
+
"ALTER TABLE ops_audit ADD COLUMN last_heartbeat_at TEXT",
|
|
32
|
+
];
|
|
33
|
+
let appliedCount = 0;
|
|
34
|
+
for (const stmt of statements) {
|
|
35
|
+
try {
|
|
36
|
+
db.exec(stmt);
|
|
37
|
+
appliedCount++;
|
|
38
|
+
console.log(`[migrate-v17] applied: ${stmt}`);
|
|
39
|
+
}
|
|
40
|
+
catch (err) {
|
|
41
|
+
const msg = String(err?.message ?? err);
|
|
42
|
+
if (msg.includes("duplicate column")) {
|
|
43
|
+
console.log(`[migrate-v17] skipped (already applied): ${stmt}`);
|
|
44
|
+
}
|
|
45
|
+
else {
|
|
46
|
+
throw err;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
// Update meta + PRAGMA
|
|
51
|
+
db.prepare("INSERT OR REPLACE INTO meta (key, value, updated_at) VALUES ('schema_version', ?, datetime('now'))").run("17");
|
|
52
|
+
db.exec("PRAGMA user_version = 17;");
|
|
53
|
+
const after = db
|
|
54
|
+
.prepare("SELECT value FROM meta WHERE key = 'schema_version'")
|
|
55
|
+
.get();
|
|
56
|
+
const pragma = db.prepare("PRAGMA user_version").get().user_version;
|
|
57
|
+
console.log(`[migrate-v17] schema_version after: ${after.value}`);
|
|
58
|
+
console.log(`[migrate-v17] PRAGMA user_version: ${pragma}`);
|
|
59
|
+
return {
|
|
60
|
+
affected_rows: appliedCount,
|
|
61
|
+
notes: `v.17 migration: ${appliedCount}/3 cols added (rest already present); meta=${after.value}, PRAGMA=${pragma}`,
|
|
62
|
+
};
|
|
63
|
+
});
|
|
64
|
+
console.log("[migrate-v17] migration complete ✅");
|
|
65
|
+
console.log("[migrate-v17] result:", JSON.stringify(result, null, 2));
|
|
66
|
+
}
|
|
67
|
+
main().catch((err) => {
|
|
68
|
+
console.error("[migrate-v17] FAILED:", err);
|
|
69
|
+
process.exit(1);
|
|
70
|
+
});
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* search-dedup.ts — 4-layer diversity filter for hybrid search results.
|
|
3
|
+
*
|
|
4
|
+
* Fase 1.6 — aplicado DEPOIS do RRF fusion, não interfere com scoring.
|
|
5
|
+
* Inspiração: garrytan/gbrain search/dedup.ts.
|
|
6
|
+
*
|
|
7
|
+
* Layers (na ordem):
|
|
8
|
+
* 1. Top 3 per source_file (evita 8 chunks do mesmo arquivo)
|
|
9
|
+
* 2. Jaccard text-similarity >0.85 entre prefixos de 180 chars removido
|
|
10
|
+
* (dedup textual sem custo de embedding; captura consolidations próximas)
|
|
11
|
+
* 3. No single chunk_type pode ser >60% do resultado final
|
|
12
|
+
* (força diversidade entre lesson / decision / code / conversation)
|
|
13
|
+
* 4. Final cap per source_file:
|
|
14
|
+
* - entity chunks (section IS NOT NULL): 3 (G12 R3 carve-out)
|
|
15
|
+
* - non-entity chunks (section IS NULL): 2 (default)
|
|
16
|
+
*
|
|
17
|
+
* G12 R3 (2026-05-21): entity-format files emitem N+2 chunks (frontmatter +
|
|
18
|
+
* compiled + timeline + N body). Cap=2 dropava o 3º chunk em queries
|
|
19
|
+
* adversarial que precisavam de múltiplas seções da mesma entity (ex: gold
|
|
20
|
+
* `<entity>::frontmatter` blocked porque ranks 1-2 já preenchidos por
|
|
21
|
+
* `compiled` + outro). Carve-out só pra section!=NULL preserva comportamento
|
|
22
|
+
* de markdown regular. Rollback rápido: NOX_DISABLE_G12_R3=1.
|
|
23
|
+
*
|
|
24
|
+
* Audit ref: audits/2026-05-21-G12-frontmatter-retrieval-audit.md §6 R3
|
|
25
|
+
*
|
|
26
|
+
* Não perde resultados únicos: se limit=5 e dedup cortar pra 3, 3 é o certo.
|
|
27
|
+
* Melhor cobertura < ruído repetido.
|
|
28
|
+
*/
|
|
29
|
+
import type { SearchResult } from "./search.js";
|
|
30
|
+
/**
|
|
31
|
+
* Layer 4 per-row cap selector. Entity chunks (section!=NULL) get
|
|
32
|
+
* MAX_PER_FILE_FINAL_ENTITY=3; everything else stays at MAX_PER_FILE_FINAL=2.
|
|
33
|
+
* Set NOX_DISABLE_G12_R3=1 to revert to flat cap=2.
|
|
34
|
+
*
|
|
35
|
+
* Exported for unit testing.
|
|
36
|
+
*/
|
|
37
|
+
export declare function _layer4Cap(r: Pick<SearchResult, "section">): number;
|
|
38
|
+
export declare function dedupe(results: SearchResult[], limit: number): SearchResult[];
|
|
39
|
+
export declare const _internals: {
|
|
40
|
+
MAX_PER_FILE_PRE: number;
|
|
41
|
+
MAX_PER_FILE_FINAL: number;
|
|
42
|
+
MAX_PER_FILE_FINAL_ENTITY: number;
|
|
43
|
+
DISABLE_G12_R3: boolean;
|
|
44
|
+
};
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* search-dedup.ts — 4-layer diversity filter for hybrid search results.
|
|
3
|
+
*
|
|
4
|
+
* Fase 1.6 — aplicado DEPOIS do RRF fusion, não interfere com scoring.
|
|
5
|
+
* Inspiração: garrytan/gbrain search/dedup.ts.
|
|
6
|
+
*
|
|
7
|
+
* Layers (na ordem):
|
|
8
|
+
* 1. Top 3 per source_file (evita 8 chunks do mesmo arquivo)
|
|
9
|
+
* 2. Jaccard text-similarity >0.85 entre prefixos de 180 chars removido
|
|
10
|
+
* (dedup textual sem custo de embedding; captura consolidations próximas)
|
|
11
|
+
* 3. No single chunk_type pode ser >60% do resultado final
|
|
12
|
+
* (força diversidade entre lesson / decision / code / conversation)
|
|
13
|
+
* 4. Final cap per source_file:
|
|
14
|
+
* - entity chunks (section IS NOT NULL): 3 (G12 R3 carve-out)
|
|
15
|
+
* - non-entity chunks (section IS NULL): 2 (default)
|
|
16
|
+
*
|
|
17
|
+
* G12 R3 (2026-05-21): entity-format files emitem N+2 chunks (frontmatter +
|
|
18
|
+
* compiled + timeline + N body). Cap=2 dropava o 3º chunk em queries
|
|
19
|
+
* adversarial que precisavam de múltiplas seções da mesma entity (ex: gold
|
|
20
|
+
* `<entity>::frontmatter` blocked porque ranks 1-2 já preenchidos por
|
|
21
|
+
* `compiled` + outro). Carve-out só pra section!=NULL preserva comportamento
|
|
22
|
+
* de markdown regular. Rollback rápido: NOX_DISABLE_G12_R3=1.
|
|
23
|
+
*
|
|
24
|
+
* Audit ref: audits/2026-05-21-G12-frontmatter-retrieval-audit.md §6 R3
|
|
25
|
+
*
|
|
26
|
+
* Não perde resultados únicos: se limit=5 e dedup cortar pra 3, 3 é o certo.
|
|
27
|
+
* Melhor cobertura < ruído repetido.
|
|
28
|
+
*/
|
|
29
|
+
const SIMILARITY_THRESHOLD = 0.85;
|
|
30
|
+
const PREFIX_LEN = 180;
|
|
31
|
+
const MAX_PER_FILE_PRE = 3;
|
|
32
|
+
const MAX_PER_FILE_FINAL = 2;
|
|
33
|
+
const MAX_PER_FILE_FINAL_ENTITY = 3; // G12 R3 — section IS NOT NULL
|
|
34
|
+
const TYPE_SATURATION_RATIO = 0.6;
|
|
35
|
+
// G12 R3 rollback flag (2026-05-21): set NOX_DISABLE_G12_R3=1 to revert
|
|
36
|
+
// Layer 4 to flat cap=2 across all chunks regardless of section.
|
|
37
|
+
const DISABLE_G12_R3 = process.env.NOX_DISABLE_G12_R3 === "1";
|
|
38
|
+
/**
|
|
39
|
+
* Jaccard similarity em shingles de 3 palavras. Cheap, good enough for
|
|
40
|
+
* "este chunk é quase o mesmo que aquele".
|
|
41
|
+
*/
|
|
42
|
+
function jaccardSim(a, b) {
|
|
43
|
+
const shingles = (s) => {
|
|
44
|
+
const tokens = s.toLowerCase().replace(/[^\p{L}\p{N}\s]/gu, " ").split(/\s+/).filter(Boolean);
|
|
45
|
+
const sh = new Set();
|
|
46
|
+
for (let i = 0; i < tokens.length - 2; i++)
|
|
47
|
+
sh.add(tokens[i] + " " + tokens[i + 1] + " " + tokens[i + 2]);
|
|
48
|
+
if (sh.size === 0 && tokens.length > 0)
|
|
49
|
+
sh.add(tokens.join(" "));
|
|
50
|
+
return sh;
|
|
51
|
+
};
|
|
52
|
+
const A = shingles(a.substring(0, PREFIX_LEN));
|
|
53
|
+
const B = shingles(b.substring(0, PREFIX_LEN));
|
|
54
|
+
if (A.size === 0 || B.size === 0)
|
|
55
|
+
return 0;
|
|
56
|
+
let inter = 0;
|
|
57
|
+
for (const x of A)
|
|
58
|
+
if (B.has(x))
|
|
59
|
+
inter++;
|
|
60
|
+
const union = A.size + B.size - inter;
|
|
61
|
+
return union > 0 ? inter / union : 0;
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Layer 4 per-row cap selector. Entity chunks (section!=NULL) get
|
|
65
|
+
* MAX_PER_FILE_FINAL_ENTITY=3; everything else stays at MAX_PER_FILE_FINAL=2.
|
|
66
|
+
* Set NOX_DISABLE_G12_R3=1 to revert to flat cap=2.
|
|
67
|
+
*
|
|
68
|
+
* Exported for unit testing.
|
|
69
|
+
*/
|
|
70
|
+
export function _layer4Cap(r) {
|
|
71
|
+
if (DISABLE_G12_R3)
|
|
72
|
+
return MAX_PER_FILE_FINAL;
|
|
73
|
+
return r.section != null ? MAX_PER_FILE_FINAL_ENTITY : MAX_PER_FILE_FINAL;
|
|
74
|
+
}
|
|
75
|
+
export function dedupe(results, limit) {
|
|
76
|
+
if (results.length === 0)
|
|
77
|
+
return results;
|
|
78
|
+
// Layer 1: max MAX_PER_FILE_PRE por source_file (preserva ordem de score)
|
|
79
|
+
const perFileCount = new Map();
|
|
80
|
+
const afterFileCap = [];
|
|
81
|
+
for (const r of results) {
|
|
82
|
+
const c = perFileCount.get(r.source_file) || 0;
|
|
83
|
+
if (c < MAX_PER_FILE_PRE) {
|
|
84
|
+
afterFileCap.push(r);
|
|
85
|
+
perFileCount.set(r.source_file, c + 1);
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
// Layer 2: remove near-duplicates por Jaccard
|
|
89
|
+
const afterJaccard = [];
|
|
90
|
+
for (const r of afterFileCap) {
|
|
91
|
+
const isDup = afterJaccard.some((kept) => jaccardSim(r.chunk_text, kept.chunk_text) >= SIMILARITY_THRESHOLD);
|
|
92
|
+
if (!isDup)
|
|
93
|
+
afterJaccard.push(r);
|
|
94
|
+
}
|
|
95
|
+
// Layer 3: satura no máximo TYPE_SATURATION_RATIO de um único chunk_type
|
|
96
|
+
// Aplica só se há diversidade disponível — senão retorna o que tem.
|
|
97
|
+
const maxOfType = Math.max(1, Math.ceil(limit * TYPE_SATURATION_RATIO));
|
|
98
|
+
const typeCount = new Map();
|
|
99
|
+
const afterTypeCap = [];
|
|
100
|
+
const benched = [];
|
|
101
|
+
for (const r of afterJaccard) {
|
|
102
|
+
const c = typeCount.get(r.chunk_type) || 0;
|
|
103
|
+
if (c < maxOfType) {
|
|
104
|
+
afterTypeCap.push(r);
|
|
105
|
+
typeCount.set(r.chunk_type, c + 1);
|
|
106
|
+
}
|
|
107
|
+
else {
|
|
108
|
+
benched.push(r);
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
// Se não chegamos no limit, recuperamos do banco (melhor ter mais resultados)
|
|
112
|
+
while (afterTypeCap.length < limit && benched.length > 0) {
|
|
113
|
+
afterTypeCap.push(benched.shift());
|
|
114
|
+
}
|
|
115
|
+
// Layer 4: final cap per source_file — G12 R3 carve-out for entity chunks
|
|
116
|
+
// (section!=NULL → 3, else → 2). Rollback: NOX_DISABLE_G12_R3=1.
|
|
117
|
+
const finalFileCount = new Map();
|
|
118
|
+
const final = [];
|
|
119
|
+
for (const r of afterTypeCap) {
|
|
120
|
+
const c = finalFileCount.get(r.source_file) || 0;
|
|
121
|
+
const localCap = _layer4Cap(r);
|
|
122
|
+
if (c < localCap) {
|
|
123
|
+
final.push(r);
|
|
124
|
+
finalFileCount.set(r.source_file, c + 1);
|
|
125
|
+
}
|
|
126
|
+
if (final.length >= limit)
|
|
127
|
+
break;
|
|
128
|
+
}
|
|
129
|
+
return final;
|
|
130
|
+
}
|
|
131
|
+
// Exported constants for tests / introspection.
|
|
132
|
+
export const _internals = {
|
|
133
|
+
MAX_PER_FILE_PRE,
|
|
134
|
+
MAX_PER_FILE_FINAL,
|
|
135
|
+
MAX_PER_FILE_FINAL_ENTITY,
|
|
136
|
+
DISABLE_G12_R3,
|
|
137
|
+
};
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* search-expansion.ts — Multi-perspective query rewriting via Gemini 2.5 Flash.
|
|
3
|
+
*
|
|
4
|
+
* Fase 1.6 — gera 2 variantes (técnica + paráfrase) além da query original.
|
|
5
|
+
* Queries com <3 palavras, config off, ou Gemini unreachable retornam [query] intacta.
|
|
6
|
+
*
|
|
7
|
+
* Telemetria: retorna também o número de variantes efetivamente usadas para
|
|
8
|
+
* gravar em search_telemetry.variants_count.
|
|
9
|
+
*/
|
|
10
|
+
export interface ExpansionResult {
|
|
11
|
+
variants: string[];
|
|
12
|
+
skipped: boolean;
|
|
13
|
+
reason?: "too_short" | "disabled" | "gemini_failed" | "no_api_key";
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Lê config `expansion_enabled` da tabela meta. Default = true (plano Fase 1.6).
|
|
17
|
+
* Toggle sem redeploy: UPDATE meta SET value='false' WHERE key='expansion_enabled';
|
|
18
|
+
*/
|
|
19
|
+
export declare function isExpansionEnabled(): boolean;
|
|
20
|
+
export declare function expandQuery(query: string): Promise<ExpansionResult>;
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* search-expansion.ts — Multi-perspective query rewriting via Gemini 2.5 Flash.
|
|
3
|
+
*
|
|
4
|
+
* Fase 1.6 — gera 2 variantes (técnica + paráfrase) além da query original.
|
|
5
|
+
* Queries com <3 palavras, config off, ou Gemini unreachable retornam [query] intacta.
|
|
6
|
+
*
|
|
7
|
+
* Telemetria: retorna também o número de variantes efetivamente usadas para
|
|
8
|
+
* gravar em search_telemetry.variants_count.
|
|
9
|
+
*/
|
|
10
|
+
import { getDb } from "./db.js";
|
|
11
|
+
const GEMINI_API_KEY = process.env.GEMINI_API_KEY || "";
|
|
12
|
+
const GEMINI_MODEL = "gemini-2.5-flash-lite";
|
|
13
|
+
const API_BASE = "https://generativelanguage.googleapis.com/v1beta";
|
|
14
|
+
const TIMEOUT_MS = 2500;
|
|
15
|
+
const EXPANSION_PROMPT = `Você reescreve queries de busca para um sistema de memória técnica/executiva (PT-BR + EN misturados). Gere 2 variantes ALÉM da original.
|
|
16
|
+
|
|
17
|
+
Variante 1 (técnica): use termos técnicos precisos, entidades explícitas, jargão do domínio (ex: "gateway", "systemd", "Gemini", "KG", "nox-mem", "FTS", nomes de projetos/ferramentas).
|
|
18
|
+
|
|
19
|
+
Variante 2 (paráfrase): reformule em linguagem natural, troque palavras por sinônimos, mantenha a intenção.
|
|
20
|
+
|
|
21
|
+
Regras: CADA variante deve ter 3-10 palavras. NUNCA repita a query original. NUNCA invente fatos. Se a query for técnica demais para parafrasear (ex: "SQLITE_BUSY"), paráfrase explica o termo em PT-BR.
|
|
22
|
+
|
|
23
|
+
Query original:
|
|
24
|
+
`;
|
|
25
|
+
/**
|
|
26
|
+
* Lê config `expansion_enabled` da tabela meta. Default = true (plano Fase 1.6).
|
|
27
|
+
* Toggle sem redeploy: UPDATE meta SET value='false' WHERE key='expansion_enabled';
|
|
28
|
+
*/
|
|
29
|
+
export function isExpansionEnabled() {
|
|
30
|
+
try {
|
|
31
|
+
const db = getDb();
|
|
32
|
+
const row = db.prepare("SELECT value FROM meta WHERE key = 'expansion_enabled'").get();
|
|
33
|
+
if (!row)
|
|
34
|
+
return true; // default on
|
|
35
|
+
return row.value !== "false" && row.value !== "0";
|
|
36
|
+
}
|
|
37
|
+
catch {
|
|
38
|
+
return true;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
export async function expandQuery(query) {
|
|
42
|
+
const trimmed = query.trim();
|
|
43
|
+
const wordCount = trimmed.split(/\s+/).filter(Boolean).length;
|
|
44
|
+
if (wordCount < 3) {
|
|
45
|
+
return { variants: [trimmed], skipped: true, reason: "too_short" };
|
|
46
|
+
}
|
|
47
|
+
if (!isExpansionEnabled()) {
|
|
48
|
+
return { variants: [trimmed], skipped: true, reason: "disabled" };
|
|
49
|
+
}
|
|
50
|
+
if (!GEMINI_API_KEY) {
|
|
51
|
+
return { variants: [trimmed], skipped: true, reason: "no_api_key" };
|
|
52
|
+
}
|
|
53
|
+
try {
|
|
54
|
+
const controller = new AbortController();
|
|
55
|
+
const timer = setTimeout(() => controller.abort(), TIMEOUT_MS);
|
|
56
|
+
const url = `${API_BASE}/models/${GEMINI_MODEL}:generateContent?key=${GEMINI_API_KEY}`;
|
|
57
|
+
const resp = await fetch(url, {
|
|
58
|
+
method: "POST",
|
|
59
|
+
headers: { "Content-Type": "application/json" },
|
|
60
|
+
signal: controller.signal,
|
|
61
|
+
body: JSON.stringify({
|
|
62
|
+
contents: [{ parts: [{ text: EXPANSION_PROMPT + trimmed }] }],
|
|
63
|
+
generationConfig: {
|
|
64
|
+
responseMimeType: "application/json",
|
|
65
|
+
responseSchema: {
|
|
66
|
+
type: "OBJECT",
|
|
67
|
+
properties: {
|
|
68
|
+
technical: { type: "STRING" },
|
|
69
|
+
paraphrase: { type: "STRING" },
|
|
70
|
+
},
|
|
71
|
+
required: ["technical", "paraphrase"],
|
|
72
|
+
},
|
|
73
|
+
temperature: 0.2,
|
|
74
|
+
maxOutputTokens: 256,
|
|
75
|
+
thinkingConfig: { thinkingBudget: 0 },
|
|
76
|
+
},
|
|
77
|
+
}),
|
|
78
|
+
}).finally(() => clearTimeout(timer));
|
|
79
|
+
if (!resp.ok) {
|
|
80
|
+
return { variants: [trimmed], skipped: true, reason: "gemini_failed" };
|
|
81
|
+
}
|
|
82
|
+
const data = await resp.json();
|
|
83
|
+
const raw = data.candidates?.[0]?.content?.parts?.[0]?.text;
|
|
84
|
+
if (!raw)
|
|
85
|
+
return { variants: [trimmed], skipped: true, reason: "gemini_failed" };
|
|
86
|
+
const parsed = JSON.parse(raw);
|
|
87
|
+
const v1 = (parsed.technical || "").trim();
|
|
88
|
+
const v2 = (parsed.paraphrase || "").trim();
|
|
89
|
+
const variants = [trimmed];
|
|
90
|
+
if (v1 && v1.toLowerCase() !== trimmed.toLowerCase() && v1.split(/\s+/).length >= 2)
|
|
91
|
+
variants.push(v1);
|
|
92
|
+
if (v2 && v2.toLowerCase() !== trimmed.toLowerCase() && v2.toLowerCase() !== v1.toLowerCase() && v2.split(/\s+/).length >= 2)
|
|
93
|
+
variants.push(v2);
|
|
94
|
+
return { variants, skipped: variants.length === 1, reason: variants.length === 1 ? "gemini_failed" : undefined };
|
|
95
|
+
}
|
|
96
|
+
catch {
|
|
97
|
+
return { variants: [trimmed], skipped: true, reason: "gemini_failed" };
|
|
98
|
+
}
|
|
99
|
+
}
|