nox-mem 3.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +179 -0
- package/dist/api/answer.d.ts +116 -0
- package/dist/api/answer.js +274 -0
- package/dist/api/answer.validate-patch.d.ts +72 -0
- package/dist/api/answer.validate-patch.js +52 -0
- package/dist/api/brief-diversity.d.ts +64 -0
- package/dist/api/brief-diversity.js +91 -0
- package/dist/api/brief.d.ts +114 -0
- package/dist/api/brief.js +524 -0
- package/dist/api/conflict.d.ts +33 -0
- package/dist/api/conflict.js +143 -0
- package/dist/api/cors.d.ts +73 -0
- package/dist/api/cors.js +124 -0
- package/dist/api/events-stream-limited.d.ts +133 -0
- package/dist/api/events-stream-limited.js +217 -0
- package/dist/api/events-stream.d.ts +53 -0
- package/dist/api/events-stream.js +125 -0
- package/dist/api/export.d.ts +42 -0
- package/dist/api/export.js +85 -0
- package/dist/api/health-confidence-adapter.d.ts +29 -0
- package/dist/api/health-confidence-adapter.js +73 -0
- package/dist/api/health-confidence.d.ts +36 -0
- package/dist/api/health-confidence.js +141 -0
- package/dist/api/hooks.d.ts +50 -0
- package/dist/api/hooks.js +115 -0
- package/dist/api/import.d.ts +38 -0
- package/dist/api/import.js +87 -0
- package/dist/api/ingest-event.d.ts +65 -0
- package/dist/api/ingest-event.js +153 -0
- package/dist/api/mark.d.ts +42 -0
- package/dist/api/mark.js +127 -0
- package/dist/api/server-deps-a2.d.ts +55 -0
- package/dist/api/server-deps-a2.js +138 -0
- package/dist/api/server-deps-l2-l3.d.ts +68 -0
- package/dist/api/server-deps-l2-l3.js +123 -0
- package/dist/api/server-deps-p1.d.ts +84 -0
- package/dist/api/server-deps-p1.js +156 -0
- package/dist/api/server-deps-p2.d.ts +32 -0
- package/dist/api/server-deps-p2.js +84 -0
- package/dist/api/server-deps-p5.d.ts +66 -0
- package/dist/api/server-deps-p5.js +139 -0
- package/dist/api/viewer-static.d.ts +30 -0
- package/dist/api/viewer-static.js +102 -0
- package/dist/api/wire-up.d.ts +54 -0
- package/dist/api/wire-up.js +521 -0
- package/dist/api-impact.d.ts +30 -0
- package/dist/api-impact.js +196 -0
- package/dist/api-server.d.ts +2 -0
- package/dist/api-server.js +614 -0
- package/dist/backfill-fts-anchor.d.ts +15 -0
- package/dist/backfill-fts-anchor.js +97 -0
- package/dist/backfill-source-type.d.ts +20 -0
- package/dist/backfill-source-type.js +182 -0
- package/dist/churn.d.ts +31 -0
- package/dist/churn.js +98 -0
- package/dist/cli/answer.d.ts +66 -0
- package/dist/cli/answer.js +287 -0
- package/dist/cli/conflict.d.ts +38 -0
- package/dist/cli/conflict.js +282 -0
- package/dist/cli/export.d.ts +51 -0
- package/dist/cli/export.js +280 -0
- package/dist/cli/hooks.d.ts +54 -0
- package/dist/cli/hooks.js +133 -0
- package/dist/cli/import.d.ts +52 -0
- package/dist/cli/import.js +274 -0
- package/dist/cli/mark.d.ts +33 -0
- package/dist/cli/mark.js +130 -0
- package/dist/cli/ocr-batch.d.ts +12 -0
- package/dist/cli/ocr-batch.js +411 -0
- package/dist/cli/snapshot-main.d.ts +30 -0
- package/dist/cli/snapshot-main.js +47 -0
- package/dist/cli/viewer.d.ts +35 -0
- package/dist/cli/viewer.js +71 -0
- package/dist/cli-telemetry.d.ts +36 -0
- package/dist/cli-telemetry.js +150 -0
- package/dist/compact.d.ts +7 -0
- package/dist/compact.js +147 -0
- package/dist/consolidate.d.ts +18 -0
- package/dist/consolidate.js +475 -0
- package/dist/consolidation.d.ts +32 -0
- package/dist/consolidation.js +212 -0
- package/dist/cross-agent-v2.d.ts +45 -0
- package/dist/cross-agent-v2.js +271 -0
- package/dist/cross-search.d.ts +11 -0
- package/dist/cross-search.js +119 -0
- package/dist/crystallize.d.ts +43 -0
- package/dist/crystallize.js +111 -0
- package/dist/db.d.ts +11 -0
- package/dist/db.js +388 -0
- package/dist/dedup.d.ts +1 -0
- package/dist/dedup.js +106 -0
- package/dist/detect-changes.d.ts +29 -0
- package/dist/detect-changes.js +236 -0
- package/dist/digest.d.ts +1 -0
- package/dist/digest.js +205 -0
- package/dist/doctor.d.ts +1 -0
- package/dist/doctor.js +71 -0
- package/dist/embed.d.ts +45 -0
- package/dist/embed.js +257 -0
- package/dist/evals.d.ts +176 -0
- package/dist/evals.js +351 -0
- package/dist/generate-user-profile.d.ts +18 -0
- package/dist/generate-user-profile.js +163 -0
- package/dist/graphify-ingest.d.ts +18 -0
- package/dist/graphify-ingest.js +158 -0
- package/dist/impact.d.ts +39 -0
- package/dist/impact.js +143 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +689 -0
- package/dist/ingest-entity.d.ts +44 -0
- package/dist/ingest-entity.js +197 -0
- package/dist/ingest.d.ts +13 -0
- package/dist/ingest.js +210 -0
- package/dist/kg-llm.d.ts +39 -0
- package/dist/kg-llm.js +295 -0
- package/dist/knowledge-graph.d.ts +72 -0
- package/dist/knowledge-graph.js +507 -0
- package/dist/lib/answer/config.d.ts +41 -0
- package/dist/lib/answer/config.js +70 -0
- package/dist/lib/answer/index.d.ts +47 -0
- package/dist/lib/answer/index.js +221 -0
- package/dist/lib/answer/prompt.d.ts +37 -0
- package/dist/lib/answer/prompt.js +88 -0
- package/dist/lib/answer/provider.d.ts +47 -0
- package/dist/lib/answer/provider.js +101 -0
- package/dist/lib/answer/retrieval.d.ts +36 -0
- package/dist/lib/answer/retrieval.js +92 -0
- package/dist/lib/answer/telemetry.d.ts +99 -0
- package/dist/lib/answer/telemetry.js +154 -0
- package/dist/lib/answer/types.d.ts +108 -0
- package/dist/lib/answer/types.js +1 -0
- package/dist/lib/api/error-leak-fix.d.ts +54 -0
- package/dist/lib/api/error-leak-fix.js +55 -0
- package/dist/lib/api/safe-error-message.d.ts +70 -0
- package/dist/lib/api/safe-error-message.js +122 -0
- package/dist/lib/archive/common-passwords.d.ts +37 -0
- package/dist/lib/archive/common-passwords.js +753 -0
- package/dist/lib/archive/encryption.d.ts +81 -0
- package/dist/lib/archive/encryption.js +236 -0
- package/dist/lib/archive/enforce-strength.d.ts +54 -0
- package/dist/lib/archive/enforce-strength.js +70 -0
- package/dist/lib/archive/entropy.d.ts +34 -0
- package/dist/lib/archive/entropy.js +180 -0
- package/dist/lib/archive/export-locking.d.ts +102 -0
- package/dist/lib/archive/export-locking.js +202 -0
- package/dist/lib/archive/format.d.ts +20 -0
- package/dist/lib/archive/format.js +174 -0
- package/dist/lib/archive/index.d.ts +23 -0
- package/dist/lib/archive/index.js +17 -0
- package/dist/lib/archive/manifest.d.ts +53 -0
- package/dist/lib/archive/manifest.js +183 -0
- package/dist/lib/archive/migration.d.ts +36 -0
- package/dist/lib/archive/migration.js +100 -0
- package/dist/lib/archive/migrations/v18_to_v19.d.ts +16 -0
- package/dist/lib/archive/migrations/v18_to_v19.js +18 -0
- package/dist/lib/archive/orchestrator.d.ts +166 -0
- package/dist/lib/archive/orchestrator.js +428 -0
- package/dist/lib/archive/serializers/chunks.d.ts +30 -0
- package/dist/lib/archive/serializers/chunks.js +113 -0
- package/dist/lib/archive/serializers/embeddings.d.ts +36 -0
- package/dist/lib/archive/serializers/embeddings.js +115 -0
- package/dist/lib/archive/serializers/kg.d.ts +28 -0
- package/dist/lib/archive/serializers/kg.js +184 -0
- package/dist/lib/archive/serializers/ops_audit.d.ts +21 -0
- package/dist/lib/archive/serializers/ops_audit.js +97 -0
- package/dist/lib/archive/server-deps.d.ts +131 -0
- package/dist/lib/archive/server-deps.js +232 -0
- package/dist/lib/archive/strength.d.ts +50 -0
- package/dist/lib/archive/strength.js +77 -0
- package/dist/lib/archive/types.d.ts +159 -0
- package/dist/lib/archive/types.js +45 -0
- package/dist/lib/archive/unpack-streaming.d.ts +70 -0
- package/dist/lib/archive/unpack-streaming.js +255 -0
- package/dist/lib/auth/localhost-guard.d.ts +106 -0
- package/dist/lib/auth/localhost-guard.js +164 -0
- package/dist/lib/confidence/config.d.ts +37 -0
- package/dist/lib/confidence/config.js +107 -0
- package/dist/lib/confidence/db-shim-singleton.d.ts +20 -0
- package/dist/lib/confidence/db-shim-singleton.js +41 -0
- package/dist/lib/confidence/db-shim.d.ts +47 -0
- package/dist/lib/confidence/db-shim.js +141 -0
- package/dist/lib/confidence/mark.d.ts +58 -0
- package/dist/lib/confidence/mark.js +168 -0
- package/dist/lib/confidence/ranking.d.ts +69 -0
- package/dist/lib/confidence/ranking.js +101 -0
- package/dist/lib/confidence/search-filter.d.ts +44 -0
- package/dist/lib/confidence/search-filter.js +103 -0
- package/dist/lib/confidence/types.d.ts +146 -0
- package/dist/lib/confidence/types.js +20 -0
- package/dist/lib/confidence/write-hooks.d.ts +50 -0
- package/dist/lib/confidence/write-hooks.js +159 -0
- package/dist/lib/conflict/audit-fk-check.d.ts +72 -0
- package/dist/lib/conflict/audit-fk-check.js +131 -0
- package/dist/lib/conflict/audit-writer.d.ts +39 -0
- package/dist/lib/conflict/audit-writer.js +133 -0
- package/dist/lib/conflict/db-singleton.d.ts +28 -0
- package/dist/lib/conflict/db-singleton.js +61 -0
- package/dist/lib/conflict/db.d.ts +27 -0
- package/dist/lib/conflict/db.js +20 -0
- package/dist/lib/conflict/detector-direct.d.ts +21 -0
- package/dist/lib/conflict/detector-direct.js +105 -0
- package/dist/lib/conflict/evidence.d.ts +24 -0
- package/dist/lib/conflict/evidence.js +76 -0
- package/dist/lib/conflict/index.d.ts +14 -0
- package/dist/lib/conflict/index.js +12 -0
- package/dist/lib/conflict/scheduler.d.ts +78 -0
- package/dist/lib/conflict/scheduler.js +111 -0
- package/dist/lib/conflict/shadow.d.ts +75 -0
- package/dist/lib/conflict/shadow.js +161 -0
- package/dist/lib/conflict/types.d.ts +133 -0
- package/dist/lib/conflict/types.js +19 -0
- package/dist/lib/cost-cap.d.ts +94 -0
- package/dist/lib/cost-cap.js +129 -0
- package/dist/lib/deps/deps-registry.d.ts +111 -0
- package/dist/lib/deps/deps-registry.js +209 -0
- package/dist/lib/error-sanitizer/middleware.d.ts +43 -0
- package/dist/lib/error-sanitizer/middleware.js +100 -0
- package/dist/lib/error-sanitizer/sanitize.d.ts +78 -0
- package/dist/lib/error-sanitizer/sanitize.js +202 -0
- package/dist/lib/eval-batch.d.ts +34 -0
- package/dist/lib/eval-batch.js +103 -0
- package/dist/lib/eval-metrics.d.ts +36 -0
- package/dist/lib/eval-metrics.js +95 -0
- package/dist/lib/eval.d.ts +106 -0
- package/dist/lib/eval.js +343 -0
- package/dist/lib/events/bus.d.ts +135 -0
- package/dist/lib/events/bus.js +95 -0
- package/dist/lib/fts-anchor.d.ts +1 -0
- package/dist/lib/fts-anchor.js +131 -0
- package/dist/lib/hooks/classifier.d.ts +47 -0
- package/dist/lib/hooks/classifier.js +129 -0
- package/dist/lib/hooks/config.d.ts +49 -0
- package/dist/lib/hooks/config.js +106 -0
- package/dist/lib/hooks/decorators.d.ts +35 -0
- package/dist/lib/hooks/decorators.js +59 -0
- package/dist/lib/hooks/pipeline.d.ts +76 -0
- package/dist/lib/hooks/pipeline.js +213 -0
- package/dist/lib/hooks/privacy-filter-adapter.d.ts +55 -0
- package/dist/lib/hooks/privacy-filter-adapter.js +84 -0
- package/dist/lib/hooks/rate-limit-constant-time.d.ts +57 -0
- package/dist/lib/hooks/rate-limit-constant-time.js +69 -0
- package/dist/lib/hooks/rate-limit-dryrun-fix.d.ts +71 -0
- package/dist/lib/hooks/rate-limit-dryrun-fix.js +110 -0
- package/dist/lib/hooks/rate-limit.d.ts +54 -0
- package/dist/lib/hooks/rate-limit.js +122 -0
- package/dist/lib/hooks/server-deps.d.ts +61 -0
- package/dist/lib/hooks/server-deps.js +92 -0
- package/dist/lib/hooks/source-allowlist.d.ts +26 -0
- package/dist/lib/hooks/source-allowlist.js +53 -0
- package/dist/lib/hooks/types.d.ts +129 -0
- package/dist/lib/hooks/types.js +24 -0
- package/dist/lib/hooks/worker.d.ts +56 -0
- package/dist/lib/hooks/worker.js +150 -0
- package/dist/lib/ingest-router.d.ts +25 -0
- package/dist/lib/ingest-router.js +103 -0
- package/dist/lib/ocr-detector.d.ts +61 -0
- package/dist/lib/ocr-detector.js +138 -0
- package/dist/lib/ocr-engine-stub.d.ts +48 -0
- package/dist/lib/ocr-engine-stub.js +190 -0
- package/dist/lib/ocr-engines/google-doc-ai.d.ts +36 -0
- package/dist/lib/ocr-engines/google-doc-ai.js +164 -0
- package/dist/lib/ocr-jobs.d.ts +67 -0
- package/dist/lib/ocr-jobs.js +129 -0
- package/dist/lib/op-audit-extension/ran-at-guard.d.ts +86 -0
- package/dist/lib/op-audit-extension/ran-at-guard.js +110 -0
- package/dist/lib/op-audit.d.ts +71 -0
- package/dist/lib/op-audit.js +777 -0
- package/dist/lib/privacy-br/detector.d.ts +42 -0
- package/dist/lib/privacy-br/detector.js +130 -0
- package/dist/lib/privacy-br/index.d.ts +20 -0
- package/dist/lib/privacy-br/index.js +20 -0
- package/dist/lib/privacy-br/integration.d.ts +71 -0
- package/dist/lib/privacy-br/integration.js +74 -0
- package/dist/lib/privacy-br/patterns.d.ts +117 -0
- package/dist/lib/privacy-br/patterns.js +434 -0
- package/dist/lib/privacy-br/redact.d.ts +42 -0
- package/dist/lib/privacy-br/redact.js +103 -0
- package/dist/lib/privacy-br/types.d.ts +55 -0
- package/dist/lib/privacy-br/types.js +25 -0
- package/dist/lib/regex-extract/extractor.d.ts +30 -0
- package/dist/lib/regex-extract/extractor.js +91 -0
- package/dist/lib/regex-extract/frontmatter.d.ts +44 -0
- package/dist/lib/regex-extract/frontmatter.js +169 -0
- package/dist/lib/regex-extract/index.d.ts +14 -0
- package/dist/lib/regex-extract/index.js +14 -0
- package/dist/lib/regex-extract/ingest-router-l4.d.ts +76 -0
- package/dist/lib/regex-extract/ingest-router-l4.js +102 -0
- package/dist/lib/regex-extract/patterns.d.ts +61 -0
- package/dist/lib/regex-extract/patterns.js +91 -0
- package/dist/lib/regex-extract/production-wire.d.ts +128 -0
- package/dist/lib/regex-extract/production-wire.js +202 -0
- package/dist/lib/regex-extract/reconcile.d.ts +162 -0
- package/dist/lib/regex-extract/reconcile.js +210 -0
- package/dist/lib/regex-extract/strip-code.d.ts +24 -0
- package/dist/lib/regex-extract/strip-code.js +52 -0
- package/dist/lib/regex-extract/types.d.ts +48 -0
- package/dist/lib/regex-extract/types.js +25 -0
- package/dist/lib/reranker.d.ts +80 -0
- package/dist/lib/reranker.js +324 -0
- package/dist/lib/shadow-tracker.d.ts +191 -0
- package/dist/lib/shadow-tracker.js +384 -0
- package/dist/lib/spo-injection.d.ts +52 -0
- package/dist/lib/spo-injection.js +166 -0
- package/dist/lib/telemetry-collector.d.ts +158 -0
- package/dist/lib/telemetry-collector.js +249 -0
- package/dist/lib/temporal-detector.d.ts +27 -0
- package/dist/lib/temporal-detector.js +81 -0
- package/dist/lib/viewer/auth.d.ts +37 -0
- package/dist/lib/viewer/auth.js +70 -0
- package/dist/lib/viewer/backpressure.d.ts +59 -0
- package/dist/lib/viewer/backpressure.js +100 -0
- package/dist/lib/viewer/broadcast-singleton.d.ts +34 -0
- package/dist/lib/viewer/broadcast-singleton.js +49 -0
- package/dist/lib/viewer/broadcast.d.ts +66 -0
- package/dist/lib/viewer/broadcast.js +96 -0
- package/dist/lib/viewer/event-types.d.ts +132 -0
- package/dist/lib/viewer/event-types.js +74 -0
- package/dist/lib/viewer/instrumentation.d.ts +106 -0
- package/dist/lib/viewer/instrumentation.js +224 -0
- package/dist/lib/viewer/migration.d.ts +23 -0
- package/dist/lib/viewer/migration.js +56 -0
- package/dist/lib/viewer/redaction.d.ts +44 -0
- package/dist/lib/viewer/redaction.js +139 -0
- package/dist/lib/viewer/session.d.ts +51 -0
- package/dist/lib/viewer/session.js +87 -0
- package/dist/mcp/tools/answer.d.ts +94 -0
- package/dist/mcp/tools/answer.js +213 -0
- package/dist/mcp/tools/archive.d.ts +152 -0
- package/dist/mcp/tools/archive.js +170 -0
- package/dist/mcp/tools/conflict.d.ts +44 -0
- package/dist/mcp/tools/conflict.js +130 -0
- package/dist/mcp/tools/hooks.d.ts +29 -0
- package/dist/mcp/tools/hooks.js +78 -0
- package/dist/mcp/tools/mark.d.ts +38 -0
- package/dist/mcp/tools/mark.js +82 -0
- package/dist/mcp/tools/viewer.d.ts +58 -0
- package/dist/mcp/tools/viewer.js +64 -0
- package/dist/mcp-server.d.ts +2 -0
- package/dist/mcp-server.js +395 -0
- package/dist/metrics.d.ts +3 -0
- package/dist/metrics.js +59 -0
- package/dist/noise-filter.d.ts +18 -0
- package/dist/noise-filter.js +142 -0
- package/dist/notion-sync.d.ts +7 -0
- package/dist/notion-sync.js +97 -0
- package/dist/observability/adapters/a3-adapter.d.ts +63 -0
- package/dist/observability/adapters/a3-adapter.js +83 -0
- package/dist/observability/adapters/p1-adapter.d.ts +49 -0
- package/dist/observability/adapters/p1-adapter.js +63 -0
- package/dist/observability/adapters/p5-adapter.d.ts +36 -0
- package/dist/observability/adapters/p5-adapter.js +71 -0
- package/dist/observability/cardinality.d.ts +61 -0
- package/dist/observability/cardinality.js +300 -0
- package/dist/observability/collectors/db-stats.collector.d.ts +9 -0
- package/dist/observability/collectors/db-stats.collector.js +88 -0
- package/dist/observability/collectors/eventbus.collector.d.ts +6 -0
- package/dist/observability/collectors/eventbus.collector.js +50 -0
- package/dist/observability/collectors/process.collector.d.ts +7 -0
- package/dist/observability/collectors/process.collector.js +93 -0
- package/dist/observability/collectors/provider-telemetry.collector.d.ts +11 -0
- package/dist/observability/collectors/provider-telemetry.collector.js +112 -0
- package/dist/observability/collectors/search-telemetry.collector.d.ts +12 -0
- package/dist/observability/collectors/search-telemetry.collector.js +76 -0
- package/dist/observability/exporter.d.ts +30 -0
- package/dist/observability/exporter.js +182 -0
- package/dist/observability/index.d.ts +22 -0
- package/dist/observability/index.js +21 -0
- package/dist/observability/metrics.d.ts +53 -0
- package/dist/observability/metrics.js +213 -0
- package/dist/observability/privacy-guard.d.ts +32 -0
- package/dist/observability/privacy-guard.js +116 -0
- package/dist/observability/record.d.ts +83 -0
- package/dist/observability/record.js +217 -0
- package/dist/observability/registry.d.ts +60 -0
- package/dist/observability/registry.js +93 -0
- package/dist/observability/types.d.ts +115 -0
- package/dist/observability/types.js +235 -0
- package/dist/observability.d.ts +131 -0
- package/dist/observability.js +234 -0
- package/dist/plugins/nox-hooks/index.d.ts +61 -0
- package/dist/plugins/nox-hooks/index.js +99 -0
- package/dist/primer.d.ts +1 -0
- package/dist/primer.js +100 -0
- package/dist/privacy/filter.d.ts +27 -0
- package/dist/privacy/filter.js +74 -0
- package/dist/privacy/patterns.d.ts +29 -0
- package/dist/privacy/patterns.js +178 -0
- package/dist/privacy/tag-parser.d.ts +24 -0
- package/dist/privacy/tag-parser.js +29 -0
- package/dist/project-context-gen.d.ts +10 -0
- package/dist/project-context-gen.js +106 -0
- package/dist/providers/embedding/gemini.d.ts +73 -0
- package/dist/providers/embedding/gemini.js +118 -0
- package/dist/providers/embedding/openai.d.ts +76 -0
- package/dist/providers/embedding/openai.js +123 -0
- package/dist/providers/embedding/types.d.ts +39 -0
- package/dist/providers/embedding/types.js +1 -0
- package/dist/providers/embedding/voyage.d.ts +36 -0
- package/dist/providers/embedding/voyage.js +29 -0
- package/dist/providers/index.d.ts +116 -0
- package/dist/providers/index.js +158 -0
- package/dist/providers/llm/anthropic.d.ts +29 -0
- package/dist/providers/llm/anthropic.js +28 -0
- package/dist/providers/llm/chain.d.ts +99 -0
- package/dist/providers/llm/chain.js +213 -0
- package/dist/providers/llm/gemini.d.ts +48 -0
- package/dist/providers/llm/gemini.js +96 -0
- package/dist/providers/llm/openai.d.ts +64 -0
- package/dist/providers/llm/openai.js +109 -0
- package/dist/providers/llm/types.d.ts +47 -0
- package/dist/providers/llm/types.js +1 -0
- package/dist/providers/telemetry.d.ts +87 -0
- package/dist/providers/telemetry.js +156 -0
- package/dist/providers/types.d.ts +42 -0
- package/dist/providers/types.js +59 -0
- package/dist/query-entity-count.d.ts +54 -0
- package/dist/query-entity-count.js +171 -0
- package/dist/reflect.d.ts +26 -0
- package/dist/reflect.js +290 -0
- package/dist/reindex-errors.d.ts +7 -0
- package/dist/reindex-errors.js +21 -0
- package/dist/reindex.d.ts +16 -0
- package/dist/reindex.js +293 -0
- package/dist/retention.d.ts +40 -0
- package/dist/retention.js +86 -0
- package/dist/salience.d.ts +85 -0
- package/dist/salience.js +245 -0
- package/dist/scripts/migrate-v17-ops-audit.d.ts +17 -0
- package/dist/scripts/migrate-v17-ops-audit.js +70 -0
- package/dist/search-dedup.d.ts +44 -0
- package/dist/search-dedup.js +137 -0
- package/dist/search-expansion.d.ts +20 -0
- package/dist/search-expansion.js +99 -0
- package/dist/search.d.ts +62 -0
- package/dist/search.js +582 -0
- package/dist/seh-detector.d.ts +31 -0
- package/dist/seh-detector.js +201 -0
- package/dist/self-improve.d.ts +1 -0
- package/dist/self-improve.js +189 -0
- package/dist/session-distill.d.ts +29 -0
- package/dist/session-distill.js +325 -0
- package/dist/session-update.d.ts +1 -0
- package/dist/session-update.js +54 -0
- package/dist/shared-memory.d.ts +24 -0
- package/dist/shared-memory.js +104 -0
- package/dist/stats.d.ts +1 -0
- package/dist/stats.js +44 -0
- package/dist/temporal-retrieval.d.ts +132 -0
- package/dist/temporal-retrieval.js +495 -0
- package/dist/tier-manager.d.ts +69 -0
- package/dist/tier-manager.js +225 -0
- package/dist/vectorize.d.ts +16 -0
- package/dist/vectorize.js +91 -0
- package/dist/watch.d.ts +8 -0
- package/dist/watch.js +124 -0
- package/package.json +74 -0
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* src/api/hooks.ts — T12: HTTP endpoints for hooks inspection + dryrun.
|
|
3
|
+
*
|
|
4
|
+
* Routes (mounted under /api/hooks):
|
|
5
|
+
*
|
|
6
|
+
* GET /api/hooks/status → 200 { config, queueDepth, rateLimitTokens }
|
|
7
|
+
* GET /api/hooks/recent → 200 { rows: [...metadata only...] }
|
|
8
|
+
* POST /api/hooks/dryrun → 200 { result, trace } — accepts { text } body
|
|
9
|
+
*
|
|
10
|
+
* Output sanitization:
|
|
11
|
+
* - status returns config + counters; never raw events
|
|
12
|
+
* - recent returns only metadata fields (event_uuid, ts, redaction_count,
|
|
13
|
+
* kind, session_id, project_slug); NEVER payload content
|
|
14
|
+
* - dryrun returns per-layer trace (layer + reason) and the redacted
|
|
15
|
+
* output preview (truncated to 200 chars)
|
|
16
|
+
*/
|
|
17
|
+
import { randomUUID } from "node:crypto";
|
|
18
|
+
import { createPipeline } from "../lib/hooks/pipeline.js";
|
|
19
|
+
import { loadConfig } from "../lib/hooks/config.js";
|
|
20
|
+
/**
|
|
21
|
+
* Route a single HTTP request. Returns an HttpResponse.
|
|
22
|
+
* No Express/Fastify dep — host wires this into whichever framework.
|
|
23
|
+
*/
|
|
24
|
+
export async function handleHooksRequest(req, deps) {
|
|
25
|
+
const { method, path } = req;
|
|
26
|
+
if (method === "GET" && path === "/api/hooks/status") {
|
|
27
|
+
const config = deps.config ?? loadConfig();
|
|
28
|
+
const inspect = deps.inspectQueue ? deps.inspectQueue() : { queueDepth: 0 };
|
|
29
|
+
return {
|
|
30
|
+
status: 200,
|
|
31
|
+
body: {
|
|
32
|
+
config: {
|
|
33
|
+
enabled: config.enabled,
|
|
34
|
+
allowed_sources: Array.from(config.allowedSources),
|
|
35
|
+
rate_limit_per_min: config.rateLimitPerMin,
|
|
36
|
+
dedup_threshold: config.dedupThreshold,
|
|
37
|
+
llm_classify: config.llmClassify,
|
|
38
|
+
dry_run: config.dryRun,
|
|
39
|
+
queue_size: config.queueSize,
|
|
40
|
+
min_length: config.minLength,
|
|
41
|
+
pii_policy: config.piiPolicy,
|
|
42
|
+
},
|
|
43
|
+
queueDepth: inspect.queueDepth,
|
|
44
|
+
rateLimitTokens: inspect.rateLimitTokens ?? null,
|
|
45
|
+
},
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
if (method === "GET" && path === "/api/hooks/recent") {
|
|
49
|
+
const limit = Math.max(1, Math.min(100, Number.parseInt(req.query?.["limit"] ?? "20", 10) || 20));
|
|
50
|
+
try {
|
|
51
|
+
const rows = await deps.readRecent(limit);
|
|
52
|
+
// Sanitize: drop payload_json entirely
|
|
53
|
+
const sanitized = rows.map((r) => ({
|
|
54
|
+
event_uuid: r.event_uuid,
|
|
55
|
+
session_id: r.session_id,
|
|
56
|
+
project_slug: r.project_slug,
|
|
57
|
+
kind: r.kind,
|
|
58
|
+
timestamp: r.timestamp,
|
|
59
|
+
redaction_count: r.redaction_count,
|
|
60
|
+
}));
|
|
61
|
+
return { status: 200, body: { rows: sanitized } };
|
|
62
|
+
}
|
|
63
|
+
catch (e) {
|
|
64
|
+
return { status: 500, body: { error: e.message } };
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
if (method === "POST" && path === "/api/hooks/dryrun") {
|
|
68
|
+
const body = (req.body ?? {});
|
|
69
|
+
if (typeof body.text !== "string" || body.text.length === 0) {
|
|
70
|
+
return { status: 400, body: { error: "missing required field: text (non-empty string)" } };
|
|
71
|
+
}
|
|
72
|
+
const role = typeof body.role === "string" ? body.role : "user";
|
|
73
|
+
const source = typeof body.source === "string" ? body.source : "api";
|
|
74
|
+
const base = deps.config ?? loadConfig();
|
|
75
|
+
const forced = {
|
|
76
|
+
...base,
|
|
77
|
+
enabled: true,
|
|
78
|
+
dryRun: true,
|
|
79
|
+
allowedSources: new Set([...base.allowedSources, "api", "cli"]),
|
|
80
|
+
};
|
|
81
|
+
const trace = [];
|
|
82
|
+
const pipeline = createPipeline({
|
|
83
|
+
config: forced,
|
|
84
|
+
telemetry: (row) => {
|
|
85
|
+
trace.push(row);
|
|
86
|
+
},
|
|
87
|
+
});
|
|
88
|
+
const event = {
|
|
89
|
+
event_id: `dr_${randomUUID()}`,
|
|
90
|
+
source: source,
|
|
91
|
+
role: role,
|
|
92
|
+
content: body.text,
|
|
93
|
+
session_id: "api-dryrun",
|
|
94
|
+
project_slug: "api",
|
|
95
|
+
ts: new Date().toISOString(),
|
|
96
|
+
};
|
|
97
|
+
const result = await pipeline.run(event);
|
|
98
|
+
return {
|
|
99
|
+
status: 200,
|
|
100
|
+
body: {
|
|
101
|
+
result,
|
|
102
|
+
trace: trace.map((t) => {
|
|
103
|
+
const p = JSON.parse(t.payload_json);
|
|
104
|
+
return {
|
|
105
|
+
layer: p.layer,
|
|
106
|
+
reason: p.reason,
|
|
107
|
+
redaction_count: t.redaction_count,
|
|
108
|
+
kind: t.kind,
|
|
109
|
+
};
|
|
110
|
+
}),
|
|
111
|
+
},
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
return { status: 404, body: { error: `no route for ${method} ${path}` } };
|
|
115
|
+
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* T13 — HTTP `POST /api/import` handler (framework-agnostic).
|
|
3
|
+
*
|
|
4
|
+
* Accepts JSON body `{ archive_b64: string, passphrase?: string, mode?: 'merge'|'replace',
|
|
5
|
+
* dry_run?: bool, verify_only?: bool }`. Caller is responsible for adapting to
|
|
6
|
+
* multipart/form-data on the host server side (we keep the contract pure JSON
|
|
7
|
+
* here to avoid pulling a multipart parser dependency into staged-A2).
|
|
8
|
+
*
|
|
9
|
+
* Returns summary JSON: counts, conflicts, duration.
|
|
10
|
+
*/
|
|
11
|
+
import { ProgressEvent } from "../lib/archive/orchestrator.js";
|
|
12
|
+
import { ChunkRow, KgEntityRow, KgRelationRow, OpsAuditRow } from "../lib/archive/types.js";
|
|
13
|
+
export interface HttpImportBody {
|
|
14
|
+
/** Base64-encoded gzipped tar archive. */
|
|
15
|
+
archive_b64?: string;
|
|
16
|
+
passphrase?: string;
|
|
17
|
+
mode?: "merge" | "replace";
|
|
18
|
+
dry_run?: boolean;
|
|
19
|
+
verify_only?: boolean;
|
|
20
|
+
}
|
|
21
|
+
export interface HttpResponse {
|
|
22
|
+
status: number;
|
|
23
|
+
headers: Record<string, string>;
|
|
24
|
+
body: Buffer | string;
|
|
25
|
+
}
|
|
26
|
+
export interface HttpImportDeps {
|
|
27
|
+
loadExisting: () => Promise<{
|
|
28
|
+
chunks: ChunkRow[];
|
|
29
|
+
kg_entities: KgEntityRow[];
|
|
30
|
+
kg_relations: KgRelationRow[];
|
|
31
|
+
ops_audit: OpsAuditRow[];
|
|
32
|
+
}>;
|
|
33
|
+
currentSchemaVersion: () => Promise<number>;
|
|
34
|
+
persist?: (resolved: import("../lib/archive/orchestrator.js").ImportResult["resolved"]) => Promise<void>;
|
|
35
|
+
signal?: AbortSignal;
|
|
36
|
+
onProgress?: (ev: ProgressEvent) => void;
|
|
37
|
+
}
|
|
38
|
+
export declare function handleImport(body: HttpImportBody, deps: HttpImportDeps): Promise<HttpResponse>;
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* T13 — HTTP `POST /api/import` handler (framework-agnostic).
|
|
3
|
+
*
|
|
4
|
+
* Accepts JSON body `{ archive_b64: string, passphrase?: string, mode?: 'merge'|'replace',
|
|
5
|
+
* dry_run?: bool, verify_only?: bool }`. Caller is responsible for adapting to
|
|
6
|
+
* multipart/form-data on the host server side (we keep the contract pure JSON
|
|
7
|
+
* here to avoid pulling a multipart parser dependency into staged-A2).
|
|
8
|
+
*
|
|
9
|
+
* Returns summary JSON: counts, conflicts, duration.
|
|
10
|
+
*/
|
|
11
|
+
import { runImport, } from "../lib/archive/orchestrator.js";
|
|
12
|
+
import { BadPassphraseError, TamperedArchiveError } from "../lib/archive/types.js";
|
|
13
|
+
export async function handleImport(body, deps) {
|
|
14
|
+
if (!body.archive_b64) {
|
|
15
|
+
return jsonResponse(400, { error: "archive_b64 required" });
|
|
16
|
+
}
|
|
17
|
+
let archive;
|
|
18
|
+
try {
|
|
19
|
+
archive = Buffer.from(body.archive_b64, "base64");
|
|
20
|
+
if (archive.length === 0) {
|
|
21
|
+
return jsonResponse(400, { error: "archive_b64 decoded to empty buffer" });
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
catch (err) {
|
|
25
|
+
return jsonResponse(400, { error: `bad base64: ${err.message}` });
|
|
26
|
+
}
|
|
27
|
+
const existing = await deps.loadExisting();
|
|
28
|
+
const currentSchemaVersion = await deps.currentSchemaVersion();
|
|
29
|
+
const req = {
|
|
30
|
+
archive,
|
|
31
|
+
passphrase: body.passphrase,
|
|
32
|
+
mode: body.mode ?? "merge",
|
|
33
|
+
dry_run: body.dry_run === true,
|
|
34
|
+
verify_only: body.verify_only === true,
|
|
35
|
+
current_schema_version: currentSchemaVersion,
|
|
36
|
+
existing,
|
|
37
|
+
signal: deps.signal,
|
|
38
|
+
onProgress: deps.onProgress,
|
|
39
|
+
};
|
|
40
|
+
let result;
|
|
41
|
+
try {
|
|
42
|
+
result = await runImport(req);
|
|
43
|
+
}
|
|
44
|
+
catch (err) {
|
|
45
|
+
if (err instanceof BadPassphraseError) {
|
|
46
|
+
return jsonResponse(401, { error: "bad passphrase" });
|
|
47
|
+
}
|
|
48
|
+
if (err instanceof TamperedArchiveError) {
|
|
49
|
+
return jsonResponse(409, { error: "archive tampered" });
|
|
50
|
+
}
|
|
51
|
+
const msg = err.message;
|
|
52
|
+
if (/encrypted/.test(msg) && !body.passphrase) {
|
|
53
|
+
return jsonResponse(401, { error: "passphrase required" });
|
|
54
|
+
}
|
|
55
|
+
if (/cancel/i.test(msg)) {
|
|
56
|
+
return jsonResponse(499, { error: "cancelled" });
|
|
57
|
+
}
|
|
58
|
+
return jsonResponse(500, { error: msg });
|
|
59
|
+
}
|
|
60
|
+
if (!body.dry_run && !body.verify_only && deps.persist) {
|
|
61
|
+
try {
|
|
62
|
+
await deps.persist(result.resolved);
|
|
63
|
+
}
|
|
64
|
+
catch (err) {
|
|
65
|
+
return jsonResponse(500, {
|
|
66
|
+
error: `persist failed: ${err.message}`,
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
return jsonResponse(200, {
|
|
71
|
+
mode: body.mode ?? "merge",
|
|
72
|
+
dry_run: body.dry_run === true,
|
|
73
|
+
verify_only: body.verify_only === true,
|
|
74
|
+
encrypted: result.manifest.encryption.enabled,
|
|
75
|
+
schema_version_archive: result.manifest.schema_version,
|
|
76
|
+
schema_version_target: currentSchemaVersion,
|
|
77
|
+
stats: result.stats,
|
|
78
|
+
duration_ms: result.duration_ms,
|
|
79
|
+
});
|
|
80
|
+
}
|
|
81
|
+
function jsonResponse(status, payload) {
|
|
82
|
+
return {
|
|
83
|
+
status,
|
|
84
|
+
headers: { "Content-Type": "application/json" },
|
|
85
|
+
body: JSON.stringify(payload),
|
|
86
|
+
};
|
|
87
|
+
}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* F4b — POST /api/ingest-event (Session Priming Loop, Fluxo D)
|
|
3
|
+
*
|
|
4
|
+
* Write-side do loop: a sessão deposita um digest tipado ao encerrar.
|
|
5
|
+
* "Toda sessão nasce contextualizada E MORRE CONTRIBUINDO."
|
|
6
|
+
*
|
|
7
|
+
* Specs (memoria-nox):
|
|
8
|
+
* - PRD: specs/2026-06-04-session-priming-loop.md (§7 Fluxo D, §4.4)
|
|
9
|
+
* - Base: specs/2026-05-17-P2-hooks-autocapture.md (§4 endpoint; este módulo
|
|
10
|
+
* implementa o SUBSET kind=session_end. Desvio documentado de P2 §6: o
|
|
11
|
+
* digest vai DIRETO pra `chunks` como type=daily — a tabela `agent_events`
|
|
12
|
+
* separada do P2 é pro autocapture full de ~170 eventos/sessão, que não é
|
|
13
|
+
* o caso aqui: 1 digest/sessão.)
|
|
14
|
+
*
|
|
15
|
+
* Invariantes:
|
|
16
|
+
* - Append-only em `chunks` (INSERT, nunca UPDATE/DELETE) — guardas de
|
|
17
|
+
* op-audit (regra #6) não aplicam; FTS entra via trigger chunks_ai;
|
|
18
|
+
* embedding fica pro vectorize (nightly cron / canary self-heal).
|
|
19
|
+
* - Decaível por padrão (PRD §4.4): chunk_type=daily, retention_days=90.
|
|
20
|
+
* O crystallize nightly promove o que sobreviver à curadoria.
|
|
21
|
+
* - Dedup por (kind, session_id) — mesma sessão NUNCA ingere 2× (re-POST
|
|
22
|
+
* idempotente retorna deduped:true).
|
|
23
|
+
* - Auth: o token gate global do api-server (F2) já exige Bearer em
|
|
24
|
+
* requests proxiadas (x-forwarded-for); localhost direto passa.
|
|
25
|
+
* - Privacy (espírito do P2 §5 sem a dependência A1 full): redaction
|
|
26
|
+
* server-side de padrões de credencial conhecidos + redaction_count
|
|
27
|
+
* no response.
|
|
28
|
+
*/
|
|
29
|
+
interface PreparedStatement {
|
|
30
|
+
all(...args: unknown[]): unknown[];
|
|
31
|
+
get(...args: unknown[]): unknown;
|
|
32
|
+
run(...args: unknown[]): unknown;
|
|
33
|
+
}
|
|
34
|
+
export interface IngestDb {
|
|
35
|
+
prepare(sql: string): PreparedStatement;
|
|
36
|
+
exec(sql: string): void;
|
|
37
|
+
}
|
|
38
|
+
export interface IngestEventRequest {
|
|
39
|
+
kind: string;
|
|
40
|
+
session_id: string;
|
|
41
|
+
scope?: string;
|
|
42
|
+
host?: string;
|
|
43
|
+
content: string;
|
|
44
|
+
/** Discriminador de ocorrência pra kinds que disparam N× por sessão
|
|
45
|
+
* (pre_compact compacta várias vezes em sessão longa). Idempotência
|
|
46
|
+
* vira (kind, session_id, seq); ausente = (kind, session_id). */
|
|
47
|
+
seq?: string;
|
|
48
|
+
}
|
|
49
|
+
export type IngestEventResponse = {
|
|
50
|
+
status: number;
|
|
51
|
+
body: unknown;
|
|
52
|
+
};
|
|
53
|
+
export declare function redactSecrets(text: string): {
|
|
54
|
+
clean: string;
|
|
55
|
+
count: number;
|
|
56
|
+
};
|
|
57
|
+
export declare function parseIngestEvent(body: unknown): {
|
|
58
|
+
ok: true;
|
|
59
|
+
req: Required<Omit<IngestEventRequest, "scope" | "host" | "seq">> & Pick<IngestEventRequest, "scope" | "host" | "seq">;
|
|
60
|
+
} | {
|
|
61
|
+
ok: false;
|
|
62
|
+
error: string;
|
|
63
|
+
};
|
|
64
|
+
export declare function handleIngestEvent(db: IngestDb, body: unknown): IngestEventResponse;
|
|
65
|
+
export {};
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* F4b — POST /api/ingest-event (Session Priming Loop, Fluxo D)
|
|
3
|
+
*
|
|
4
|
+
* Write-side do loop: a sessão deposita um digest tipado ao encerrar.
|
|
5
|
+
* "Toda sessão nasce contextualizada E MORRE CONTRIBUINDO."
|
|
6
|
+
*
|
|
7
|
+
* Specs (memoria-nox):
|
|
8
|
+
* - PRD: specs/2026-06-04-session-priming-loop.md (§7 Fluxo D, §4.4)
|
|
9
|
+
* - Base: specs/2026-05-17-P2-hooks-autocapture.md (§4 endpoint; este módulo
|
|
10
|
+
* implementa o SUBSET kind=session_end. Desvio documentado de P2 §6: o
|
|
11
|
+
* digest vai DIRETO pra `chunks` como type=daily — a tabela `agent_events`
|
|
12
|
+
* separada do P2 é pro autocapture full de ~170 eventos/sessão, que não é
|
|
13
|
+
* o caso aqui: 1 digest/sessão.)
|
|
14
|
+
*
|
|
15
|
+
* Invariantes:
|
|
16
|
+
* - Append-only em `chunks` (INSERT, nunca UPDATE/DELETE) — guardas de
|
|
17
|
+
* op-audit (regra #6) não aplicam; FTS entra via trigger chunks_ai;
|
|
18
|
+
* embedding fica pro vectorize (nightly cron / canary self-heal).
|
|
19
|
+
* - Decaível por padrão (PRD §4.4): chunk_type=daily, retention_days=90.
|
|
20
|
+
* O crystallize nightly promove o que sobreviver à curadoria.
|
|
21
|
+
* - Dedup por (kind, session_id) — mesma sessão NUNCA ingere 2× (re-POST
|
|
22
|
+
* idempotente retorna deduped:true).
|
|
23
|
+
* - Auth: o token gate global do api-server (F2) já exige Bearer em
|
|
24
|
+
* requests proxiadas (x-forwarded-for); localhost direto passa.
|
|
25
|
+
* - Privacy (espírito do P2 §5 sem a dependência A1 full): redaction
|
|
26
|
+
* server-side de padrões de credencial conhecidos + redaction_count
|
|
27
|
+
* no response.
|
|
28
|
+
*/
|
|
29
|
+
const SUPPORTED_KINDS = new Set(["session_end", "pre_compact"]);
|
|
30
|
+
const SESSION_ID_RE = /^[\p{L}\p{N}][\p{L}\p{N}._:-]{0,99}$/u;
|
|
31
|
+
const SCOPE_RE = /^[\p{L}\p{N}][\p{L}\p{N}._-]{0,63}$/u;
|
|
32
|
+
const HOST_RE = /^[a-z0-9][a-z0-9.-]{0,31}$/;
|
|
33
|
+
const SEQ_RE = /^[A-Za-z0-9._-]{1,32}$/;
|
|
34
|
+
const MAX_CONTENT_BYTES = 16 * 1024;
|
|
35
|
+
const RETENTION_DAYS_DAILY = 90;
|
|
36
|
+
// ─── Redaction (padrões de credencial conhecidos; P2 §5 espírito) ────────────
|
|
37
|
+
const REDACTION_PATTERNS = [
|
|
38
|
+
/AIza[0-9A-Za-z_-]{30,}/g, // Google API keys
|
|
39
|
+
/AQ\.[0-9A-Za-z_-]{30,}/g, // Google API keys formato 2026
|
|
40
|
+
/sk-[0-9A-Za-z_-]{20,}/g, // OpenAI-style
|
|
41
|
+
/ghp_[0-9A-Za-z]{30,}/g, // GitHub PAT
|
|
42
|
+
/xox[baprs]-[0-9A-Za-z-]{10,}/g, // Slack
|
|
43
|
+
/Bearer\s+[0-9A-Za-z._~+/=-]{16,}/g, // Authorization headers colados
|
|
44
|
+
/-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----/g,
|
|
45
|
+
];
|
|
46
|
+
export function redactSecrets(text) {
|
|
47
|
+
let count = 0;
|
|
48
|
+
let clean = text;
|
|
49
|
+
for (const re of REDACTION_PATTERNS) {
|
|
50
|
+
clean = clean.replace(re, () => {
|
|
51
|
+
count++;
|
|
52
|
+
return "[REDACTED]";
|
|
53
|
+
});
|
|
54
|
+
}
|
|
55
|
+
return { clean, count };
|
|
56
|
+
}
|
|
57
|
+
// ─── Validação ───────────────────────────────────────────────────────────────
|
|
58
|
+
export function parseIngestEvent(body) {
|
|
59
|
+
if (body === null || typeof body !== "object" || Array.isArray(body)) {
|
|
60
|
+
return { ok: false, error: "body JSON objeto é obrigatório" };
|
|
61
|
+
}
|
|
62
|
+
const b = body;
|
|
63
|
+
const kind = typeof b.kind === "string" ? b.kind : "";
|
|
64
|
+
if (!SUPPORTED_KINDS.has(kind)) {
|
|
65
|
+
return { ok: false, error: `kind não suportado (v1: ${[...SUPPORTED_KINDS].join(", ")})` };
|
|
66
|
+
}
|
|
67
|
+
const sessionId = typeof b.session_id === "string" ? b.session_id.trim() : "";
|
|
68
|
+
if (!SESSION_ID_RE.test(sessionId)) {
|
|
69
|
+
return { ok: false, error: "session_id inválido (alfanumérico ._:- , máx 100)" };
|
|
70
|
+
}
|
|
71
|
+
const content = typeof b.content === "string" ? b.content : "";
|
|
72
|
+
if (!content.trim())
|
|
73
|
+
return { ok: false, error: "content é obrigatório" };
|
|
74
|
+
if (Buffer.byteLength(content, "utf8") > MAX_CONTENT_BYTES) {
|
|
75
|
+
return { ok: false, error: `content excede ${MAX_CONTENT_BYTES} bytes` };
|
|
76
|
+
}
|
|
77
|
+
let scope;
|
|
78
|
+
if (b.scope !== undefined && b.scope !== "") {
|
|
79
|
+
if (typeof b.scope !== "string" || !SCOPE_RE.test(b.scope)) {
|
|
80
|
+
return { ok: false, error: "scope inválido" };
|
|
81
|
+
}
|
|
82
|
+
scope = b.scope;
|
|
83
|
+
}
|
|
84
|
+
let host;
|
|
85
|
+
if (b.host !== undefined && b.host !== "") {
|
|
86
|
+
if (typeof b.host !== "string" || !HOST_RE.test(b.host)) {
|
|
87
|
+
return { ok: false, error: "host inválido" };
|
|
88
|
+
}
|
|
89
|
+
host = b.host;
|
|
90
|
+
}
|
|
91
|
+
let seq;
|
|
92
|
+
if (b.seq !== undefined && b.seq !== "") {
|
|
93
|
+
if (typeof b.seq !== "string" || !SEQ_RE.test(b.seq)) {
|
|
94
|
+
return { ok: false, error: "seq inválido (alfanumérico ._- , máx 32)" };
|
|
95
|
+
}
|
|
96
|
+
seq = b.seq;
|
|
97
|
+
}
|
|
98
|
+
return { ok: true, req: { kind, session_id: sessionId, content, scope, host, seq } };
|
|
99
|
+
}
|
|
100
|
+
// ─── Handler ─────────────────────────────────────────────────────────────────
|
|
101
|
+
export function handleIngestEvent(db, body) {
|
|
102
|
+
const parsed = parseIngestEvent(body);
|
|
103
|
+
if (!parsed.ok)
|
|
104
|
+
return { status: 400, body: { error: parsed.error } };
|
|
105
|
+
const req = parsed.req;
|
|
106
|
+
// Dedup por (kind, session_id, seq) — idempotente. seq ausente compara
|
|
107
|
+
// contra '' dos dois lados (session_end clássico = 1 por sessão).
|
|
108
|
+
const dupe = db
|
|
109
|
+
.prepare(`SELECT id FROM chunks
|
|
110
|
+
WHERE chunk_type = 'daily'
|
|
111
|
+
AND metadata IS NOT NULL
|
|
112
|
+
AND json_extract(metadata, '$.session_id') = ?
|
|
113
|
+
AND json_extract(metadata, '$.kind') = ?
|
|
114
|
+
AND IFNULL(json_extract(metadata, '$.seq'), '') = ?
|
|
115
|
+
LIMIT 1`)
|
|
116
|
+
.get(req.session_id, req.kind, req.seq ?? "");
|
|
117
|
+
if (dupe) {
|
|
118
|
+
return { status: 200, body: { deduped: true, chunk_id: dupe.id } };
|
|
119
|
+
}
|
|
120
|
+
const { clean, count: redactionCount } = redactSecrets(req.content);
|
|
121
|
+
const host = req.host ?? "unknown";
|
|
122
|
+
const scope = req.scope ?? "unscoped";
|
|
123
|
+
// Namespace `events/` — novo, não colide com scope mapping do brief
|
|
124
|
+
// (sessions/, memory/, shared/). Futuro: scope=events pra auditar o loop.
|
|
125
|
+
const fileSuffix = req.seq ? `-${req.seq}` : "";
|
|
126
|
+
const sourceFile = `events/${host}/${scope}/${req.session_id}${fileSuffix}.md`;
|
|
127
|
+
const today = new Date().toISOString().slice(0, 10);
|
|
128
|
+
const headLabel = req.kind === "pre_compact" ? "Compaction digest" : "Session digest";
|
|
129
|
+
const text = `## ${headLabel} — ${scope} (${host}, ${today})\n\n${clean}`;
|
|
130
|
+
const metadata = JSON.stringify({
|
|
131
|
+
source: "ingest-event",
|
|
132
|
+
kind: req.kind,
|
|
133
|
+
session_id: req.session_id,
|
|
134
|
+
...(req.seq ? { seq: req.seq } : {}),
|
|
135
|
+
scope,
|
|
136
|
+
host,
|
|
137
|
+
redaction_count: redactionCount,
|
|
138
|
+
});
|
|
139
|
+
const info = db
|
|
140
|
+
.prepare(`INSERT INTO chunks (source_file, chunk_text, chunk_type, source_date,
|
|
141
|
+
retention_days, metadata)
|
|
142
|
+
VALUES (?, ?, 'daily', ?, ?, ?)`)
|
|
143
|
+
.run(sourceFile, text, today, RETENTION_DAYS_DAILY, metadata);
|
|
144
|
+
return {
|
|
145
|
+
status: 201,
|
|
146
|
+
body: {
|
|
147
|
+
ingested: true,
|
|
148
|
+
chunk_id: Number(info.lastInsertRowid),
|
|
149
|
+
retention_days: RETENTION_DAYS_DAILY,
|
|
150
|
+
redaction_count: redactionCount,
|
|
151
|
+
},
|
|
152
|
+
};
|
|
153
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* src/api/mark.ts — HTTP routes for L3 mark workflow.
|
|
3
|
+
*
|
|
4
|
+
* Routes:
|
|
5
|
+
* POST /api/chunk/:id/mark body { kind: "canonical"|"refuted"|"stale", notes?: string }
|
|
6
|
+
* POST /api/chunk/:id/supersede body { by_chunk_id: number, notes?: string, reason?: string }
|
|
7
|
+
*
|
|
8
|
+
* Returns 200 + JSON on success, 400 on bad request, 404 on missing chunk,
|
|
9
|
+
* 500 on unexpected.
|
|
10
|
+
*
|
|
11
|
+
* Framework-agnostic: exposes request/response handlers that take a minimal
|
|
12
|
+
* Request shape. Production caller (Express/Fastify/native http) wires them
|
|
13
|
+
* via `handleMarkRequest()` and `handleSupersedeRequest()`.
|
|
14
|
+
*/
|
|
15
|
+
import type { Db } from "../lib/confidence/db-shim.js";
|
|
16
|
+
import type { MarkResult } from "../lib/confidence/types.js";
|
|
17
|
+
export interface ApiResponse<T = unknown> {
|
|
18
|
+
status: number;
|
|
19
|
+
body: T | {
|
|
20
|
+
ok: false;
|
|
21
|
+
error: string;
|
|
22
|
+
code: string;
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
interface MarkBody {
|
|
26
|
+
kind?: string;
|
|
27
|
+
notes?: string;
|
|
28
|
+
}
|
|
29
|
+
interface SupersedeBody {
|
|
30
|
+
by_chunk_id?: number;
|
|
31
|
+
notes?: string;
|
|
32
|
+
reason?: string;
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* handleMarkRequest(db, idStr, body) → ApiResponse<MarkResult>
|
|
36
|
+
*/
|
|
37
|
+
export declare function handleMarkRequest(db: Db, idStr: string, body: MarkBody | null | undefined): ApiResponse<MarkResult>;
|
|
38
|
+
/**
|
|
39
|
+
* handleSupersedeRequest(db, idStr, body) → ApiResponse<MarkResult>
|
|
40
|
+
*/
|
|
41
|
+
export declare function handleSupersedeRequest(db: Db, idStr: string, body: SupersedeBody | null | undefined): ApiResponse<MarkResult>;
|
|
42
|
+
export {};
|
package/dist/api/mark.js
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* src/api/mark.ts — HTTP routes for L3 mark workflow.
|
|
3
|
+
*
|
|
4
|
+
* Routes:
|
|
5
|
+
* POST /api/chunk/:id/mark body { kind: "canonical"|"refuted"|"stale", notes?: string }
|
|
6
|
+
* POST /api/chunk/:id/supersede body { by_chunk_id: number, notes?: string, reason?: string }
|
|
7
|
+
*
|
|
8
|
+
* Returns 200 + JSON on success, 400 on bad request, 404 on missing chunk,
|
|
9
|
+
* 500 on unexpected.
|
|
10
|
+
*
|
|
11
|
+
* Framework-agnostic: exposes request/response handlers that take a minimal
|
|
12
|
+
* Request shape. Production caller (Express/Fastify/native http) wires them
|
|
13
|
+
* via `handleMarkRequest()` and `handleSupersedeRequest()`.
|
|
14
|
+
*/
|
|
15
|
+
import { markChunk, supersedeChunk, } from "../lib/confidence/mark.js";
|
|
16
|
+
import { resolveConfig } from "../lib/confidence/config.js";
|
|
17
|
+
function validateKind(raw) {
|
|
18
|
+
return raw === "canonical" || raw === "refuted" || raw === "stale";
|
|
19
|
+
}
|
|
20
|
+
function validateReason(raw) {
|
|
21
|
+
return (raw === "auto_supersede_temporal" ||
|
|
22
|
+
raw === "manual_resolution" ||
|
|
23
|
+
raw === "stale_link_reconciliation" ||
|
|
24
|
+
raw === "dismiss");
|
|
25
|
+
}
|
|
26
|
+
function parseChunkId(idStr) {
|
|
27
|
+
const id = parseInt(idStr, 10);
|
|
28
|
+
if (!Number.isFinite(id) || id <= 0)
|
|
29
|
+
return null;
|
|
30
|
+
return id;
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* handleMarkRequest(db, idStr, body) → ApiResponse<MarkResult>
|
|
34
|
+
*/
|
|
35
|
+
export function handleMarkRequest(db, idStr, body) {
|
|
36
|
+
const chunk_id = parseChunkId(idStr);
|
|
37
|
+
if (chunk_id === null) {
|
|
38
|
+
return {
|
|
39
|
+
status: 400,
|
|
40
|
+
body: { ok: false, error: `invalid chunk id: ${idStr}`, code: "bad_id" },
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
if (!body || typeof body !== "object") {
|
|
44
|
+
return {
|
|
45
|
+
status: 400,
|
|
46
|
+
body: { ok: false, error: "missing JSON body", code: "bad_body" },
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
if (!validateKind(body.kind)) {
|
|
50
|
+
return {
|
|
51
|
+
status: 400,
|
|
52
|
+
body: {
|
|
53
|
+
ok: false,
|
|
54
|
+
error: `invalid kind: ${String(body.kind)} — expected canonical|refuted|stale`,
|
|
55
|
+
code: "bad_kind",
|
|
56
|
+
},
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
try {
|
|
60
|
+
const result = markChunk({
|
|
61
|
+
db,
|
|
62
|
+
chunk_id,
|
|
63
|
+
kind: body.kind,
|
|
64
|
+
notes: body.notes,
|
|
65
|
+
cfg: resolveConfig(),
|
|
66
|
+
});
|
|
67
|
+
return { status: 200, body: result };
|
|
68
|
+
}
|
|
69
|
+
catch (err) {
|
|
70
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
71
|
+
const status = /not found/i.test(msg) ? 404 : 500;
|
|
72
|
+
return {
|
|
73
|
+
status,
|
|
74
|
+
body: { ok: false, error: msg, code: status === 404 ? "not_found" : "runtime" },
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* handleSupersedeRequest(db, idStr, body) → ApiResponse<MarkResult>
|
|
80
|
+
*/
|
|
81
|
+
export function handleSupersedeRequest(db, idStr, body) {
|
|
82
|
+
const chunk_id = parseChunkId(idStr);
|
|
83
|
+
if (chunk_id === null) {
|
|
84
|
+
return {
|
|
85
|
+
status: 400,
|
|
86
|
+
body: { ok: false, error: `invalid chunk id: ${idStr}`, code: "bad_id" },
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
if (!body || typeof body !== "object") {
|
|
90
|
+
return {
|
|
91
|
+
status: 400,
|
|
92
|
+
body: { ok: false, error: "missing JSON body", code: "bad_body" },
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
const by_chunk_id = typeof body.by_chunk_id === "number" ? body.by_chunk_id : NaN;
|
|
96
|
+
if (!Number.isFinite(by_chunk_id) || by_chunk_id <= 0) {
|
|
97
|
+
return {
|
|
98
|
+
status: 400,
|
|
99
|
+
body: {
|
|
100
|
+
ok: false,
|
|
101
|
+
error: `invalid by_chunk_id: ${String(body.by_chunk_id)}`,
|
|
102
|
+
code: "bad_by_id",
|
|
103
|
+
},
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
const reason = validateReason(body.reason)
|
|
107
|
+
? body.reason
|
|
108
|
+
: "manual_resolution";
|
|
109
|
+
try {
|
|
110
|
+
const result = supersedeChunk({
|
|
111
|
+
db,
|
|
112
|
+
chunk_id,
|
|
113
|
+
by_chunk_id,
|
|
114
|
+
notes: body.notes,
|
|
115
|
+
reason,
|
|
116
|
+
});
|
|
117
|
+
return { status: 200, body: result };
|
|
118
|
+
}
|
|
119
|
+
catch (err) {
|
|
120
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
121
|
+
const status = /missing|not found/i.test(msg) ? 404 : 500;
|
|
122
|
+
return {
|
|
123
|
+
status,
|
|
124
|
+
body: { ok: false, error: msg, code: status === 404 ? "not_found" : "runtime" },
|
|
125
|
+
};
|
|
126
|
+
}
|
|
127
|
+
}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* src/api/server-deps-a2.ts — Wave O T2: A2 (export/import) wire-up adapter.
|
|
3
|
+
*
|
|
4
|
+
* Companion to `src/lib/archive/server-deps.ts`. This module re-exports the
|
|
5
|
+
* deps builders under the `/api/*` path used by tests + provides convenience
|
|
6
|
+
* helpers for streaming + multipart parsing that the wire-up.ts router
|
|
7
|
+
* intentionally does NOT couple to (keeping wire-up framework-agnostic).
|
|
8
|
+
*
|
|
9
|
+
* Two streaming concerns are handled here:
|
|
10
|
+
*
|
|
11
|
+
* 1. Export response: when the archive size > NOX_EXPORT_STREAM_THRESHOLD
|
|
12
|
+
* (default 16 MiB), we set `Transfer-Encoding: chunked` and write the
|
|
13
|
+
* buffer in 1 MiB slices, yielding to the event loop between writes so
|
|
14
|
+
* we don't starve other requests (regra de ouro #4 — Node single-thread).
|
|
15
|
+
*
|
|
16
|
+
* 2. Import request: the wire-up.ts contract is JSON body with
|
|
17
|
+
* `archive_b64`. We also accept `multipart/form-data` when
|
|
18
|
+
* `Content-Type` starts with `multipart/`, parsing the first file part
|
|
19
|
+
* out as the binary archive (no @types/formidable dep — minimal parser).
|
|
20
|
+
* This lets curl users `--data-binary @file.tgz` upload directly.
|
|
21
|
+
*
|
|
22
|
+
* Singleton DB resolution stays in deps-registry. This module is pure
|
|
23
|
+
* stream/parsing glue.
|
|
24
|
+
*/
|
|
25
|
+
import type { ServerResponse, IncomingMessage } from "node:http";
|
|
26
|
+
export { buildExportDeps, buildImportDeps, type HttpExportDeps, type HttpImportDeps, } from "../lib/archive/server-deps.js";
|
|
27
|
+
/**
|
|
28
|
+
* Write a Buffer back to the response. Small payloads get a single `end()`;
|
|
29
|
+
* large payloads stream via `Transfer-Encoding: chunked` to avoid blocking
|
|
30
|
+
* the event loop.
|
|
31
|
+
*
|
|
32
|
+
* Returns a promise that resolves when the response is fully drained.
|
|
33
|
+
*/
|
|
34
|
+
export declare function writeExportResponse(res: ServerResponse, body: Buffer, baseHeaders: Record<string, string>, threshold?: number): Promise<void>;
|
|
35
|
+
export interface MultipartFile {
|
|
36
|
+
name: string;
|
|
37
|
+
filename: string;
|
|
38
|
+
contentType: string;
|
|
39
|
+
content: Buffer;
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Parse a multipart/form-data body. Returns the first file part found.
|
|
43
|
+
* This is a minimal RFC 7578 implementation — no dependency on `busboy` /
|
|
44
|
+
* `formidable`. For payloads <64 MiB (wire-up.ts cap) this is plenty.
|
|
45
|
+
*
|
|
46
|
+
* Returns `null` when the content-type isn't multipart or when no file part
|
|
47
|
+
* is present. Throws on malformed boundary structure.
|
|
48
|
+
*/
|
|
49
|
+
export declare function parseMultipartFirstFile(rawBody: Buffer, contentType: string): MultipartFile | null;
|
|
50
|
+
/**
|
|
51
|
+
* Collect the request body as a Buffer (binary-safe). Wire-up's `readBody()`
|
|
52
|
+
* decodes to UTF-8 which mangles archives. Adapter callers must use this
|
|
53
|
+
* helper when the route can receive multipart/binary payloads.
|
|
54
|
+
*/
|
|
55
|
+
export declare function readRequestBodyBuffer(req: IncomingMessage, limit?: number): Promise<Buffer>;
|