nox-mem 3.1.1 → 3.2.1
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/README.md +24 -16
- package/dist/__tests__/brief-diversity.test.js +266 -0
- package/dist/__tests__/brief.test.js +287 -0
- package/dist/__tests__/churn.test.js +66 -0
- package/dist/__tests__/edge-typing.test.js +99 -0
- package/dist/__tests__/ingest-event.test.js +151 -0
- package/dist/__tests__/op-audit-e2e.test.js +130 -0
- package/dist/__tests__/pragma-alignment.test.js +123 -0
- package/dist/__tests__/reranker.test.js +326 -0
- package/dist/__tests__/retention.test.js +99 -0
- package/dist/__tests__/search-track-access.test.js +49 -0
- package/dist/__tests__/spo-injection.test.js +172 -0
- package/dist/__tests__/temporal-detector.test.js +103 -0
- package/dist/api/wire-up.js +12 -381
- package/dist/api-server.js +6 -102
- package/dist/crystallize.js +3 -5
- package/dist/db.js +61 -2
- package/dist/embed.js +23 -2
- package/dist/index.js +1 -22
- package/dist/knowledge-graph.js +20 -0
- package/dist/lib/answer/__tests__/e2e-gemini.test.js +229 -0
- package/dist/lib/answer/__tests__/integration-sqlite.test.js +388 -0
- package/dist/lib/answer/__tests__/integration.test.js +347 -0
- package/dist/lib/answer/__tests__/prompt.test.js +117 -0
- package/dist/lib/answer/__tests__/t5-t10.test.js +501 -0
- package/dist/lib/answer/provider.js +29 -4
- package/dist/lib/api/__tests__/safe-error-message.test.js +155 -0
- package/dist/lib/auth/__tests__/localhost-guard.test.js +144 -0
- package/dist/lib/error-sanitizer/__tests__/sanitize.test.js +354 -0
- package/dist/lib/events/__tests__/bus.test.js +208 -0
- package/dist/lib/ingest-router.js +0 -43
- package/dist/lib/op-audit-extension/__tests__/ran-at-guard.test.js +109 -0
- package/dist/lib/regex-extract/__tests__/extractor.test.js +197 -0
- package/dist/lib/regex-extract/__tests__/frontmatter.test.js +75 -0
- package/dist/lib/regex-extract/__tests__/ingest-router-l4.test.js +139 -0
- package/dist/lib/regex-extract/__tests__/production-wire.test.js +177 -0
- package/dist/lib/regex-extract/__tests__/reconcile.test.js +170 -0
- package/dist/lib/regex-extract/__tests__/strip-code.test.js +36 -0
- package/dist/privacy/__tests__/filter.test.js +352 -0
- package/dist/providers/__tests__/conformance-extended.test.js +249 -0
- package/dist/providers/__tests__/conformance.test.js +98 -0
- package/dist/providers/__tests__/cost-cap.test.js +151 -0
- package/dist/providers/__tests__/e2e-real.test.js +79 -0
- package/dist/providers/__tests__/factory.test.js +80 -0
- package/dist/providers/__tests__/fallback.test.js +223 -0
- package/dist/providers/__tests__/gemini.test.js +191 -0
- package/dist/providers/__tests__/health.test.js +128 -0
- package/dist/providers/__tests__/telemetry.test.js +219 -0
- package/dist/reindex.js +2 -2
- package/package.json +3 -4
- package/dist/api/answer.d.ts +0 -116
- package/dist/api/answer.validate-patch.d.ts +0 -72
- package/dist/api/brief-diversity.d.ts +0 -64
- package/dist/api/brief.d.ts +0 -114
- package/dist/api/conflict.d.ts +0 -33
- package/dist/api/conflict.js +0 -143
- package/dist/api/cors.d.ts +0 -73
- package/dist/api/events-stream-limited.d.ts +0 -133
- package/dist/api/events-stream-limited.js +0 -217
- package/dist/api/events-stream.d.ts +0 -53
- package/dist/api/events-stream.js +0 -125
- package/dist/api/export.d.ts +0 -42
- package/dist/api/export.js +0 -85
- package/dist/api/health-confidence-adapter.d.ts +0 -29
- package/dist/api/health-confidence-adapter.js +0 -73
- package/dist/api/health-confidence.d.ts +0 -36
- package/dist/api/health-confidence.js +0 -141
- package/dist/api/hooks.d.ts +0 -50
- package/dist/api/hooks.js +0 -115
- package/dist/api/import.d.ts +0 -38
- package/dist/api/import.js +0 -87
- package/dist/api/ingest-event.d.ts +0 -65
- package/dist/api/mark.d.ts +0 -42
- package/dist/api/mark.js +0 -127
- package/dist/api/server-deps-a2.d.ts +0 -55
- package/dist/api/server-deps-a2.js +0 -138
- package/dist/api/server-deps-l2-l3.d.ts +0 -68
- package/dist/api/server-deps-l2-l3.js +0 -123
- package/dist/api/server-deps-p1.d.ts +0 -84
- package/dist/api/server-deps-p2.d.ts +0 -32
- package/dist/api/server-deps-p2.js +0 -84
- package/dist/api/server-deps-p5.d.ts +0 -66
- package/dist/api/server-deps-p5.js +0 -139
- package/dist/api/viewer-static.d.ts +0 -30
- package/dist/api/viewer-static.js +0 -102
- package/dist/api/wire-up.d.ts +0 -54
- package/dist/api-impact.d.ts +0 -30
- package/dist/api-server.d.ts +0 -2
- package/dist/backfill-fts-anchor.d.ts +0 -15
- package/dist/backfill-source-type.d.ts +0 -20
- package/dist/churn.d.ts +0 -31
- package/dist/cli/answer.d.ts +0 -66
- package/dist/cli/conflict.d.ts +0 -38
- package/dist/cli/conflict.js +0 -282
- package/dist/cli/export.d.ts +0 -51
- package/dist/cli/export.js +0 -280
- package/dist/cli/hooks.d.ts +0 -54
- package/dist/cli/hooks.js +0 -133
- package/dist/cli/import.d.ts +0 -52
- package/dist/cli/import.js +0 -274
- package/dist/cli/mark.d.ts +0 -33
- package/dist/cli/mark.js +0 -130
- package/dist/cli/ocr-batch.d.ts +0 -12
- package/dist/cli/ocr-batch.js +0 -411
- package/dist/cli/snapshot-main.d.ts +0 -30
- package/dist/cli/snapshot-main.js +0 -47
- package/dist/cli/viewer.d.ts +0 -35
- package/dist/cli/viewer.js +0 -71
- package/dist/cli-telemetry.d.ts +0 -36
- package/dist/cli-telemetry.js +0 -150
- package/dist/compact.d.ts +0 -7
- package/dist/consolidate.d.ts +0 -18
- package/dist/consolidation.d.ts +0 -32
- package/dist/cross-agent-v2.d.ts +0 -45
- package/dist/cross-search.d.ts +0 -11
- package/dist/crystallize.d.ts +0 -43
- package/dist/db.d.ts +0 -11
- package/dist/dedup.d.ts +0 -1
- package/dist/detect-changes.d.ts +0 -29
- package/dist/digest.d.ts +0 -1
- package/dist/doctor.d.ts +0 -1
- package/dist/embed.d.ts +0 -57
- package/dist/evals.d.ts +0 -176
- package/dist/evals.js +0 -351
- package/dist/generate-user-profile.d.ts +0 -18
- package/dist/graphify-ingest.d.ts +0 -18
- package/dist/impact.d.ts +0 -39
- package/dist/index.d.ts +0 -2
- package/dist/ingest-entity.d.ts +0 -44
- package/dist/ingest.d.ts +0 -13
- package/dist/kg-llm.d.ts +0 -39
- package/dist/knowledge-graph.d.ts +0 -72
- package/dist/lib/answer/config.d.ts +0 -41
- package/dist/lib/answer/index.d.ts +0 -47
- package/dist/lib/answer/prompt.d.ts +0 -37
- package/dist/lib/answer/provider.d.ts +0 -47
- package/dist/lib/answer/retrieval.d.ts +0 -36
- package/dist/lib/answer/telemetry.d.ts +0 -99
- package/dist/lib/answer/types.d.ts +0 -108
- package/dist/lib/api/error-leak-fix.d.ts +0 -54
- package/dist/lib/api/safe-error-message.d.ts +0 -70
- package/dist/lib/archive/common-passwords.d.ts +0 -37
- package/dist/lib/archive/common-passwords.js +0 -753
- package/dist/lib/archive/encryption.d.ts +0 -81
- package/dist/lib/archive/encryption.js +0 -236
- package/dist/lib/archive/enforce-strength.d.ts +0 -54
- package/dist/lib/archive/enforce-strength.js +0 -70
- package/dist/lib/archive/entropy.d.ts +0 -34
- package/dist/lib/archive/entropy.js +0 -180
- package/dist/lib/archive/export-locking.d.ts +0 -102
- package/dist/lib/archive/export-locking.js +0 -202
- package/dist/lib/archive/format.d.ts +0 -20
- package/dist/lib/archive/format.js +0 -174
- package/dist/lib/archive/index.d.ts +0 -23
- package/dist/lib/archive/index.js +0 -17
- package/dist/lib/archive/manifest.d.ts +0 -53
- package/dist/lib/archive/manifest.js +0 -183
- package/dist/lib/archive/migration.d.ts +0 -36
- package/dist/lib/archive/migration.js +0 -100
- package/dist/lib/archive/migrations/v18_to_v19.d.ts +0 -16
- package/dist/lib/archive/migrations/v18_to_v19.js +0 -18
- package/dist/lib/archive/orchestrator.d.ts +0 -166
- package/dist/lib/archive/orchestrator.js +0 -428
- package/dist/lib/archive/serializers/chunks.d.ts +0 -30
- package/dist/lib/archive/serializers/chunks.js +0 -113
- package/dist/lib/archive/serializers/embeddings.d.ts +0 -36
- package/dist/lib/archive/serializers/embeddings.js +0 -115
- package/dist/lib/archive/serializers/kg.d.ts +0 -28
- package/dist/lib/archive/serializers/kg.js +0 -184
- package/dist/lib/archive/serializers/ops_audit.d.ts +0 -21
- package/dist/lib/archive/serializers/ops_audit.js +0 -97
- package/dist/lib/archive/server-deps.d.ts +0 -131
- package/dist/lib/archive/server-deps.js +0 -232
- package/dist/lib/archive/strength.d.ts +0 -50
- package/dist/lib/archive/strength.js +0 -77
- package/dist/lib/archive/types.d.ts +0 -159
- package/dist/lib/archive/types.js +0 -45
- package/dist/lib/archive/unpack-streaming.d.ts +0 -70
- package/dist/lib/archive/unpack-streaming.js +0 -255
- package/dist/lib/auth/localhost-guard.d.ts +0 -106
- package/dist/lib/confidence/config.d.ts +0 -37
- package/dist/lib/confidence/config.js +0 -107
- package/dist/lib/confidence/db-shim-singleton.d.ts +0 -20
- package/dist/lib/confidence/db-shim-singleton.js +0 -41
- package/dist/lib/confidence/db-shim.d.ts +0 -47
- package/dist/lib/confidence/db-shim.js +0 -141
- package/dist/lib/confidence/mark.d.ts +0 -58
- package/dist/lib/confidence/mark.js +0 -168
- package/dist/lib/confidence/ranking.d.ts +0 -69
- package/dist/lib/confidence/ranking.js +0 -101
- package/dist/lib/confidence/search-filter.d.ts +0 -44
- package/dist/lib/confidence/search-filter.js +0 -103
- package/dist/lib/confidence/types.d.ts +0 -146
- package/dist/lib/confidence/types.js +0 -20
- package/dist/lib/confidence/write-hooks.d.ts +0 -50
- package/dist/lib/confidence/write-hooks.js +0 -159
- package/dist/lib/conflict/audit-fk-check.d.ts +0 -72
- package/dist/lib/conflict/audit-fk-check.js +0 -131
- package/dist/lib/conflict/audit-writer.d.ts +0 -39
- package/dist/lib/conflict/audit-writer.js +0 -133
- package/dist/lib/conflict/db-singleton.d.ts +0 -28
- package/dist/lib/conflict/db-singleton.js +0 -61
- package/dist/lib/conflict/db.d.ts +0 -27
- package/dist/lib/conflict/db.js +0 -20
- package/dist/lib/conflict/detector-direct.d.ts +0 -21
- package/dist/lib/conflict/detector-direct.js +0 -105
- package/dist/lib/conflict/evidence.d.ts +0 -24
- package/dist/lib/conflict/evidence.js +0 -76
- package/dist/lib/conflict/index.d.ts +0 -14
- package/dist/lib/conflict/index.js +0 -12
- package/dist/lib/conflict/scheduler.d.ts +0 -78
- package/dist/lib/conflict/scheduler.js +0 -111
- package/dist/lib/conflict/shadow.d.ts +0 -75
- package/dist/lib/conflict/shadow.js +0 -161
- package/dist/lib/conflict/types.d.ts +0 -133
- package/dist/lib/conflict/types.js +0 -19
- package/dist/lib/cost-cap.d.ts +0 -94
- package/dist/lib/deps/deps-registry.d.ts +0 -111
- package/dist/lib/error-sanitizer/middleware.d.ts +0 -43
- package/dist/lib/error-sanitizer/sanitize.d.ts +0 -78
- package/dist/lib/eval-batch.d.ts +0 -34
- package/dist/lib/eval-batch.js +0 -103
- package/dist/lib/eval-metrics.d.ts +0 -36
- package/dist/lib/eval-metrics.js +0 -95
- package/dist/lib/eval.d.ts +0 -106
- package/dist/lib/eval.js +0 -343
- package/dist/lib/events/bus.d.ts +0 -135
- package/dist/lib/fts-anchor.d.ts +0 -1
- package/dist/lib/hooks/classifier.d.ts +0 -47
- package/dist/lib/hooks/classifier.js +0 -129
- package/dist/lib/hooks/config.d.ts +0 -49
- package/dist/lib/hooks/config.js +0 -106
- package/dist/lib/hooks/decorators.d.ts +0 -35
- package/dist/lib/hooks/decorators.js +0 -59
- package/dist/lib/hooks/pipeline.d.ts +0 -76
- package/dist/lib/hooks/pipeline.js +0 -213
- package/dist/lib/hooks/privacy-filter-adapter.d.ts +0 -55
- package/dist/lib/hooks/privacy-filter-adapter.js +0 -84
- package/dist/lib/hooks/rate-limit-constant-time.d.ts +0 -57
- package/dist/lib/hooks/rate-limit-constant-time.js +0 -69
- package/dist/lib/hooks/rate-limit-dryrun-fix.d.ts +0 -71
- package/dist/lib/hooks/rate-limit-dryrun-fix.js +0 -110
- package/dist/lib/hooks/rate-limit.d.ts +0 -54
- package/dist/lib/hooks/rate-limit.js +0 -122
- package/dist/lib/hooks/server-deps.d.ts +0 -61
- package/dist/lib/hooks/server-deps.js +0 -92
- package/dist/lib/hooks/source-allowlist.d.ts +0 -26
- package/dist/lib/hooks/source-allowlist.js +0 -53
- package/dist/lib/hooks/types.d.ts +0 -129
- package/dist/lib/hooks/types.js +0 -24
- package/dist/lib/hooks/worker.d.ts +0 -56
- package/dist/lib/hooks/worker.js +0 -150
- package/dist/lib/ingest-router.d.ts +0 -25
- package/dist/lib/ocr-detector.d.ts +0 -61
- package/dist/lib/ocr-detector.js +0 -138
- package/dist/lib/ocr-engine-stub.d.ts +0 -48
- package/dist/lib/ocr-engine-stub.js +0 -190
- package/dist/lib/ocr-engines/google-doc-ai.d.ts +0 -36
- package/dist/lib/ocr-engines/google-doc-ai.js +0 -164
- package/dist/lib/ocr-jobs.d.ts +0 -67
- package/dist/lib/ocr-jobs.js +0 -129
- package/dist/lib/op-audit-extension/ran-at-guard.d.ts +0 -86
- package/dist/lib/op-audit.d.ts +0 -71
- package/dist/lib/privacy-br/detector.d.ts +0 -42
- package/dist/lib/privacy-br/detector.js +0 -130
- package/dist/lib/privacy-br/index.d.ts +0 -20
- package/dist/lib/privacy-br/index.js +0 -20
- package/dist/lib/privacy-br/integration.d.ts +0 -71
- package/dist/lib/privacy-br/integration.js +0 -74
- package/dist/lib/privacy-br/patterns.d.ts +0 -117
- package/dist/lib/privacy-br/patterns.js +0 -434
- package/dist/lib/privacy-br/redact.d.ts +0 -42
- package/dist/lib/privacy-br/redact.js +0 -103
- package/dist/lib/privacy-br/types.d.ts +0 -55
- package/dist/lib/privacy-br/types.js +0 -25
- package/dist/lib/regex-extract/extractor.d.ts +0 -30
- package/dist/lib/regex-extract/frontmatter.d.ts +0 -44
- package/dist/lib/regex-extract/index.d.ts +0 -14
- package/dist/lib/regex-extract/ingest-router-l4.d.ts +0 -76
- package/dist/lib/regex-extract/patterns.d.ts +0 -61
- package/dist/lib/regex-extract/production-wire.d.ts +0 -128
- package/dist/lib/regex-extract/reconcile.d.ts +0 -162
- package/dist/lib/regex-extract/strip-code.d.ts +0 -24
- package/dist/lib/regex-extract/types.d.ts +0 -48
- package/dist/lib/reranker.d.ts +0 -80
- package/dist/lib/shadow-tracker.d.ts +0 -191
- package/dist/lib/shadow-tracker.js +0 -384
- package/dist/lib/spo-injection.d.ts +0 -52
- package/dist/lib/telemetry-collector.d.ts +0 -158
- package/dist/lib/telemetry-collector.js +0 -249
- package/dist/lib/temporal-detector.d.ts +0 -27
- package/dist/lib/viewer/auth.d.ts +0 -37
- package/dist/lib/viewer/auth.js +0 -70
- package/dist/lib/viewer/backpressure.d.ts +0 -59
- package/dist/lib/viewer/backpressure.js +0 -100
- package/dist/lib/viewer/broadcast-singleton.d.ts +0 -34
- package/dist/lib/viewer/broadcast-singleton.js +0 -49
- package/dist/lib/viewer/broadcast.d.ts +0 -66
- package/dist/lib/viewer/broadcast.js +0 -96
- package/dist/lib/viewer/event-types.d.ts +0 -132
- package/dist/lib/viewer/event-types.js +0 -74
- package/dist/lib/viewer/instrumentation.d.ts +0 -106
- package/dist/lib/viewer/instrumentation.js +0 -224
- package/dist/lib/viewer/migration.d.ts +0 -23
- package/dist/lib/viewer/migration.js +0 -56
- package/dist/lib/viewer/redaction.d.ts +0 -44
- package/dist/lib/viewer/redaction.js +0 -139
- package/dist/lib/viewer/session.d.ts +0 -51
- package/dist/lib/viewer/session.js +0 -87
- package/dist/mcp/tools/answer.d.ts +0 -94
- package/dist/mcp/tools/archive.d.ts +0 -152
- package/dist/mcp/tools/archive.js +0 -170
- package/dist/mcp/tools/conflict.d.ts +0 -44
- package/dist/mcp/tools/conflict.js +0 -130
- package/dist/mcp/tools/hooks.d.ts +0 -29
- package/dist/mcp/tools/hooks.js +0 -78
- package/dist/mcp/tools/mark.d.ts +0 -38
- package/dist/mcp/tools/mark.js +0 -82
- package/dist/mcp/tools/viewer.d.ts +0 -58
- package/dist/mcp/tools/viewer.js +0 -64
- package/dist/mcp-server.d.ts +0 -2
- package/dist/metrics.d.ts +0 -3
- package/dist/noise-filter.d.ts +0 -18
- package/dist/notion-sync.d.ts +0 -7
- package/dist/notion-sync.js +0 -97
- package/dist/observability/adapters/a3-adapter.d.ts +0 -63
- package/dist/observability/adapters/a3-adapter.js +0 -83
- package/dist/observability/adapters/p1-adapter.d.ts +0 -49
- package/dist/observability/adapters/p1-adapter.js +0 -63
- package/dist/observability/adapters/p5-adapter.d.ts +0 -36
- package/dist/observability/adapters/p5-adapter.js +0 -71
- package/dist/observability/cardinality.d.ts +0 -61
- package/dist/observability/cardinality.js +0 -300
- package/dist/observability/collectors/db-stats.collector.d.ts +0 -9
- package/dist/observability/collectors/db-stats.collector.js +0 -88
- package/dist/observability/collectors/eventbus.collector.d.ts +0 -6
- package/dist/observability/collectors/eventbus.collector.js +0 -50
- package/dist/observability/collectors/process.collector.d.ts +0 -7
- package/dist/observability/collectors/process.collector.js +0 -93
- package/dist/observability/collectors/provider-telemetry.collector.d.ts +0 -11
- package/dist/observability/collectors/provider-telemetry.collector.js +0 -112
- package/dist/observability/collectors/search-telemetry.collector.d.ts +0 -12
- package/dist/observability/collectors/search-telemetry.collector.js +0 -76
- package/dist/observability/exporter.d.ts +0 -30
- package/dist/observability/exporter.js +0 -182
- package/dist/observability/index.d.ts +0 -22
- package/dist/observability/index.js +0 -21
- package/dist/observability/metrics.d.ts +0 -53
- package/dist/observability/metrics.js +0 -213
- package/dist/observability/privacy-guard.d.ts +0 -32
- package/dist/observability/privacy-guard.js +0 -116
- package/dist/observability/record.d.ts +0 -83
- package/dist/observability/record.js +0 -217
- package/dist/observability/registry.d.ts +0 -60
- package/dist/observability/registry.js +0 -93
- package/dist/observability/types.d.ts +0 -115
- package/dist/observability/types.js +0 -235
- package/dist/observability.d.ts +0 -131
- package/dist/plugins/nox-hooks/index.d.ts +0 -61
- package/dist/plugins/nox-hooks/index.js +0 -99
- package/dist/primer.d.ts +0 -1
- package/dist/privacy/filter.d.ts +0 -27
- package/dist/privacy/patterns.d.ts +0 -29
- package/dist/privacy/tag-parser.d.ts +0 -24
- package/dist/project-context-gen.d.ts +0 -10
- package/dist/providers/embedding/gemini.d.ts +0 -73
- package/dist/providers/embedding/openai.d.ts +0 -76
- package/dist/providers/embedding/types.d.ts +0 -39
- package/dist/providers/embedding/voyage.d.ts +0 -36
- package/dist/providers/index.d.ts +0 -116
- package/dist/providers/llm/anthropic.d.ts +0 -29
- package/dist/providers/llm/chain.d.ts +0 -99
- package/dist/providers/llm/gemini.d.ts +0 -48
- package/dist/providers/llm/openai.d.ts +0 -64
- package/dist/providers/llm/types.d.ts +0 -47
- package/dist/providers/telemetry.d.ts +0 -87
- package/dist/providers/types.d.ts +0 -42
- package/dist/query-entity-count.d.ts +0 -54
- package/dist/reflect.d.ts +0 -26
- package/dist/reindex-errors.d.ts +0 -7
- package/dist/reindex.d.ts +0 -16
- package/dist/retention.d.ts +0 -40
- package/dist/salience.d.ts +0 -85
- package/dist/scripts/migrate-v17-ops-audit.d.ts +0 -17
- package/dist/search-dedup.d.ts +0 -44
- package/dist/search-expansion.d.ts +0 -20
- package/dist/search.d.ts +0 -62
- package/dist/seh-detector.d.ts +0 -31
- package/dist/self-improve.d.ts +0 -1
- package/dist/session-distill.d.ts +0 -29
- package/dist/session-update.d.ts +0 -1
- package/dist/shared-memory.d.ts +0 -24
- package/dist/stats.d.ts +0 -1
- package/dist/temporal-retrieval.d.ts +0 -132
- package/dist/tier-manager.d.ts +0 -69
- package/dist/vectorize.d.ts +0 -16
- package/dist/version.d.ts +0 -1
- package/dist/watch.d.ts +0 -8
package/dist/api-server.js
CHANGED
|
@@ -13,18 +13,13 @@ import { getRetentionDistribution, countArchiveCandidates, getSalienceDistributi
|
|
|
13
13
|
import { getSalienceMode } from "./salience.js";
|
|
14
14
|
import { getOpAuditStats, reapZombies } from "./lib/op-audit.js";
|
|
15
15
|
import { getVaultFacts } from "./lib/spo-injection.js";
|
|
16
|
-
import { getEvalMetricsSnapshot } from "./lib/eval.js";
|
|
17
16
|
import { execFileSync } from "child_process";
|
|
18
17
|
import { applyCorsHeaders, handlePreflight } from "./api/cors.js";
|
|
18
|
+
import { safeErrorMessage } from "./lib/api/safe-error-message.js";
|
|
19
19
|
import { registerWireUpRoutes } from "./api/wire-up.js";
|
|
20
20
|
import { handleBrief } from "./api/brief.js";
|
|
21
21
|
import { handleIngestEvent } from "./api/ingest-event.js";
|
|
22
22
|
import { handleObsHealth, handleObsRecentOps, handleObsCanaryTail, } from "./observability.js";
|
|
23
|
-
import { handleObsEvals } from "./evals.js";
|
|
24
|
-
import { recordRequest, handleObsTelemetry, } from "./lib/telemetry-collector.js";
|
|
25
|
-
import { handleObsShadow, tracker as shadowTracker, } from "./lib/shadow-tracker.js";
|
|
26
|
-
import { join } from "path";
|
|
27
|
-
import { readFileSync as fsReadFile, statSync as fsStat } from "fs";
|
|
28
23
|
const PORT = parseInt(process.env.NOX_API_PORT || "18800");
|
|
29
24
|
// Security 2026-04-23: bind to loopback by default (was 0.0.0.0).
|
|
30
25
|
// retentionDistribution + chunks/types fields are info-leak if exposed publicly
|
|
@@ -33,9 +28,6 @@ const HOST = process.env.NOX_API_HOST || "127.0.0.1";
|
|
|
33
28
|
function json(res, data, status = 200) {
|
|
34
29
|
res.writeHead(status, {
|
|
35
30
|
"Content-Type": "application/json",
|
|
36
|
-
"Access-Control-Allow-Origin": "*",
|
|
37
|
-
"Access-Control-Allow-Methods": "GET, POST, OPTIONS",
|
|
38
|
-
"Access-Control-Allow-Headers": "Content-Type, X-Agent-Name",
|
|
39
31
|
});
|
|
40
32
|
res.end(JSON.stringify(data));
|
|
41
33
|
}
|
|
@@ -300,61 +292,6 @@ async function handleRequest(req, res) {
|
|
|
300
292
|
json(res, handleObsCanaryTail(Number.isFinite(n) ? n : 3));
|
|
301
293
|
break;
|
|
302
294
|
}
|
|
303
|
-
case "/api/observability/evals": {
|
|
304
|
-
const params = parseQuery(url);
|
|
305
|
-
const limit = parseInt(params.limit || "500", 10);
|
|
306
|
-
const dbSource = params.db_source || params.dbSource || undefined;
|
|
307
|
-
// Explicit auditsRoot pointing to workspace-level audits dir
|
|
308
|
-
// (default `cwd/../audits` resolves to `tools/audits` em VPS, errado).
|
|
309
|
-
const workspace = process.env.OPENCLAW_WORKSPACE ?? "/root/.openclaw/workspace";
|
|
310
|
-
json(res, handleObsEvals({ dbSource, limit: Number.isFinite(limit) ? limit : 500 }, { auditsRoot: `${workspace}/audits` }));
|
|
311
|
-
break;
|
|
312
|
-
}
|
|
313
|
-
case "/api/observability/telemetry": {
|
|
314
|
-
// F10 Phase C Phase 1 (2026-05-24): in-process latency/throughput telemetry.
|
|
315
|
-
const params = parseQuery(url);
|
|
316
|
-
json(res, handleObsTelemetry(params));
|
|
317
|
-
break;
|
|
318
|
-
}
|
|
319
|
-
case "/api/observability/shadow": {
|
|
320
|
-
// F10 Phase D (2026-05-24): shadow-mode baseline-vs-candidate A/B comparisons.
|
|
321
|
-
const params = parseQuery(url);
|
|
322
|
-
json(res, handleObsShadow(params));
|
|
323
|
-
break;
|
|
324
|
-
}
|
|
325
|
-
case "/observability/health.html":
|
|
326
|
-
case "/observability/health.js":
|
|
327
|
-
case "/observability/health.css":
|
|
328
|
-
case "/observability/evals.html":
|
|
329
|
-
case "/observability/evals.js":
|
|
330
|
-
case "/observability/evals.css":
|
|
331
|
-
case "/observability/telemetry.html":
|
|
332
|
-
case "/observability/telemetry.js":
|
|
333
|
-
case "/observability/telemetry.css":
|
|
334
|
-
case "/observability/shadow.html":
|
|
335
|
-
case "/observability/shadow.js":
|
|
336
|
-
case "/observability/shadow.css":
|
|
337
|
-
case "/observability/gate-annotations.json": {
|
|
338
|
-
const filename = path.split("/").pop();
|
|
339
|
-
const fullPath = join(process.cwd(), "public", "observability", filename);
|
|
340
|
-
try {
|
|
341
|
-
fsStat(fullPath);
|
|
342
|
-
const body = fsReadFile(fullPath, "utf-8");
|
|
343
|
-
const ext = filename.split(".").pop();
|
|
344
|
-
const ct = ext === "html" ? "text/html; charset=utf-8" :
|
|
345
|
-
ext === "js" ? "application/javascript; charset=utf-8" :
|
|
346
|
-
ext === "css" ? "text/css; charset=utf-8" :
|
|
347
|
-
ext === "json" ? "application/json; charset=utf-8" :
|
|
348
|
-
"application/octet-stream";
|
|
349
|
-
res.writeHead(200, { "Content-Type": ct, "Cache-Control": "no-store" });
|
|
350
|
-
res.end(body);
|
|
351
|
-
}
|
|
352
|
-
catch {
|
|
353
|
-
res.writeHead(404, { "Content-Type": "text/plain" });
|
|
354
|
-
res.end("not found");
|
|
355
|
-
}
|
|
356
|
-
break;
|
|
357
|
-
}
|
|
358
295
|
case "/api/agents": {
|
|
359
296
|
json(res, profileAllAgents());
|
|
360
297
|
break;
|
|
@@ -387,11 +324,6 @@ async function handleRequest(req, res) {
|
|
|
387
324
|
json(res, { path: result });
|
|
388
325
|
break;
|
|
389
326
|
}
|
|
390
|
-
case "/api/eval-metrics": {
|
|
391
|
-
// R01a (2026-05-02): eval harness metrics surface.
|
|
392
|
-
json(res, getEvalMetricsSnapshot());
|
|
393
|
-
break;
|
|
394
|
-
}
|
|
395
327
|
case "/api/ingest-event": {
|
|
396
328
|
// F4b Fluxo D (2026-06-04): write-side do Session Priming Loop —
|
|
397
329
|
// digest de sessão vira chunk type=daily/90d, dedup por session_id.
|
|
@@ -412,7 +344,6 @@ async function handleRequest(req, res) {
|
|
|
412
344
|
if ("text" in out) {
|
|
413
345
|
res.writeHead(out.status, {
|
|
414
346
|
"Content-Type": "text/plain; charset=utf-8",
|
|
415
|
-
"Access-Control-Allow-Origin": "*",
|
|
416
347
|
});
|
|
417
348
|
res.end(out.text);
|
|
418
349
|
}
|
|
@@ -422,8 +353,6 @@ async function handleRequest(req, res) {
|
|
|
422
353
|
break;
|
|
423
354
|
}
|
|
424
355
|
case "/api/search": {
|
|
425
|
-
// F10 Phase C Phase 1 (2026-05-24): in-process telemetry capture
|
|
426
|
-
const _t0 = Date.now();
|
|
427
356
|
// 2026-05-05 fix: accept both GET (query string) and POST (JSON body).
|
|
428
357
|
// Previously POST silently failed with q-required because parseQuery only reads URL.
|
|
429
358
|
let qText;
|
|
@@ -457,19 +386,6 @@ async function handleRequest(req, res) {
|
|
|
457
386
|
// E03a (2026-05-02): SPO injection envelope. Mode shadow → compute+log only.
|
|
458
387
|
// Mode active → surface vaultFacts in response. Mode off → no compute.
|
|
459
388
|
const vf = getVaultFacts(qText, getDb());
|
|
460
|
-
// F10 Phase C: record request telemetry (fire-and-forget, sync, zero overhead).
|
|
461
|
-
// searchHybrid returns Array<Result> directly OR { results: [...], meta: {...} }
|
|
462
|
-
// depending on search.ts version. Probe both shapes; fall back safely.
|
|
463
|
-
const _isArr = Array.isArray(results);
|
|
464
|
-
const _resArr = _isArr
|
|
465
|
-
? results
|
|
466
|
-
: results?.results;
|
|
467
|
-
const _meta = _isArr
|
|
468
|
-
? undefined
|
|
469
|
-
: results?.meta;
|
|
470
|
-
const _pathUsed = _meta?.path_used ?? "hybrid";
|
|
471
|
-
const _semantic = _meta?.semantic_used !== false; // default true
|
|
472
|
-
recordRequest("search", _t0, Date.now(), Array.isArray(_resArr) ? _resArr.length : 0, _pathUsed, _semantic);
|
|
473
389
|
if (vf.surface && vf.block) {
|
|
474
390
|
json(res, { results, vaultFacts: vf.block });
|
|
475
391
|
}
|
|
@@ -560,18 +476,17 @@ async function handleRequest(req, res) {
|
|
|
560
476
|
"/api/health", "/api/health/lite", "/api/agents", "/api/kg", "/api/kg/path",
|
|
561
477
|
"/api/search", "/api/brief", "/api/ingest-event", "/api/cross-kg", "/api/reflect",
|
|
562
478
|
"/api/procedures", "/api/crystallize", "/api/crystallize/validate",
|
|
479
|
+
"/api/answer",
|
|
563
480
|
"/api/observability/health", "/api/observability/recent-ops",
|
|
564
|
-
"/api/observability/canary-tail"
|
|
565
|
-
"/api/observability/evals", "/observability/evals.html",
|
|
566
|
-
"/api/observability/telemetry", "/observability/telemetry.html",
|
|
567
|
-
"/api/observability/shadow", "/observability/shadow.html",
|
|
568
|
-
"/observability/gate-annotations.json"
|
|
481
|
+
"/api/observability/canary-tail"
|
|
569
482
|
]
|
|
570
483
|
}, 404);
|
|
571
484
|
}
|
|
572
485
|
}
|
|
573
486
|
catch (err) {
|
|
574
|
-
|
|
487
|
+
const { message, correlationId } = safeErrorMessage(err);
|
|
488
|
+
console.error(`[nox-mem-api] unhandled error [${correlationId}]:`, err);
|
|
489
|
+
json(res, { error: message, correlationId }, 500);
|
|
575
490
|
}
|
|
576
491
|
}
|
|
577
492
|
const server = createServer(handleRequest);
|
|
@@ -586,17 +501,6 @@ server.listen(PORT, HOST, () => {
|
|
|
586
501
|
catch (err) {
|
|
587
502
|
console.error(`[nox-mem-api] reapZombies failed:`, err);
|
|
588
503
|
}
|
|
589
|
-
// F10 Phase D (2026-05-24): wire shared DB handle into the shadow tracker
|
|
590
|
-
// singleton so append-only shadow_runs persistence is live for any caller
|
|
591
|
-
// that invokes recordShadowComparison(). Schema was applied via out-of-band
|
|
592
|
-
// migration (CHANGE 0 Option B in api-server.shadow-wire-up.md).
|
|
593
|
-
try {
|
|
594
|
-
shadowTracker.setDB(getDb());
|
|
595
|
-
console.log(`[nox-mem-api] shadow tracker DB handle wired`);
|
|
596
|
-
}
|
|
597
|
-
catch (err) {
|
|
598
|
-
console.error(`[nox-mem-api] shadow tracker setDB failed (persistence will fall back to in-memory only):`, err);
|
|
599
|
-
}
|
|
600
504
|
// D01 (2026-05-07): pre-warm reranker model se mode != off pra evitar p95 cold-start (~12-90s).
|
|
601
505
|
// Spec specs/2026-05-07-D01-cross-encoder-reranker.md §risks §1. Single-shot, fire-and-forget.
|
|
602
506
|
const rerankerMode = process.env.NOX_RERANKER_MODE ?? "off";
|
package/dist/crystallize.js
CHANGED
|
@@ -35,11 +35,9 @@ export async function crystallize(input) {
|
|
|
35
35
|
VALUES (?, 'procedure', ?, datetime('now'), ?)
|
|
36
36
|
`).run(`procedure/${input.title.toLowerCase().replace(/\s+/g, "-")}`, chunkText, metadata);
|
|
37
37
|
const id = result.lastInsertRowid;
|
|
38
|
-
//
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
}
|
|
42
|
-
catch { }
|
|
38
|
+
// FTS indexing is handled by the chunks_ai AFTER INSERT trigger (external-content, content=chunks).
|
|
39
|
+
// A manual INSERT here duplicated the FTS posting and broke the index 1:1 invariant,
|
|
40
|
+
// causing SQLITE_CORRUPT_VTAB on the next delete/update. Removed 2026-06-17.
|
|
43
41
|
// Best-effort embed so procedures are immediately hybrid-searchable.
|
|
44
42
|
// Skip silently if GEMINI_API_KEY is missing or embed fails — FTS still works.
|
|
45
43
|
try {
|
package/dist/db.js
CHANGED
|
@@ -151,11 +151,17 @@ function ensureSchema(db) {
|
|
|
151
151
|
);`);
|
|
152
152
|
const row = db.prepare("SELECT value FROM meta WHERE key = 'schema_version'").get();
|
|
153
153
|
const currentVersion = row ? parseInt(row.value, 10) : 0;
|
|
154
|
-
if (currentVersion === SCHEMA_VERSION)
|
|
155
|
-
return;
|
|
156
154
|
if (currentVersion > SCHEMA_VERSION) {
|
|
157
155
|
throw new Error(`DB schema ${currentVersion} > expected ${SCHEMA_VERSION}`);
|
|
158
156
|
}
|
|
157
|
+
// Always re-align PRAGMA user_version with the canonical schema version, even
|
|
158
|
+
// when migrations are already applied (meta.schema_version is the source of
|
|
159
|
+
// truth). Covers the recovery scenario where user_version was manually reset
|
|
160
|
+
// to 0 (legacy/partial-restore DBs) while the meta row is current — re-open
|
|
161
|
+
// must re-bump the PRAGMA without reprocessing migrations. Idempotent.
|
|
162
|
+
db.pragma(`user_version = ${SCHEMA_VERSION}`);
|
|
163
|
+
if (currentVersion === SCHEMA_VERSION)
|
|
164
|
+
return;
|
|
159
165
|
if (currentVersion < 1)
|
|
160
166
|
migrateToV1(db);
|
|
161
167
|
if (currentVersion < 2)
|
|
@@ -173,6 +179,8 @@ function ensureSchema(db) {
|
|
|
173
179
|
if (currentVersion < 18)
|
|
174
180
|
migrateToV8(db);
|
|
175
181
|
db.prepare("INSERT OR REPLACE INTO meta (key, value, updated_at) VALUES ('schema_version', ?, datetime('now'))").run(String(SCHEMA_VERSION));
|
|
182
|
+
// Keep PRAGMA user_version in sync so op-audit and tests can rely on it.
|
|
183
|
+
db.pragma(`user_version = ${SCHEMA_VERSION}`);
|
|
176
184
|
}
|
|
177
185
|
function migrateToV8(db) {
|
|
178
186
|
// Standalone consolidation of the column additions that the canonical engine
|
|
@@ -199,6 +207,57 @@ function migrateToV8(db) {
|
|
|
199
207
|
}
|
|
200
208
|
catch { }
|
|
201
209
|
db.exec(`CREATE INDEX IF NOT EXISTS idx_chunks_section ON chunks(section);`);
|
|
210
|
+
// Knowledge-graph schema. ensureGraphTables() (knowledge-graph.ts) creates
|
|
211
|
+
// these lazily on the first KG operation, but a clean install that calls
|
|
212
|
+
// impact.ts / lib/spo-injection.ts / kg-* before any KG write would hit
|
|
213
|
+
// "no such table: kg_relations". Materialize the canonical KG schema here so
|
|
214
|
+
// getDb() always provides it. Definitions mirror ensureGraphTables();
|
|
215
|
+
// relation_reason (E05 edge typing) defaults to 'unknown'.
|
|
216
|
+
db.exec(`
|
|
217
|
+
CREATE TABLE IF NOT EXISTS kg_entities (
|
|
218
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
219
|
+
name TEXT NOT NULL,
|
|
220
|
+
entity_type TEXT NOT NULL,
|
|
221
|
+
attributes TEXT,
|
|
222
|
+
first_seen TEXT DEFAULT (datetime('now')),
|
|
223
|
+
last_seen TEXT DEFAULT (datetime('now')),
|
|
224
|
+
mention_count INTEGER DEFAULT 1,
|
|
225
|
+
UNIQUE(name, entity_type)
|
|
226
|
+
);
|
|
227
|
+
CREATE TABLE IF NOT EXISTS kg_relations (
|
|
228
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
229
|
+
source_entity_id INTEGER NOT NULL,
|
|
230
|
+
relation_type TEXT NOT NULL,
|
|
231
|
+
target_entity_id INTEGER NOT NULL,
|
|
232
|
+
evidence_chunk_id INTEGER,
|
|
233
|
+
confidence REAL DEFAULT 0.8,
|
|
234
|
+
created_at TEXT DEFAULT (datetime('now')),
|
|
235
|
+
expires_at TEXT DEFAULT (datetime('now', '+90 days')),
|
|
236
|
+
last_confirmed TEXT DEFAULT (datetime('now')),
|
|
237
|
+
relation_reason TEXT DEFAULT 'unknown',
|
|
238
|
+
FOREIGN KEY (source_entity_id) REFERENCES kg_entities(id),
|
|
239
|
+
FOREIGN KEY (target_entity_id) REFERENCES kg_entities(id)
|
|
240
|
+
);
|
|
241
|
+
CREATE INDEX IF NOT EXISTS idx_kg_entities_name ON kg_entities(name);
|
|
242
|
+
CREATE INDEX IF NOT EXISTS idx_kg_entities_type ON kg_entities(entity_type);
|
|
243
|
+
CREATE INDEX IF NOT EXISTS idx_kg_relations_source ON kg_relations(source_entity_id);
|
|
244
|
+
CREATE INDEX IF NOT EXISTS idx_kg_relations_target ON kg_relations(target_entity_id);
|
|
245
|
+
CREATE INDEX IF NOT EXISTS idx_kg_relations_expires ON kg_relations(expires_at);
|
|
246
|
+
CREATE INDEX IF NOT EXISTS idx_kg_relations_reason ON kg_relations(relation_reason);
|
|
247
|
+
`);
|
|
248
|
+
// Idempotent column add for pre-existing KG tables (created before E05).
|
|
249
|
+
try {
|
|
250
|
+
db.exec(`ALTER TABLE kg_relations ADD COLUMN relation_reason TEXT DEFAULT 'unknown'`);
|
|
251
|
+
}
|
|
252
|
+
catch { }
|
|
253
|
+
try {
|
|
254
|
+
db.exec(`CREATE INDEX IF NOT EXISTS idx_kg_relations_reason ON kg_relations(relation_reason)`);
|
|
255
|
+
}
|
|
256
|
+
catch { }
|
|
257
|
+
try {
|
|
258
|
+
db.exec(`UPDATE kg_relations SET relation_reason = 'unknown' WHERE relation_reason IS NULL`);
|
|
259
|
+
}
|
|
260
|
+
catch { }
|
|
202
261
|
}
|
|
203
262
|
function migrateToV7(db) {
|
|
204
263
|
// Fase 1.7a — Core Memory Quality
|
package/dist/embed.js
CHANGED
|
@@ -10,6 +10,8 @@
|
|
|
10
10
|
* RETRIEVAL_DOCUMENT / RETRIEVAL_QUERY) is preserved 100% when using gemini.
|
|
11
11
|
*/
|
|
12
12
|
import * as path from "path";
|
|
13
|
+
import { dirname } from "node:path";
|
|
14
|
+
import { fileURLToPath } from "node:url";
|
|
13
15
|
import { selectEmbeddingProvider } from "./providers/index.js";
|
|
14
16
|
// @ts-ignore
|
|
15
17
|
import { load as loadVec, getLoadablePath as vecLoadablePath } from "sqlite-vec";
|
|
@@ -21,7 +23,7 @@ const VEC0_PATH = (() => {
|
|
|
21
23
|
return vecLoadablePath();
|
|
22
24
|
}
|
|
23
25
|
catch { /* fall back to legacy path below */ }
|
|
24
|
-
return path.join(import.meta.dirname
|
|
26
|
+
return path.join(import.meta.dirname ?? dirname(fileURLToPath(import.meta.url)), "../node_modules/sqlite-vec-linux-x64/vec0");
|
|
25
27
|
})();
|
|
26
28
|
// Wrapper para garantir que vec0 carrega corretamente
|
|
27
29
|
function loadVecSafe(db) {
|
|
@@ -261,11 +263,30 @@ export async function embedBatch(texts) {
|
|
|
261
263
|
*/
|
|
262
264
|
export function ensureVecTable(db) {
|
|
263
265
|
loadVecSafe(db);
|
|
266
|
+
const wantDim = activeEmbeddingDim();
|
|
267
|
+
// Detect dimension mismatch on existing vec_chunks tables before CREATE.
|
|
268
|
+
// IF NOT EXISTS silently keeps the old table; if the provider changed the dim
|
|
269
|
+
// every subsequent INSERT will crash with an unhelpful vec0 error.
|
|
270
|
+
const existingRow = db.prepare(`SELECT sql FROM sqlite_master WHERE type='table' AND name='vec_chunks'`).get();
|
|
271
|
+
if (existingRow) {
|
|
272
|
+
const m = existingRow.sql.match(/FLOAT\[(\d+)\]/i);
|
|
273
|
+
if (m) {
|
|
274
|
+
const existingDim = parseInt(m[1], 10);
|
|
275
|
+
if (existingDim !== wantDim) {
|
|
276
|
+
const providerName = (process.env.NOX_EMBEDDING_PROVIDER ??
|
|
277
|
+
process.env.NOX_EMBED_PROVIDER ??
|
|
278
|
+
"gemini").trim();
|
|
279
|
+
throw new Error(`Embedding dim mismatch: vec_chunks is ${existingDim}-dim but provider ` +
|
|
280
|
+
`"${providerName}" produces ${wantDim}-dim. ` +
|
|
281
|
+
`Re-vectorize: clear vec_chunks and run \`nox-mem vectorize --force\`.`);
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
}
|
|
264
285
|
// Use activeEmbeddingDim() so the vec0 column dimension matches the active provider.
|
|
265
286
|
// For the default Gemini path this resolves to EMBEDDING_DIM (3072) — no behaviour change.
|
|
266
287
|
db.exec(`
|
|
267
288
|
CREATE VIRTUAL TABLE IF NOT EXISTS vec_chunks USING vec0(
|
|
268
|
-
embedding FLOAT[${
|
|
289
|
+
embedding FLOAT[${wantDim}]
|
|
269
290
|
);
|
|
270
291
|
CREATE TABLE IF NOT EXISTS vec_chunk_map (
|
|
271
292
|
vec_rowid INTEGER PRIMARY KEY,
|
package/dist/index.js
CHANGED
|
@@ -102,11 +102,7 @@ program
|
|
|
102
102
|
.description("Consolidate daily notes into topic files (requires Ollama)")
|
|
103
103
|
.action(async () => {
|
|
104
104
|
const { consolidate } = await import("./consolidate.js");
|
|
105
|
-
const { syncToNotion } = await import("./notion-sync.js");
|
|
106
105
|
const result = await consolidate();
|
|
107
|
-
if (result.notionItems.length > 0) {
|
|
108
|
-
await syncToNotion(result.notionItems);
|
|
109
|
-
}
|
|
110
106
|
if (result.remaining > 0) {
|
|
111
107
|
console.log(`[INFO] ${result.remaining} daily notes still pending — run again or wait for next cron`);
|
|
112
108
|
}
|
|
@@ -117,11 +113,7 @@ program
|
|
|
117
113
|
.description("Retry consolidation of previously failed daily notes")
|
|
118
114
|
.action(async () => {
|
|
119
115
|
const { consolidate } = await import("./consolidate.js");
|
|
120
|
-
|
|
121
|
-
const result = await consolidate({ retryFailed: true });
|
|
122
|
-
if (result.notionItems.length > 0) {
|
|
123
|
-
await syncToNotion(result.notionItems);
|
|
124
|
-
}
|
|
116
|
+
await consolidate({ retryFailed: true });
|
|
125
117
|
closeDb();
|
|
126
118
|
});
|
|
127
119
|
program
|
|
@@ -132,19 +124,6 @@ program
|
|
|
132
124
|
await digest();
|
|
133
125
|
closeDb();
|
|
134
126
|
});
|
|
135
|
-
program
|
|
136
|
-
.command("sync-notion")
|
|
137
|
-
.description("Re-sync last consolidation items to Notion")
|
|
138
|
-
.action(async () => {
|
|
139
|
-
const { syncToNotion, loadSyncLog } = await import("./notion-sync.js");
|
|
140
|
-
const items = loadSyncLog();
|
|
141
|
-
if (items.length === 0) {
|
|
142
|
-
console.log("[INFO] No items to sync — run consolidate first");
|
|
143
|
-
return;
|
|
144
|
-
}
|
|
145
|
-
console.log(`[INFO] Re-syncing ${items.length} items from last consolidation...`);
|
|
146
|
-
await syncToNotion(items);
|
|
147
|
-
});
|
|
148
127
|
program
|
|
149
128
|
.command("doctor")
|
|
150
129
|
.description("Diagnostic check — Ollama, SQLite, FTS5, watcher, Notion")
|
package/dist/knowledge-graph.js
CHANGED
|
@@ -56,6 +56,7 @@ export function ensureGraphTables() {
|
|
|
56
56
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
57
57
|
name TEXT NOT NULL,
|
|
58
58
|
entity_type TEXT NOT NULL,
|
|
59
|
+
attributes TEXT,
|
|
59
60
|
first_seen TEXT DEFAULT (datetime('now')),
|
|
60
61
|
last_seen TEXT DEFAULT (datetime('now')),
|
|
61
62
|
mention_count INTEGER DEFAULT 1,
|
|
@@ -71,6 +72,7 @@ export function ensureGraphTables() {
|
|
|
71
72
|
created_at TEXT DEFAULT (datetime('now')),
|
|
72
73
|
expires_at TEXT DEFAULT (datetime('now', '+90 days')),
|
|
73
74
|
last_confirmed TEXT DEFAULT (datetime('now')),
|
|
75
|
+
relation_reason TEXT DEFAULT 'unknown',
|
|
74
76
|
FOREIGN KEY (source_entity_id) REFERENCES kg_entities(id),
|
|
75
77
|
FOREIGN KEY (target_entity_id) REFERENCES kg_entities(id)
|
|
76
78
|
);
|
|
@@ -79,6 +81,11 @@ export function ensureGraphTables() {
|
|
|
79
81
|
CREATE INDEX IF NOT EXISTS idx_kg_relations_source ON kg_relations(source_entity_id);
|
|
80
82
|
CREATE INDEX IF NOT EXISTS idx_kg_relations_target ON kg_relations(target_entity_id);
|
|
81
83
|
`);
|
|
84
|
+
// Idempotent: add attributes column to DBs created before this fix
|
|
85
|
+
try {
|
|
86
|
+
db.exec(`ALTER TABLE kg_entities ADD COLUMN attributes TEXT`);
|
|
87
|
+
}
|
|
88
|
+
catch { /* already exists */ }
|
|
82
89
|
// Migrate existing tables: add TTL columns if they don't exist
|
|
83
90
|
const db2 = getDb();
|
|
84
91
|
try {
|
|
@@ -89,14 +96,27 @@ export function ensureGraphTables() {
|
|
|
89
96
|
db2.exec(`ALTER TABLE kg_relations ADD COLUMN last_confirmed TEXT`);
|
|
90
97
|
}
|
|
91
98
|
catch { /* already exists */ }
|
|
99
|
+
// E05 edge typing: relation_reason column (default 'unknown' so existing rows
|
|
100
|
+
// and inserts without an explicit reason read back as 'unknown'). Consumed by
|
|
101
|
+
// impact.ts (blast-radius grouping) and lib/spo-injection.ts (vault facts).
|
|
102
|
+
try {
|
|
103
|
+
db2.exec(`ALTER TABLE kg_relations ADD COLUMN relation_reason TEXT DEFAULT 'unknown'`);
|
|
104
|
+
}
|
|
105
|
+
catch { /* already exists */ }
|
|
92
106
|
// Backfill values for existing rows
|
|
93
107
|
db2.exec(`UPDATE kg_relations SET expires_at = datetime(created_at, '+90 days') WHERE expires_at IS NULL`);
|
|
94
108
|
db2.exec(`UPDATE kg_relations SET last_confirmed = created_at WHERE last_confirmed IS NULL`);
|
|
109
|
+
db2.exec(`UPDATE kg_relations SET relation_reason = 'unknown' WHERE relation_reason IS NULL`);
|
|
95
110
|
// Index on expires_at (safe now that column exists)
|
|
96
111
|
try {
|
|
97
112
|
db2.exec(`CREATE INDEX IF NOT EXISTS idx_kg_relations_expires ON kg_relations(expires_at)`);
|
|
98
113
|
}
|
|
99
114
|
catch { /* ok */ }
|
|
115
|
+
// Index on relation_reason (edge-typing lookups + impact grouping)
|
|
116
|
+
try {
|
|
117
|
+
db2.exec(`CREATE INDEX IF NOT EXISTS idx_kg_relations_reason ON kg_relations(relation_reason)`);
|
|
118
|
+
}
|
|
119
|
+
catch { /* ok */ }
|
|
100
120
|
}
|
|
101
121
|
// ─── Entity extraction patterns ──────────────────────────────────────────────
|
|
102
122
|
// These static regex patterns are used ONLY by the legacy buildGraph() extractor.
|
|
@@ -0,0 +1,229 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* src/lib/answer/__tests__/e2e-gemini.test.ts — P1 T12.
|
|
3
|
+
*
|
|
4
|
+
* **GATED** end-to-end tests against the real Gemini API. SKIPPED unless
|
|
5
|
+
* `NOX_E2E_GEMINI=1` is set in the environment AND `GEMINI_API_KEY` is
|
|
6
|
+
* present.
|
|
7
|
+
*
|
|
8
|
+
* Cost cap: hardcoded `MAX_TOKENS_TEST = 200` on every call. Total run
|
|
9
|
+
* (4 tests × ~250 tokens in + 200 tokens out, flash-lite pricing
|
|
10
|
+
* $0.10/M in + $0.40/M out) ≈ $0.0004 — well under the $0.01 budget.
|
|
11
|
+
*
|
|
12
|
+
* Coverage when active (4 tests):
|
|
13
|
+
* E2E-01 real Gemini call returns non-empty answer + at least one citation
|
|
14
|
+
* E2E-02 citations resolve to real chunk_ids from the synthetic fixture
|
|
15
|
+
* E2E-03 telemetry row written; model = 'gemini-2.5-flash-lite'
|
|
16
|
+
* E2E-04 adversarial out-of-corpus question yields "no memory matches" via retrieval_empty
|
|
17
|
+
*
|
|
18
|
+
* When gated off, ONE skip-marker test runs that logs the gate reason —
|
|
19
|
+
* keeps the report honest ("test skipped because NOX_E2E_GEMINI != 1").
|
|
20
|
+
*
|
|
21
|
+
* The Gemini provider is wired inline here using the public REST endpoint
|
|
22
|
+
* (no SDK dependency required — keeps staged-P1 installable without
|
|
23
|
+
* `@google/genai` in the dev dep set). Replace with the SDK in the VPS
|
|
24
|
+
* apply step if/when A3 provider abstraction merges.
|
|
25
|
+
*/
|
|
26
|
+
import { describe, it, before, after } from "node:test";
|
|
27
|
+
import assert from "node:assert/strict";
|
|
28
|
+
import Database from "better-sqlite3";
|
|
29
|
+
import { answer as realAnswer, __setRawSearchForTests, } from "../index.js";
|
|
30
|
+
import { recordAnswer, INSERT_SQL, } from "../telemetry.js";
|
|
31
|
+
// ─── Gating ────────────────────────────────────────────────────────────────
|
|
32
|
+
const GATE_ON = process.env.NOX_E2E_GEMINI === "1";
|
|
33
|
+
const API_KEY = process.env.GEMINI_API_KEY ?? "";
|
|
34
|
+
const ACTIVE = GATE_ON && API_KEY.length > 0;
|
|
35
|
+
const MAX_TOKENS_TEST = 200;
|
|
36
|
+
const MODEL = "gemini-2.5-flash-lite";
|
|
37
|
+
// ─── Skip-marker stub ──────────────────────────────────────────────────────
|
|
38
|
+
describe("T12 E2E Gemini — gating", () => {
|
|
39
|
+
it("gate is honoured (active iff NOX_E2E_GEMINI=1 AND GEMINI_API_KEY set)", () => {
|
|
40
|
+
if (!ACTIVE) {
|
|
41
|
+
const reason = !GATE_ON
|
|
42
|
+
? "NOX_E2E_GEMINI != 1"
|
|
43
|
+
: "GEMINI_API_KEY empty";
|
|
44
|
+
// node:test prints this in default reporter; humans see why we skipped.
|
|
45
|
+
process.stdout.write(`[T12] SKIPPED real-Gemini suite — reason: ${reason}\n`);
|
|
46
|
+
assert.ok(true, "skip path");
|
|
47
|
+
return;
|
|
48
|
+
}
|
|
49
|
+
process.stdout.write("[T12] real-Gemini suite ACTIVE — running 4 tests against API\n");
|
|
50
|
+
assert.ok(API_KEY.length > 0);
|
|
51
|
+
});
|
|
52
|
+
});
|
|
53
|
+
class GeminiRestProvider {
|
|
54
|
+
apiKey;
|
|
55
|
+
maxTokensCap;
|
|
56
|
+
name = "gemini";
|
|
57
|
+
constructor(apiKey, maxTokensCap = MAX_TOKENS_TEST) {
|
|
58
|
+
this.apiKey = apiKey;
|
|
59
|
+
this.maxTokensCap = maxTokensCap;
|
|
60
|
+
}
|
|
61
|
+
async complete(opts) {
|
|
62
|
+
const t0 = Date.now();
|
|
63
|
+
const url = `https://generativelanguage.googleapis.com/v1beta/models/` +
|
|
64
|
+
`${opts.model}:generateContent?key=${this.apiKey}`;
|
|
65
|
+
const body = {
|
|
66
|
+
systemInstruction: { parts: [{ text: opts.system }] },
|
|
67
|
+
contents: [{ role: "user", parts: [{ text: opts.user }] }],
|
|
68
|
+
generationConfig: {
|
|
69
|
+
temperature: opts.temperature,
|
|
70
|
+
maxOutputTokens: Math.min(opts.maxTokens, this.maxTokensCap),
|
|
71
|
+
},
|
|
72
|
+
};
|
|
73
|
+
const resp = await fetch(url, {
|
|
74
|
+
method: "POST",
|
|
75
|
+
headers: { "Content-Type": "application/json" },
|
|
76
|
+
body: JSON.stringify(body),
|
|
77
|
+
});
|
|
78
|
+
if (!resp.ok) {
|
|
79
|
+
throw new Error(`Gemini HTTP ${resp.status}: ${await resp.text()}`);
|
|
80
|
+
}
|
|
81
|
+
const data = (await resp.json());
|
|
82
|
+
const text = data.candidates?.[0]?.content?.parts?.[0]?.text?.trim() ?? "";
|
|
83
|
+
return {
|
|
84
|
+
text,
|
|
85
|
+
tokensIn: data.usageMetadata?.promptTokenCount ?? 0,
|
|
86
|
+
tokensOut: data.usageMetadata?.candidatesTokenCount ?? 0,
|
|
87
|
+
latencyMs: Date.now() - t0,
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
// ─── Synthetic corpus (no real DB needed for E2E quality smoke) ────────────
|
|
92
|
+
const E2E_CHUNKS = [
|
|
93
|
+
{
|
|
94
|
+
chunk_id: 9001,
|
|
95
|
+
file_path: "memory/entities/decision/d41.md",
|
|
96
|
+
line_range: "L1-L5",
|
|
97
|
+
content: "Decision D41 #1 — Default model for the nox-mem answer primitive " +
|
|
98
|
+
"is gemini-2.5-flash-lite. Rationale: cost optimized vs quality. " +
|
|
99
|
+
"Override with NOX_ANSWER_MODEL or --model flag.",
|
|
100
|
+
content_hash: "h-d41",
|
|
101
|
+
score: 0.95,
|
|
102
|
+
},
|
|
103
|
+
{
|
|
104
|
+
chunk_id: 9002,
|
|
105
|
+
file_path: "memory/entities/feedback/salience.md",
|
|
106
|
+
line_range: "L1-L3",
|
|
107
|
+
content: "Salience formula in nox-mem is salience = recency × pain × " +
|
|
108
|
+
"importance. Exposed via /api/health.salience.",
|
|
109
|
+
content_hash: "h-sal",
|
|
110
|
+
score: 0.9,
|
|
111
|
+
},
|
|
112
|
+
{
|
|
113
|
+
chunk_id: 9003,
|
|
114
|
+
file_path: "memory/entities/lesson/never-sed.md",
|
|
115
|
+
line_range: "L1-L2",
|
|
116
|
+
content: "Never use sed -i on SQLite .db files — it corrupts page boundaries. " +
|
|
117
|
+
"Filter file lists by extension before sweeps.",
|
|
118
|
+
content_hash: "h-sed",
|
|
119
|
+
score: 0.8,
|
|
120
|
+
},
|
|
121
|
+
];
|
|
122
|
+
// ─── Telemetry adapter (real SQLite in-memory) ─────────────────────────────
|
|
123
|
+
class Sqlite3TelemetryStore {
|
|
124
|
+
db;
|
|
125
|
+
stmt;
|
|
126
|
+
constructor(db) {
|
|
127
|
+
this.db = db;
|
|
128
|
+
this.stmt = db.prepare(INSERT_SQL);
|
|
129
|
+
}
|
|
130
|
+
insert(row) {
|
|
131
|
+
this.stmt.run(row);
|
|
132
|
+
}
|
|
133
|
+
latest() {
|
|
134
|
+
return this.db
|
|
135
|
+
.prepare("SELECT * FROM answer_telemetry ORDER BY id DESC LIMIT 1")
|
|
136
|
+
.get();
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
const SCHEMA_V11 = `
|
|
140
|
+
CREATE TABLE IF NOT EXISTS answer_telemetry (
|
|
141
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
142
|
+
question_hash TEXT NOT NULL, session_id TEXT,
|
|
143
|
+
timestamp_ms INTEGER NOT NULL, provider TEXT NOT NULL, model TEXT NOT NULL,
|
|
144
|
+
retrieval_count INTEGER NOT NULL, citation_count INTEGER NOT NULL,
|
|
145
|
+
tokens_in INTEGER, tokens_out INTEGER, latency_ms INTEGER NOT NULL,
|
|
146
|
+
fallback_used INTEGER NOT NULL DEFAULT 0, failed_reason TEXT,
|
|
147
|
+
cost_estimate_usd REAL NOT NULL DEFAULT 0,
|
|
148
|
+
CHECK (failed_reason IS NULL OR failed_reason IN
|
|
149
|
+
('hallucinated_citation', 'provider_down', 'token_budget'))
|
|
150
|
+
);
|
|
151
|
+
`;
|
|
152
|
+
// ─── Active suite (only if gated on) ───────────────────────────────────────
|
|
153
|
+
if (ACTIVE) {
|
|
154
|
+
describe("T12 E2E Gemini — real API calls (flash-lite, capped)", () => {
|
|
155
|
+
let db;
|
|
156
|
+
let store;
|
|
157
|
+
let provider;
|
|
158
|
+
before(() => {
|
|
159
|
+
db = new Database(":memory:");
|
|
160
|
+
db.exec(SCHEMA_V11);
|
|
161
|
+
store = new Sqlite3TelemetryStore(db);
|
|
162
|
+
provider = new GeminiRestProvider(API_KEY, MAX_TOKENS_TEST);
|
|
163
|
+
__setRawSearchForTests(async () => E2E_CHUNKS);
|
|
164
|
+
});
|
|
165
|
+
after(() => {
|
|
166
|
+
db.close();
|
|
167
|
+
});
|
|
168
|
+
it("E2E-01 returns non-empty answer with ≥1 citation", async () => {
|
|
169
|
+
const res = await realAnswer({
|
|
170
|
+
question: "What is the default model for the answer primitive?",
|
|
171
|
+
providerOverride: provider,
|
|
172
|
+
maxTokens: MAX_TOKENS_TEST,
|
|
173
|
+
temperature: 0,
|
|
174
|
+
});
|
|
175
|
+
assert.ok(res.answer.length > 0, "answer text non-empty");
|
|
176
|
+
assert.ok(res.citations.length >= 1, "≥1 citation parsed");
|
|
177
|
+
});
|
|
178
|
+
it("E2E-02 citation resolves to a real chunk_id from fixture", async () => {
|
|
179
|
+
const res = await realAnswer({
|
|
180
|
+
question: "What is the salience formula in nox-mem?",
|
|
181
|
+
providerOverride: provider,
|
|
182
|
+
maxTokens: MAX_TOKENS_TEST,
|
|
183
|
+
temperature: 0,
|
|
184
|
+
});
|
|
185
|
+
assert.ok(res.citations.length >= 1);
|
|
186
|
+
const validIds = new Set(E2E_CHUNKS.map((c) => c.chunk_id));
|
|
187
|
+
for (const c of res.citations) {
|
|
188
|
+
assert.ok(validIds.has(c.chunk_id), `citation chunk_id=${c.chunk_id} not in fixture`);
|
|
189
|
+
}
|
|
190
|
+
});
|
|
191
|
+
it("E2E-03 telemetry row persists with model=gemini-2.5-flash-lite", async () => {
|
|
192
|
+
const question = "Never use what on .db files?";
|
|
193
|
+
const res = await realAnswer({
|
|
194
|
+
question,
|
|
195
|
+
providerOverride: provider,
|
|
196
|
+
maxTokens: MAX_TOKENS_TEST,
|
|
197
|
+
temperature: 0,
|
|
198
|
+
});
|
|
199
|
+
recordAnswer(store, {
|
|
200
|
+
question,
|
|
201
|
+
citationCount: res.citations.length,
|
|
202
|
+
metadata: res.metadata,
|
|
203
|
+
sessionId: "e2e-03",
|
|
204
|
+
});
|
|
205
|
+
const row = store.latest();
|
|
206
|
+
assert.strictEqual(row.model, MODEL);
|
|
207
|
+
assert.strictEqual(row.session_id, "e2e-03");
|
|
208
|
+
assert.ok((row.tokens_in ?? 0) > 0, "real tokens reported");
|
|
209
|
+
assert.ok((row.tokens_out ?? 0) > 0, "real tokens reported");
|
|
210
|
+
assert.ok(row.cost_estimate_usd > 0, "real cost estimate > 0");
|
|
211
|
+
});
|
|
212
|
+
it("E2E-04 empty retrieval → canonical 'no memory matches' (no real LLM spend)", async () => {
|
|
213
|
+
__setRawSearchForTests(async () => []);
|
|
214
|
+
const res = await realAnswer({
|
|
215
|
+
question: "What is the capital of Mars?",
|
|
216
|
+
providerOverride: provider,
|
|
217
|
+
maxTokens: MAX_TOKENS_TEST,
|
|
218
|
+
temperature: 0,
|
|
219
|
+
});
|
|
220
|
+
assert.match(res.answer, /no memory matches/i);
|
|
221
|
+
assert.strictEqual(res.citations.length, 0);
|
|
222
|
+
assert.strictEqual(res.metadata.failed_reason, "retrieval_empty");
|
|
223
|
+
assert.strictEqual(res.metadata.tokens_in, 0);
|
|
224
|
+
assert.strictEqual(res.metadata.tokens_out, 0);
|
|
225
|
+
// restore for any subsequent tests
|
|
226
|
+
__setRawSearchForTests(async () => E2E_CHUNKS);
|
|
227
|
+
});
|
|
228
|
+
});
|
|
229
|
+
}
|