nox-mem 3.1.1 → 3.2.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/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/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
|
@@ -1,53 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* src/lib/hooks/source-allowlist.ts — T2: Layer 2 of the privacy pipeline.
|
|
3
|
-
*
|
|
4
|
-
* Filters HookEvent by `source` AND `role`. Only events with:
|
|
5
|
-
* - source ∈ NOX_HOOK_SOURCES (default {openclaw})
|
|
6
|
-
* - role ∈ {user, assistant} (system/tool/unknown rejected by default)
|
|
7
|
-
*
|
|
8
|
-
* pass through. "unknown" source is ALWAYS rejected (it indicates the
|
|
9
|
-
* event was constructed without explicit channel attribution — risk vector).
|
|
10
|
-
*
|
|
11
|
-
* No content access. No telemetry write here — pipeline (T6) records the
|
|
12
|
-
* decision via the trace mechanism.
|
|
13
|
-
*/
|
|
14
|
-
/** Roles we accept as conversation content. */
|
|
15
|
-
const ALLOWED_ROLES = new Set(["user", "assistant"]);
|
|
16
|
-
/**
|
|
17
|
-
* Evaluate Layer 2 against a HookEvent given the active config.
|
|
18
|
-
* Pure function — safe to test in isolation.
|
|
19
|
-
*/
|
|
20
|
-
export function evaluateSourceAllowlist(event, config, opts = {}) {
|
|
21
|
-
const roles = opts.allowedRoles ?? ALLOWED_ROLES;
|
|
22
|
-
// Reject unknown source unconditionally — explicit attribution required.
|
|
23
|
-
if (event.source === "unknown") {
|
|
24
|
-
return {
|
|
25
|
-
capture: false,
|
|
26
|
-
reason: "source=unknown is never allowed (explicit channel attribution required)",
|
|
27
|
-
layer: "source-allowlist",
|
|
28
|
-
};
|
|
29
|
-
}
|
|
30
|
-
if (!config.allowedSources.has(event.source)) {
|
|
31
|
-
return {
|
|
32
|
-
capture: false,
|
|
33
|
-
reason: `source=${event.source} not in NOX_HOOK_SOURCES allowlist`,
|
|
34
|
-
layer: "source-allowlist",
|
|
35
|
-
};
|
|
36
|
-
}
|
|
37
|
-
if (!roles.has(event.role)) {
|
|
38
|
-
return {
|
|
39
|
-
capture: false,
|
|
40
|
-
reason: `role=${event.role} not in {user,assistant}`,
|
|
41
|
-
layer: "source-allowlist",
|
|
42
|
-
};
|
|
43
|
-
}
|
|
44
|
-
return {
|
|
45
|
-
capture: true,
|
|
46
|
-
reason: `source=${event.source} role=${event.role} allowed`,
|
|
47
|
-
layer: "source-allowlist",
|
|
48
|
-
};
|
|
49
|
-
}
|
|
50
|
-
/** Returns true if a given source string is recognized at all. */
|
|
51
|
-
export function isKnownSource(s) {
|
|
52
|
-
return ["openclaw", "cli", "manual", "mcp", "api", "unknown"].includes(s);
|
|
53
|
-
}
|
|
@@ -1,129 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* src/lib/hooks/types.ts — T1: Hook contract types.
|
|
3
|
-
*
|
|
4
|
-
* Public interfaces consumed by the 5-layer pipeline (T6) and all callers
|
|
5
|
-
* (plugin T8, CLI T11, HTTP T12, MCP T13).
|
|
6
|
-
*
|
|
7
|
-
* Schema dependency: `agent_events` table (v11) already exists per spec §6.1
|
|
8
|
-
* and is used by telemetry (T6 emits one row per rejection/capture).
|
|
9
|
-
*
|
|
10
|
-
* Privacy invariant: HookEvent.content is RAW until it leaves Layer 3.
|
|
11
|
-
* After Layer 3, content has been passed through staged-A1 redact().
|
|
12
|
-
* Telemetry rows NEVER include raw content — only layer name + reason + ts.
|
|
13
|
-
*/
|
|
14
|
-
/**
|
|
15
|
-
* Roles we recognize from the source agent's turn.
|
|
16
|
-
* Layer 2 (source allowlist) constrains which roles get processed.
|
|
17
|
-
*/
|
|
18
|
-
export type HookRole = "user" | "assistant" | "system" | "tool" | "unknown";
|
|
19
|
-
/**
|
|
20
|
-
* Origin channel of the event. Determines source allowlist (Layer 2).
|
|
21
|
-
* - openclaw : afterTurn hook from the OpenClaw gateway
|
|
22
|
-
* - cli : explicit `nox-mem hooks ingest` (manual or scripted)
|
|
23
|
-
* - manual : in-process API client (tests, REPL, ad-hoc)
|
|
24
|
-
* - mcp : MCP tool call
|
|
25
|
-
* - api : HTTP endpoint
|
|
26
|
-
* - unknown : default; ALWAYS rejected by Layer 2 unless explicitly allowed
|
|
27
|
-
*/
|
|
28
|
-
export type HookSource = "openclaw" | "cli" | "manual" | "mcp" | "api" | "unknown";
|
|
29
|
-
/**
|
|
30
|
-
* Five-layer rejection reasons (one per layer + ok).
|
|
31
|
-
* Stored in `agent_events.kind`-like telemetry column.
|
|
32
|
-
*/
|
|
33
|
-
export type RejectionReason = "env_disabled" | "source_not_allowed" | "pii_detected_skip" | "classifier_low_signal" | "rate_limited" | "dedup_hit" | "queue_full" | "explicit_skip" | "dry_run" | "invalid_input";
|
|
34
|
-
/** A capture decision returned by any layer. */
|
|
35
|
-
export interface CaptureDecision {
|
|
36
|
-
/** True → forward to next layer (or persist if last). */
|
|
37
|
-
capture: boolean;
|
|
38
|
-
/** Human-readable reason. Stored in telemetry. NEVER includes raw content. */
|
|
39
|
-
reason: string;
|
|
40
|
-
/** Optional layer-name; pipeline fills this if missing. */
|
|
41
|
-
layer?: string;
|
|
42
|
-
/** Optional score in [0,1] when classifier returned ambiguous. */
|
|
43
|
-
score?: number;
|
|
44
|
-
}
|
|
45
|
-
/**
|
|
46
|
-
* A normalized event before any layer touches it.
|
|
47
|
-
* Source must populate role + content; rest is metadata.
|
|
48
|
-
*/
|
|
49
|
-
export interface HookEvent {
|
|
50
|
-
/** ULID assigned by caller or pipeline; used for dedup key + telemetry. */
|
|
51
|
-
event_id: string;
|
|
52
|
-
/** Where this event came from. */
|
|
53
|
-
source: HookSource;
|
|
54
|
-
/** Speaker. Layer 2 may filter by allowed roles. */
|
|
55
|
-
role: HookRole;
|
|
56
|
-
/** Raw text content (potentially containing PII). */
|
|
57
|
-
content: string;
|
|
58
|
-
/** Optional session_id (groups events from same convo). */
|
|
59
|
-
session_id?: string;
|
|
60
|
-
/** Optional project slug (cwd → slug mapping in plugin). */
|
|
61
|
-
project_slug?: string;
|
|
62
|
-
/** ISO 8601 timestamp. */
|
|
63
|
-
ts: string;
|
|
64
|
-
/** Optional decorator hints (T10 parses these). */
|
|
65
|
-
decorators?: ReadonlyArray<"capture" | "skip">;
|
|
66
|
-
/** Free-form metadata (model name, tool name, etc). NEVER content. */
|
|
67
|
-
meta?: Readonly<Record<string, string | number | boolean>>;
|
|
68
|
-
}
|
|
69
|
-
/**
|
|
70
|
-
* Mutable per-event state threaded through the pipeline.
|
|
71
|
-
* Lets each layer attach side-data without mutating the original HookEvent.
|
|
72
|
-
*/
|
|
73
|
-
export interface HookContext {
|
|
74
|
-
event: HookEvent;
|
|
75
|
-
/** Redacted text + redaction count after Layer 3. */
|
|
76
|
-
redacted?: {
|
|
77
|
-
text: string;
|
|
78
|
-
redaction_count: number;
|
|
79
|
-
kinds: string[];
|
|
80
|
-
};
|
|
81
|
-
/** Classifier output after Layer 4. */
|
|
82
|
-
classification?: {
|
|
83
|
-
score: number;
|
|
84
|
-
reason: string;
|
|
85
|
-
};
|
|
86
|
-
/** Per-layer trace (debug + dryrun). */
|
|
87
|
-
trace: Array<{
|
|
88
|
-
layer: string;
|
|
89
|
-
decision: CaptureDecision;
|
|
90
|
-
t_ms: number;
|
|
91
|
-
}>;
|
|
92
|
-
/** Set once when pipeline short-circuits or persists. */
|
|
93
|
-
outcome?: HookResult;
|
|
94
|
-
}
|
|
95
|
-
/** Final pipeline result. */
|
|
96
|
-
export interface HookResult {
|
|
97
|
-
captured: boolean;
|
|
98
|
-
/** Reason for rejection, or "ok" when captured. */
|
|
99
|
-
reason: RejectionReason | "ok";
|
|
100
|
-
/** Layer that fired the rejection, or "persisted" on success. */
|
|
101
|
-
layer: string;
|
|
102
|
-
/** chunk_id when captured (set by ingestText). */
|
|
103
|
-
chunk_id?: number;
|
|
104
|
-
/** Total wall-clock time. */
|
|
105
|
-
duration_ms: number;
|
|
106
|
-
/** Whether dry-run mode was on (no persistence even if captured=true). */
|
|
107
|
-
dry_run: boolean;
|
|
108
|
-
}
|
|
109
|
-
/**
|
|
110
|
-
* Telemetry row written by pipeline for EVERY event (captured or rejected).
|
|
111
|
-
* Maps onto `agent_events` columns; payload_json is a sanitized stub
|
|
112
|
-
* (NEVER raw content).
|
|
113
|
-
*/
|
|
114
|
-
export interface HookTelemetryRow {
|
|
115
|
-
event_uuid: string;
|
|
116
|
-
session_id: string;
|
|
117
|
-
project_slug: string;
|
|
118
|
-
kind: "tool_use" | "user_prompt" | "session_start" | "session_end" | "pre_compact";
|
|
119
|
-
timestamp: string;
|
|
120
|
-
payload_json: string;
|
|
121
|
-
redaction_count: number;
|
|
122
|
-
retention_days: number;
|
|
123
|
-
}
|
|
124
|
-
/** Standard error class for hook pipeline failures. */
|
|
125
|
-
export declare class HookError extends Error {
|
|
126
|
-
readonly code: RejectionReason | "internal";
|
|
127
|
-
readonly layer?: string;
|
|
128
|
-
constructor(code: RejectionReason | "internal", message: string, layer?: string);
|
|
129
|
-
}
|
package/dist/lib/hooks/types.js
DELETED
|
@@ -1,24 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* src/lib/hooks/types.ts — T1: Hook contract types.
|
|
3
|
-
*
|
|
4
|
-
* Public interfaces consumed by the 5-layer pipeline (T6) and all callers
|
|
5
|
-
* (plugin T8, CLI T11, HTTP T12, MCP T13).
|
|
6
|
-
*
|
|
7
|
-
* Schema dependency: `agent_events` table (v11) already exists per spec §6.1
|
|
8
|
-
* and is used by telemetry (T6 emits one row per rejection/capture).
|
|
9
|
-
*
|
|
10
|
-
* Privacy invariant: HookEvent.content is RAW until it leaves Layer 3.
|
|
11
|
-
* After Layer 3, content has been passed through staged-A1 redact().
|
|
12
|
-
* Telemetry rows NEVER include raw content — only layer name + reason + ts.
|
|
13
|
-
*/
|
|
14
|
-
/** Standard error class for hook pipeline failures. */
|
|
15
|
-
export class HookError extends Error {
|
|
16
|
-
code;
|
|
17
|
-
layer;
|
|
18
|
-
constructor(code, message, layer) {
|
|
19
|
-
super(message);
|
|
20
|
-
this.name = "HookError";
|
|
21
|
-
this.code = code;
|
|
22
|
-
this.layer = layer;
|
|
23
|
-
}
|
|
24
|
-
}
|
|
@@ -1,56 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* src/lib/hooks/worker.ts — T9: Async worker queue.
|
|
3
|
-
*
|
|
4
|
-
* Backpressure-aware bounded queue:
|
|
5
|
-
* - enqueue() returns synchronously (non-blocking for callers like
|
|
6
|
-
* OpenClaw afterTurn hook). Returns {accepted, reason}.
|
|
7
|
-
* - When full, oldest event is dropped + telemetry "queue_full" row
|
|
8
|
-
* emitted. New event takes its slot (most-recent-wins).
|
|
9
|
-
* - A drain loop runs every `tickMs` ms, processing batches of up to
|
|
10
|
-
* `batchSize` events through the pipeline.
|
|
11
|
-
*
|
|
12
|
-
* The worker is the bridge between the synchronous hook trigger (an
|
|
13
|
-
* OpenClaw turn ended) and the async pipeline (which may call out to
|
|
14
|
-
* embed/ingest).
|
|
15
|
-
*
|
|
16
|
-
* Lifecycle:
|
|
17
|
-
* const w = createWorker({ pipeline, ...opts });
|
|
18
|
-
* w.start();
|
|
19
|
-
* w.enqueue(event);
|
|
20
|
-
* ...
|
|
21
|
-
* await w.stop(); // drains remaining + shuts down
|
|
22
|
-
*/
|
|
23
|
-
import type { PipelineHandle } from "./pipeline.js";
|
|
24
|
-
import type { HookEvent, HookResult, HookTelemetryRow } from "./types.js";
|
|
25
|
-
export interface WorkerOpts {
|
|
26
|
-
pipeline: PipelineHandle;
|
|
27
|
-
/** Max events held in queue. Default 10_000 (matches spec ring buffer). */
|
|
28
|
-
maxSize?: number;
|
|
29
|
-
/** Drain tick interval. Default 250ms (matches spec §3 T3). */
|
|
30
|
-
tickMs?: number;
|
|
31
|
-
/** Max events processed per tick. Default 100. */
|
|
32
|
-
batchSize?: number;
|
|
33
|
-
/** Optional sink for queue-overflow telemetry. */
|
|
34
|
-
telemetry?: (row: HookTelemetryRow) => void | Promise<void>;
|
|
35
|
-
}
|
|
36
|
-
export interface WorkerStats {
|
|
37
|
-
enqueued: number;
|
|
38
|
-
processed: number;
|
|
39
|
-
rejected: number;
|
|
40
|
-
captured: number;
|
|
41
|
-
dropped: number;
|
|
42
|
-
errors: number;
|
|
43
|
-
queueDepth: number;
|
|
44
|
-
}
|
|
45
|
-
export interface WorkerHandle {
|
|
46
|
-
enqueue(event: HookEvent): {
|
|
47
|
-
accepted: boolean;
|
|
48
|
-
reason: string;
|
|
49
|
-
depth: number;
|
|
50
|
-
};
|
|
51
|
-
start(): void;
|
|
52
|
-
stop(): Promise<void>;
|
|
53
|
-
drain(): Promise<HookResult[]>;
|
|
54
|
-
stats(): WorkerStats;
|
|
55
|
-
}
|
|
56
|
-
export declare function createWorker(opts: WorkerOpts): WorkerHandle;
|
package/dist/lib/hooks/worker.js
DELETED
|
@@ -1,150 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* src/lib/hooks/worker.ts — T9: Async worker queue.
|
|
3
|
-
*
|
|
4
|
-
* Backpressure-aware bounded queue:
|
|
5
|
-
* - enqueue() returns synchronously (non-blocking for callers like
|
|
6
|
-
* OpenClaw afterTurn hook). Returns {accepted, reason}.
|
|
7
|
-
* - When full, oldest event is dropped + telemetry "queue_full" row
|
|
8
|
-
* emitted. New event takes its slot (most-recent-wins).
|
|
9
|
-
* - A drain loop runs every `tickMs` ms, processing batches of up to
|
|
10
|
-
* `batchSize` events through the pipeline.
|
|
11
|
-
*
|
|
12
|
-
* The worker is the bridge between the synchronous hook trigger (an
|
|
13
|
-
* OpenClaw turn ended) and the async pipeline (which may call out to
|
|
14
|
-
* embed/ingest).
|
|
15
|
-
*
|
|
16
|
-
* Lifecycle:
|
|
17
|
-
* const w = createWorker({ pipeline, ...opts });
|
|
18
|
-
* w.start();
|
|
19
|
-
* w.enqueue(event);
|
|
20
|
-
* ...
|
|
21
|
-
* await w.stop(); // drains remaining + shuts down
|
|
22
|
-
*/
|
|
23
|
-
export function createWorker(opts) {
|
|
24
|
-
const pipeline = opts.pipeline;
|
|
25
|
-
const maxSize = opts.maxSize ?? 10_000;
|
|
26
|
-
const tickMs = opts.tickMs ?? 250;
|
|
27
|
-
const batchSize = opts.batchSize ?? 100;
|
|
28
|
-
const telemetry = opts.telemetry;
|
|
29
|
-
const queue = [];
|
|
30
|
-
let timer = null;
|
|
31
|
-
let running = false;
|
|
32
|
-
let inFlight = null;
|
|
33
|
-
const counters = {
|
|
34
|
-
enqueued: 0,
|
|
35
|
-
processed: 0,
|
|
36
|
-
rejected: 0,
|
|
37
|
-
captured: 0,
|
|
38
|
-
dropped: 0,
|
|
39
|
-
errors: 0,
|
|
40
|
-
queueDepth: 0,
|
|
41
|
-
};
|
|
42
|
-
function refreshDepth() {
|
|
43
|
-
counters.queueDepth = queue.length;
|
|
44
|
-
}
|
|
45
|
-
function emitOverflow(droppedEvent) {
|
|
46
|
-
if (!telemetry)
|
|
47
|
-
return;
|
|
48
|
-
try {
|
|
49
|
-
void telemetry({
|
|
50
|
-
event_uuid: droppedEvent.event_id,
|
|
51
|
-
session_id: droppedEvent.session_id ?? "unknown",
|
|
52
|
-
project_slug: droppedEvent.project_slug ?? "unknown",
|
|
53
|
-
kind: "tool_use",
|
|
54
|
-
timestamp: droppedEvent.ts,
|
|
55
|
-
payload_json: JSON.stringify({ layer: "worker", reason: "queue_full_dropped_oldest" }),
|
|
56
|
-
redaction_count: 0,
|
|
57
|
-
retention_days: 30,
|
|
58
|
-
});
|
|
59
|
-
}
|
|
60
|
-
catch {
|
|
61
|
-
/* ignore */
|
|
62
|
-
}
|
|
63
|
-
}
|
|
64
|
-
async function tick(force = false) {
|
|
65
|
-
if ((!running && !force) || queue.length === 0)
|
|
66
|
-
return;
|
|
67
|
-
const batch = queue.splice(0, batchSize);
|
|
68
|
-
refreshDepth();
|
|
69
|
-
for (const ev of batch) {
|
|
70
|
-
try {
|
|
71
|
-
const result = await pipeline.run(ev);
|
|
72
|
-
counters.processed += 1;
|
|
73
|
-
if (result.captured)
|
|
74
|
-
counters.captured += 1;
|
|
75
|
-
else
|
|
76
|
-
counters.rejected += 1;
|
|
77
|
-
}
|
|
78
|
-
catch {
|
|
79
|
-
counters.errors += 1;
|
|
80
|
-
}
|
|
81
|
-
}
|
|
82
|
-
}
|
|
83
|
-
function scheduleTick() {
|
|
84
|
-
inFlight = tick().finally(() => {
|
|
85
|
-
inFlight = null;
|
|
86
|
-
});
|
|
87
|
-
}
|
|
88
|
-
return {
|
|
89
|
-
enqueue(event) {
|
|
90
|
-
counters.enqueued += 1;
|
|
91
|
-
if (queue.length >= maxSize) {
|
|
92
|
-
// Drop oldest, append new
|
|
93
|
-
const dropped = queue.shift();
|
|
94
|
-
if (dropped) {
|
|
95
|
-
counters.dropped += 1;
|
|
96
|
-
emitOverflow(dropped);
|
|
97
|
-
}
|
|
98
|
-
queue.push(event);
|
|
99
|
-
refreshDepth();
|
|
100
|
-
return { accepted: true, reason: "queue_full_dropped_oldest", depth: queue.length };
|
|
101
|
-
}
|
|
102
|
-
queue.push(event);
|
|
103
|
-
refreshDepth();
|
|
104
|
-
return { accepted: true, reason: "enqueued", depth: queue.length };
|
|
105
|
-
},
|
|
106
|
-
start() {
|
|
107
|
-
if (running)
|
|
108
|
-
return;
|
|
109
|
-
running = true;
|
|
110
|
-
timer = setInterval(scheduleTick, tickMs);
|
|
111
|
-
},
|
|
112
|
-
async stop() {
|
|
113
|
-
running = false;
|
|
114
|
-
if (timer) {
|
|
115
|
-
clearInterval(timer);
|
|
116
|
-
timer = null;
|
|
117
|
-
}
|
|
118
|
-
// Drain remaining (force=true to bypass running check)
|
|
119
|
-
if (inFlight)
|
|
120
|
-
await inFlight;
|
|
121
|
-
while (queue.length > 0) {
|
|
122
|
-
await tick(true);
|
|
123
|
-
}
|
|
124
|
-
},
|
|
125
|
-
async drain() {
|
|
126
|
-
const out = [];
|
|
127
|
-
while (queue.length > 0) {
|
|
128
|
-
const ev = queue.shift();
|
|
129
|
-
refreshDepth();
|
|
130
|
-
try {
|
|
131
|
-
const r = await pipeline.run(ev);
|
|
132
|
-
counters.processed += 1;
|
|
133
|
-
if (r.captured)
|
|
134
|
-
counters.captured += 1;
|
|
135
|
-
else
|
|
136
|
-
counters.rejected += 1;
|
|
137
|
-
out.push(r);
|
|
138
|
-
}
|
|
139
|
-
catch {
|
|
140
|
-
counters.errors += 1;
|
|
141
|
-
}
|
|
142
|
-
}
|
|
143
|
-
return out;
|
|
144
|
-
},
|
|
145
|
-
stats() {
|
|
146
|
-
refreshDepth();
|
|
147
|
-
return { ...counters };
|
|
148
|
-
},
|
|
149
|
-
};
|
|
150
|
-
}
|
|
@@ -1,25 +0,0 @@
|
|
|
1
|
-
import type Database from "better-sqlite3";
|
|
2
|
-
export type IngestKind = "entity" | "markdown" | "graphify" | "pdf-scanned";
|
|
3
|
-
export interface IngestRouteResult {
|
|
4
|
-
chunks: number;
|
|
5
|
-
kind: IngestKind;
|
|
6
|
-
routedTo: string;
|
|
7
|
-
/** Para 'pdf-scanned' kind: jobId enfileirado. */
|
|
8
|
-
ocrJobId?: number;
|
|
9
|
-
}
|
|
10
|
-
export interface IngestOpts {
|
|
11
|
-
externalDb?: Database.Database;
|
|
12
|
-
skipDelete?: boolean;
|
|
13
|
-
forceKind?: IngestKind;
|
|
14
|
-
}
|
|
15
|
-
/**
|
|
16
|
-
* Detect ingest kind from path conventions. Centralizada aqui — mexer só nesse
|
|
17
|
-
* arquivo quando adicionar novo tipo (ex: "pdf-text-layer", "fathom-transcript").
|
|
18
|
-
*/
|
|
19
|
-
export declare function detectIngestKind(filePath: string): IngestKind;
|
|
20
|
-
/**
|
|
21
|
-
* Single dispatch entry point. Todos callers devem usar isso em vez de chamar
|
|
22
|
-
* ingestFile()/ingestEntityFile() direto. Backward compat: kinds não-implementados
|
|
23
|
-
* caem no markdown handler (ingestFile).
|
|
24
|
-
*/
|
|
25
|
-
export declare function routeIngest(filePath: string, opts?: IngestOpts): Promise<IngestRouteResult>;
|
|
@@ -1,61 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Threshold de char count abaixo do qual um PDF é considerado scaneado.
|
|
3
|
-
* Markitdown sem OCR tipicamente retorna 2-50 chars em PDFs imagem.
|
|
4
|
-
*/
|
|
5
|
-
export declare const SCANNED_PDF_CHAR_THRESHOLD = 100;
|
|
6
|
-
/**
|
|
7
|
-
* Threshold de tamanho/ratio: PDF >5MB com <0.001 chars/byte → provável scan
|
|
8
|
-
* (densidade de texto extremamente baixa).
|
|
9
|
-
*/
|
|
10
|
-
export declare const LARGE_PDF_BYTES_THRESHOLD = 5000000;
|
|
11
|
-
export declare const LARGE_PDF_CHAR_RATIO = 0.001;
|
|
12
|
-
/**
|
|
13
|
-
* Threshold da pdftotext probe na primeira página.
|
|
14
|
-
* <50 chars na 1ª página é forte indicador de scan.
|
|
15
|
-
*/
|
|
16
|
-
export declare const PROBE_FIRST_PAGE_THRESHOLD = 50;
|
|
17
|
-
/**
|
|
18
|
-
* Heurística primária pós-markitdown.
|
|
19
|
-
*
|
|
20
|
-
* @param markitdownOutput texto extraído pelo markitdown (vazio ou ~2 chars = sinal forte)
|
|
21
|
-
* @param fileSize tamanho do PDF em bytes
|
|
22
|
-
* @returns true se PDF é provavelmente scaneado
|
|
23
|
-
*/
|
|
24
|
-
export declare function isScannedPdf(markitdownOutput: string, fileSize: number): boolean;
|
|
25
|
-
export interface PdftotextProbeResult {
|
|
26
|
-
likelyScan: boolean;
|
|
27
|
-
firstPageChars: number;
|
|
28
|
-
/** -1 sentinela quando pdftotext não está disponível ou crash. */
|
|
29
|
-
error?: string;
|
|
30
|
-
}
|
|
31
|
-
/**
|
|
32
|
-
* Pre-flight zero-cost: extrai apenas a 1ª página via pdftotext e conta chars.
|
|
33
|
-
* Usa execFileSync (regra security: argumento como array, sem shell).
|
|
34
|
-
*
|
|
35
|
-
* Graceful: se pdftotext não está instalado, retorna `{ likelyScan: false, firstPageChars: -1 }`
|
|
36
|
-
* com warn em stderr — caller decide fallback (markitdown direto, OCR enqueue, etc).
|
|
37
|
-
*/
|
|
38
|
-
export declare function pdftotextProbe(filePath: string): Promise<PdftotextProbeResult>;
|
|
39
|
-
export interface OcrRouteHint {
|
|
40
|
-
/** Override manual: força routing pra OCR mesmo se probe disser não. */
|
|
41
|
-
force?: boolean;
|
|
42
|
-
/** Path/folder prior (ex: PPR/, PESSOAL/) — força route=true sem probe. */
|
|
43
|
-
folder?: string;
|
|
44
|
-
}
|
|
45
|
-
export interface OcrRouteDecision {
|
|
46
|
-
route: boolean;
|
|
47
|
-
reason: string;
|
|
48
|
-
}
|
|
49
|
-
/**
|
|
50
|
-
* Combina file-size + pdftotext probe + hints (force, folder prior) pra decidir
|
|
51
|
-
* se PDF deve ser roteado pra OCR pipeline.
|
|
52
|
-
*
|
|
53
|
-
* Ordem de precedência:
|
|
54
|
-
* 1. opts.force=true → route=true ("forced")
|
|
55
|
-
* 2. arquivo não existe → route=false ("file-not-found")
|
|
56
|
-
* 3. arquivo está em SCAN_PRIOR_FOLDERS → route=true ("folder-prior")
|
|
57
|
-
* 4. probe.firstPageChars < threshold → route=true ("probe-scan")
|
|
58
|
-
* 5. probe.firstPageChars > threshold → route=false ("probe-text")
|
|
59
|
-
* 6. probe error/unavailable → route=false ("probe-unavailable", caller usa heurística pós-markitdown)
|
|
60
|
-
*/
|
|
61
|
-
export declare function shouldRouteToOcr(filePath: string, hint?: OcrRouteHint): Promise<OcrRouteDecision>;
|
package/dist/lib/ocr-detector.js
DELETED
|
@@ -1,138 +0,0 @@
|
|
|
1
|
-
// ocr-detector.ts — Heurísticas de detecção de PDF scaneado (E12 Tier 3).
|
|
2
|
-
// Spec: memoria-nox/specs/2026-05-07-E12-tier3-ocr.md §2
|
|
3
|
-
//
|
|
4
|
-
// Sem cloud calls. Apenas:
|
|
5
|
-
// 1. char count pós-markitdown (heurística primária)
|
|
6
|
-
// 2. pdftotext probe na primeira página (zero-cost pre-flight)
|
|
7
|
-
// 3. routing decision combinando probe + hints (force, folder prior)
|
|
8
|
-
//
|
|
9
|
-
// Memória ref: feedback_scanned_pdf_heuristic (markitdown sem OCR retorna ~2 chars).
|
|
10
|
-
// execFileSync (não execSync) — regra security feedback_execfilesync_over_execsync_for_user_input.
|
|
11
|
-
import { execFileSync } from "node:child_process";
|
|
12
|
-
import { existsSync, statSync } from "node:fs";
|
|
13
|
-
import { resolve } from "node:path";
|
|
14
|
-
/**
|
|
15
|
-
* Threshold de char count abaixo do qual um PDF é considerado scaneado.
|
|
16
|
-
* Markitdown sem OCR tipicamente retorna 2-50 chars em PDFs imagem.
|
|
17
|
-
*/
|
|
18
|
-
export const SCANNED_PDF_CHAR_THRESHOLD = 100;
|
|
19
|
-
/**
|
|
20
|
-
* Threshold de tamanho/ratio: PDF >5MB com <0.001 chars/byte → provável scan
|
|
21
|
-
* (densidade de texto extremamente baixa).
|
|
22
|
-
*/
|
|
23
|
-
export const LARGE_PDF_BYTES_THRESHOLD = 5_000_000;
|
|
24
|
-
export const LARGE_PDF_CHAR_RATIO = 0.001;
|
|
25
|
-
/**
|
|
26
|
-
* Threshold da pdftotext probe na primeira página.
|
|
27
|
-
* <50 chars na 1ª página é forte indicador de scan.
|
|
28
|
-
*/
|
|
29
|
-
export const PROBE_FIRST_PAGE_THRESHOLD = 50;
|
|
30
|
-
/**
|
|
31
|
-
* Folders com prior alto de PDF scaneado. Gera `route=true` mesmo sem probe.
|
|
32
|
-
* Lista propositalmente conservadora — overrides via `--force-ocr` no CLI.
|
|
33
|
-
*/
|
|
34
|
-
const SCAN_PRIOR_FOLDERS = ["/Documents/PPR/", "/Documents/PESSOAL/"];
|
|
35
|
-
/**
|
|
36
|
-
* Heurística primária pós-markitdown.
|
|
37
|
-
*
|
|
38
|
-
* @param markitdownOutput texto extraído pelo markitdown (vazio ou ~2 chars = sinal forte)
|
|
39
|
-
* @param fileSize tamanho do PDF em bytes
|
|
40
|
-
* @returns true se PDF é provavelmente scaneado
|
|
41
|
-
*/
|
|
42
|
-
export function isScannedPdf(markitdownOutput, fileSize) {
|
|
43
|
-
if (!markitdownOutput)
|
|
44
|
-
return true;
|
|
45
|
-
// Strip whitespace pra char count "real".
|
|
46
|
-
const stripped = markitdownOutput.replace(/\s+/g, "").trim();
|
|
47
|
-
if (stripped.length < SCANNED_PDF_CHAR_THRESHOLD)
|
|
48
|
-
return true;
|
|
49
|
-
// Sanity check: PDF grande com densidade text/byte muito baixa = scan.
|
|
50
|
-
if (fileSize > LARGE_PDF_BYTES_THRESHOLD && stripped.length / fileSize < LARGE_PDF_CHAR_RATIO) {
|
|
51
|
-
return true;
|
|
52
|
-
}
|
|
53
|
-
return false;
|
|
54
|
-
}
|
|
55
|
-
/**
|
|
56
|
-
* Pre-flight zero-cost: extrai apenas a 1ª página via pdftotext e conta chars.
|
|
57
|
-
* Usa execFileSync (regra security: argumento como array, sem shell).
|
|
58
|
-
*
|
|
59
|
-
* Graceful: se pdftotext não está instalado, retorna `{ likelyScan: false, firstPageChars: -1 }`
|
|
60
|
-
* com warn em stderr — caller decide fallback (markitdown direto, OCR enqueue, etc).
|
|
61
|
-
*/
|
|
62
|
-
export async function pdftotextProbe(filePath) {
|
|
63
|
-
if (!existsSync(filePath)) {
|
|
64
|
-
return { likelyScan: false, firstPageChars: -1, error: `file not found: ${filePath}` };
|
|
65
|
-
}
|
|
66
|
-
try {
|
|
67
|
-
const out = execFileSync("pdftotext", ["-l", "1", filePath, "-"], {
|
|
68
|
-
encoding: "utf-8",
|
|
69
|
-
timeout: 30_000,
|
|
70
|
-
maxBuffer: 5 * 1024 * 1024,
|
|
71
|
-
stdio: ["ignore", "pipe", "ignore"],
|
|
72
|
-
});
|
|
73
|
-
const stripped = (out || "").replace(/\s+/g, "").trim();
|
|
74
|
-
return {
|
|
75
|
-
likelyScan: stripped.length < PROBE_FIRST_PAGE_THRESHOLD,
|
|
76
|
-
firstPageChars: stripped.length,
|
|
77
|
-
};
|
|
78
|
-
}
|
|
79
|
-
catch (err) {
|
|
80
|
-
const code = err?.code || err?.errno;
|
|
81
|
-
const msg = String(err?.message ?? err);
|
|
82
|
-
// ENOENT = pdftotext não instalado (não-fatal: caller decide).
|
|
83
|
-
if (code === "ENOENT") {
|
|
84
|
-
console.warn("[ocr-detector] pdftotext not installed; skipping probe (apt install poppler-utils OR brew install poppler)");
|
|
85
|
-
return { likelyScan: false, firstPageChars: -1, error: "pdftotext not installed" };
|
|
86
|
-
}
|
|
87
|
-
console.warn(`[ocr-detector] pdftotext probe failed: ${msg}`);
|
|
88
|
-
return { likelyScan: false, firstPageChars: -1, error: msg };
|
|
89
|
-
}
|
|
90
|
-
}
|
|
91
|
-
/**
|
|
92
|
-
* Combina file-size + pdftotext probe + hints (force, folder prior) pra decidir
|
|
93
|
-
* se PDF deve ser roteado pra OCR pipeline.
|
|
94
|
-
*
|
|
95
|
-
* Ordem de precedência:
|
|
96
|
-
* 1. opts.force=true → route=true ("forced")
|
|
97
|
-
* 2. arquivo não existe → route=false ("file-not-found")
|
|
98
|
-
* 3. arquivo está em SCAN_PRIOR_FOLDERS → route=true ("folder-prior")
|
|
99
|
-
* 4. probe.firstPageChars < threshold → route=true ("probe-scan")
|
|
100
|
-
* 5. probe.firstPageChars > threshold → route=false ("probe-text")
|
|
101
|
-
* 6. probe error/unavailable → route=false ("probe-unavailable", caller usa heurística pós-markitdown)
|
|
102
|
-
*/
|
|
103
|
-
export async function shouldRouteToOcr(filePath, hint = {}) {
|
|
104
|
-
if (hint.force)
|
|
105
|
-
return { route: true, reason: "forced" };
|
|
106
|
-
if (!existsSync(filePath))
|
|
107
|
-
return { route: false, reason: "file-not-found" };
|
|
108
|
-
const abs = resolve(filePath);
|
|
109
|
-
// Normaliza separadores pra cobrir POSIX (Linux VPS) + Windows-likely-never.
|
|
110
|
-
const folderHint = hint.folder ? resolve(hint.folder) : abs;
|
|
111
|
-
for (const prior of SCAN_PRIOR_FOLDERS) {
|
|
112
|
-
if (folderHint.includes(prior) || abs.includes(prior)) {
|
|
113
|
-
return { route: true, reason: "folder-prior" };
|
|
114
|
-
}
|
|
115
|
-
}
|
|
116
|
-
// Não é PDF? routing pra OCR não se aplica.
|
|
117
|
-
if (!filePath.toLowerCase().endsWith(".pdf")) {
|
|
118
|
-
return { route: false, reason: "not-pdf" };
|
|
119
|
-
}
|
|
120
|
-
const probe = await pdftotextProbe(filePath);
|
|
121
|
-
if (probe.firstPageChars < 0) {
|
|
122
|
-
return { route: false, reason: `probe-unavailable:${probe.error ?? "unknown"}` };
|
|
123
|
-
}
|
|
124
|
-
if (probe.likelyScan) {
|
|
125
|
-
return { route: true, reason: `probe-scan:firstPageChars=${probe.firstPageChars}` };
|
|
126
|
-
}
|
|
127
|
-
// Sanity: file gigante com poucos chars na probe → também route.
|
|
128
|
-
try {
|
|
129
|
-
const sizeBytes = statSync(filePath).size;
|
|
130
|
-
if (sizeBytes > LARGE_PDF_BYTES_THRESHOLD && probe.firstPageChars < SCANNED_PDF_CHAR_THRESHOLD) {
|
|
131
|
-
return { route: true, reason: `large-file-low-text:${sizeBytes}b-${probe.firstPageChars}chars` };
|
|
132
|
-
}
|
|
133
|
-
}
|
|
134
|
-
catch {
|
|
135
|
-
/* stat failure non-fatal */
|
|
136
|
-
}
|
|
137
|
-
return { route: false, reason: `probe-text:firstPageChars=${probe.firstPageChars}` };
|
|
138
|
-
}
|
|
@@ -1,48 +0,0 @@
|
|
|
1
|
-
export interface OcrResult {
|
|
2
|
-
/** Markdown rendered output. Tabelas Doc AI → markdown tables; preserva \n\n. */
|
|
3
|
-
markdown: string;
|
|
4
|
-
/** Page count detectado (Tesseract via pdfinfo, Doc AI via response). */
|
|
5
|
-
pageCount: number;
|
|
6
|
-
/** Cost real do engine (Tesseract = 0; cloud = chamada billable). */
|
|
7
|
-
costUsd: number;
|
|
8
|
-
}
|
|
9
|
-
export interface OcrEngine {
|
|
10
|
-
/** Identificador estável do engine (persistido em ocr_jobs.engine). */
|
|
11
|
-
readonly name: string;
|
|
12
|
-
/**
|
|
13
|
-
* Custo estimado em USD pra processar `pageCount` páginas.
|
|
14
|
-
* Tesseract: 0. Google Doc AI: ~$1.50/1k pages.
|
|
15
|
-
*/
|
|
16
|
-
estimateCostUsd(pageCount: number): number;
|
|
17
|
-
/** Roda OCR no arquivo e retorna markdown + metadata. */
|
|
18
|
-
ocrFile(filePath: string): Promise<OcrResult>;
|
|
19
|
-
}
|
|
20
|
-
/**
|
|
21
|
-
* Detecta se tesseract + pdftoppm estão instalados.
|
|
22
|
-
* Retorna { available, missing[] } pra mensagens UX claras.
|
|
23
|
-
*/
|
|
24
|
-
export declare function detectTesseractAvailability(): {
|
|
25
|
-
available: boolean;
|
|
26
|
-
missing: string[];
|
|
27
|
-
};
|
|
28
|
-
export declare class TesseractEngine implements OcrEngine {
|
|
29
|
-
readonly name = "tesseract";
|
|
30
|
-
private readonly lang;
|
|
31
|
-
constructor(opts?: {
|
|
32
|
-
lang?: string;
|
|
33
|
-
});
|
|
34
|
-
estimateCostUsd(_pageCount: number): number;
|
|
35
|
-
ocrFile(filePath: string): Promise<OcrResult>;
|
|
36
|
-
private ocrImage;
|
|
37
|
-
private ocrPdfViaConversion;
|
|
38
|
-
private runTesseract;
|
|
39
|
-
private detectPageCount;
|
|
40
|
-
}
|
|
41
|
-
/**
|
|
42
|
-
* Factory por nome. Cria engine apropriado.
|
|
43
|
-
* - "tesseract" → TesseractEngine (CPU local, $0)
|
|
44
|
-
* - "google_doc_ai" → GoogleDocAiEngine (cloud, $1.50/1k pages)
|
|
45
|
-
*/
|
|
46
|
-
export declare function createEngine(name: string, opts?: Record<string, unknown>): OcrEngine;
|
|
47
|
-
/** Alias: caller-friendly name esperado pela spec. */
|
|
48
|
-
export declare function getEngine(name: string, opts?: Record<string, unknown>): OcrEngine;
|