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/reindex.js
ADDED
|
@@ -0,0 +1,293 @@
|
|
|
1
|
+
// reindex.ts — UPSERT-based reindex (emergency fix 2026-05-23)
|
|
2
|
+
//
|
|
3
|
+
// 🚨 INCIDENT HISTORY (3 occurrences):
|
|
4
|
+
// - 2026-04-25: end-of-day cron reindex wiped section/retention metadata of 183 entities.
|
|
5
|
+
// Patched by switching cron to `consolidate`. Reindex CODE itself still buggy.
|
|
6
|
+
// - 2026-05-19: eval ingest cruzou pro main DB (~5828 chunks lost). PR #145 4-layer guard.
|
|
7
|
+
// - 2026-05-23 23:17 BRT: nightly reindex SOBRESCREVEU chunks. Recovery via snapshot
|
|
8
|
+
// atlas in /root/backups/nox-mem-incident-20260523-2317/ (69032 chunks).
|
|
9
|
+
//
|
|
10
|
+
// ROOT CAUSE (3rd incident):
|
|
11
|
+
// Pre-fix flow was DESTRUCTIVE-THEN-REBUILD:
|
|
12
|
+
// 1. SELECT access metadata into in-memory Map (snapshot)
|
|
13
|
+
// 2. `DELETE FROM chunks` <- IRREVERSIBLE in-band
|
|
14
|
+
// 3. For each file: routeIngest (re-INSERT)
|
|
15
|
+
// 4. UPDATE chunks SET tier=... (restore from Map by prefix match)
|
|
16
|
+
//
|
|
17
|
+
// Failure modes:
|
|
18
|
+
// a) Gemini API quota / network failure mid-ingest -> partial DB
|
|
19
|
+
// b) Single bad file throw -> caught per-file but no resume
|
|
20
|
+
// c) Map key collision (chunk_text prefix 80 chars) -> restore mis-attributes
|
|
21
|
+
// d) sqlite-vec trigger failure -> DELETE itself fails (fixed 2026-05-21)
|
|
22
|
+
// e) Concurrent watcher write between DELETE and routeIngest -> race
|
|
23
|
+
//
|
|
24
|
+
// FIX — 4 DEFENSE LAYERS:
|
|
25
|
+
//
|
|
26
|
+
// Layer 1 (UPSERT): replace destructive DELETE+INSERT with content-addressed UPSERT.
|
|
27
|
+
// New chunks added, existing chunks preserved (no metadata loss),
|
|
28
|
+
// orphaned chunks (file deleted on disk) marked tombstone for review.
|
|
29
|
+
// Layer 2 (Audit): wrap entire flow in withOpAudit('reindex', ...) - already present,
|
|
30
|
+
// kept for snapshot-pre-op + audit log.
|
|
31
|
+
// Layer 3 (Dry-run): expand --dry-run preview with row-count delta projection.
|
|
32
|
+
// Layer 4 (Invariant): post-reindex sanity check: row_count >= MIN(pre, projected) * 0.90
|
|
33
|
+
// (allow up to 10% legitimate dedup; abort + rollback if more).
|
|
34
|
+
// Throws OnWipeDetected so withOpAudit failure path runs and
|
|
35
|
+
// operator can restore via safeRestore().
|
|
36
|
+
import { getDb } from "./db.js";
|
|
37
|
+
import { withOpAudit } from "./lib/op-audit.js";
|
|
38
|
+
import { routeIngest } from "./lib/ingest-router.js";
|
|
39
|
+
import { readdirSync } from "fs";
|
|
40
|
+
import { createHash } from "crypto";
|
|
41
|
+
import { join, resolve } from "path";
|
|
42
|
+
import { ReindexWipeDetectedError, MIN_RETENTION_RATIO } from "./reindex-errors.js";
|
|
43
|
+
export { ReindexWipeDetectedError } from "./reindex-errors.js";
|
|
44
|
+
const WORKSPACE = process.env.OPENCLAW_WORKSPACE || "/root/.openclaw/workspace";
|
|
45
|
+
// Layer 4: tunable safety thresholds (env-overridable for emergency operations).
|
|
46
|
+
// MIN_RETENTION_RATIO imported from reindex-errors.ts (single source of truth).
|
|
47
|
+
const ALLOW_WIPE = process.env.NOX_REINDEX_ALLOW_WIPE === "1";
|
|
48
|
+
function findFiles(dir, extensions) {
|
|
49
|
+
const results = [];
|
|
50
|
+
try {
|
|
51
|
+
const entries = readdirSync(dir, { withFileTypes: true });
|
|
52
|
+
for (const entry of entries) {
|
|
53
|
+
const fullPath = join(dir, entry.name);
|
|
54
|
+
if (entry.isDirectory() && entry.name !== "node_modules" && entry.name !== ".git") {
|
|
55
|
+
results.push(...findFiles(fullPath, extensions));
|
|
56
|
+
}
|
|
57
|
+
else if (entry.isFile() && extensions.some((ext) => entry.name.endsWith(ext))) {
|
|
58
|
+
results.push(fullPath);
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
catch {
|
|
63
|
+
/* dir may not exist; e.g. shared/ absent on fresh deploy */
|
|
64
|
+
}
|
|
65
|
+
return results;
|
|
66
|
+
}
|
|
67
|
+
// Content-addressed fingerprint for UPSERT identity.
|
|
68
|
+
// (source_file, sha256(chunk_text)) is stable across reindex runs as long as the
|
|
69
|
+
// chunker output is deterministic for the same input file. The schema's autoincrement
|
|
70
|
+
// `id` is NOT suitable as upsert key because routeIngest produces fresh ids on each call.
|
|
71
|
+
function chunkFingerprint(sourceFile, chunkText) {
|
|
72
|
+
return createHash("sha256").update(sourceFile).update("\0").update(chunkText).digest("hex").substring(0, 32);
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* Core reindex implementation — UPSERT-based, non-destructive.
|
|
76
|
+
*
|
|
77
|
+
* Strategy:
|
|
78
|
+
* 1. Snapshot existing (source_file, chunk_text) -> {id, tier, access_count, importance, last_accessed_at, section, retention_days, source_type, is_compiled, pain}
|
|
79
|
+
* 2. Walk files, route via routeIngest into ISOLATED staging set (in-memory accumulator).
|
|
80
|
+
* NOTE: routeIngest currently writes directly to DB. We pre-mark new ingests with
|
|
81
|
+
* `__reindex_stage` chunk_type prefix and finalize via UPDATE.
|
|
82
|
+
* Until routeIngest supports a staging mode (follow-up PR), we use the safer pattern:
|
|
83
|
+
* preserve old chunks until ALL new ingests succeed, then UPSERT-merge.
|
|
84
|
+
* 3. For each file processed by routeIngest, the NEW chunks have fresh ids. Match against
|
|
85
|
+
* old chunks via content fingerprint and copy access metadata over.
|
|
86
|
+
* 4. After ALL files succeed: DELETE old chunks that did NOT survive the fingerprint match
|
|
87
|
+
* (i.e. content actually changed/removed). This is the SOLE destructive op, and only
|
|
88
|
+
* runs AFTER all ingests completed without throwing.
|
|
89
|
+
*/
|
|
90
|
+
async function _reindexImpl() {
|
|
91
|
+
const db = getDb();
|
|
92
|
+
// Defensive: load sqlite-vec BEFORE any chunk mutation (2026-05-21 fix preserved).
|
|
93
|
+
// Dynamic import via Function() avoids TS2307 in the staged-dir build (no sqlite-vec
|
|
94
|
+
// dep here — real module installed on VPS via package.json at deploy target).
|
|
95
|
+
try {
|
|
96
|
+
const dynImport = new Function("m", "return import(m)");
|
|
97
|
+
const sqliteVec = await dynImport("sqlite-vec");
|
|
98
|
+
sqliteVec.load(db);
|
|
99
|
+
}
|
|
100
|
+
catch (err) {
|
|
101
|
+
console.error(`[reindex] WARN: failed to load sqlite-vec extension: ${err}`);
|
|
102
|
+
throw new Error("sqlite-vec module not available; cannot safely reindex (vec_chunks trigger would fail)");
|
|
103
|
+
}
|
|
104
|
+
// ── Phase 1: snapshot pre-state ────────────────────────────────────────────
|
|
105
|
+
const preCount = db.prepare("SELECT COUNT(*) AS c FROM chunks").get().c;
|
|
106
|
+
// Tolerant select: schema may lack some columns on older DBs (pre-v10).
|
|
107
|
+
// `SELECT *` would force coupling; instead probe column existence.
|
|
108
|
+
const cols = new Set(db.prepare("PRAGMA table_info(chunks)").all().map((r) => r.name));
|
|
109
|
+
const has = (c) => cols.has(c);
|
|
110
|
+
const selectCols = [
|
|
111
|
+
"id",
|
|
112
|
+
"source_file",
|
|
113
|
+
"chunk_text",
|
|
114
|
+
has("tier") ? "tier" : "NULL AS tier",
|
|
115
|
+
has("access_count") ? "access_count" : "NULL AS access_count",
|
|
116
|
+
has("importance") ? "importance" : "NULL AS importance",
|
|
117
|
+
has("last_accessed_at") ? "last_accessed_at" : "NULL AS last_accessed_at",
|
|
118
|
+
has("section") ? "section" : "NULL AS section",
|
|
119
|
+
has("section_boost") ? "section_boost" : "NULL AS section_boost",
|
|
120
|
+
has("retention_days") ? "retention_days" : "NULL AS retention_days",
|
|
121
|
+
has("pain") ? "pain" : "NULL AS pain",
|
|
122
|
+
has("source_type") ? "source_type" : "NULL AS source_type",
|
|
123
|
+
has("is_compiled") ? "is_compiled" : "NULL AS is_compiled",
|
|
124
|
+
].join(", ");
|
|
125
|
+
const oldChunks = db.prepare(`SELECT ${selectCols} FROM chunks`).all();
|
|
126
|
+
// Build content fingerprint -> oldChunk index.
|
|
127
|
+
const oldByFingerprint = new Map();
|
|
128
|
+
for (const row of oldChunks) {
|
|
129
|
+
oldByFingerprint.set(chunkFingerprint(row.source_file, row.chunk_text), row);
|
|
130
|
+
}
|
|
131
|
+
console.log(`[reindex] Phase 1: snapshotted ${oldChunks.length} existing chunks`);
|
|
132
|
+
// ── Phase 2: ingest new chunks into a staging set ──────────────────────────
|
|
133
|
+
// Strategy: do NOT delete first. Let routeIngest INSERT new chunks alongside old ones.
|
|
134
|
+
// After all files succeed, we merge: keep new chunks (overlap by fingerprint inherits old metadata),
|
|
135
|
+
// delete pure-old chunks (no matching fingerprint = content removed).
|
|
136
|
+
//
|
|
137
|
+
// To distinguish "old" vs "new" rows we capture max(id) before any ingest.
|
|
138
|
+
const maxIdBefore = db.prepare("SELECT COALESCE(MAX(id), 0) AS m FROM chunks").get().m;
|
|
139
|
+
const memoryFiles = findFiles(resolve(WORKSPACE, "memory"), [".md", ".json"]);
|
|
140
|
+
const sharedFiles = findFiles(resolve(WORKSPACE, "shared"), [".md"]);
|
|
141
|
+
const allFiles = [...memoryFiles, ...sharedFiles];
|
|
142
|
+
let totalChunksIngested = 0;
|
|
143
|
+
const fileErrors = [];
|
|
144
|
+
for (const file of allFiles) {
|
|
145
|
+
try {
|
|
146
|
+
// skipDelete=true: do NOT let routeIngest call its own DELETE FROM chunks WHERE source_file=?
|
|
147
|
+
// We handle merge globally after the loop.
|
|
148
|
+
const result = await routeIngest(file, { externalDb: db, skipDelete: true });
|
|
149
|
+
totalChunksIngested += result.chunks;
|
|
150
|
+
// Verbose log gated behind env to avoid blasting nightly cron output.
|
|
151
|
+
if (process.env.NOX_REINDEX_VERBOSE === "1") {
|
|
152
|
+
console.log(`[reindex] ${file}: ${result.chunks} chunks`);
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
catch (err) {
|
|
156
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
157
|
+
fileErrors.push({ file, error: msg });
|
|
158
|
+
console.error(`[reindex] ERROR ingesting ${file}: ${msg}`);
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
const newChunks = db
|
|
162
|
+
.prepare("SELECT id, source_file, chunk_text FROM chunks WHERE id > ?")
|
|
163
|
+
.all(maxIdBefore);
|
|
164
|
+
// For each new chunk, look up by fingerprint to inherit access metadata.
|
|
165
|
+
const updateNewMetadata = db.prepare(`
|
|
166
|
+
UPDATE chunks
|
|
167
|
+
SET tier = COALESCE(?, tier),
|
|
168
|
+
access_count = COALESCE(?, access_count),
|
|
169
|
+
importance = COALESCE(?, importance),
|
|
170
|
+
last_accessed_at = COALESCE(?, last_accessed_at)
|
|
171
|
+
WHERE id = ?
|
|
172
|
+
`);
|
|
173
|
+
const seenOldIds = new Set();
|
|
174
|
+
let inheritedCount = 0;
|
|
175
|
+
const mergeTxn = db.transaction(() => {
|
|
176
|
+
for (const nc of newChunks) {
|
|
177
|
+
const fp = chunkFingerprint(nc.source_file, nc.chunk_text);
|
|
178
|
+
const oldRow = oldByFingerprint.get(fp);
|
|
179
|
+
if (oldRow) {
|
|
180
|
+
seenOldIds.add(oldRow.id);
|
|
181
|
+
updateNewMetadata.run(oldRow.tier, oldRow.access_count, oldRow.importance, oldRow.last_accessed_at, nc.id);
|
|
182
|
+
inheritedCount++;
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
});
|
|
186
|
+
mergeTxn();
|
|
187
|
+
// ── Phase 4: delete pure-old chunks (no fingerprint match in new set) ──────
|
|
188
|
+
// This is the SOLE destructive op. Runs AFTER all ingests succeeded.
|
|
189
|
+
// If fileErrors is non-empty AND would cause a wipe, the Layer 4 invariant
|
|
190
|
+
// check below will throw and roll back.
|
|
191
|
+
const orphanIds = oldChunks.map((r) => r.id).filter((id) => !seenOldIds.has(id));
|
|
192
|
+
let orphanedDeleted = 0;
|
|
193
|
+
if (orphanIds.length > 0) {
|
|
194
|
+
const deleteOrphan = db.prepare("DELETE FROM chunks WHERE id = ?");
|
|
195
|
+
const deleteOrphansTxn = db.transaction(() => {
|
|
196
|
+
for (const id of orphanIds) {
|
|
197
|
+
const r = deleteOrphan.run(id);
|
|
198
|
+
if (r.changes > 0)
|
|
199
|
+
orphanedDeleted++;
|
|
200
|
+
}
|
|
201
|
+
});
|
|
202
|
+
deleteOrphansTxn();
|
|
203
|
+
}
|
|
204
|
+
// Re-rebuild FTS index (cheap, idempotent — content= table optimization).
|
|
205
|
+
db.exec("INSERT INTO chunks_fts(chunks_fts) VALUES('rebuild')");
|
|
206
|
+
// ── Phase 5: core tier retention_days = NULL contract (preserved) ───────────
|
|
207
|
+
if (cols.has("retention_days") && cols.has("tier")) {
|
|
208
|
+
db.exec("UPDATE chunks SET retention_days = NULL WHERE tier = 'core'");
|
|
209
|
+
}
|
|
210
|
+
const postCount = db.prepare("SELECT COUNT(*) AS c FROM chunks").get().c;
|
|
211
|
+
// ── Layer 4: invariant check ────────────────────────────────────────────────
|
|
212
|
+
// Compute retention ratio. If we lost more than (1 - MIN_RETENTION_RATIO) of chunks,
|
|
213
|
+
// assume wipe-class failure and throw — withOpAudit failure path will preserve snapshot.
|
|
214
|
+
const ratio = preCount === 0 ? 1 : postCount / preCount;
|
|
215
|
+
if (preCount > 0 && ratio < MIN_RETENTION_RATIO && !ALLOW_WIPE) {
|
|
216
|
+
throw new ReindexWipeDetectedError(preCount, postCount, MIN_RETENTION_RATIO);
|
|
217
|
+
}
|
|
218
|
+
console.log(`[reindex] DONE files=${allFiles.length} pre=${preCount} post=${postCount} ` +
|
|
219
|
+
`ratio=${(ratio * 100).toFixed(1)}% inherited=${inheritedCount} ` +
|
|
220
|
+
`orphans-deleted=${orphanedDeleted} ingest-errors=${fileErrors.length}`);
|
|
221
|
+
if (fileErrors.length > 0) {
|
|
222
|
+
console.error(`[reindex] ${fileErrors.length} files failed; first 5:`);
|
|
223
|
+
for (const fe of fileErrors.slice(0, 5))
|
|
224
|
+
console.error(` - ${fe.file}: ${fe.error}`);
|
|
225
|
+
}
|
|
226
|
+
return {
|
|
227
|
+
files: allFiles.length,
|
|
228
|
+
chunks: totalChunksIngested,
|
|
229
|
+
preCount,
|
|
230
|
+
postCount,
|
|
231
|
+
upserted: inheritedCount,
|
|
232
|
+
inserted: newChunks.length - inheritedCount,
|
|
233
|
+
preserved: inheritedCount,
|
|
234
|
+
orphaned: orphanedDeleted,
|
|
235
|
+
};
|
|
236
|
+
}
|
|
237
|
+
export async function reindex(opts) {
|
|
238
|
+
if (opts?.dryRun) {
|
|
239
|
+
const db = getDb();
|
|
240
|
+
const memoryFiles = findFiles(resolve(WORKSPACE, "memory"), [".md", ".json"]);
|
|
241
|
+
const sharedFiles = findFiles(resolve(WORKSPACE, "shared"), [".md"]);
|
|
242
|
+
const allFiles = [...memoryFiles, ...sharedFiles];
|
|
243
|
+
const currentChunks = db.prepare("SELECT COUNT(*) AS c FROM chunks").get().c;
|
|
244
|
+
const entityFiles = allFiles.filter((f) => f.includes("/memory/entities/")).length;
|
|
245
|
+
const macDocsFiles = allFiles.filter((f) => f.includes("/memory/mac-docs/")).length;
|
|
246
|
+
const sharedCount = sharedFiles.length;
|
|
247
|
+
const otherMemory = memoryFiles.length - entityFiles - macDocsFiles;
|
|
248
|
+
console.log(JSON.stringify({
|
|
249
|
+
dryRun: true,
|
|
250
|
+
operation: "reindex",
|
|
251
|
+
mode: "UPSERT (emergency fix 2026-05-23)",
|
|
252
|
+
wouldUpsert: {
|
|
253
|
+
currentChunks,
|
|
254
|
+
note: "existing chunks preserved by content-fingerprint; metadata inherited",
|
|
255
|
+
},
|
|
256
|
+
wouldProcess: {
|
|
257
|
+
totalFiles: allFiles.length,
|
|
258
|
+
breakdown: {
|
|
259
|
+
entityFiles,
|
|
260
|
+
macDocsFiles,
|
|
261
|
+
sharedFiles: sharedCount,
|
|
262
|
+
otherMemoryFiles: otherMemory,
|
|
263
|
+
},
|
|
264
|
+
},
|
|
265
|
+
protected: {
|
|
266
|
+
snapshotPreOp: "YES via withOpAudit",
|
|
267
|
+
coreTierRetention: "YES",
|
|
268
|
+
entityRouting: "YES via routeIngest",
|
|
269
|
+
wipeGuard: `YES via Layer-4 invariant (min ratio ${MIN_RETENTION_RATIO})`,
|
|
270
|
+
upsert: "YES via content-fingerprint match (no DELETE FROM chunks)",
|
|
271
|
+
},
|
|
272
|
+
estimatedDuration: "2-5 min depending on Gemini API latency",
|
|
273
|
+
}, null, 2));
|
|
274
|
+
return { files: allFiles.length, chunks: currentChunks, dryRun: true };
|
|
275
|
+
}
|
|
276
|
+
// NOTE: withOpAudit(opName, fn) — 2 args, matches prod src/lib/op-audit.ts.
|
|
277
|
+
// db_source context (was "main") folded into notes for audit row visibility.
|
|
278
|
+
return withOpAudit("reindex", async () => {
|
|
279
|
+
const r = await _reindexImpl();
|
|
280
|
+
return {
|
|
281
|
+
files: r.files,
|
|
282
|
+
chunks: r.chunks,
|
|
283
|
+
affected_rows: r.upserted + r.inserted,
|
|
284
|
+
notes: `db_source=main | ${r.files} files reindexed | pre=${r.preCount} post=${r.postCount} ` +
|
|
285
|
+
`inherited=${r.upserted} new=${r.inserted} orphans=${r.orphaned}`,
|
|
286
|
+
preCount: r.preCount,
|
|
287
|
+
postCount: r.postCount,
|
|
288
|
+
upserted: r.upserted,
|
|
289
|
+
inserted: r.inserted,
|
|
290
|
+
orphaned: r.orphaned,
|
|
291
|
+
};
|
|
292
|
+
});
|
|
293
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
export type RetentionDays = number | null;
|
|
2
|
+
/**
|
|
3
|
+
* RETENTION_BY_TYPE — mapping canônico chunk_type → retention_days.
|
|
4
|
+
* Deve ficar em sync com o UPDATE no migrateToV8 (db.ts).
|
|
5
|
+
*
|
|
6
|
+
* Derivado do paper "Claude Memory Setup" + calibração com os 2106 chunks
|
|
7
|
+
* reais do nox-mem (distribuição em 2026-04-23):
|
|
8
|
+
* team=961, daily=630, other=278, decision=138, lesson=45,
|
|
9
|
+
* feedback=17, project=15, pending=9, digest=7, person=6
|
|
10
|
+
*/
|
|
11
|
+
export declare const RETENTION_BY_TYPE: Record<string, RetentionDays>;
|
|
12
|
+
export declare const DEFAULT_RETENTION_DAYS = 90;
|
|
13
|
+
/**
|
|
14
|
+
* Resolve retention pro chunk baseado no tipo.
|
|
15
|
+
* Retorna null (never-decay) ou número de dias.
|
|
16
|
+
*/
|
|
17
|
+
export declare function getRetentionForType(chunkType: string): RetentionDays;
|
|
18
|
+
/**
|
|
19
|
+
* Detecta override de retention em HTML comment no markdown fonte.
|
|
20
|
+
* Formatos aceitos:
|
|
21
|
+
* <!-- retention: never -->
|
|
22
|
+
* <!-- retention: 365 -->
|
|
23
|
+
* <!-- retention: 30 days -->
|
|
24
|
+
*
|
|
25
|
+
* Retorna:
|
|
26
|
+
* { found: true, value: null } — explicit never-decay
|
|
27
|
+
* { found: true, value: <days> } — explicit days
|
|
28
|
+
* { found: false } — no override (caller uses chunk_type default)
|
|
29
|
+
*/
|
|
30
|
+
export declare function parseRetentionOverride(source: string): {
|
|
31
|
+
found: true;
|
|
32
|
+
value: RetentionDays;
|
|
33
|
+
} | {
|
|
34
|
+
found: false;
|
|
35
|
+
};
|
|
36
|
+
/**
|
|
37
|
+
* Determina retention_days final pro chunk sendo ingested.
|
|
38
|
+
* Precedência: override HTML comment > chunk_type default.
|
|
39
|
+
*/
|
|
40
|
+
export declare function resolveRetention(chunkType: string, sourceContent?: string): RetentionDays;
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
// Fase 1.7b-a — Typed Source Retention Matrix
|
|
2
|
+
// Central source of truth para políticas de retenção por chunk_type.
|
|
3
|
+
// Alinhado com migration v8 em db.ts.
|
|
4
|
+
//
|
|
5
|
+
// Regra de projeto: NULL = never auto-decay (user-declared preservation).
|
|
6
|
+
// Valores em dias desde created_at. Core tier ignora retention (sempre preservado).
|
|
7
|
+
/**
|
|
8
|
+
* RETENTION_BY_TYPE — mapping canônico chunk_type → retention_days.
|
|
9
|
+
* Deve ficar em sync com o UPDATE no migrateToV8 (db.ts).
|
|
10
|
+
*
|
|
11
|
+
* Derivado do paper "Claude Memory Setup" + calibração com os 2106 chunks
|
|
12
|
+
* reais do nox-mem (distribuição em 2026-04-23):
|
|
13
|
+
* team=961, daily=630, other=278, decision=138, lesson=45,
|
|
14
|
+
* feedback=17, project=15, pending=9, digest=7, person=6
|
|
15
|
+
*/
|
|
16
|
+
export const RETENTION_BY_TYPE = {
|
|
17
|
+
feedback: null, // never — user feedback é evidência preservada
|
|
18
|
+
person: null, // never — ontology estável de pessoas
|
|
19
|
+
lesson: 180, // mistakes caros merecem 6 meses
|
|
20
|
+
decision: 365, // decisões têm lifespan longo
|
|
21
|
+
project: 365, // projetos duram
|
|
22
|
+
daily: 90, // daily session notes
|
|
23
|
+
team: 120, // team state evolui
|
|
24
|
+
digest: 180, // digest consolida várias sessões
|
|
25
|
+
pending: 30, // se 30d sem resolver, escala pra review
|
|
26
|
+
graph_node: 60, // repos externos indexados via graphify — research-like, decay rápido
|
|
27
|
+
other: 90, // default
|
|
28
|
+
};
|
|
29
|
+
export const DEFAULT_RETENTION_DAYS = 90;
|
|
30
|
+
/**
|
|
31
|
+
* Resolve retention pro chunk baseado no tipo.
|
|
32
|
+
* Retorna null (never-decay) ou número de dias.
|
|
33
|
+
*/
|
|
34
|
+
export function getRetentionForType(chunkType) {
|
|
35
|
+
if (chunkType in RETENTION_BY_TYPE)
|
|
36
|
+
return RETENTION_BY_TYPE[chunkType];
|
|
37
|
+
return DEFAULT_RETENTION_DAYS;
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Detecta override de retention em HTML comment no markdown fonte.
|
|
41
|
+
* Formatos aceitos:
|
|
42
|
+
* <!-- retention: never -->
|
|
43
|
+
* <!-- retention: 365 -->
|
|
44
|
+
* <!-- retention: 30 days -->
|
|
45
|
+
*
|
|
46
|
+
* Retorna:
|
|
47
|
+
* { found: true, value: null } — explicit never-decay
|
|
48
|
+
* { found: true, value: <days> } — explicit days
|
|
49
|
+
* { found: false } — no override (caller uses chunk_type default)
|
|
50
|
+
*/
|
|
51
|
+
export function parseRetentionOverride(source) {
|
|
52
|
+
// Case-insensitive, tolerant to whitespace and CRLF line endings.
|
|
53
|
+
// Multiline anchors: comment MUST be alone on its line (frontmatter-style).
|
|
54
|
+
// Prevents false matches when docs describe the syntax in prose.
|
|
55
|
+
// Only scans the first 30 lines (frontmatter window) to avoid scanning long files.
|
|
56
|
+
const normalized = source.replace(/\r\n/g, "\n"); // CRLF → LF for Windows files
|
|
57
|
+
const head = normalized.split("\n").slice(0, 30).join("\n");
|
|
58
|
+
const re = /^[ \t]*<!--\s*retention:\s*([^-\s][^-]*?)\s*-->[ \t]*$/im;
|
|
59
|
+
const m = head.match(re);
|
|
60
|
+
if (!m)
|
|
61
|
+
return { found: false };
|
|
62
|
+
const raw = m[1].trim().toLowerCase();
|
|
63
|
+
if (raw === "never" || raw === "null" || raw === "infinite") {
|
|
64
|
+
return { found: true, value: null };
|
|
65
|
+
}
|
|
66
|
+
// Extract leading integer (handles "30", "30 days", "30d")
|
|
67
|
+
const numMatch = raw.match(/^(\d+)/);
|
|
68
|
+
if (!numMatch)
|
|
69
|
+
return { found: false };
|
|
70
|
+
const days = parseInt(numMatch[1], 10);
|
|
71
|
+
if (!Number.isFinite(days) || days <= 0 || days > 36500)
|
|
72
|
+
return { found: false };
|
|
73
|
+
return { found: true, value: days };
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* Determina retention_days final pro chunk sendo ingested.
|
|
77
|
+
* Precedência: override HTML comment > chunk_type default.
|
|
78
|
+
*/
|
|
79
|
+
export function resolveRetention(chunkType, sourceContent) {
|
|
80
|
+
if (sourceContent) {
|
|
81
|
+
const override = parseRetentionOverride(sourceContent);
|
|
82
|
+
if (override.found)
|
|
83
|
+
return override.value;
|
|
84
|
+
}
|
|
85
|
+
return getRetentionForType(chunkType);
|
|
86
|
+
}
|
|
@@ -0,0 +1,85 @@
|
|
|
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 type SalienceMode = "shadow" | "active" | "off";
|
|
29
|
+
export declare function getSalienceMode(): SalienceMode;
|
|
30
|
+
export declare function resolveRetentionDays(retention_days: number | null | undefined, chunk_type: string | null | undefined): number;
|
|
31
|
+
export declare function recencyComponent(source_date: string | null | undefined, last_accessed_at: string | null | undefined, retention_days: number, nowMs?: number): number;
|
|
32
|
+
export declare function importanceComponent(chunk_type: string | null | undefined, explicitImportance?: number | null): number;
|
|
33
|
+
export declare function painComponent(pain: number | null | undefined): number;
|
|
34
|
+
export declare function inferPain(chunk_type: string | null | undefined, content: string | null | undefined): number;
|
|
35
|
+
export declare function inferImportance(chunk_type: string | null | undefined): number;
|
|
36
|
+
export interface SalienceInput {
|
|
37
|
+
chunk_type?: string | null;
|
|
38
|
+
source_type?: string | null;
|
|
39
|
+
tier?: string | null;
|
|
40
|
+
pain?: number | null;
|
|
41
|
+
importance?: number | null;
|
|
42
|
+
retention_days?: number | null;
|
|
43
|
+
source_date?: string | null;
|
|
44
|
+
created_at?: string | null;
|
|
45
|
+
last_accessed_at?: string | null;
|
|
46
|
+
/** Binary used/unused signal (introduced 2026-05-19 salience-additive refactor) */
|
|
47
|
+
access_count?: number | null;
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Access-count component. Maps 0 → 0, log-saturating toward 1.0 at ~1000 accesses.
|
|
51
|
+
*/
|
|
52
|
+
export declare function accessCountComponent(access_count: number | null | undefined): number;
|
|
53
|
+
/**
|
|
54
|
+
* Pure salience computation. Returns a number in [0, 1].
|
|
55
|
+
* Does NOT consult NOX_SALIENCE_MODE — that gating lives in the caller (search.ts),
|
|
56
|
+
* so this function stays pure and testable.
|
|
57
|
+
*
|
|
58
|
+
* v2 (2026-05-19): additive evidence-weighted formula.
|
|
59
|
+
* See docs/audits/2026-05-19-salience-distribution-audit.md for rationale.
|
|
60
|
+
* Previous multiplicative formula is preserved at `calculateSalienceLegacy`
|
|
61
|
+
* for ablation comparison and shadow-discipline regression detection.
|
|
62
|
+
*/
|
|
63
|
+
export declare function calculateSalience(chunk: SalienceInput, nowMs?: number): number;
|
|
64
|
+
/**
|
|
65
|
+
* Legacy multiplicative formula. Retained for ablation comparison only.
|
|
66
|
+
* DO NOT USE in production scoring paths — proven to concentrate 99.7%
|
|
67
|
+
* of chunks in a narrow dead-range (G4 ablation 2026-05-19).
|
|
68
|
+
*/
|
|
69
|
+
export declare function calculateSalienceLegacy(chunk: SalienceInput, nowMs?: number): number;
|
|
70
|
+
/**
|
|
71
|
+
* Mirror of `src/lib/salience.ts:computeSalience` on the VPS — kept as an alias
|
|
72
|
+
* so existing call-sites (e.g. /api/health.salience) keep working when the
|
|
73
|
+
* staged patch lands on top of the VPS module graph.
|
|
74
|
+
*/
|
|
75
|
+
export declare const computeSalience: typeof calculateSalience;
|
|
76
|
+
/**
|
|
77
|
+
* Classify salience score into a tier action (for /api/health.sectionDistribution).
|
|
78
|
+
* Reconstructed from tier-manager.ts usage 2026-05-19 hotfix — pre-A `classifySalience`
|
|
79
|
+
* was not preserved in PR #148 salience.ts rewrite; this restores backwards-compat.
|
|
80
|
+
* promote: score >= 0.7 (candidate for tier promotion if not core)
|
|
81
|
+
* retain: 0.4 <= score < 0.7
|
|
82
|
+
* review: 0.15 <= score < 0.4
|
|
83
|
+
* archive: score < 0.15
|
|
84
|
+
*/
|
|
85
|
+
export declare function classifySalience(score: number): "promote" | "retain" | "review" | "archive";
|