@remnic/core 9.65.6 → 9.65.7
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/dist/access-admin-ops-surface.d.ts +11 -11
- package/dist/access-admin-ops-surface.js +31 -31
- package/dist/access-audit.js +2 -2
- package/dist/access-authorization-probe.d.ts +11 -11
- package/dist/access-authorization-probe.js +32 -32
- package/dist/access-boundary.d.ts +11 -11
- package/dist/access-boundary.js +31 -31
- package/dist/access-cli.js +111 -106
- package/dist/access-cli.js.map +1 -1
- package/dist/access-coding-context-resolution.d.ts +1 -1
- package/dist/access-extraction-force-flush.d.ts +11 -11
- package/dist/access-extraction-force-flush.js +31 -31
- package/dist/access-health-types.d.ts +1 -1
- package/dist/access-http-lcm-compaction.d.ts +11 -11
- package/dist/access-http-lifecycle-flush.d.ts +11 -11
- package/dist/access-http-offline-stream.d.ts +11 -11
- package/dist/access-http-query.d.ts +2 -2
- package/dist/access-http-query.js +33 -33
- package/dist/access-http.d.ts +13 -18
- package/dist/access-http.js +50 -48
- package/dist/access-identity-continuity-surface.d.ts +9 -9
- package/dist/access-identity-continuity-surface.js +31 -31
- package/dist/access-lcm-surface.d.ts +11 -11
- package/dist/access-lcm-surface.js +31 -31
- package/dist/access-mcp-output-schemas.js +1 -1
- package/dist/access-mcp.d.ts +11 -11
- package/dist/access-mcp.js +42 -40
- package/dist/access-memory-search-fanout.d.ts +2 -2
- package/dist/{access-namespace-preflight-D_6mo8ms.d.ts → access-namespace-preflight-8VYKmRX0.d.ts} +1 -1
- package/dist/access-namespace-preflight.d.ts +3 -3
- package/dist/access-namespace-preflight.js +31 -31
- package/dist/access-observe-write-surface.d.ts +11 -11
- package/dist/access-observe-write-surface.js +31 -31
- package/dist/access-offline-manifest.d.ts +9 -9
- package/dist/access-operations-batch.js +34 -34
- package/dist/access-operations.d.ts +12 -12
- package/dist/access-operations.js +39 -37
- package/dist/access-recall-concurrency.d.ts +11 -11
- package/dist/access-recall-concurrency.js +31 -31
- package/dist/access-recall-response.d.ts +11 -11
- package/dist/access-recall-response.js +31 -31
- package/dist/access-recall-surface.d.ts +11 -11
- package/dist/access-recall-surface.js +31 -31
- package/dist/access-schema.js +3 -3
- package/dist/{access-service-sbiNS5UB.d.ts → access-service-Crk__Git.d.ts} +8 -8
- package/dist/access-service-helpers.d.ts +11 -11
- package/dist/access-service.d.ts +11 -11
- package/dist/access-service.js +31 -31
- package/dist/access-surface-catalog.d.ts +11 -11
- package/dist/access-surface-catalog.js +43 -33
- package/dist/access-surface-catalog.js.map +1 -1
- package/dist/access-wearables-meetings-surface.d.ts +3 -3
- package/dist/action-confidence.d.ts +1 -1
- package/dist/active-memory-bridge.d.ts +1 -1
- package/dist/active-recall.d.ts +1 -1
- package/dist/active-recall.js +4 -4
- package/dist/adapters/index.js +4 -4
- package/dist/adapters/registry.js +2 -2
- package/dist/ambient-provenance.d.ts +1 -1
- package/dist/artifact-search.d.ts +1 -1
- package/dist/behavior-learner.d.ts +1 -1
- package/dist/behavior-signals.d.ts +1 -1
- package/dist/bootstrap.d.ts +9 -9
- package/dist/briefing-window.d.ts +2 -2
- package/dist/briefing.d.ts +2 -2
- package/dist/briefing.js +10 -10
- package/dist/buffer-surprise-report.d.ts +1 -1
- package/dist/buffer-turn-helpers.d.ts +1 -1
- package/dist/buffer.d.ts +2 -2
- package/dist/bulk-import/index.d.ts +3 -3
- package/dist/calibration.d.ts +1 -1
- package/dist/capabilities.d.ts +1 -1
- package/dist/{capsule-crypto-GWVG7LGC.js → capsule-crypto-7FJQINUR.js} +2 -2
- package/dist/{catalog-DO_7zfkv.d.ts → catalog-DybwVNW3.d.ts} +1 -1
- package/dist/causal-behavior.d.ts +1 -1
- package/dist/causal-behavior.js +2 -2
- package/dist/causal-chain.js +2 -2
- package/dist/causal-consolidation.d.ts +1 -1
- package/dist/causal-consolidation.js +13 -13
- package/dist/causal-retrieval.js +2 -2
- package/dist/causal-trajectory-graph.d.ts +1 -1
- package/dist/causal-trajectory-graph.js +2 -2
- package/dist/causal-trajectory.js +1 -1
- package/dist/{chunk-OWHERGF2.js → chunk-2NLLXCJG.js} +2 -2
- package/dist/{chunk-NZPFCP5A.js → chunk-2PSX5BJU.js} +2 -2
- package/dist/chunk-3BCULS4U.js +1093 -0
- package/dist/chunk-3BCULS4U.js.map +1 -0
- package/dist/{chunk-W6J4POB6.js → chunk-3RI5Y7KU.js} +2 -2
- package/dist/{chunk-H7BZBSP6.js → chunk-52II7PB6.js} +4 -4
- package/dist/{chunk-IF4EY26E.js → chunk-5DH6PG4B.js} +2 -2
- package/dist/{chunk-M4AHBM72.js → chunk-5HERQ5FX.js} +10 -10
- package/dist/{chunk-IRXMJLTW.js → chunk-5HK3CJAR.js} +2 -2
- package/dist/{chunk-XAWIL7TC.js → chunk-5S4LQOPE.js} +2 -2
- package/dist/{chunk-IDQ6DKXC.js → chunk-5VPQSRQO.js} +3 -3
- package/dist/{chunk-ROEAEANL.js → chunk-6CPUQ5D6.js} +10 -10
- package/dist/{chunk-SR7JIRAR.js → chunk-7F27PCSN.js} +2 -2
- package/dist/{chunk-7OZSHBWK.js → chunk-7TCGNUVP.js} +2 -2
- package/dist/{chunk-KBOG7FJV.js → chunk-7WR462EM.js} +2 -2
- package/dist/{chunk-AYAZWXJI.js → chunk-A32YEQAM.js} +2 -2
- package/dist/{chunk-5GIZM4RX.js → chunk-ACOC27BB.js} +2 -2
- package/dist/{chunk-5W7MKXMU.js → chunk-AFR6AIM4.js} +144 -78
- package/dist/chunk-AFR6AIM4.js.map +1 -0
- package/dist/{chunk-OMZLBT4B.js → chunk-ANJXPFRS.js} +47 -26
- package/dist/chunk-ANJXPFRS.js.map +1 -0
- package/dist/{chunk-FC7TIRFS.js → chunk-AX7UXCHJ.js} +6 -1
- package/dist/chunk-AX7UXCHJ.js.map +1 -0
- package/dist/{chunk-6LS5OX3U.js → chunk-BJTHRFFC.js} +6 -6
- package/dist/chunk-BWGCOLEL.js +61 -0
- package/dist/chunk-BWGCOLEL.js.map +1 -0
- package/dist/{chunk-PGW64IFQ.js → chunk-CFGU52XJ.js} +2 -2
- package/dist/{chunk-DPNXADEI.js → chunk-D4QVPP3G.js} +2 -2
- package/dist/{chunk-2RXUZVPU.js → chunk-EOHKUWXW.js} +2 -2
- package/dist/{chunk-YNDLCWXS.js → chunk-EZ25VE3G.js} +4 -4
- package/dist/{chunk-ZK4BFABK.js → chunk-F635GAL7.js} +4 -4
- package/dist/{chunk-HWVNYNIV.js → chunk-F6QHHRWP.js} +2 -2
- package/dist/{chunk-YUTTMSC7.js → chunk-FMQ4MOQO.js} +89 -26
- package/dist/chunk-FMQ4MOQO.js.map +1 -0
- package/dist/{chunk-LDBFXD4F.js → chunk-FP7YTTVO.js} +3 -1
- package/dist/chunk-FP7YTTVO.js.map +1 -0
- package/dist/{chunk-O4BAGJDN.js → chunk-GEPACVWN.js} +2 -2
- package/dist/{chunk-XZBXINXZ.js → chunk-GIC6BASP.js} +4 -4
- package/dist/{chunk-PP7R754B.js → chunk-GPFZFCRN.js} +1 -1
- package/dist/{chunk-LSYD7GHZ.js → chunk-GTSVEEP3.js} +2 -2
- package/dist/{chunk-RQ2EQRRR.js → chunk-I4343FIA.js} +79 -6
- package/dist/chunk-I4343FIA.js.map +1 -0
- package/dist/{chunk-YWBOOBDP.js → chunk-I7EX6KSH.js} +58 -58
- package/dist/{chunk-3I22VWB3.js → chunk-IP4ZNT4U.js} +2 -2
- package/dist/{chunk-AXGFOFNY.js → chunk-IY7UXD3J.js} +2 -2
- package/dist/{chunk-6FUMA6AA.js → chunk-JAQXUGLN.js} +2 -2
- package/dist/{chunk-RKNJBZ55.js → chunk-JBPKEARU.js} +4 -4
- package/dist/chunk-JCCWJHOP.js +240 -0
- package/dist/chunk-JCCWJHOP.js.map +1 -0
- package/dist/{chunk-5W7CTZ2E.js → chunk-KQAFEZQX.js} +4 -4
- package/dist/{chunk-D2YNNDML.js → chunk-KWIGDKM2.js} +2 -2
- package/dist/{chunk-2JHRCWHT.js → chunk-LLQCM2U2.js} +85 -85
- package/dist/{chunk-OLBZ2WGG.js → chunk-LTBKKSCX.js} +2 -2
- package/dist/{chunk-RACZB5HT.js → chunk-N37X5RU7.js} +4 -4
- package/dist/{chunk-FEO2CDXR.js → chunk-NG3MBQV4.js} +2 -2
- package/dist/{chunk-AG46P24C.js → chunk-NNBZS3DY.js} +4 -4
- package/dist/{chunk-JGG5HVI2.js → chunk-OPGL46PX.js} +2 -2
- package/dist/{chunk-OUKBMQ2O.js → chunk-PD66CVSD.js} +2 -2
- package/dist/{chunk-7SSRXEZJ.js → chunk-PDDSFELN.js} +2 -2
- package/dist/{chunk-MVIYRRVJ.js → chunk-PMVPCZJZ.js} +5 -5
- package/dist/{chunk-D35XLYQ7.js → chunk-RGCF4XNH.js} +9 -9
- package/dist/{chunk-PNAGNVGK.js → chunk-RQE4TITU.js} +35 -30
- package/dist/chunk-RQE4TITU.js.map +1 -0
- package/dist/{chunk-X2DWBWOX.js → chunk-S3K2CIK5.js} +2 -2
- package/dist/{chunk-TWBQQ3FT.js → chunk-SEA6M7SS.js} +2 -2
- package/dist/{chunk-DYO24BNB.js → chunk-SVVIASVX.js} +2 -2
- package/dist/{chunk-7K5Q6COX.js → chunk-TVVEYCNW.js} +4 -4
- package/dist/{chunk-4K7IW3F7.js → chunk-UD7UNYRD.js} +34 -3
- package/dist/chunk-UD7UNYRD.js.map +1 -0
- package/dist/chunk-ULM7JCDH.js +154 -0
- package/dist/chunk-ULM7JCDH.js.map +1 -0
- package/dist/{chunk-NLUCDKLT.js → chunk-VKCAHCBI.js} +2 -2
- package/dist/{chunk-BXXOPKT5.js → chunk-VXVZ2GM3.js} +2 -2
- package/dist/chunk-W2UOAATB.js +521 -0
- package/dist/chunk-W2UOAATB.js.map +1 -0
- package/dist/{chunk-JFWZRUKP.js → chunk-WTOZBZNN.js} +3 -3
- package/dist/{chunk-UVYI6VIX.js → chunk-X7Y7WX73.js} +1 -1
- package/dist/{chunk-5TG4MU2U.js → chunk-YKWFK7XA.js} +5 -5
- package/dist/{chunk-BIJAWZYW.js → chunk-YMOPYG3K.js} +6 -6
- package/dist/{chunk-XUZ5CIEE.js → chunk-YRVAKONL.js} +1 -1
- package/dist/{chunk-53MZQEBD.js → chunk-YWSQD2IB.js} +2 -2
- package/dist/{chunk-US4IRASK.js → chunk-Z4U3UN56.js} +2 -2
- package/dist/{chunk-QMZY3GG6.js → chunk-ZAOHJDKH.js} +3 -3
- package/dist/{chunk-ZXUZ54Z5.js → chunk-ZIJDI4CP.js} +2 -2
- package/dist/{cli-Bfgo0n1L.d.ts → cli-B322UMvB.d.ts} +5 -5
- package/dist/cli.d.ts +13 -13
- package/dist/cli.js +75 -74
- package/dist/coding/pre-action-gate.d.ts +1 -1
- package/dist/coding/pre-action-gate.js +2 -2
- package/dist/compounding/engine.d.ts +2 -2
- package/dist/compounding/engine.js +10 -10
- package/dist/compounding/preference-consolidator.d.ts +1 -1
- package/dist/compression-optimizer.d.ts +1 -1
- package/dist/config.d.ts +1 -1
- package/dist/config.js +4 -4
- package/dist/connectors/codex-materialize-runner.d.ts +1 -1
- package/dist/connectors/codex-materialize-runner.js +10 -10
- package/dist/connectors/codex-materialize.d.ts +1 -1
- package/dist/connectors/index.d.ts +1 -1
- package/dist/connectors/index.js +10 -10
- package/dist/consolidation-provenance-check.d.ts +2 -2
- package/dist/consolidation-undo.d.ts +2 -2
- package/dist/contradiction/index.d.ts +3 -3
- package/dist/converge-config.d.ts +1 -1
- package/dist/convergence-refresh.d.ts +2 -2
- package/dist/convergence-refresh.js +12 -12
- package/dist/conversation-index/backend.d.ts +1 -1
- package/dist/conversation-index/chunker.d.ts +1 -1
- package/dist/conversation-index/faiss-adapter.d.ts +1 -1
- package/dist/conversation-index/indexer.d.ts +1 -1
- package/dist/conversation-index/search.d.ts +1 -1
- package/dist/corpus-watermark.d.ts +1 -1
- package/dist/corpus-watermark.js +12 -12
- package/dist/cross-lingual-recall.d.ts +1 -1
- package/dist/dashboard-runtime.js +2 -2
- package/dist/day-summary.d.ts +1 -1
- package/dist/delinearize.d.ts +1 -1
- package/dist/dependency-propagation-config.d.ts +1 -1
- package/dist/{dependency-propagation-delivery-D23_x-s5.d.ts → dependency-propagation-delivery-BGcNairQ.d.ts} +1 -1
- package/dist/direct-answer-wiring.d.ts +1 -1
- package/dist/direct-answer.d.ts +1 -1
- package/dist/embedding-fallback.d.ts +1 -1
- package/dist/enrichment/index.d.ts +1 -1
- package/dist/entity-origin-fields.d.ts +1 -1
- package/dist/entity-retrieval.d.ts +2 -2
- package/dist/entity-retrieval.js +10 -10
- package/dist/entity-schema.d.ts +1 -1
- package/dist/episodic-context.d.ts +1 -1
- package/dist/eval-trajectory-contracts.d.ts +256 -0
- package/dist/eval-trajectory-contracts.js +56 -0
- package/dist/eval-trajectory-store.d.ts +39 -0
- package/dist/eval-trajectory-store.js +19 -0
- package/dist/eval-trajectory-store.js.map +1 -0
- package/dist/eval-trajectory.d.ts +67 -0
- package/dist/eval-trajectory.js +46 -0
- package/dist/eval-trajectory.js.map +1 -0
- package/dist/event-order-recall.js +2 -2
- package/dist/explicit-capture.d.ts +9 -9
- package/dist/external-wiki-access.d.ts +11 -11
- package/dist/external-wiki-access.js +32 -32
- package/dist/external-wiki-collection-registration.d.ts +1 -1
- package/dist/external-wiki-collection.d.ts +1 -1
- package/dist/external-wiki-mcp-tools.d.ts +11 -11
- package/dist/extraction-error-classification.d.ts +1 -1
- package/dist/extraction-faithfulness.d.ts +1 -1
- package/dist/extraction-judge-telemetry.d.ts +1 -1
- package/dist/extraction-judge-training.d.ts +1 -1
- package/dist/extraction-judge.d.ts +1 -1
- package/dist/extraction-liveness.d.ts +1 -1
- package/dist/extraction-normalization.d.ts +1 -1
- package/dist/extraction-prompt.d.ts +1 -1
- package/dist/extraction-source-grounding-rules.d.ts +1 -1
- package/dist/extraction-source-grounding.d.ts +1 -1
- package/dist/extraction.d.ts +1 -1
- package/dist/extraction.js +12 -12
- package/dist/fallback-llm.d.ts +1 -1
- package/dist/graph-dashboard-diff.d.ts +1 -1
- package/dist/graph-dashboard-key.d.ts +1 -1
- package/dist/graph-dashboard-parser.d.ts +1 -1
- package/dist/{graph-edge-decay-FXGELBFA.js → graph-edge-decay-A4SDFMMS.js} +4 -4
- package/dist/graph-edge-decay-A4SDFMMS.js.map +1 -0
- package/dist/graph-edge-reinforcement.d.ts +1 -1
- package/dist/graph-path-reconstruction.d.ts +1 -1
- package/dist/graph-path-scoring.d.ts +1 -1
- package/dist/graph-snapshot.d.ts +1 -1
- package/dist/graph-snapshot.js +3 -3
- package/dist/graph.d.ts +1 -1
- package/dist/graph.js +3 -3
- package/dist/harmonic-retrieval.js +1 -1
- package/dist/importance.d.ts +1 -1
- package/dist/importers/index.d.ts +1 -1
- package/dist/in-flight-reads.d.ts +1 -1
- package/dist/{index--QhGIXF2.d.ts → index-By2QUAMh.d.ts} +2 -2
- package/dist/index.d.ts +26 -23
- package/dist/index.js +184 -142
- package/dist/intent.d.ts +1 -1
- package/dist/lcm/engine.d.ts +1 -1
- package/dist/lcm/engine.js +4 -4
- package/dist/lcm/index.d.ts +1 -1
- package/dist/lcm/index.js +13 -13
- package/dist/lcm/tools.d.ts +1 -1
- package/dist/lifecycle.d.ts +1 -1
- package/dist/live-connectors-runner.d.ts +1 -1
- package/dist/local-llm.d.ts +1 -1
- package/dist/local-model-endpoint.d.ts +1 -1
- package/dist/location/index.d.ts +128 -1
- package/dist/location/index.js +60 -750
- package/dist/location/index.js.map +1 -1
- package/dist/maintenance/memory-governance.d.ts +1 -1
- package/dist/maintenance/memory-governance.js +10 -10
- package/dist/maintenance/rebuild-memory-lifecycle-ledger.d.ts +2 -2
- package/dist/maintenance/rebuild-memory-lifecycle-ledger.js +10 -10
- package/dist/maintenance/rebuild-memory-projection.d.ts +2 -2
- package/dist/maintenance/rebuild-memory-projection.js +11 -11
- package/dist/{maintenance-PFvY1Pw_.d.ts → maintenance-Dm2McrIx.d.ts} +4 -3
- package/dist/mcp-memory-inspector-app.d.ts +11 -11
- package/dist/mcp-read-only-tools.js +1 -1
- package/dist/memory-action-policy.d.ts +1 -1
- package/dist/memory-cache.d.ts +1 -1
- package/dist/memory-controller.d.ts +1 -1
- package/dist/memory-lifecycle-ledger-utils.d.ts +1 -1
- package/dist/memory-projection-store.d.ts +1 -1
- package/dist/memory-provenance.d.ts +1 -1
- package/dist/memory-snapshot.d.ts +1 -1
- package/dist/memory-subject-cli.d.ts +11 -11
- package/dist/memory-subject.d.ts +11 -11
- package/dist/memory-worth-outcomes.d.ts +47 -3
- package/dist/memory-worth-outcomes.js +5 -3
- package/dist/models-json.d.ts +1 -1
- package/dist/namespaces/migrate.d.ts +3 -3
- package/dist/namespaces/migrate.js +11 -11
- package/dist/namespaces/principal.d.ts +1 -1
- package/dist/namespaces/search.d.ts +1 -1
- package/dist/namespaces/search.js +7 -7
- package/dist/namespaces/storage.d.ts +3 -3
- package/dist/namespaces/storage.js +10 -10
- package/dist/native-knowledge.d.ts +1 -1
- package/dist/offline-sync-impression-drain.d.ts +1 -1
- package/dist/operator-doctor-corpus.d.ts +1 -1
- package/dist/operator-doctor-corpus.js +13 -13
- package/dist/operator-doctor-replica.d.ts +1 -1
- package/dist/operator-toolkit.d.ts +3 -3
- package/dist/operator-toolkit.js +24 -24
- package/dist/orchestration/compression-guideline-coordinator.d.ts +2 -2
- package/dist/orchestration/maintenance.d.ts +4 -4
- package/dist/orchestration/maintenance.js +18 -16
- package/dist/{orchestrator-4wzJrPVm.d.ts → orchestrator-Co1DyfuP.d.ts} +8 -8
- package/dist/orchestrator.d.ts +9 -9
- package/dist/orchestrator.js +111 -106
- package/dist/patterns-cli.d.ts +1 -1
- package/dist/{pipeline-CgXgdIrF.d.ts → pipeline-DotMnb6y.d.ts} +1 -1
- package/dist/policy-runtime.d.ts +1 -1
- package/dist/proactive-contention.d.ts +1 -1
- package/dist/provenance.d.ts +1 -1
- package/dist/{public-http-BP3VQDl5.d.ts → public-http-PJRtnSi-.d.ts} +1 -1
- package/dist/{qmd-BppGGxsi.d.ts → qmd-BP0n11fR.d.ts} +1 -1
- package/dist/qmd-preflight.d.ts +2 -2
- package/dist/qmd-recall-cache.d.ts +1 -1
- package/dist/qmd.d.ts +2 -2
- package/dist/recall-concurrency-config.d.ts +1 -1
- package/dist/recall-disclosure-escalation.d.ts +1 -1
- package/dist/recall-explain-renderer.d.ts +1 -1
- package/dist/recall-memory-map.d.ts +1 -1
- package/dist/recall-planner-llm.d.ts +1 -1
- package/dist/recall-state.d.ts +1 -1
- package/dist/recall-tag-filter.d.ts +1 -1
- package/dist/recall-timings.d.ts +1 -1
- package/dist/recall-xray-cli.d.ts +1 -1
- package/dist/recall-xray-renderer.d.ts +1 -1
- package/dist/recall-xray.d.ts +1 -1
- package/dist/reconcile/cursor.d.ts +1 -1
- package/dist/reconcile/manifest.d.ts +1 -1
- package/dist/reconcile/plan.d.ts +1 -1
- package/dist/replay/normalizers/chatgpt.d.ts +1 -1
- package/dist/replay/normalizers/claude.d.ts +1 -1
- package/dist/replay/normalizers/openclaw.d.ts +1 -1
- package/dist/replay/normalizers/shared.d.ts +1 -1
- package/dist/replay/runner.d.ts +1 -1
- package/dist/replay/types.d.ts +1 -1
- package/dist/replica-divergence.d.ts +1 -1
- package/dist/replica-peers-config.d.ts +1 -1
- package/dist/resolve-auth-token.d.ts +1 -1
- package/dist/resume-bundles.js +5 -5
- package/dist/retrieval-agents.d.ts +2 -2
- package/dist/retrieval-tiers.d.ts +1 -1
- package/dist/routing/engine.d.ts +1 -1
- package/dist/routing/store.d.ts +1 -1
- package/dist/salvage-envelope.d.ts +1 -1
- package/dist/{scope-profiles-ChZUtxDU.d.ts → scope-profiles-6ChZKTy-.d.ts} +1 -1
- package/dist/search/embed-helper.d.ts +1 -1
- package/dist/search/factory.d.ts +1 -1
- package/dist/search/factory.js +6 -6
- package/dist/search/index.d.ts +1 -1
- package/dist/search/index.js +10 -10
- package/dist/search/lancedb-backend.d.ts +1 -1
- package/dist/search/lancedb-backend.js +2 -2
- package/dist/search/meilisearch-backend.d.ts +1 -1
- package/dist/search/meilisearch-backend.js +2 -2
- package/dist/search/noop-backend.d.ts +1 -1
- package/dist/search/orama-backend.d.ts +1 -1
- package/dist/search/orama-backend.js +2 -2
- package/dist/search/port.d.ts +1 -1
- package/dist/search/remote-backend.d.ts +1 -1
- package/dist/{semantic-consolidation-mSPwQSmF.d.ts → semantic-consolidation-DziYcW5J.d.ts} +1 -1
- package/dist/semantic-consolidation.d.ts +2 -2
- package/dist/semantic-consolidation.js +11 -11
- package/dist/semantic-rule-promotion.js +10 -10
- package/dist/semantic-rule-verifier.d.ts +1 -1
- package/dist/semantic-rule-verifier.js +10 -10
- package/dist/{service-BICWLwSP.d.ts → service-C7rIBuK_.d.ts} +2 -2
- package/dist/session-observer-bands.d.ts +1 -1
- package/dist/session-observer-state.d.ts +1 -1
- package/dist/shared-context/manager.d.ts +1 -1
- package/dist/signal.d.ts +1 -1
- package/dist/source-agent-qualifier.d.ts +1 -1
- package/dist/source-agent-qualifier.js +10 -10
- package/dist/{storage-B7urx1K3.d.ts → storage-B1hEx8Xg.d.ts} +1 -1
- package/dist/storage.d.ts +2 -2
- package/dist/storage.js +9 -9
- package/dist/subject-config.d.ts +1 -1
- package/dist/summarizer.d.ts +1 -1
- package/dist/summary-snapshot.d.ts +1 -1
- package/dist/support-passport/index.d.ts +14 -14
- package/dist/support-passport/index.js +34 -34
- package/dist/temporal-supersession.d.ts +2 -2
- package/dist/temporal-timeline-recall.d.ts +1 -1
- package/dist/temporal-validity.d.ts +1 -1
- package/dist/threading.d.ts +1 -1
- package/dist/tier-migration.d.ts +2 -2
- package/dist/tier-routing.d.ts +1 -1
- package/dist/topics.d.ts +1 -1
- package/dist/transcript.d.ts +1 -1
- package/dist/transfer/backup.js +2 -2
- package/dist/transfer/capsule-export.js +2 -2
- package/dist/transfer/capsule-import.js +2 -2
- package/dist/trust-score-stage.d.ts +1 -1
- package/dist/trust-score.d.ts +1 -1
- package/dist/{types-ETU5N6nB.d.ts → types-BHDNxGTT.d.ts} +1 -1
- package/dist/types.d.ts +1 -1
- package/dist/utility-runtime.d.ts +1 -1
- package/dist/verified-recall.js +10 -10
- package/dist/who-knows-cli.d.ts +11 -11
- package/dist/who-knows-cli.js +11 -11
- package/dist/who-knows.d.ts +11 -11
- package/dist/who-knows.js +10 -10
- package/dist/write-envelope.d.ts +1 -1
- package/package.json +2 -2
- package/src/access-boundary.ts +5 -0
- package/src/access-http.ts +15 -16
- package/src/access-mcp-output-schemas.ts +5 -0
- package/src/access-mcp.ts +6 -6
- package/src/access-operations.ts +2 -0
- package/src/access-surface-catalog.ts +10 -0
- package/src/eval-trajectory-contracts.ts +411 -0
- package/src/eval-trajectory-store.ts +306 -0
- package/src/eval-trajectory.test.ts +534 -0
- package/src/eval-trajectory.ts +773 -0
- package/src/index.ts +2 -0
- package/src/location/access-operations.ts +84 -0
- package/src/location/http-glue.test.ts +100 -0
- package/src/location/http-glue.ts +85 -0
- package/src/location/index.ts +3 -0
- package/src/location/mcp-tools.ts +82 -0
- package/src/location/provider-setup.test.ts +106 -0
- package/src/location/provider-setup.ts +103 -0
- package/src/location/scheduler.test.ts +113 -0
- package/src/location/scheduler.ts +98 -0
- package/src/location/surfaces.test.ts +241 -0
- package/src/location/surfaces.ts +329 -0
- package/src/maintenance/day-summary-cron.ts +45 -0
- package/src/mcp-read-only-tools.ts +2 -0
- package/src/memory-worth-outcomes.test.ts +53 -18
- package/src/memory-worth-outcomes.ts +91 -9
- package/src/orchestration/maintenance.ts +22 -30
- package/src/wearables/http-glue.ts +28 -0
- package/dist/chunk-4K7IW3F7.js.map +0 -1
- package/dist/chunk-5W7MKXMU.js.map +0 -1
- package/dist/chunk-FC7TIRFS.js.map +0 -1
- package/dist/chunk-LDBFXD4F.js.map +0 -1
- package/dist/chunk-OMZLBT4B.js.map +0 -1
- package/dist/chunk-PNAGNVGK.js.map +0 -1
- package/dist/chunk-RQ2EQRRR.js.map +0 -1
- package/dist/chunk-YUTTMSC7.js.map +0 -1
- /package/dist/{capsule-crypto-GWVG7LGC.js.map → capsule-crypto-7FJQINUR.js.map} +0 -0
- /package/dist/{chunk-OWHERGF2.js.map → chunk-2NLLXCJG.js.map} +0 -0
- /package/dist/{chunk-NZPFCP5A.js.map → chunk-2PSX5BJU.js.map} +0 -0
- /package/dist/{chunk-W6J4POB6.js.map → chunk-3RI5Y7KU.js.map} +0 -0
- /package/dist/{chunk-H7BZBSP6.js.map → chunk-52II7PB6.js.map} +0 -0
- /package/dist/{chunk-IF4EY26E.js.map → chunk-5DH6PG4B.js.map} +0 -0
- /package/dist/{chunk-M4AHBM72.js.map → chunk-5HERQ5FX.js.map} +0 -0
- /package/dist/{chunk-IRXMJLTW.js.map → chunk-5HK3CJAR.js.map} +0 -0
- /package/dist/{chunk-XAWIL7TC.js.map → chunk-5S4LQOPE.js.map} +0 -0
- /package/dist/{chunk-IDQ6DKXC.js.map → chunk-5VPQSRQO.js.map} +0 -0
- /package/dist/{chunk-ROEAEANL.js.map → chunk-6CPUQ5D6.js.map} +0 -0
- /package/dist/{chunk-SR7JIRAR.js.map → chunk-7F27PCSN.js.map} +0 -0
- /package/dist/{chunk-7OZSHBWK.js.map → chunk-7TCGNUVP.js.map} +0 -0
- /package/dist/{chunk-KBOG7FJV.js.map → chunk-7WR462EM.js.map} +0 -0
- /package/dist/{chunk-AYAZWXJI.js.map → chunk-A32YEQAM.js.map} +0 -0
- /package/dist/{chunk-5GIZM4RX.js.map → chunk-ACOC27BB.js.map} +0 -0
- /package/dist/{chunk-6LS5OX3U.js.map → chunk-BJTHRFFC.js.map} +0 -0
- /package/dist/{chunk-PGW64IFQ.js.map → chunk-CFGU52XJ.js.map} +0 -0
- /package/dist/{chunk-DPNXADEI.js.map → chunk-D4QVPP3G.js.map} +0 -0
- /package/dist/{chunk-2RXUZVPU.js.map → chunk-EOHKUWXW.js.map} +0 -0
- /package/dist/{chunk-YNDLCWXS.js.map → chunk-EZ25VE3G.js.map} +0 -0
- /package/dist/{chunk-ZK4BFABK.js.map → chunk-F635GAL7.js.map} +0 -0
- /package/dist/{chunk-HWVNYNIV.js.map → chunk-F6QHHRWP.js.map} +0 -0
- /package/dist/{chunk-O4BAGJDN.js.map → chunk-GEPACVWN.js.map} +0 -0
- /package/dist/{chunk-XZBXINXZ.js.map → chunk-GIC6BASP.js.map} +0 -0
- /package/dist/{chunk-PP7R754B.js.map → chunk-GPFZFCRN.js.map} +0 -0
- /package/dist/{chunk-LSYD7GHZ.js.map → chunk-GTSVEEP3.js.map} +0 -0
- /package/dist/{chunk-YWBOOBDP.js.map → chunk-I7EX6KSH.js.map} +0 -0
- /package/dist/{chunk-3I22VWB3.js.map → chunk-IP4ZNT4U.js.map} +0 -0
- /package/dist/{chunk-AXGFOFNY.js.map → chunk-IY7UXD3J.js.map} +0 -0
- /package/dist/{chunk-6FUMA6AA.js.map → chunk-JAQXUGLN.js.map} +0 -0
- /package/dist/{chunk-RKNJBZ55.js.map → chunk-JBPKEARU.js.map} +0 -0
- /package/dist/{chunk-5W7CTZ2E.js.map → chunk-KQAFEZQX.js.map} +0 -0
- /package/dist/{chunk-D2YNNDML.js.map → chunk-KWIGDKM2.js.map} +0 -0
- /package/dist/{chunk-2JHRCWHT.js.map → chunk-LLQCM2U2.js.map} +0 -0
- /package/dist/{chunk-OLBZ2WGG.js.map → chunk-LTBKKSCX.js.map} +0 -0
- /package/dist/{chunk-RACZB5HT.js.map → chunk-N37X5RU7.js.map} +0 -0
- /package/dist/{chunk-FEO2CDXR.js.map → chunk-NG3MBQV4.js.map} +0 -0
- /package/dist/{chunk-AG46P24C.js.map → chunk-NNBZS3DY.js.map} +0 -0
- /package/dist/{chunk-JGG5HVI2.js.map → chunk-OPGL46PX.js.map} +0 -0
- /package/dist/{chunk-OUKBMQ2O.js.map → chunk-PD66CVSD.js.map} +0 -0
- /package/dist/{chunk-7SSRXEZJ.js.map → chunk-PDDSFELN.js.map} +0 -0
- /package/dist/{chunk-MVIYRRVJ.js.map → chunk-PMVPCZJZ.js.map} +0 -0
- /package/dist/{chunk-D35XLYQ7.js.map → chunk-RGCF4XNH.js.map} +0 -0
- /package/dist/{chunk-X2DWBWOX.js.map → chunk-S3K2CIK5.js.map} +0 -0
- /package/dist/{chunk-TWBQQ3FT.js.map → chunk-SEA6M7SS.js.map} +0 -0
- /package/dist/{chunk-DYO24BNB.js.map → chunk-SVVIASVX.js.map} +0 -0
- /package/dist/{chunk-7K5Q6COX.js.map → chunk-TVVEYCNW.js.map} +0 -0
- /package/dist/{chunk-NLUCDKLT.js.map → chunk-VKCAHCBI.js.map} +0 -0
- /package/dist/{chunk-BXXOPKT5.js.map → chunk-VXVZ2GM3.js.map} +0 -0
- /package/dist/{chunk-JFWZRUKP.js.map → chunk-WTOZBZNN.js.map} +0 -0
- /package/dist/{chunk-UVYI6VIX.js.map → chunk-X7Y7WX73.js.map} +0 -0
- /package/dist/{chunk-5TG4MU2U.js.map → chunk-YKWFK7XA.js.map} +0 -0
- /package/dist/{chunk-BIJAWZYW.js.map → chunk-YMOPYG3K.js.map} +0 -0
- /package/dist/{chunk-XUZ5CIEE.js.map → chunk-YRVAKONL.js.map} +0 -0
- /package/dist/{chunk-53MZQEBD.js.map → chunk-YWSQD2IB.js.map} +0 -0
- /package/dist/{chunk-US4IRASK.js.map → chunk-Z4U3UN56.js.map} +0 -0
- /package/dist/{chunk-QMZY3GG6.js.map → chunk-ZAOHJDKH.js.map} +0 -0
- /package/dist/{chunk-ZXUZ54Z5.js.map → chunk-ZIJDI4CP.js.map} +0 -0
- /package/dist/{graph-edge-decay-FXGELBFA.js.map → eval-trajectory-contracts.js.map} +0 -0
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/access-http.ts","../src/meetings/errors.ts","../src/meetings/http-glue.ts","../src/chat/chat-http.ts","../src/support-passport/access-http-base.ts","../src/review/review-deck-http-base.ts"],"sourcesContent":["import { createServer, type IncomingMessage, type Server, type ServerResponse } from \"node:http\";\nimport { randomUUID, timingSafeEqual } from \"node:crypto\";\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport { existsSync } from \"node:fs\";\nimport { readFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { fileURLToPath, URL } from \"node:url\";\nimport { gunzipSync } from \"node:zlib\";\nimport { log } from \"./logger.js\";\nimport { WriteRateLimiter, type WriteRateLimitReservation } from \"./write-rate-limiter.js\";\nimport { abortError, isAbortError } from \"./abort-error.js\";\nimport { EngramAccessForbiddenError } from \"./access-errors.js\";\nimport {\n EngramAccessInputError,\n type EngramAccessService,\n type WearablesMeetingsScope,\n type EngramAccessMemoryResponse,\n type EngramAccessWriteResponse,\n type EngramAccessRecallResponse,\n} from \"./access-service.js\";\nimport { maybeHandleLifecycleFlush, type LifecycleFlushHttpDeps } from \"./access-http-lifecycle-flush.js\";\nimport {\n respondOfflineManifestStream,\n respondOfflineSnapshotStream,\n} from \"./access-http-offline-stream.js\";\nimport { nonEmptyQueryParam, optionalNamespaceKindQueryParam, optionalQueryString, positiveIntQueryParam } from \"./access-http-query.js\";\nimport { CorrectionContractError } from \"./correction/correction-contract.js\";\nimport { WearablesInputError } from \"./wearables/errors.js\"; import { respondMeetingsList, respondMeetingsGet, respondMeetingsBuild } from \"./meetings/http-glue.js\";\nimport { EngramMcpServer, MCP_SUPPORTED_PROTOCOL_VERSIONS } from \"./access-mcp.js\";\nimport { validateRequest, type SchemaName, type SchemaTypeFor } from \"./access-schema.js\";\nimport {\n OFFLINE_SYNC_APPLY_MAX_BODY_BYTES,\n OFFLINE_SYNC_FILE_CONTENT_MAX_CHUNK_BYTES,\n OFFLINE_SYNC_SNAPSHOT_BASE_MAX_BODY_BYTES,\n} from \"./offline-sync.js\";\nimport type { RecallDisclosure } from \"./types.js\";\nimport { isRecallDisclosure } from \"./types.js\";\nimport { isTrustZoneName, type TrustZoneName, type TrustZoneRecordKind, type TrustZoneSourceClass } from \"./trust-zones.js\";\nimport { AdapterRegistry, type ResolvedIdentity } from \"./adapters/index.js\";\nimport type { CitationEntry } from \"./citations.js\";\nimport {\n subscribeGraphEvents,\n type GraphEvent,\n} from \"./graph-events.js\";\nimport { expandTildePath } from \"./utils/path.js\";\nimport { projectTagProjectId } from \"./coding/coding-namespace.js\";\nimport { getOperation, type OperationName } from \"./access-boundary.js\";\nimport { authorizationProbeNamespaces, authorizationProbeRequiresPrincipalNamespace, probeOperationAuthorization } from \"./access-authorization-probe.js\";\nimport { resolveQueryNamespaceWritablePreflight } from \"./access-namespace-preflight.js\";\nimport { respondAccessCapabilitiesHttp } from \"./access-http-lcm-compaction.js\";\nimport { handleWhoKnowsHttpQuery } from \"./who-knows.js\";\nimport {\n assertOperationAllowed,\n capabilityAllowsOp,\n enforceNamespaceAllowList,\n isCapabilityRestricted,\n tokenCapabilityStore,\n type TokenCapabilities,\n} from \"./access-token-capabilities.js\";\n// Importing access-operations registers the pilot boundary operations\n// (memory_get / memory_store) as a side effect; the HTTP handlers below\n// dispatch the migrated routes through the registry (issue #1525).\nimport \"./access-operations.js\";\nimport { handleChatMessage, handleChatEventsSSE } from \"./chat/chat-http.js\";\n// cleanupExpiredChatSessions wires the chat session TTL sweep into the\n// server lifecycle (issue #1685 item 1 / #1687 Thread 21).\nimport { cleanupExpiredChatSessions, enforceChatSessionNamespace } from \"./chat/chat-session.js\";\nimport { isDefaultReviewNamespace, listPairs, readPair } from \"./contradiction/contradiction-review.js\";\nimport { isValidResolutionVerb, executeResolution } from \"./contradiction/resolution.js\";\nimport { RelayMissionStoreError } from \"./relay/mission.js\";\nimport { ReviewDeckAccessHttpBase } from \"./review/review-deck-http-base.js\";\nimport { serializeInlineScriptValue } from \"./inline-script.js\";\nimport type { SupportPassportExternalRequestHandler } from \"./support-passport/public-http.js\";\nexport interface AccessHttpReadinessState {\n ready: boolean;\n warmupAttempts: number;\n lastError?: string | null;\n /**\n * True when the standalone init gate opened before search warm-up completed\n * (issue #2215): the service is functional (recall serves via fallback\n * retrieval), so health answers 200 with degraded info instead of 503.\n */\n degraded?: boolean;\n}\nexport interface EngramAccessHttpServerOptions {\n service: EngramAccessService;\n host?: string;\n port?: number;\n authToken?: string;\n /** Additional valid tokens (for multi-connector auth). Checked alongside authToken. */\n authTokens?: string[];\n /** Dynamic token loader — called on each auth check so new/revoked tokens take effect without restart. */\n authTokensGetter?: () => string[];\n /**\n * Dynamic token-ENTRY loader ({token, connector} pairs from one coherent\n * snapshot). Preferred over `authTokensGetter` when a `tokenPathPolicy`\n * is set: the connector used for the policy decision comes from the SAME\n * entry that validated, so identity can never lag validation.\n */\n authTokenEntriesGetter?: () => ReadonlyArray<{ token: string; connector?: string; capabilities?: TokenCapabilities }>;\n /**\n * Optional per-request scope policy for tokens sourced from\n * `authTokenEntriesGetter`. Return false to deny the (validated) token\n * for this pathname. Static `authToken`/`authTokens` (operator-supplied)\n * bypass the policy. Entries whose connector is missing FAIL CLOSED when\n * a policy is configured.\n */\n tokenPathPolicy?: (connector: string, pathname: string | undefined) => boolean;\n principal?: string;\n maxBodyBytes?: number;\n /**\n * Max non-replayed write requests per rolling window before 429\n * `write_rate_limited` (issue #1937). Positive integer; defaults to 30.\n */\n writeRateLimitMaxRequests?: number;\n /** Rolling window for the write rate limit, in ms. Positive integer; defaults to 60000. */\n writeRateLimitWindowMs?: number;\n adminConsoleEnabled?: boolean;\n adminConsolePublicDir?: string;\n /** Inject the primary auth token into the admin console shell for trusted launch surfaces. */\n adminConsolePrefillToken?: boolean;\n trustPrincipalHeader?: boolean;\n /** Enable adapter-based identity resolution from request headers */\n enableAdapters?: boolean;\n /** Custom adapter registry (defaults to built-in adapters) */\n adapterRegistry?: AdapterRegistry;\n /** Enable oai-mem-citation blocks in recall responses (issue #379). */\n citationsEnabled?: boolean;\n /** Auto-enable citations for Codex adapter connections (issue #379). */\n citationsAutoDetect?: boolean;\n /** Advertise legacy engram.* tool aliases on tools/list (issue #1427). Default true. */\n emitLegacyTools?: boolean;\n /** Optional authenticated admin dashboard/config controls supplied by the host server. */\n adminControls?: RemnicAdminControls;\n /**\n * Standalone readiness state. Defaults to ready so embedded hosts keep their\n * existing health behavior.\n */\n readiness?: () => AccessHttpReadinessState;\n /**\n * When set, every 401 response includes\n * `WWW-Authenticate: Bearer resource_metadata=\"<value>\"` so MCP clients\n * can discover the OAuth 2.0 protected-resource metadata document\n * (RFC 9728). Must be an absolute http(s) URL; constructor throws on\n * anything else. Unset → bare `Bearer`.\n */\n resourceMetadataUrl?: string;\n /**\n * Optional pre-auth request handler (e.g. OAuth facade mounted by\n * `@remnic/server`). Runs after the admin-console handler and BEFORE\n * bearer authorization. Return true if the request was fully handled\n * (response ended). `ctx.authorized` reports whether the request\n * carries a valid operator bearer token, so the handler can gate\n * operator-only endpoints without owning token validation.\n * Errors thrown by the handler flow into the existing error handling.\n */\n externalRequestHandler?: SupportPassportExternalRequestHandler;\n}\n\nexport interface EngramAccessHttpServerStatus {\n running: boolean;\n host: string;\n port: number;\n maxBodyBytes: number;\n}\n\nexport interface RemnicAdminHarnessStatus {\n id: string;\n label: string;\n detected: boolean;\n enabled: boolean;\n source?: string;\n detail?: string;\n}\n\nexport interface RemnicAdminModelOption {\n id: string;\n label: string;\n provider: string;\n detected: boolean;\n enabled: boolean;\n default?: boolean;\n source?: string;\n endpoint?: string;\n}\n\nexport interface RemnicAdminFeatureStatus {\n key: string;\n label: string;\n enabled: boolean;\n writable: boolean;\n restartRequired?: boolean;\n}\n\nexport interface RemnicAdminConfigStatus {\n path: string;\n exists: boolean;\n writable: boolean;\n restartRequired: boolean;\n values: Record<string, string | number | boolean | null>;\n}\n\nexport interface RemnicAdminDashboardStatus {\n config: RemnicAdminConfigStatus;\n harnesses: RemnicAdminHarnessStatus[];\n providers?: RemnicAdminHarnessStatus[];\n models: RemnicAdminModelOption[];\n features: RemnicAdminFeatureStatus[];\n}\n\nexport type RemnicAdminConfigPatch = Record<string, unknown>;\n\nexport interface RemnicAdminControls {\n status: () => Promise<RemnicAdminDashboardStatus>;\n update?: (patch: RemnicAdminConfigPatch) => Promise<RemnicAdminDashboardStatus>;\n}\n\nexport function resolveDefaultAdminConsolePublicDir(sourceUrl = import.meta.url): string {\n const thisDir = path.dirname(fileURLToPath(sourceUrl));\n const candidates = [\n path.resolve(thisDir, \"../../../admin-console/public\"),\n path.resolve(thisDir, \"../dist/admin-console/public\"),\n path.resolve(thisDir, \"./admin-console/public\"),\n path.resolve(thisDir, \"../../admin-console/public\"),\n ];\n return candidates.find((candidate) => existsSync(candidate)) ?? candidates[0];\n}\n\nconst defaultAdminConsolePublicDir = resolveDefaultAdminConsolePublicDir();\nconst correlationIdStore = new AsyncLocalStorage<string>();\nconst RELAY_ADMIN_CONSOLE_ASSETS = new Map<string, string>([\n [\"relay.css\", \"text/css; charset=utf-8\"],\n [\"relay-model.js\", \"application/javascript; charset=utf-8\"],\n [\"relay.js\", \"application/javascript; charset=utf-8\"],\n [\"replay.json\", \"application/json; charset=utf-8\"],\n]);\n\nconst TRUST_ZONE_RECORD_KINDS = [\"memory\", \"artifact\", \"state\", \"trajectory\", \"external\"] as const;\nconst TRUST_ZONE_SOURCE_CLASSES = [\"tool_output\", \"web_content\", \"subagent_trace\", \"system_memory\", \"user_input\", \"manual\"] as const;\n\nclass HttpError extends Error {\n readonly code: string;\n readonly details?: unknown;\n constructor(readonly status: number, message: string, code?: string, details?: unknown) {\n super(message);\n this.code = code ?? `http_${status}`;\n this.details = details;\n }\n}\n\nfunction hostToUrlAuthority(host: string): string {\n if (host.includes(\":\") && !host.startsWith(\"[\") && !host.endsWith(\"]\")) {\n return `[${host}]`;\n }\n return host;\n}\n\nfunction parseHttpServerPort(port: number | undefined): number {\n if (port === undefined) return 0;\n if (!Number.isInteger(port) || port < 0 || port > 65535) {\n throw new Error(\"access HTTP port must be an integer from 0 to 65535\");\n }\n return port;\n}\nfunction assertResourceMetadataUrl(value: string | undefined): string | undefined {\n if (value === undefined) return undefined;\n let parsed: URL;\n try {\n parsed = new URL(value);\n } catch {\n throw new Error(\n `access HTTP resourceMetadataUrl must be an absolute http(s) URL, got: ${value}`,\n );\n }\n if (parsed.protocol !== \"http:\" && parsed.protocol !== \"https:\") {\n throw new Error(\n `access HTTP resourceMetadataUrl must use http or https, got: ${parsed.protocol}`,\n );\n }\n return value;\n}\n\nfunction parseTrustZoneKindFilter(raw: string | null): TrustZoneRecordKind | undefined {\n if (raw === null) return undefined;\n if ((TRUST_ZONE_RECORD_KINDS as readonly string[]).includes(raw)) {\n return raw as TrustZoneRecordKind;\n }\n throw new HttpError(400, `kind must be one of ${TRUST_ZONE_RECORD_KINDS.join(\"|\")}`, \"invalid_kind_filter\");\n}\n\nfunction parseTrustZoneSourceClassFilter(raw: string | null): TrustZoneSourceClass | undefined {\n if (raw === null) return undefined;\n if ((TRUST_ZONE_SOURCE_CLASSES as readonly string[]).includes(raw)) {\n return raw as TrustZoneSourceClass;\n }\n throw new HttpError(400, `sourceClass must be one of ${TRUST_ZONE_SOURCE_CLASSES.join(\"|\")}`, \"invalid_source_class_filter\");\n}\n\nfunction parseTrustZoneFilter(raw: string | null): TrustZoneName | undefined {\n if (raw === null) return undefined;\n if (isTrustZoneName(raw)) {\n return raw;\n }\n throw new HttpError(400, \"zone must be one of quarantine|working|trusted\", \"invalid_zone_filter\");\n}\n\nfunction summarizeHttpRequest(req: IncomingMessage): string {\n const method = req.method ?? \"UNKNOWN\";\n try {\n const parsed = new URL(req.url ?? \"/\", \"http://localhost\");\n return `${method} ${parsed.pathname}`;\n } catch {\n return `${method} ${(req.url ?? \"/\").split(\"?\")[0]}`;\n }\n}\n\nfunction parseStrictIntegerQuery(\n raw: string | null,\n field: string,\n defaultValue: number,\n minValue: number,\n): number {\n if (raw === null) return defaultValue;\n if (!/^(?:0|[1-9]\\d*)$/.test(raw)) {\n throw new HttpError(400, `${field} must be an integer`, `invalid_${field}`);\n }\n const value = Number(raw);\n if (!Number.isInteger(value) || value < minValue) {\n throw new HttpError(400, `${field} must be an integer >= ${minValue}`, `invalid_${field}`);\n }\n return value;\n}\n\nfunction parseMemorySort(raw: string | null): \"updated_desc\" | \"updated_asc\" | \"created_desc\" | \"created_asc\" | undefined {\n if (raw === null) return undefined;\n if (\n raw === \"updated_desc\" ||\n raw === \"updated_asc\" ||\n raw === \"created_desc\" ||\n raw === \"created_asc\"\n ) {\n return raw;\n }\n throw new HttpError(400, \"sort must be one of updated_desc|updated_asc|created_desc|created_asc\", \"invalid_sort\");\n}\n\n/**\n * Decode a `:peerId` URL path segment, converting malformed percent-encoded\n * input (e.g., `%E0%A4%A`) into a 400 client error rather than letting\n * `URIError` bubble up as a 500 `internal_error`.\n */\nfunction decodePeerIdSegment(raw: string): string {\n try {\n return decodeURIComponent(raw);\n } catch {\n throw new EngramAccessInputError(\"peerId path segment is not valid percent-encoded input\");\n }\n}\n\nfunction decodeRelayMissionIdSegment(raw: string): string {\n try {\n return decodeURIComponent(raw);\n } catch {\n throw new EngramAccessInputError(\"missionId path segment is not valid percent-encoded input\");\n }\n}\n\nfunction rejectBlankRelayNamespace(value: string | null | undefined): void {\n if (value !== undefined && value !== null && value.trim().length === 0) {\n throw new EngramAccessInputError(\"Relay namespace must not be blank when provided\");\n }\n}\n\nfunction codingContextFromProjectTag(projectTag: string): {\n projectId: string;\n branch: string | null;\n rootPath: string;\n defaultBranch: string | null;\n} {\n const projectId = projectTagProjectId(projectTag);\n return {\n projectId,\n branch: null,\n rootPath: projectId,\n defaultBranch: null,\n };\n}\n\nexport class EngramAccessHttpServer extends ReviewDeckAccessHttpBase {\n protected readonly service: EngramAccessService;\n private readonly host: string;\n private readonly requestedPort: number;\n private readonly authToken?: string;\n private readonly authTokens: string[];\n private readonly authTokensGetter?: () => string[];\n private readonly authTokenEntriesGetter?: () => ReadonlyArray<{ token: string; connector?: string; capabilities?: TokenCapabilities }>;\n private readonly tokenPathPolicy?: (connector: string, pathname: string | undefined) => boolean;\n private readonly authenticatedPrincipal?: string;\n protected readonly maxBodyBytes: number;\n private readonly adminConsoleEnabled: boolean;\n protected readonly adminConsolePublicDir: string;\n private readonly adminConsolePrefillToken?: string;\n private readonly adminControls?: RemnicAdminControls;\n private readonly trustPrincipalHeader: boolean;\n private readonly adapterRegistry: AdapterRegistry | null;\n private readonly readiness: () => AccessHttpReadinessState;\n private readonly resourceMetadataUrl?: string;\n private readonly externalRequestHandler?: SupportPassportExternalRequestHandler;\n private readonly writeLimiter: WriteRateLimiter;\n private readonly mcpServer: EngramMcpServer;\n private server: Server | null = null;\n private boundPort = 0;\n /** Active SSE response objects for /engram/v1/graph/events. */\n private readonly sseClients = new Set<ServerResponse>();\n /** Throttle batch: pending SSE event batches per client. */\n private readonly sseBatchTimers = new Map<ServerResponse, ReturnType<typeof setTimeout>>();\n private readonly ssePendingBatches = new Map<ServerResponse, GraphEvent[]>();\n /**\n * Per-client cleanup callbacks: clear heartbeat interval, flush timer,\n * unsubscribe from bus, and end the response. Stored here so `stop()`\n * can invoke them even when the client hasn't disconnected yet\n * (Cursor review thread `access-http.ts:232`).\n */\n private readonly sseCleanupFns = new Set<() => void>();\n\n /**\n * Periodic chat-session TTL sweep handle (issue #1685 item 1 /\n * #1687 Thread 21). unref'd so it never blocks process exit\n * (rule 47); cleared in `stop()`.\n */\n private chatTtlTimer: NodeJS.Timeout | null = null;\n\n constructor(options: EngramAccessHttpServerOptions) {\n super();\n this.service = options.service;\n this.host = options.host?.trim() || \"127.0.0.1\";\n this.requestedPort = parseHttpServerPort(options.port);\n this.authToken = options.authToken?.trim() || undefined;\n this.authTokens = (options.authTokens ?? []).map((t) => t.trim()).filter(Boolean);\n this.authTokensGetter = options.authTokensGetter;\n this.authTokenEntriesGetter = options.authTokenEntriesGetter;\n this.tokenPathPolicy = options.tokenPathPolicy;\n this.authenticatedPrincipal = options.principal?.trim() || undefined;\n this.maxBodyBytes = Number.isFinite(options.maxBodyBytes)\n ? Math.max(1, Math.floor(options.maxBodyBytes ?? 131072))\n : 131072;\n this.writeLimiter = new WriteRateLimiter(\n options.writeRateLimitMaxRequests,\n options.writeRateLimitWindowMs,\n );\n this.adminConsoleEnabled = options.adminConsoleEnabled !== false;\n this.adminConsolePublicDir = options.adminConsolePublicDir ?? defaultAdminConsolePublicDir;\n this.adminConsolePrefillToken = options.adminConsolePrefillToken === true ? this.authToken : undefined;\n this.adminControls = options.adminControls;\n this.trustPrincipalHeader = options.trustPrincipalHeader === true;\n this.readiness = options.readiness ?? (() => ({ ready: true, warmupAttempts: 0 }));\n this.resourceMetadataUrl = assertResourceMetadataUrl(options.resourceMetadataUrl);\n this.externalRequestHandler = options.externalRequestHandler;\n this.adapterRegistry = options.enableAdapters !== false\n ? (options.adapterRegistry ?? new AdapterRegistry())\n : null;\n this.mcpServer = new EngramMcpServer(this.service, {\n principal: options.principal,\n citationsEnabled: options.citationsEnabled,\n citationsAutoDetect: options.citationsAutoDetect,\n emitLegacyTools: options.emitLegacyTools,\n codingDecisionVisible: this.service.decisionRecordSurfaceVisible,\n architectureCardVisible: this.service.architectureCardSurfaceVisible,\n codegraphVisible: this.service.codegraphSurfaceVisible,\n sessionDeltaVisible: this.service.sessionDeltaSurfaceVisible,\n chatVisible: this.service.configRef?.chat?.enabled === true,\n correctionVisible: this.service.correctionSurfaceVisible,\n });\n }\n\n async start(): Promise<EngramAccessHttpServerStatus> {\n if (!this.authToken && this.authTokens.length === 0 && !this.authTokensGetter && !this.authTokenEntriesGetter) {\n throw new Error(\"engram access HTTP requires authToken or authTokens\");\n }\n if (this.server) return this.status();\n\n const server = createServer((req, res) => {\n const correlationId = randomUUID();\n const abortController = new AbortController();\n const abortDisconnectedRequest = () => {\n if (!res.writableFinished && !abortController.signal.aborted) {\n abortController.abort(abortError(\"HTTP client disconnected\"));\n }\n };\n req.once(\"aborted\", abortDisconnectedRequest);\n res.once(\"close\", abortDisconnectedRequest);\n correlationIdStore.run(correlationId, () => {\n void this.handle(req, res, correlationId, abortController.signal).catch((err) => {\n if (isAbortError(err)) {\n if (!res.destroyed && !res.writableEnded) {\n res.end();\n }\n return;\n }\n log.debug(`engram access HTTP request failed [${correlationId}]: ${err}`);\n if (err instanceof HttpError) {\n const payload: Record<string, unknown> = { error: err.message, code: err.code };\n if (err.details) payload.details = err.details;\n this.respondJson(res, err.status, payload);\n return;\n }\n if (err instanceof EngramAccessInputError) {\n this.respondJson(res, 400, { error: err.message, code: \"input_error\" });\n return;\n }\n if (err instanceof EngramAccessForbiddenError) {\n this.respondJson(res, 403, { error: err.message, code: \"forbidden\" });\n return;\n }\n if (err instanceof CorrectionContractError) {\n this.respondJson(res, 400, { error: err.message, code: \"correction_contract_error\" });\n return;\n }\n if (err instanceof RelayMissionStoreError) {\n const status = err.code === \"idempotency_conflict\"\n ? 409\n : err.code === \"limit_exceeded\"\n ? 413\n : err.code === \"lock_unavailable\"\n ? 503\n : 500;\n this.respondJson(res, status, {\n error: status >= 500 ? \"relay_backend_unavailable\" : err.message,\n code: `relay_${err.code}`,\n });\n return;\n }\n if (res.headersSent) {\n res.destroy(err as Error);\n return;\n }\n log.error(\n `engram access HTTP internal error [${correlationId}] ${summarizeHttpRequest(req)}`,\n err,\n );\n this.respondJson(res, 500, { error: \"internal_error\", code: \"internal_error\" });\n }).finally(() => {\n req.off(\"aborted\", abortDisconnectedRequest);\n res.off(\"close\", abortDisconnectedRequest);\n });\n });\n });\n\n try {\n await new Promise<void>((resolve, reject) => {\n const onError = (err: Error) => {\n server.off(\"listening\", onListening);\n reject(err);\n };\n const onListening = () => {\n server.off(\"error\", onError);\n resolve();\n };\n server.once(\"error\", onError);\n server.once(\"listening\", onListening);\n server.listen(this.requestedPort, this.host);\n });\n } catch (err) {\n server.close();\n throw err;\n }\n\n this.server = server;\n const address = server.address();\n this.boundPort = typeof address === \"object\" && address ? address.port : this.requestedPort;\n\n // ── Chat session TTL sweep (issue #1685 item 1 / #1687 Thread 21) ──\n // Expire idle chat sessions so the JSONL store cannot grow unbounded.\n // A one-shot sweep runs on startup; a periodic re-sweep follows on an\n // unref'd 1-hour cadence (rule 47 — never blocks process exit). Both\n // are no-ops when chat is disabled (no TTL configured).\n this.scheduleChatSessionTtlSweep();\n\n return this.status();\n }\n\n async stop(): Promise<void> {\n if (!this.server) return;\n // Release the chat-session TTL sweep timer (issue #1685) alongside\n // the SSE cleanups below.\n if (this.chatTtlTimer) {\n clearInterval(this.chatTtlTimer);\n this.chatTtlTimer = null;\n }\n const server = this.server;\n this.server = null;\n this.boundPort = 0;\n // Invoke each SSE client's cleanup callback so heartbeat intervals,\n // batch timers, and graph-bus subscriptions are all released before the\n // HTTP server closes. Without this, long-running SSE connections leak\n // setInterval handles and EventEmitter listeners (Cursor review thread\n // `access-http.ts:232`).\n for (const cleanup of this.sseCleanupFns) {\n try { cleanup(); } catch { /* ignore */ }\n }\n this.sseCleanupFns.clear();\n // Belt-and-suspenders: clear any state not yet reached by cleanup fns.\n for (const [res, timer] of this.sseBatchTimers.entries()) {\n clearTimeout(timer);\n this.sseBatchTimers.delete(res);\n }\n this.ssePendingBatches.clear();\n for (const res of this.sseClients) {\n try { res.end(); } catch { /* ignore */ }\n }\n this.sseClients.clear();\n await new Promise<void>((resolve, reject) => {\n server.close((err) => (err ? reject(err) : resolve()));\n });\n }\n\n /**\n * Schedule the chat-session TTL sweep: one immediate pass plus a\n * recurring hourly pass (issue #1685 item 1 / #1687 Thread 21). Both\n * are skipped when chat is disabled. The recurring timer is unref'd\n * so it never keeps the event loop alive on its own (rule 47). The\n * sweep itself is best-effort — cleanup failures are swallowed inside\n * `cleanupExpiredChatSessions`.\n */\n private scheduleChatSessionTtlSweep(): void {\n // Clear any prior handle so a second start() without an intervening\n // stop() cannot leak a dangling setInterval (Kilo review thread).\n if (this.chatTtlTimer) {\n clearInterval(this.chatTtlTimer);\n this.chatTtlTimer = null;\n }\n const chat = this.service.configRef?.chat;\n if (!chat?.enabled) return;\n const ttlHours = typeof chat.sessionTtlHours === \"number\" && chat.sessionTtlHours > 0\n ? chat.sessionTtlHours\n : 72;\n // Startup sweep — fire and forget; failures never block the server.\n void cleanupExpiredChatSessions(this.service.memoryDir, ttlHours).catch(() => { /* best-effort */ });\n // Hourly re-sweep (unref'd — rule 47).\n const SWEEP_INTERVAL_MS = 60 * 60 * 1000;\n this.chatTtlTimer = setInterval(() => {\n void cleanupExpiredChatSessions(this.service.memoryDir, ttlHours).catch(() => { /* best-effort */ });\n }, SWEEP_INTERVAL_MS);\n this.chatTtlTimer.unref?.();\n }\n\n status(): EngramAccessHttpServerStatus {\n return {\n running: this.server !== null,\n host: this.host,\n port: this.boundPort,\n maxBodyBytes: this.maxBodyBytes,\n };\n }\n\n /**\n * Resolve the adapter identity for the incoming request.\n * Includes MCP clientInfo from the last initialize handshake if available.\n * Returns null if no adapter matches or adapters are disabled.\n */\n resolveAdapterIdentity(req: IncomingMessage): ResolvedIdentity | null {\n if (!this.adapterRegistry) return null;\n // Look up clientInfo for this specific MCP session to avoid cross-session leaks.\n // Non-MCP requests (no mcp-session-id header) get undefined clientInfo and\n // rely on HTTP headers for adapter matching.\n const sessionId = (() => {\n const raw = req.headers[\"mcp-session-id\"];\n return typeof raw === \"string\" ? raw.trim() : undefined;\n })();\n return this.adapterRegistry.resolve({\n headers: req.headers as Record<string, string | string[] | undefined>,\n clientInfo: this.mcpServer.getClientInfo(sessionId),\n });\n }\n\n /** Cache for per-request identity resolution (avoids double adapter resolution) */\n private identityCache = new WeakMap<IncomingMessage, { principal?: string; namespace?: string; sessionKey?: string }>();\n\n /** Resolve principal, namespace, and session key from request headers and adapter identity */\n private resolveRequestIdentity(req: IncomingMessage): { principal?: string; namespace?: string; sessionKey?: string } {\n const cached = this.identityCache.get(req);\n if (cached) return cached;\n let principal: string | undefined;\n let namespace: string | undefined;\n let sessionKey: string | undefined;\n\n // Explicit header override takes priority for principal\n if (this.trustPrincipalHeader) {\n const headerVal = req.headers[\"x-engram-principal\"];\n const raw = Array.isArray(headerVal) ? headerVal[0] : headerVal;\n if (typeof raw === \"string\") {\n const trimmed = raw.trim();\n if (trimmed.length > 0) {\n principal = trimmed;\n }\n }\n }\n\n if (!principal) {\n principal = this.authenticatedPrincipal;\n }\n\n // Try adapter-based identity resolution for namespace and, only when no\n // server principal is configured, an adapter-owned default principal.\n const adapterIdentity = this.resolveAdapterIdentity(req);\n if (adapterIdentity) {\n if (!principal) {\n principal = adapterIdentity.principal;\n }\n namespace = adapterIdentity.namespace;\n sessionKey = adapterIdentity.sessionKey;\n }\n\n const result = { principal, namespace, sessionKey };\n this.identityCache.set(req, result);\n return result;\n }\n\n protected resolveRequestPrincipal(req: IncomingMessage): string | undefined {\n return this.resolveRequestIdentity(req).principal;\n }\n\n /** Caller scope for wearables/meetings ops (issue #2123): request principal +\n * gated namespace + optional sessionKey, so reads/writes resolve to the caller\n * namespace instead of the machine default. */\n private wearablesScope(req: IncomingMessage, namespace?: string, sessionKey?: string): WearablesMeetingsScope {\n return { authenticatedPrincipal: this.resolveRequestPrincipal(req), namespace: this.resolveNamespace(req, namespace), ...(sessionKey ? { sessionKey } : {}) };\n }\n\n /** Resolve namespace: only use the explicit body value. Adapter-inferred namespace\n * is intentionally NOT used as a fallback for REST requests — omitting namespace\n * should default to the server's global namespace, not silently scope to an adapter. */\n protected resolveNamespace(_req: IncomingMessage, bodyNamespace?: string): string | undefined {\n const namespace = bodyNamespace || undefined;\n // Per-token namespace enforcement (issues #1837/#1850): every HTTP\n // namespace-scoped route routes through this helper so none can dodge the\n // allow-list by dropping the param. The check is delegated to the SINGLE\n // chokepoint (`enforceNamespaceAllowList`) shared with the MCP dispatch\n // and the id-loaded contradiction routes — one rule, every surface. The\n // effective namespace (explicit OR server default) must be a member; fail\n // closed. No-op for unrestricted tokens (no namespaces allow-list).\n enforceNamespaceAllowList(tokenCapabilityStore.getStore(), namespace, this.service.configRef?.defaultNamespace);\n return namespace;\n }\n\n /**\n * Resolve + enforce the `namespace` field carried in a POST request body,\n * returning a shallow-copied envelope with the gated namespace stamped on.\n * Used by the coding/correction POST routes that pass `body` straight to\n * `op.run`: the body `namespace` is a user-controlled field that MUST flow\n * through the same effective-namespace allow-list gate as the query-param\n * routes, otherwise a scoped bearer can scope its call to another tenant\n * by setting `body.namespace` (issue #1850 finding 2). Throws 403 for a\n * scoped token whose allow-list does not cover the effective namespace.\n *\n * A `namespace` that is neither a string nor `null` is REJECTED here rather\n * than coerced to `undefined`: silently reinterpreting it would default the\n * request to the principal's namespace set and answer 200, hiding the\n * caller's mistake behind a plausible result (AGENTS.md pattern 39). `null`\n * and an absent field keep their documented \"no explicit namespace\" meaning.\n */\n private gatedBodyNamespace(\n req: IncomingMessage,\n body: Record<string, unknown>,\n ): Record<string, unknown> {\n const requested = body.namespace;\n if (requested !== undefined && requested !== null && typeof requested !== \"string\") {\n throw new EngramAccessInputError(\n `namespace must be a string or null (got: ${typeof requested})`,\n );\n }\n // Trim BEFORE the allow-list gate: the operation schemas normalize\n // `namespace` with `.trim()`, so checking the raw value would 403 a\n // `\" team \"` that the MCP path accepts as `team` — the same envelope\n // succeeding or failing on harmless whitespace. The trimmed value is what\n // gets stamped, so the gate and the operation see one namespace.\n const trimmed = typeof requested === \"string\" ? requested.trim() : undefined;\n const namespace = this.resolveNamespace(req, trimmed || undefined);\n return { ...body, namespace };\n }\n\n /**\n * Resolve the recall disclosure depth from the request (issue #677 PR\n * 2/4). Explicit body value wins; otherwise we accept a\n * `?disclosure=...` query parameter so curl/browser tooling can use the\n * three-tier surface without rewriting JSON. Invalid query values\n * throw `EngramAccessInputError` (CLAUDE.md rule 51 — no silent\n * fallback). An absent body field AND an absent query param yields\n * `undefined`, which the service maps to `DEFAULT_RECALL_DISCLOSURE`.\n */\n private resolveRecallDisclosure(\n bodyDisclosure: RecallDisclosure | undefined,\n parsed: URL,\n ): RecallDisclosure | undefined {\n if (bodyDisclosure !== undefined) {\n return bodyDisclosure;\n }\n const queryDisclosure = parsed.searchParams.get(\"disclosure\");\n if (queryDisclosure === null) {\n return undefined;\n }\n if (!isRecallDisclosure(queryDisclosure)) {\n throw new EngramAccessInputError(\n `disclosure must be one of: chunk, section, raw (got: ${queryDisclosure})`,\n );\n }\n return queryDisclosure;\n }\n\n private async handle(\n req: IncomingMessage,\n res: ServerResponse,\n correlationId: string,\n abortSignal: AbortSignal,\n ): Promise<void> {\n const parsed = new URL(req.url ?? \"/\", `http://${hostToUrlAuthority(this.host)}`);\n const pathname = parsed.pathname;\n if (await this.handleSupportPassportUi(req, res, pathname)) return;\n\n if (this.adminConsoleEnabled && await this.handleAdminConsole(req, res, pathname)) return;\n\n if (req.method === \"GET\" && (pathname === \"/engram/v1/live\" || pathname === \"/engram/v1/health\")) {\n const { ready, warmupAttempts, lastError } = this.readiness();\n if (!ready) {\n this.respondJson(res, 503, {\n ok: false, ready: false, warmupAttempts, lastError: lastError ?? null, code: \"not_ready\",\n });\n return;\n }\n }\n\n if (await this.handleSupportPassportPublicRequest(req, res)) return;\n // Run any host-supplied pre-auth request handler after public UI assets and before the\n // operator bearer gate. The handler decides whether it has fully\n // owned the response (return true) or wants the request to fall\n // through to the normal pipeline. `ctx.authorized` is computed\n // here so the handler can implement operator-only endpoints\n // (e.g. /oauth/pending) without owning token validation.\n if (this.externalRequestHandler) {\n // Operator-only endpoints (OAuth pending/approve/deny) must only pass\n // for unrestricted tokens — a scoped (least-privileged) token must NOT\n // reach operator surfaces (issue #1837).\n const tokenAuthorized = this.isAuthorized(req, pathname);\n const capabilities = this.resolveTokenCapabilities(req, pathname);\n const authorized = tokenAuthorized && !isCapabilityRestricted(capabilities);\n if (await this.externalRequestHandler(req, res, {\n authorized,\n tokenAuthorized,\n })) return;\n }\n\n if (!this.isAuthorized(req, pathname)) {\n const body = JSON.stringify({ error: \"unauthorized\", code: \"unauthorized\" });\n res.writeHead(401, {\n \"content-type\": \"application/json; charset=utf-8\",\n \"www-authenticate\": this.bearerChallenge(),\n \"x-request-id\": correlationId,\n });\n res.end(body);\n return;\n }\n\n // Bind the presenting token's capabilities to this request's async\n // context via run() (NOT enterWith). enterWith mutates the CURRENT async\n // resource and does NOT reliably isolate the store across the awaits and\n // concurrent requests that fill this handler — the store could read\n // undefined mid-handler, and undefined caps == unrestricted/legacy,\n // which would SILENTLY FAIL OPEN, bypassing the op + namespace gates.\n // run() establishes a fresh, request-private async scope for the WHOLE\n // dispatch so concurrent requests never bleed capabilities and the store\n // stays bound across every await (issue #1850 round 7).\n const caps = this.resolveTokenCapabilities(req, pathname);\n await tokenCapabilityStore.run(caps, async () => {\n await this.dispatchAuthorizedRequest(req, res, parsed, pathname, correlationId, abortSignal);\n });\n }\n\n private async dispatchAuthorizedRequest(\n req: IncomingMessage,\n res: ServerResponse,\n parsed: URL,\n pathname: string,\n correlationId: string,\n abortSignal: AbortSignal,\n ): Promise<void> {\n // Method-conformance for the streamable-HTTP MCP endpoint:\n // GET/DELETE on /mcp must return 405 + Allow: POST instead of\n // silently falling through to the generic 404. POST continues\n // to the normal handler below.\n if (pathname === \"/mcp\" && (req.method === \"GET\" || req.method === \"DELETE\")) {\n const body = JSON.stringify({ error: \"method_not_allowed\", code: \"method_not_allowed\" });\n res.writeHead(405, {\n \"content-type\": \"application/json; charset=utf-8\",\n allow: \"POST\",\n \"x-request-id\": correlationId,\n });\n res.end(body);\n return;\n }\n\n if (req.method === \"POST\" && pathname === \"/mcp\") return this.handleMcpRequest(req, res, abortSignal);\n\n if (await this.handleSupportPassportOwnerRequest(req, res, pathname, parsed.search.length > 0, abortSignal)) return;\n if (await this.handleReviewDeckRequest(req, res, pathname, abortSignal)) return;\n\n if (req.method === \"GET\" && pathname === \"/engram/v1/live\") return this.respondJson(res, 200, { ok: true, ready: true });\n if (req.method === \"GET\" && pathname === \"/engram/v1/health\") {\n const { degraded, warmupAttempts, lastError } = this.readiness();\n const health = await this.service.health();\n this.respondJson(res, 200, degraded !== true ? health : {\n ...health, degraded: true, warmupAttempts, lastError: lastError ?? null,\n });\n return;\n }\n if (req.method === \"GET\" && pathname === \"/engram/v1/capabilities\") return respondAccessCapabilitiesHttp(res);\n if (req.method === \"GET\" && pathname === \"/engram/v1/authorization\") {\n res.setHeader(\"cache-control\", \"no-store\");\n const probe = probeOperationAuthorization(tokenCapabilityStore.getStore(), parsed.searchParams.getAll(\"op\"));\n for (const namespace of authorizationProbeNamespaces(probe.operations, parsed.searchParams.get(\"namespace\") ?? undefined))\n this.resolveNamespace(req, namespace);\n if (authorizationProbeRequiresPrincipalNamespace(probe.operations))\n await this.enforceSupportPassportAuthorizationProbe(req);\n this.respondJson(res, 200, probe);\n return;\n }\n\n if (req.method === \"GET\" && pathname === \"/engram/v1/adapters\") {\n this.enforceTokenOp(\"adapters_status\"); // boundary dispatch (issue #1850)\n const identity = this.resolveAdapterIdentity(req);\n this.respondJson(res, 200, {\n adaptersEnabled: this.adapterRegistry !== null,\n registered: this.adapterRegistry?.list() ?? [],\n resolved: identity,\n });\n return;\n }\n\n if (\n req.method === \"GET\" &&\n (pathname === \"/engram/v1/admin/dashboard\" || pathname === \"/remnic/v1/admin/dashboard\")\n ) {\n this.requireOperatorToken();\n if (!this.adminControls) {\n this.respondJson(res, 404, { error: \"admin_controls_unavailable\", code: \"admin_controls_unavailable\" });\n return;\n }\n this.respondJson(res, 200, await this.adminControls.status());\n return;\n }\n\n if (\n req.method === \"PATCH\" &&\n (pathname === \"/engram/v1/admin/config\" || pathname === \"/remnic/v1/admin/config\")\n ) {\n this.requireOperatorToken();\n if (!this.adminControls?.update) {\n this.respondJson(res, 404, { error: \"admin_controls_unavailable\", code: \"admin_controls_unavailable\" });\n return;\n }\n try {\n this.respondJson(res, 200, await this.adminControls.update(await this.readJsonBody(req)));\n } catch (error) {\n throw new HttpError(\n 400,\n error instanceof Error ? error.message : \"invalid_admin_config_patch\",\n \"invalid_admin_config_patch\",\n );\n }\n return;\n }\n if (\n req.method === \"POST\" &&\n (pathname === \"/engram/v1/external-wikis/search\" ||\n pathname === \"/remnic/v1/external-wikis/search\")\n ) {\n this.enforceTokenOp(\"external_wiki_search\");\n const operation = getOperation(\"external_wiki_search\");\n if (!operation) throw new EngramAccessInputError(\"external_wiki_search operation is not registered\");\n const output = await operation.run(await this.readJsonBody(req), { service: this.service });\n if (!output || typeof output !== \"object\" || !(\"result\" in output)) {\n throw new Error(\"external_wiki_search returned an invalid operation result\");\n }\n this.respondJson(res, 200, output.result);\n return;\n }\n if (\n req.method === \"POST\" &&\n (pathname === \"/engram/v1/memories/search\" ||\n pathname === \"/remnic/v1/memories/search\")\n ) {\n // Semantic memory search over HTTP. `GET /engram/v1/memories` is a\n // substring browse; this is the QMD-backed ranked search the MCP\n // `memory_search` tool already exposes, reachable by HTTP-only clients.\n this.enforceTokenOp(\"memory_search\"); // boundary dispatch (issue #1525)\n const operation = getOperation(\"memory_search\");\n if (!operation) {\n throw new EngramAccessInputError(\n \"access-boundary: operation not registered: memory_search\",\n );\n }\n // The body `namespace` is user-controlled, so it must pass the same\n // effective-namespace allow-list gate as every other namespace-scoped\n // route (issue #1850 finding 2); the authenticated principal — never a\n // client-supplied value — then scopes the readable namespace fan-out.\n const body = this.gatedBodyNamespace(req, await this.readJsonBody(req));\n // memory_search is a FAN-OUT: an absent namespace searches everything\n // the principal can read. A namespace-scoped bearer may read fewer\n // namespaces than its principal, so leaving it absent would return\n // results the token was never authorized for. The allow-list gate above\n // already proved the server default is permitted for such a token, so\n // binding the effective namespace explicitly is both safe and closed.\n if (body.namespace === undefined && tokenCapabilityStore.getStore()?.namespaces !== undefined) {\n body.namespace = this.service.configRef?.defaultNamespace ?? \"\";\n }\n const output = (await operation.run(body, {\n service: this.service,\n authenticatedPrincipal: this.resolveRequestPrincipal(req),\n })) as { result: unknown };\n this.respondJson(res, 200, output.result);\n return;\n }\n\n if (req.method === \"POST\" && pathname === \"/engram/v1/recall\") {\n this.enforceTokenOp(\"recall\"); // boundary dispatch (issue #1525)\n const body = await this.readValidatedBody(req, \"recall\");\n // `codingContext` presence (null = explicit clear vs absent = untouched)\n // is preserved by spreading the parsed body into the boundary envelope.\n // Disclosure resolution (issue #677 PR 2/4): accept the value from\n // the validated body OR the `?disclosure=` query parameter, with\n // the body taking precedence so an explicit JSON payload is never\n // silently overridden by a stale URL. CLAUDE.md rule 51: invalid\n // query-param values throw, never fall back silently.\n const disclosure = this.resolveRecallDisclosure(body.disclosure, parsed);\n // Issue #680 — historical recall pin (`asOf`). Body field wins\n // over `?as_of=` query param. Empty query is rejected only when\n // the body didn't supply a valid pin (codex P2 + cursor Medium).\n const asOfQueryRaw = parsed.searchParams.get(\"as_of\");\n const bodyHasAsOf =\n typeof body.asOf === \"string\" && body.asOf.length > 0;\n if (\n !bodyHasAsOf &&\n asOfQueryRaw !== null &&\n asOfQueryRaw.length === 0\n ) {\n throw new EngramAccessInputError(\n \"as_of must be a non-empty timestamp (got empty value)\",\n );\n }\n const asOf =\n body.asOf ??\n (asOfQueryRaw !== null && asOfQueryRaw.length > 0\n ? asOfQueryRaw\n : undefined);\n // Tag filter (issue #689). Body presence wins over query params\n // — explicit `tags: []` in body clears the filter even with\n // stale `?tag=` URLs.\n const bodyHasTagsField =\n body !== null &&\n typeof body === \"object\" &&\n \"tags\" in (body as Record<string, unknown>);\n const bodyTagsValue = bodyHasTagsField\n ? (body as { tags?: unknown }).tags\n : undefined;\n const bodyTags = Array.isArray(bodyTagsValue)\n ? (bodyTagsValue as string[])\n : undefined;\n const queryTags = parsed.searchParams.getAll(\"tag\");\n const tags = bodyHasTagsField\n ? bodyTags\n : queryTags.length > 0\n ? queryTags\n : undefined;\n const bodyTagMatch = (body as { tagMatch?: unknown }).tagMatch;\n let tagMatch: \"any\" | \"all\" | undefined;\n if (bodyTagMatch !== undefined) {\n if (bodyTagMatch === \"any\" || bodyTagMatch === \"all\") {\n tagMatch = bodyTagMatch;\n }\n } else {\n const queryTagMatch = parsed.searchParams.get(\"tag_match\");\n if (queryTagMatch !== null) {\n if (queryTagMatch !== \"any\" && queryTagMatch !== \"all\") {\n throw new EngramAccessInputError(\n `tag_match must be one of: any, all (got: ${queryTagMatch})`,\n );\n }\n tagMatch = queryTagMatch;\n }\n }\n // Issue #681 — `?include_low_confidence=true|false` mirrors the CLI\n // `--include-low-confidence` flag. Body field wins so a JSON payload can\n // explicitly clear a stale query parameter.\n const bodyIncludeLowConfidence =\n (body as { includeLowConfidence?: unknown }).includeLowConfidence;\n const queryIncludeLowConfidence = parsed.searchParams.get(\"include_low_confidence\");\n if (\n bodyIncludeLowConfidence === undefined &&\n queryIncludeLowConfidence !== null &&\n queryIncludeLowConfidence !== \"true\" &&\n queryIncludeLowConfidence !== \"false\"\n ) {\n throw new EngramAccessInputError(\n `include_low_confidence must be one of: true, false (got: ${queryIncludeLowConfidence})`,\n );\n }\n const includeLowConfidence =\n bodyIncludeLowConfidence === true ||\n (bodyIncludeLowConfidence === undefined &&\n queryIncludeLowConfidence === \"true\");\n // Boundary dispatch (issue #2482): same registry path as memory_store —\n // the canonical recallRequestSchema re-validates the envelope the\n // transport assembled (resolved namespace + query-param overlays).\n const op = getOperation(\"recall\");\n if (!op) {\n throw new EngramAccessInputError(\"access-boundary: operation not registered: recall\");\n }\n const output = (await op.run(\n {\n ...body,\n namespace: this.resolveNamespace(req, body.namespace),\n ...(disclosure !== undefined ? { disclosure } : {}),\n ...(asOf !== undefined ? { asOf } : {}),\n ...(tags !== undefined ? { tags } : {}),\n ...(tagMatch !== undefined ? { tagMatch } : {}),\n ...(includeLowConfidence ? { includeLowConfidence: true } : {}),\n },\n {\n service: this.service,\n authenticatedPrincipal: this.resolveRequestPrincipal(req),\n sourceConnector: this.resolveConnector(req),\n ...(abortSignal ? { abortSignal } : {}),\n },\n )) as { result: EngramAccessRecallResponse };\n this.respondJson(res, 200, output.result);\n return;\n }\n\n if (req.method === \"POST\" && pathname === \"/engram/v1/coding-context\") {\n this.enforceTokenOp(\"set_coding_context\"); // boundary dispatch (issue #1525)\n const body = await this.readValidatedBody(req, \"setCodingContext\");\n const codingContext =\n body.codingContext !== undefined\n ? body.codingContext\n : typeof body.projectTag === \"string\"\n ? codingContextFromProjectTag(body.projectTag)\n : (() => {\n throw new EngramAccessInputError(\"codingContext or projectTag is required\");\n })();\n this.service.setCodingContext({\n sessionKey: body.sessionKey,\n codingContext,\n });\n this.respondJson(res, 200, { ok: true });\n return;\n }\n\n if (\n req.method === \"POST\" &&\n (pathname === \"/engram/v1/capsules/export\" || pathname === \"/remnic/v1/capsules/export\")\n ) {\n this.enforceTokenOp(\"capsule_export\"); // boundary dispatch (issue #1525)\n const body = await this.readValidatedBody(req, \"capsuleExport\");\n this.ensureWriteRateLimitAvailable(req);\n const result = await this.service.capsuleExport({\n name: body.name,\n namespace: this.resolveNamespace(req, body.namespace),\n principal: this.resolveRequestPrincipal(req),\n since: body.since,\n includeKinds: body.includeKinds,\n peerIds: body.peerIds,\n includeTranscripts: body.includeTranscripts,\n encrypt: body.encrypt,\n });\n this.recordWriteRateLimitHit(req);\n this.respondJson(res, 200, result);\n return;\n }\n\n if (\n req.method === \"POST\" &&\n (pathname === \"/engram/v1/capsules/import\" || pathname === \"/remnic/v1/capsules/import\")\n ) {\n this.enforceTokenOp(\"capsule_import\"); // boundary dispatch (issue #1525)\n const body = await this.readValidatedBody(req, \"capsuleImport\");\n this.ensureWriteRateLimitAvailable(req);\n const result = await this.service.capsuleImport({\n archivePath: expandTildePath(body.archivePath),\n namespace: this.resolveNamespace(req, body.namespace),\n principal: this.resolveRequestPrincipal(req),\n mode: body.mode,\n passphrase: body.passphrase,\n });\n this.recordWriteRateLimitHit(req);\n this.respondJson(res, 200, result);\n return;\n }\n\n if (\n req.method === \"GET\" &&\n (pathname === \"/engram/v1/offline-sync/capabilities\" ||\n pathname === \"/remnic/v1/offline-sync/capabilities\")\n ) {\n this.enforceTokenOp(\"offline_sync_snapshot\");\n this.respondJson(res, 200, {\n version: 1,\n convergenceFinalization: true,\n manifestStream: true,\n });\n return;\n }\n\n if (\n req.method === \"GET\" &&\n (pathname === \"/engram/v1/offline-sync/snapshot\" || pathname === \"/remnic/v1/offline-sync/snapshot\")\n ) {\n this.enforceTokenOp(\"offline_sync_snapshot\"); // boundary dispatch (issue #1525)\n const includeTranscriptsRaw = parsed.searchParams.get(\"include_transcripts\");\n const includeContentRaw = parsed.searchParams.get(\"content\");\n if (\n includeTranscriptsRaw !== null &&\n includeTranscriptsRaw !== \"true\" &&\n includeTranscriptsRaw !== \"false\"\n ) {\n throw new EngramAccessInputError(\n `include_transcripts must be one of: true, false (got: ${includeTranscriptsRaw})`,\n );\n }\n if (\n includeContentRaw !== null &&\n includeContentRaw !== \"true\" &&\n includeContentRaw !== \"false\"\n ) {\n throw new EngramAccessInputError(\n `content must be one of: true, false (got: ${includeContentRaw})`,\n );\n }\n const namespaceParam = parsed.searchParams.get(\"namespace\");\n const result = await this.service.offlineSyncSnapshot({\n namespace: this.resolveNamespace(\n req,\n namespaceParam && namespaceParam.length > 0 ? namespaceParam : undefined,\n ),\n principal: this.resolveRequestPrincipal(req),\n includeTranscripts: includeTranscriptsRaw !== \"false\",\n includeContent: includeContentRaw !== \"false\",\n });\n this.respondJson(res, 200, result);\n return;\n }\n\n if (\n req.method === \"GET\" &&\n (pathname === \"/engram/v1/offline-sync/snapshot-stream\" ||\n pathname === \"/remnic/v1/offline-sync/snapshot-stream\")\n ) {\n this.enforceTokenOp(\"offline_sync_snapshot_stream\"); // boundary dispatch (issue #1525)\n const includeTranscriptsRaw = parsed.searchParams.get(\"include_transcripts\");\n const includeContentRaw = parsed.searchParams.get(\"content\");\n if (\n includeTranscriptsRaw !== null &&\n includeTranscriptsRaw !== \"true\" &&\n includeTranscriptsRaw !== \"false\"\n ) {\n throw new EngramAccessInputError(\n `include_transcripts must be one of: true, false (got: ${includeTranscriptsRaw})`,\n );\n }\n if (\n includeContentRaw !== null &&\n includeContentRaw !== \"false\"\n ) {\n throw new EngramAccessInputError(\"snapshot-stream content must be false\");\n }\n const namespaceParam = parsed.searchParams.get(\"namespace\");\n const result = await this.service.offlineSyncSnapshotStream({\n namespace: this.resolveNamespace(\n req,\n namespaceParam && namespaceParam.length > 0 ? namespaceParam : undefined,\n ),\n principal: this.resolveRequestPrincipal(req),\n includeTranscripts: includeTranscriptsRaw !== \"false\",\n includeContent: false,\n signal: this.createRequestAbortSignal(req, res),\n });\n await respondOfflineSnapshotStream(res, result, correlationIdStore.getStore());\n return;\n }\n if (\n req.method === \"GET\" &&\n (pathname === \"/engram/v1/offline-sync/manifest-stream\" ||\n pathname === \"/remnic/v1/offline-sync/manifest-stream\")\n ) {\n this.enforceTokenOp(\"offline_sync_snapshot_stream\");\n const includeTranscriptsRaw = parsed.searchParams.get(\"include_transcripts\");\n const includeContentRaw = parsed.searchParams.get(\"content\");\n if (\n includeTranscriptsRaw !== null &&\n includeTranscriptsRaw !== \"true\" &&\n includeTranscriptsRaw !== \"false\"\n ) {\n throw new EngramAccessInputError(\n `include_transcripts must be one of: true, false (got: ${includeTranscriptsRaw})`,\n );\n }\n if (includeContentRaw !== null && includeContentRaw !== \"false\") {\n throw new EngramAccessInputError(\"manifest-stream content must be false\");\n }\n const namespaceParam = parsed.searchParams.get(\"namespace\");\n const result = await this.service.offlineSyncManifestStream({\n namespace: this.resolveNamespace(\n req,\n namespaceParam && namespaceParam.length > 0 ? namespaceParam : undefined,\n ),\n principal: this.resolveRequestPrincipal(req),\n includeTranscripts: includeTranscriptsRaw !== \"false\",\n signal: this.createRequestAbortSignal(req, res),\n });\n await respondOfflineManifestStream(res, result, correlationIdStore.getStore());\n return;\n }\n\n\n if (\n req.method === \"POST\" &&\n (pathname === \"/engram/v1/offline-sync/snapshot\" || pathname === \"/remnic/v1/offline-sync/snapshot\")\n ) {\n this.enforceTokenOp(\"offline_sync_snapshot\"); // boundary dispatch (issue #1525)\n const body = await this.readValidatedBody(\n req,\n \"offlineSyncSnapshot\",\n OFFLINE_SYNC_SNAPSHOT_BASE_MAX_BODY_BYTES,\n );\n const result = await this.service.offlineSyncSnapshot({\n namespace: this.resolveNamespace(req, body.namespace),\n principal: this.resolveRequestPrincipal(req),\n includeTranscripts: body.includeTranscripts,\n includeContent: body.includeContent,\n baseFiles: body.baseFiles,\n ...(body.baseCapturedAt ? { baseCapturedAt: new Date(body.baseCapturedAt) } : {}),\n signal: this.createRequestAbortSignal(req, res),\n });\n this.respondJson(res, 200, result);\n return;\n }\n\n if (\n req.method === \"POST\" &&\n (pathname === \"/engram/v1/offline-sync/files\" || pathname === \"/remnic/v1/offline-sync/files\")\n ) {\n this.enforceTokenOp(\"offline_sync_files\"); // boundary dispatch (issue #1525)\n const body = await this.readValidatedBody(req, \"offlineSyncFiles\");\n const result = await this.service.offlineSyncFiles({\n namespace: this.resolveNamespace(req, body.namespace),\n principal: this.resolveRequestPrincipal(req),\n includeTranscripts: body.includeTranscripts,\n paths: body.paths,\n });\n this.respondJson(res, 200, result);\n return;\n }\n\n if (\n req.method === \"POST\" &&\n (\n pathname === \"/engram/v1/offline-sync/file-content\" ||\n pathname === \"/remnic/v1/offline-sync/file-content\"\n )\n ) {\n this.enforceTokenOp(\"offline_sync_file_content\"); // boundary dispatch (issue #1525)\n const body = await this.readValidatedBody(req, \"offlineSyncFileContent\");\n const result = await this.service.offlineSyncFileContent({\n namespace: this.resolveNamespace(req, body.namespace),\n principal: this.resolveRequestPrincipal(req),\n includeTranscripts: body.includeTranscripts,\n path: body.path,\n offset: body.offset,\n length: body.length,\n });\n this.respondBinary(res, 200, result.content, {\n \"x-remnic-namespace\": encodeURIComponent(result.namespace),\n \"x-remnic-file-path\": encodeURIComponent(result.path),\n \"x-remnic-file-bytes\": String(result.bytes),\n \"x-remnic-file-mtime-ms\": String(result.mtimeMs),\n \"x-remnic-chunk-offset\": String(result.offset),\n \"x-remnic-chunk-bytes\": String(result.chunkBytes),\n ...(result.sha256 ? { \"x-remnic-file-sha256\": result.sha256 } : {}),\n });\n return;\n }\n\n if (\n req.method === \"POST\" &&\n (\n pathname === \"/engram/v1/offline-sync/apply-file-content\" ||\n pathname === \"/remnic/v1/offline-sync/apply-file-content\"\n )\n ) {\n this.enforceTokenOp(\"offline_sync_apply_file_content\"); // boundary dispatch (issue #1525)\n const namespaceParam = parsed.searchParams.get(\"namespace\");\n const bytes = this.readRequiredIntegerHeader(req, \"x-remnic-file-bytes\");\n const offset = this.readOptionalIntegerHeader(req, \"x-remnic-chunk-offset\") ?? 0;\n const content = await this.readBinaryBody(req, OFFLINE_SYNC_FILE_CONTENT_MAX_CHUNK_BYTES);\n const result = await this.service.offlineSyncApplyFileContent({\n namespace: this.resolveNamespace(\n req,\n namespaceParam && namespaceParam.length > 0 ? namespaceParam : undefined,\n ),\n principal: this.resolveRequestPrincipal(req),\n includeTranscripts: this.parseOptionalBooleanHeader(\n req,\n \"x-remnic-include-transcripts\",\n true,\n ),\n sourceId: this.readRequiredDecodedHeader(req, \"x-remnic-source-id\"),\n path: this.readRequiredDecodedHeader(req, \"x-remnic-file-path\"),\n sha256: this.readRequiredHeader(req, \"x-remnic-file-sha256\"),\n bytes,\n mtimeMs: this.readRequiredNumberHeader(req, \"x-remnic-file-mtime-ms\"),\n offset,\n baseSha256: this.readOptionalHeader(req, \"x-remnic-base-sha256\"),\n content,\n });\n this.respondJson(res, 200, result);\n return;\n }\n\n\n if (\n req.method === \"POST\" &&\n (\n pathname === \"/engram/v1/offline-sync/convergence-complete\" ||\n pathname === \"/remnic/v1/offline-sync/convergence-complete\"\n )\n ) {\n void getOperation(\"offline_sync_apply_file_content\");\n this.enforceTokenAnyOf([\"offline_sync_apply_file_content\", \"offline_sync_apply\"]);\n const namespaceParams = parsed.searchParams.getAll(\"namespace\").filter(Boolean);\n const requestedNamespaces: Array<string | undefined> =\n namespaceParams.length > 0 ? namespaceParams : [undefined];\n const namespaces = requestedNamespaces\n .map((namespace) => this.resolveNamespace(req, namespace))\n .filter((namespace): namespace is string => namespace !== undefined);\n this.ensureWriteRateLimitAvailable(req);\n const result = await this.service.offlineSyncFinalizeConvergence({\n ...(namespaces.length > 0 ? { namespaces } : {}),\n principal: this.resolveRequestPrincipal(req),\n sourceId: this.readRequiredDecodedHeader(req, \"x-remnic-source-id\"),\n });\n this.recordWriteRateLimitHit(req);\n this.respondJson(res, 200, result);\n return;\n }\n\n if (\n req.method === \"POST\" &&\n (pathname === \"/engram/v1/offline-sync/apply\" || pathname === \"/remnic/v1/offline-sync/apply\")\n ) {\n this.enforceTokenOp(\"offline_sync_apply\"); // boundary dispatch (issue #1525)\n const body = await this.readValidatedBody(req, \"offlineSyncApply\", OFFLINE_SYNC_APPLY_MAX_BODY_BYTES);\n const result = await this.service.offlineSyncApply({\n namespace: this.resolveNamespace(req, body.namespace),\n principal: this.resolveRequestPrincipal(req),\n changeset: body.changeset,\n returnCurrentFiles: body.returnCurrentFiles,\n });\n this.respondJson(res, 200, result);\n return;\n }\n\n if (req.method === \"POST\" && pathname === \"/engram/v1/recall/explain\") {\n this.enforceTokenOp(\"recall_explain\"); // boundary dispatch (issue #1525)\n const body = await this.readValidatedBody(req, \"recallExplain\");\n const response = await this.service.recallExplain({\n sessionKey: body.sessionKey,\n namespace: this.resolveNamespace(req, body.namespace),\n authenticatedPrincipal: this.resolveRequestPrincipal(req),\n });\n this.respondJson(res, 200, response);\n return;\n }\n\n if (\n req.method === \"POST\" &&\n (pathname === \"/engram/v1/action-confidence\" || pathname === \"/remnic/v1/action-confidence\")\n ) {\n this.enforceTokenOp(\"action_confidence\"); // boundary dispatch (issue #1525)\n const body = await this.readValidatedBody(req, \"actionConfidence\");\n this.respondJson(res, 200, await this.service.actionConfidence(body));\n return;\n }\n\n if (req.method === \"GET\" && pathname === \"/engram/v1/recall/tier-explain\") {\n this.enforceTokenOp(\"recall_tier_explain\"); // boundary dispatch (issue #1525)\n const sessionParam = parsed.searchParams.get(\"session\");\n const sessionKey = sessionParam && sessionParam.length > 0 ? sessionParam : undefined;\n const namespaceParam = parsed.searchParams.get(\"namespace\");\n const namespace = this.resolveNamespace(\n req,\n namespaceParam && namespaceParam.length > 0 ? namespaceParam : undefined,\n );\n const payload = await this.service.recallTierExplain(sessionKey, namespace, this.resolveRequestPrincipal(req));\n this.respondJson(res, 200, payload);\n return;\n }\n\n // Recall X-ray (issue #570 PR 4): unified per-result attribution\n // snapshot. Requires bearer auth (same as every other endpoint\n // here) and enforces namespace scope before the recall fires\n // (CLAUDE.md rule 42). Query comes from the `q` search param so\n // GET stays cacheable; `namespace` / `session` / `budget` are\n // optional.\n if (req.method === \"GET\" && pathname === \"/engram/v1/recall/xray\") {\n this.enforceTokenOp(\"recall_xray\"); // boundary dispatch (issue #1525)\n const queryParam = parsed.searchParams.get(\"q\");\n if (!queryParam || queryParam.trim().length === 0) {\n this.respondJson(res, 400, {\n error: \"missing_query\",\n code: \"missing_query\",\n message: \"q search parameter is required and must be non-empty\",\n });\n return;\n }\n const sessionParam = parsed.searchParams.get(\"session\");\n const sessionKey = sessionParam && sessionParam.length > 0\n ? sessionParam\n : undefined;\n const namespaceParam = parsed.searchParams.get(\"namespace\");\n const namespace = this.resolveNamespace(\n req,\n namespaceParam && namespaceParam.length > 0\n ? namespaceParam\n : undefined,\n );\n const budgetParam = parsed.searchParams.get(\"budget\");\n // Reject invalid `budget` with 400 rather than silently\n // defaulting (CLAUDE.md rules 14 + 51).\n let budget: number | undefined;\n if (budgetParam !== null && budgetParam !== \"\") {\n const parsedBudget = Number(budgetParam);\n if (\n !Number.isFinite(parsedBudget)\n || parsedBudget <= 0\n || !Number.isInteger(parsedBudget)\n ) {\n this.respondJson(res, 400, {\n error: \"invalid_budget\",\n code: \"invalid_budget\",\n message:\n \"budget expects a positive integer\",\n });\n return;\n }\n budget = parsedBudget;\n }\n // Disclosure depth (issue #677 PR 3/4 telemetry plumbing). When\n // present, must match the chunk|section|raw allow-list; invalid\n // values surface as a 400 (CLAUDE.md rule 51 — no silent\n // fallback) rather than silently disabling the per-disclosure\n // summary table.\n const disclosureParam = parsed.searchParams.get(\"disclosure\");\n let disclosure: RecallDisclosure | undefined;\n if (disclosureParam !== null && disclosureParam.length > 0) {\n if (!isRecallDisclosure(disclosureParam)) {\n this.respondJson(res, 400, {\n error: \"invalid_disclosure\",\n code: \"invalid_disclosure\",\n message:\n \"disclosure must be one of: chunk, section, raw\",\n });\n return;\n }\n disclosure = disclosureParam;\n }\n // Only translate validation errors (empty query, bad budget)\n // into 400s. Backend faults (timeouts, storage errors,\n // unexpected orchestrator failures) must bubble to the global\n // `handle()` error handler so they return 500 and get logged\n // properly. `service.recallXray` prefixes its validation\n // errors with \"recallXray:\" so we key off that prefix rather\n // than catching everything.\n let payload: Awaited<ReturnType<typeof this.service.recallXray>>;\n try {\n payload = await this.service.recallXray({\n query: queryParam,\n sessionKey,\n namespace,\n budget,\n authenticatedPrincipal: this.resolveRequestPrincipal(req),\n sourceConnector: this.resolveConnector(req),\n ...(disclosure !== undefined ? { disclosure } : {}),\n });\n } catch (err) {\n // Only surface the message for the deliberately-prefixed recallXray\n // input-validation errors, and only when it is a real Error.message —\n // never String(err) of an arbitrary throw, which CodeQL flags as\n // stack-trace exposure (js/stack-trace-exposure). Validation errors are\n // always thrown as Error instances (see access-service.ts), so this is\n // behavior-preserving; anything else is a server-side fault and is\n // rethrown so the outer `handle()` catch returns 500 + logs it.\n if (err instanceof Error && err.message.startsWith(\"recallXray:\")) {\n this.respondJson(res, 400, {\n error: \"invalid_request\",\n code: \"invalid_request\",\n message: err.message,\n });\n return;\n }\n throw err;\n }\n this.respondJson(res, 200, payload);\n return;\n }\n\n // who_knows (issue #2057): deterministic entity expertise ranking.\n // Thin route — param parsing + 400 mapping live in who-knows.ts.\n if (req.method === \"GET\" && (pathname === \"/engram/v1/who-knows\" || pathname === \"/remnic/v1/who-knows\")) {\n this.enforceTokenOp(\"who_knows\");\n const outcome = await handleWhoKnowsHttpQuery({\n getParam: (name) => parsed.searchParams.get(name),\n resolveNamespace: (namespace) => this.resolveNamespace(req, namespace),\n principal: this.resolveRequestPrincipal(req),\n run: (request) => this.service.whoKnows(request),\n });\n this.respondJson(res, outcome.status, outcome.body);\n return;\n }\n\n if (req.method === \"GET\" && pathname === \"/engram/v1/namespace/writable\") {\n if (!getOperation(\"namespace_writable\")) throw new Error(\"namespace_writable operation is not registered\");\n this.respondJson(\n res,\n 200,\n await resolveQueryNamespaceWritablePreflight(\n tokenCapabilityStore.getStore(),\n parsed.searchParams,\n this.resolveRequestPrincipal(req),\n this.service.configRef.defaultNamespace,\n (request) => this.service.namespaceWritablePreflight(request),\n ),\n );\n return;\n }\n\n if (\n req.method === \"GET\" &&\n (pathname === \"/engram/v1/wearables/status\" || pathname === \"/remnic/v1/wearables/status\")\n ) {\n this.enforceTokenOp(\"wearables_status\"); // boundary dispatch (issue #1525)\n this.respondJson(res, 200, await this.service.wearablesStatus(this.wearablesScope(req, parsed.searchParams.get(\"namespace\") ?? undefined, parsed.searchParams.get(\"sessionKey\") ?? undefined)));\n return;\n }\n\n if (\n req.method === \"POST\" &&\n (pathname === \"/engram/v1/wearables/sync\" || pathname === \"/remnic/v1/wearables/sync\")\n ) {\n this.enforceTokenOp(\"wearables_sync\"); // boundary dispatch (issue #1525)\n const body = (await this.readJsonBody(req)) as Record<string, unknown>;\n const source = optionalQueryString(body.source, \"source\");\n const date = optionalQueryString(body.date, \"date\");\n let days: number | undefined;\n if (body.days !== undefined && body.days !== null) {\n if (\n typeof body.days !== \"number\" ||\n !Number.isInteger(body.days) ||\n body.days < 1\n ) {\n throw new EngramAccessInputError(\n `days must be a positive integer (got ${JSON.stringify(body.days)})`,\n );\n }\n days = body.days;\n }\n if (body.forceMemories !== undefined && typeof body.forceMemories !== \"boolean\") {\n throw new EngramAccessInputError(\n `forceMemories must be a boolean (got ${JSON.stringify(body.forceMemories)})`,\n );\n }\n try {\n const summaries = await this.service.wearablesSync({ source, date, days, forceMemories: body.forceMemories === true, ...this.wearablesScope(req, optionalQueryString(body.namespace, \"namespace\"), optionalQueryString(body.sessionKey, \"sessionKey\")) });\n this.respondJson(res, 200, { summaries });\n } catch (err) {\n if (this.respondWearablesError(res, err)) return;\n throw err;\n }\n return;\n }\n\n if (\n req.method === \"GET\" &&\n (pathname === \"/engram/v1/wearables/transcript\" || pathname === \"/remnic/v1/wearables/transcript\")\n ) {\n this.enforceTokenOp(\"transcript_day\"); // boundary dispatch (issue #1525)\n const date = parsed.searchParams.get(\"date\");\n if (!date || date.trim().length === 0) {\n throw new EngramAccessInputError(\n \"date query parameter is required (YYYY-MM-DD)\",\n );\n }\n const sourceParam = parsed.searchParams.get(\"source\");\n try {\n const transcripts = await this.service.wearablesTranscriptDay({ date, source: sourceParam && sourceParam.length > 0 ? sourceParam : undefined, ...this.wearablesScope(req, parsed.searchParams.get(\"namespace\") ?? undefined, parsed.searchParams.get(\"sessionKey\") ?? undefined) });\n this.respondJson(res, 200, { transcripts });\n } catch (err) {\n if (this.respondWearablesError(res, err)) return;\n throw err;\n }\n return;\n }\n\n if (\n req.method === \"GET\" &&\n (pathname === \"/engram/v1/wearables/transcripts/search\" ||\n pathname === \"/remnic/v1/wearables/transcripts/search\")\n ) {\n this.enforceTokenOp(\"transcript_search\"); // boundary dispatch (issue #1525)\n const queryParam = parsed.searchParams.get(\"q\");\n if (!queryParam || queryParam.trim().length === 0) {\n throw new EngramAccessInputError(\n \"q query parameter is required and must be non-empty\",\n );\n }\n try {\n const results = await this.service.wearablesTranscriptSearch({ query: queryParam, source: nonEmptyQueryParam(parsed.searchParams.get(\"source\")), from: nonEmptyQueryParam(parsed.searchParams.get(\"from\")), to: nonEmptyQueryParam(parsed.searchParams.get(\"to\")), limit: positiveIntQueryParam(parsed.searchParams.get(\"limit\"), \"limit\"), ...this.wearablesScope(req, parsed.searchParams.get(\"namespace\") ?? undefined, parsed.searchParams.get(\"sessionKey\") ?? undefined) });\n this.respondJson(res, 200, { results });\n } catch (err) {\n if (this.respondWearablesError(res, err)) return;\n throw err;\n }\n return;\n }\n\n if (\n req.method === \"GET\" &&\n (pathname === \"/engram/v1/wearables/memories\" || pathname === \"/remnic/v1/wearables/memories\")\n ) {\n this.enforceTokenOp(\"transcript_memories\"); // boundary dispatch (issue #1525)\n try {\n const memories = await this.service.wearablesTranscriptMemories({ source: nonEmptyQueryParam(parsed.searchParams.get(\"source\")), date: nonEmptyQueryParam(parsed.searchParams.get(\"date\")), limit: positiveIntQueryParam(parsed.searchParams.get(\"limit\"), \"limit\"), ...this.wearablesScope(req, parsed.searchParams.get(\"namespace\") ?? undefined, parsed.searchParams.get(\"sessionKey\") ?? undefined) });\n this.respondJson(res, 200, { memories });\n } catch (err) {\n if (this.respondWearablesError(res, err)) return;\n throw err;\n }\n return;\n }\n\n if (req.method === \"GET\" && (pathname === \"/engram/v1/meetings\" || pathname === \"/remnic/v1/meetings\")) {\n this.enforceTokenOp(\"meetings_list\"); await respondMeetingsList(res, this.respondJson.bind(this), this.service, nonEmptyQueryParam(parsed.searchParams.get(\"date\")), this.wearablesScope(req, parsed.searchParams.get(\"namespace\") ?? undefined, parsed.searchParams.get(\"sessionKey\") ?? undefined)); return; }\n if (req.method === \"POST\" && (pathname === \"/engram/v1/meetings/build\" || pathname === \"/remnic/v1/meetings/build\")) {\n this.enforceTokenOp(\"meetings_build\"); await respondMeetingsBuild(req, res, this.respondJson.bind(this), this.readJsonBody.bind(this), this.service, { enforceQuota: () => this.ensureWriteRateLimitAvailable(req), recordHit: () => this.recordWriteRateLimitHit(req) }, (ns, sk) => this.wearablesScope(req, ns, sk)); return; }\n const meetingGetEngram = /^\\/engram\\/v1\\/meetings\\/([^/]+)$/.exec(pathname);\n if (req.method === \"GET\" && meetingGetEngram) { this.enforceTokenOp(\"meetings_get\"); await respondMeetingsGet(res, this.respondJson.bind(this), this.service, meetingGetEngram[1] ?? \"\", this.wearablesScope(req, parsed.searchParams.get(\"namespace\") ?? undefined, parsed.searchParams.get(\"sessionKey\") ?? undefined)); return; }\n const meetingGetRemnic = /^\\/remnic\\/v1\\/meetings\\/([^/]+)$/.exec(pathname);\n if (req.method === \"GET\" && meetingGetRemnic) { this.enforceTokenOp(\"meetings_get\"); await respondMeetingsGet(res, this.respondJson.bind(this), this.service, meetingGetRemnic[1] ?? \"\", this.wearablesScope(req, parsed.searchParams.get(\"namespace\") ?? undefined, parsed.searchParams.get(\"sessionKey\") ?? undefined)); return; }\n\n if (req.method === \"POST\" && pathname === \"/engram/v1/observe\") {\n this.enforceTokenOp(\"observe\"); // boundary dispatch (issue #1525)\n const body = await this.readValidatedBody(req, \"observe\");\n // Boundary dispatch (issue #2482): same registry path as memory_store.\n // The write-quota hook is forwarded via ctx.hooks so it fires INSIDE\n // the service's idempotency lock (beforeExecute, only on a real miss).\n // A retried observe that hits the replay path must NOT be rejected with\n // 429 — the original attempt may have consumed the last quota slot; the\n // retry returns the cached response without requiring another (#1434\n // invariant, preserved by the boundary migration).\n const op = getOperation(\"observe\");\n if (!op) {\n throw new EngramAccessInputError(\"access-boundary: operation not registered: observe\");\n }\n const output = (await op.run(\n { ...body, namespace: this.resolveNamespace(req, body.namespace) },\n {\n service: this.service,\n authenticatedPrincipal: this.resolveRequestPrincipal(req),\n hooks: { enforceWriteQuota: () => this.ensureWriteRateLimitAvailable(req) },\n // Phase 1 provenance: server-resolved connector identity from the\n // bearer token (REST path, mirroring the MCP tools/call dispatch).\n sourceConnector: this.resolveConnector(req),\n },\n )) as { result: { dryRun?: boolean; idempotencyReplay?: boolean } };\n // A replayed (deduplicated) observe must not consume a second write-quota\n // slot — same invariant as memory_store/suggestion_submit (#1434).\n if (this.shouldCountWriteRateLimit(output.result)) {\n this.recordWriteRateLimitHit(req);\n }\n this.respondJson(res, 202, output.result);\n return;\n }\n\n if (req.method === \"POST\" && pathname === \"/engram/v1/lcm/search\") {\n this.enforceTokenOp(\"lcm_search\"); // boundary dispatch (issue #1525)\n const body = await this.readValidatedBody(req, \"lcmSearch\");\n const response = await this.service.lcmSearch({\n query: body.query,\n sessionKey: body.sessionKey,\n sessionPrefix: body.sessionPrefix,\n namespace: this.resolveNamespace(req, body.namespace),\n authenticatedPrincipal: this.resolveRequestPrincipal(req),\n limit: body.limit,\n });\n this.respondJson(res, 200, response);\n return;\n }\n if (await maybeHandleLifecycleFlush(\n this.lifecycleFlushDeps(req, res), req.method, pathname, abortSignal,\n )) return;\n\n if (req.method === \"GET\" && pathname === \"/engram/v1/lcm/status\") {\n this.enforceTokenOp(\"lcm_status\"); // boundary dispatch (issue #1525)\n this.respondJson(res, 200, await this.service.lcmStatus());\n return;\n }\n\n // Remnic Relay mission receipts (issue #1966). These two routes share the\n // access-boundary schemas and namespace-resolved storage contract. The\n // browser receives an already-reduced snapshot; it never scans general\n // memories, recall logs, or production state.\n const relayEventMatch = /^\\/engram\\/v1\\/relay\\/missions\\/([^/]+)\\/events$/.exec(pathname);\n if (req.method === \"POST\" && relayEventMatch) {\n const missionId = decodeRelayMissionIdSegment(relayEventMatch[1] ?? \"\");\n const body = await this.readJsonBody(req);\n const unexpectedFields = Object.keys(body).filter(\n (key) => key !== \"namespace\" && key !== \"event\",\n );\n if (unexpectedFields.length > 0) {\n throw new EngramAccessInputError(\n `Relay append body contains unexpected field(s): ${unexpectedFields.sort().join(\", \")}`,\n );\n }\n if (!Object.prototype.hasOwnProperty.call(body, \"event\")) {\n throw new EngramAccessInputError(\"Relay append body must contain an event object\");\n }\n if (\n Object.prototype.hasOwnProperty.call(body, \"namespace\") &&\n body.namespace !== undefined &&\n body.namespace !== null &&\n typeof body.namespace !== \"string\"\n ) {\n throw new EngramAccessInputError(\"namespace must be a string when provided\");\n }\n rejectBlankRelayNamespace(\n typeof body.namespace === \"string\" ? body.namespace : undefined,\n );\n const namespace = this.resolveNamespace(\n req,\n typeof body.namespace === \"string\" ? body.namespace : undefined,\n );\n const op = getOperation(\"relay_mission_append\");\n if (!op) {\n throw new Error(\"access-boundary: operation not registered: relay_mission_append\");\n }\n let writeQuota: WriteRateLimitReservation | undefined;\n try {\n const output = (await op.run(\n { missionId, namespace, event: body.event },\n {\n service: this.service,\n authenticatedPrincipal: this.resolveRequestPrincipal(req),\n hooks: {\n enforceWriteQuota: () => {\n writeQuota ??= this.reserveWriteRateLimitSlot(req);\n },\n },\n },\n )) as { result: { appended: boolean; replayed: boolean; event: unknown } };\n if (output.result.appended) {\n writeQuota?.commit();\n writeQuota = undefined;\n }\n this.respondJson(res, output.result.appended ? 201 : 200, output.result);\n } finally {\n writeQuota?.release();\n }\n return;\n }\n\n const relayMissionMatch = /^\\/engram\\/v1\\/relay\\/missions\\/([^/]+)$/.exec(pathname);\n if (req.method === \"GET\" && relayMissionMatch) {\n const missionId = decodeRelayMissionIdSegment(relayMissionMatch[1] ?? \"\");\n rejectBlankRelayNamespace(parsed.searchParams.get(\"namespace\"));\n const namespace = this.resolveNamespace(\n req,\n parsed.searchParams.get(\"namespace\") ?? undefined,\n );\n const op = getOperation(\"relay_mission_read\");\n if (!op) {\n throw new Error(\"access-boundary: operation not registered: relay_mission_read\");\n }\n const authenticatedPrincipal = this.resolveRequestPrincipal(req)?.trim() || undefined;\n const output = (await op.run(\n {\n missionId,\n namespace,\n since: parsed.searchParams.get(\"since\") ?? undefined,\n until: parsed.searchParams.get(\"until\") ?? undefined,\n limit: parsed.searchParams.get(\"limit\") ?? undefined,\n },\n {\n service: this.service,\n authenticatedPrincipal,\n },\n )) as { result: unknown };\n res.setHeader(\"cache-control\", \"no-store\");\n if (authenticatedPrincipal !== undefined) {\n try {\n // Percent-encode so every configured principal remains a valid HTTP\n // header value. Mission Control decodes this before constructing the\n // server-validated human approval envelope.\n res.setHeader(\"x-remnic-authenticated-principal\", encodeURIComponent(authenticatedPrincipal));\n } catch {\n // An invalid Unicode principal cannot be represented as a Relay actor\n // identifier. Omit it so Mission Control fails closed at the gate.\n }\n }\n this.respondJson(res, 200, output.result);\n return;\n }\n\n if (req.method === \"POST\" && pathname === \"/engram/v1/memories\") {\n // Migrated through the access boundary (issue #1525): the registry\n // entry owns schema validation, normalization, and service dispatch.\n // The HTTP transport resolves the request-scoped namespace and principal\n // BEFORE the boundary re-validates the cleaned envelope. The write-quota\n // hook is forwarded via ctx.hooks so it still fires atomically inside\n // the service's idempotent-write lock — never before, never on a replay\n // (#1434 invariant preserved by the boundary migration).\n const body = await this.readValidatedBody(req, \"memoryStore\");\n const envelope = {\n ...body,\n namespace: this.resolveNamespace(req, body.namespace),\n };\n const op = getOperation(\"memory_store\");\n if (!op) {\n throw new EngramAccessInputError(\"access-boundary: operation not registered: memory_store\");\n }\n const output = (await op.run(envelope, {\n service: this.service,\n authenticatedPrincipal: this.resolveRequestPrincipal(req),\n hooks: { enforceWriteQuota: () => this.ensureWriteRateLimitAvailable(req) },\n // Phase 1 provenance: server-resolved connector identity from the\n // bearer token (REST path, mirroring the MCP tools/call dispatch).\n sourceConnector: this.resolveConnector(req),\n })) as { result: EngramAccessWriteResponse };\n const response = output.result;\n if (this.shouldCountWriteRateLimit(response as { dryRun?: boolean; idempotencyReplay?: boolean })) {\n this.recordWriteRateLimitHit(req);\n }\n this.respondJson(res, this.writeResponseStatus(response), response);\n return;\n }\n\n if (req.method === \"POST\" && pathname === \"/engram/v1/coding/decisions\") {\n // Migrated through the access boundary (issue #1525/#1548): the\n // registry entry owns schema validation and service dispatch. HTTP\n // resolves the request principal; the boundary re-validates the\n // cleaned envelope. record/supersede persist decision memories, so they\n // are gated by the same 30/min write quota as /engram/v1/memories,\n // suggestions, and observe; list/get are pure reads and stay uncounted\n // (review P2: apply write quotas to decision writes).\n const body = await this.readJsonBody(req);\n const isWriteSubcommand =\n body.subcommand === \"record\" || body.subcommand === \"supersede\";\n if (isWriteSubcommand) {\n this.ensureWriteRateLimitAvailable(req);\n }\n const op = getOperation(\"coding_decision\");\n if (!op) {\n throw new EngramAccessInputError(\"access-boundary: operation not registered: coding_decision\");\n }\n const output = (await op.run(this.gatedBodyNamespace(req, body), {\n service: this.service,\n authenticatedPrincipal: this.resolveRequestPrincipal(req),\n sourceConnector: this.resolveConnector(req),\n })) as { result: unknown };\n if (isWriteSubcommand) {\n this.recordWriteRateLimitHit(req);\n }\n this.respondJson(res, 200, output.result);\n return;\n }\n\n if (req.method === \"POST\" && pathname === \"/engram/v1/coding/architecture\") {\n // Migrated through the access boundary (issue #1525/#1548 PR3):\n // refresh persists the card, so it is gated by the 30/min write quota;\n // get is a pure read and stays uncounted.\n const body = await this.readJsonBody(req);\n const isWriteSubcommand = body.subcommand === \"refresh\";\n if (isWriteSubcommand) {\n this.ensureWriteRateLimitAvailable(req);\n }\n const op = getOperation(\"coding_architecture\");\n if (!op) {\n throw new EngramAccessInputError(\"access-boundary: operation not registered: coding_architecture\");\n }\n const output = (await op.run(this.gatedBodyNamespace(req, body), {\n service: this.service,\n authenticatedPrincipal: this.resolveRequestPrincipal(req),\n sourceConnector: this.resolveConnector(req),\n })) as { result: unknown };\n if (isWriteSubcommand) {\n this.recordWriteRateLimitHit(req);\n }\n this.respondJson(res, 200, output.result);\n return;\n }\n\n if (req.method === \"POST\" && pathname === \"/engram/v1/coding/delta\") {\n // Migrated through the access boundary (issue #1525/#1548 PR4):\n // get is read-only with respect to user memory content. It DOES write\n // the operator-side state file (last-seen-head marker), but that is\n // bookkeeping — the same way calibration.ts writes are uncounted. No\n // write-quota enforcement.\n const body = await this.readJsonBody(req);\n const op = getOperation(\"coding_delta\");\n if (!op) {\n throw new EngramAccessInputError(\"access-boundary: operation not registered: coding_delta\");\n }\n const output = (await op.run(this.gatedBodyNamespace(req, body), {\n service: this.service,\n authenticatedPrincipal: this.resolveRequestPrincipal(req),\n })) as { result: unknown };\n this.respondJson(res, 200, output.result);\n return;\n }\n\n // ── Correction Contract (issue #1580) — plan / apply / pending ─────────\n // All three routes dispatch through the boundary operations so schema\n // validation + namespace policy reach every correction path (rule 22/39).\n if (req.method === \"POST\" && pathname === \"/engram/v1/correction/plan\") {\n // Planning persists a pending plan JSON file on every successful call\n // (review thread UhA), so it is a state write for rate-limit purposes —\n // mirror the apply route's precheck + accounting to bound files under\n // state/corrections/pending instead of letting an HTTP client create\n // unbounded plan files without consuming write quota.\n this.ensureWriteRateLimitAvailable(req);\n const body = await this.readJsonBody(req);\n const op = getOperation(\"memory_correct_plan\");\n if (!op) {\n throw new EngramAccessInputError(\"access-boundary: operation not registered: memory_correct_plan\");\n }\n const output = (await op.run(this.gatedBodyNamespace(req, body), {\n service: this.service,\n authenticatedPrincipal: this.resolveRequestPrincipal(req),\n })) as { result: unknown };\n this.recordWriteRateLimitHit(req);\n this.respondJson(res, 200, output.result);\n return;\n }\n\n if (req.method === \"POST\" && pathname === \"/engram/v1/correction/apply\") {\n this.ensureWriteRateLimitAvailable(req);\n const body = await this.readJsonBody(req);\n const op = getOperation(\"memory_correct_apply\");\n if (!op) {\n throw new EngramAccessInputError(\"access-boundary: operation not registered: memory_correct_apply\");\n }\n const output = (await op.run(this.gatedBodyNamespace(req, body), {\n service: this.service,\n authenticatedPrincipal: this.resolveRequestPrincipal(req),\n })) as { result: unknown };\n this.recordWriteRateLimitHit(req);\n this.respondJson(res, 200, output.result);\n return;\n }\n\n if (req.method === \"GET\" && pathname === \"/engram/v1/correction/pending\") {\n const op = getOperation(\"correction_pending\");\n if (op) {\n const output = (await op.run(\n { namespace: this.resolveNamespace(req, parsed.searchParams.get(\"namespace\") ?? undefined), sessionKey: parsed.searchParams.get(\"sessionKey\") ?? undefined },\n { service: this.service, authenticatedPrincipal: this.resolveRequestPrincipal(req) },\n )) as { result: unknown };\n this.respondJson(res, 200, output.result);\n } else {\n const namespace = this.resolveNamespace(req, parsed.searchParams.get(\"namespace\") ?? undefined);\n const sessionKey = parsed.searchParams.get(\"sessionKey\") ?? undefined;\n const plans = await this.service.correctionListPending({\n ...(namespace ? { namespace } : {}),\n ...(sessionKey ? { sessionKey } : {}),\n principal: this.resolveRequestPrincipal(req),\n });\n this.respondJson(res, 200, plans);\n }\n return;\n }\n\n if (req.method === \"POST\" && pathname === \"/engram/v1/suggestions\") {\n this.enforceTokenOp(\"suggestion_submit\"); // boundary dispatch (issue #1525)\n const body = await this.readValidatedBody(req, \"suggestionSubmit\");\n const request = {\n schemaVersion: body.schemaVersion,\n idempotencyKey: body.idempotencyKey,\n dryRun: body.dryRun === true,\n sessionKey: body.sessionKey,\n authenticatedPrincipal: this.resolveRequestPrincipal(req),\n content: body.content,\n category: body.category,\n confidence: body.confidence,\n namespace: this.resolveNamespace(req, body.namespace),\n tags: body.tags,\n entityRef: body.entityRef,\n ttl: body.ttl,\n sourceReason: body.sourceReason,\n cwd: body.cwd,\n projectTag: body.projectTag,\n // Phase 1 provenance: server-resolved connector identity from the\n // bearer token (REST path, mirroring the MCP tools/call dispatch).\n sourceConnector: this.resolveConnector(req),\n };\n // Quota enforcement is solely authoritative inside suggestionSubmit\n // (enforceWriteQuota), atomic with the real miss and never on a replay; no\n // HTTP pre-check, so a stale peek can't 429 a safe replay (#1434 Codex review).\n const response = await this.service.suggestionSubmit(request, {\n enforceWriteQuota: () => this.ensureWriteRateLimitAvailable(req),\n });\n if (this.shouldCountWriteRateLimit(response as { dryRun?: boolean; idempotencyReplay?: boolean })) {\n this.recordWriteRateLimitHit(req);\n }\n this.respondJson(res, this.writeResponseStatus(response), response);\n return;\n }\n\n if (req.method === \"GET\" && pathname === \"/engram/v1/memories\") {\n this.enforceTokenOp(\"memory_list\"); // boundary dispatch (issue #1525)\n const limit = parseStrictIntegerQuery(parsed.searchParams.get(\"limit\"), \"limit\", 50, 1);\n const offset = parseStrictIntegerQuery(parsed.searchParams.get(\"offset\"), \"offset\", 0, 0);\n const sort = parseMemorySort(parsed.searchParams.get(\"sort\"));\n const response = await this.service.memoryBrowse({\n query: parsed.searchParams.get(\"q\") ?? undefined,\n status: parsed.searchParams.get(\"status\") ?? undefined,\n category: parsed.searchParams.get(\"category\") ?? undefined,\n namespace: this.resolveNamespace(req, parsed.searchParams.get(\"namespace\") ?? undefined),\n authenticatedPrincipal: this.resolveRequestPrincipal(req),\n sort,\n limit,\n offset,\n });\n this.respondJson(res, 200, response);\n return;\n }\n\n if (req.method === \"GET\" && pathname === \"/engram/v1/recall/timings\") {\n const op = getOperation(\"recall_timings\"); // boundary dispatch (issue #1830)\n if (!op) {\n throw new Error(\"access-boundary: operation not registered: recall_timings\");\n }\n // Live diagnostic route; no response (success or denial) is cacheable.\n // Set before dispatch so the 403 path carries the header too.\n res.setHeader(\"cache-control\", \"no-store\");\n // Dispatch through the registered operation so the HTTP route and the\n // boundary registration share one gate. The server's own principal is\n // the transport-level operator fallback; a configured\n // agentAccessHttp.principal outranks it.\n const output = (await op.run({}, {\n service: this.service,\n authenticatedPrincipal: this.resolveRequestPrincipal(req),\n operatorPrincipal: this.authenticatedPrincipal,\n })) as { result: unknown };\n this.respondJson(res, 200, output.result);\n return;\n }\n\n const memoryMatch = pathname.match(/^\\/engram\\/v1\\/memories\\/([^/]+)$/);\n if (req.method === \"GET\" && memoryMatch) {\n const memoryId = decodeURIComponent(memoryMatch[1] ?? \"\");\n const namespace = this.resolveNamespace(req, parsed.searchParams.get(\"namespace\") ?? undefined);\n // Issue #1582 — thread the transport session key so a `[m:xxxx]` handle in\n // the path resolves against this session's recall history (codex review).\n // resolveRequestIdentity reads it from adapter identity / request headers.\n const sessionKey =\n this.resolveRequestIdentity(req).sessionKey\n ?? parsed.searchParams.get(\"session\")\n ?? parsed.searchParams.get(\"sessionKey\")\n ?? undefined;\n // Migrated through the access boundary (issue #1525): the registry\n // entry owns memoryId presence/shape validation (rule 51: reject empty\n // ids loudly instead of silently passing \"\" into the service) and the\n // service dispatch.\n const op = getOperation(\"memory_get\");\n if (!op) {\n throw new EngramAccessInputError(\"access-boundary: operation not registered: memory_get\");\n }\n const output = (await op.run(\n { memoryId, namespace: namespace ?? null, sessionKey: sessionKey ?? null },\n { service: this.service, authenticatedPrincipal: this.resolveRequestPrincipal(req) },\n )) as { result: EngramAccessMemoryResponse };\n const response = output.result;\n this.respondJson(res, response.found ? 200 : 404, response);\n return;\n }\n\n const timelineMatch = pathname.match(/^\\/engram\\/v1\\/memories\\/([^/]+)\\/timeline$/);\n if (req.method === \"GET\" && timelineMatch) {\n this.enforceTokenOp(\"memory_timeline\"); // boundary dispatch (issue #1525)\n const memoryId = decodeURIComponent(timelineMatch[1] ?? \"\");\n const namespace = this.resolveNamespace(req, parsed.searchParams.get(\"namespace\") ?? undefined);\n const limit = parseStrictIntegerQuery(parsed.searchParams.get(\"limit\"), \"limit\", 200, 1);\n const response = await this.service.memoryTimeline(memoryId, namespace, limit, this.resolveRequestPrincipal(req));\n this.respondJson(res, response.found ? 200 : 404, response);\n return;\n }\n\n if (req.method === \"GET\" && pathname === \"/engram/v1/entities\") {\n this.enforceTokenOp(\"entity_list\"); // boundary dispatch (issue #1525)\n const limit = parseStrictIntegerQuery(parsed.searchParams.get(\"limit\"), \"limit\", 50, 1);\n const offset = parseStrictIntegerQuery(parsed.searchParams.get(\"offset\"), \"offset\", 0, 0);\n const response = await this.service.entityList({\n namespace: this.resolveNamespace(req, parsed.searchParams.get(\"namespace\") ?? undefined),\n query: parsed.searchParams.get(\"q\") ?? undefined,\n limit,\n offset,\n });\n this.respondJson(res, 200, response);\n return;\n }\n\n const entityMatch = pathname.match(/^\\/engram\\/v1\\/entities\\/([^/]+)$/);\n if (req.method === \"GET\" && entityMatch) {\n this.enforceTokenOp(\"entity_get\"); // boundary dispatch (issue #1525)\n const entityName = decodeURIComponent(entityMatch[1] ?? \"\");\n const namespace = this.resolveNamespace(req, parsed.searchParams.get(\"namespace\") ?? undefined);\n const response = await this.service.entityGet(entityName, namespace);\n this.respondJson(res, response.found ? 200 : 404, response);\n return;\n }\n\n if (req.method === \"GET\" && pathname === \"/engram/v1/review-queue\") {\n this.enforceTokenOp(\"review_queue_list\"); // boundary dispatch (issue #1525)\n const response = await this.service.reviewQueue(\n parsed.searchParams.get(\"runId\") ?? undefined,\n this.resolveNamespace(req, parsed.searchParams.get(\"namespace\") ?? undefined),\n this.resolveRequestPrincipal(req),\n );\n this.respondJson(res, 200, response);\n return;\n }\n\n if (req.method === \"GET\" && pathname === \"/engram/v1/maintenance\") {\n this.enforceTokenOp(\"maintenance_status\"); // boundary dispatch (issue #1525)\n const namespace = this.resolveNamespace(req, parsed.searchParams.get(\"namespace\") ?? undefined);\n this.respondJson(res, 200, await this.service.maintenance(namespace, this.resolveRequestPrincipal(req)));\n return;\n }\n\n if (req.method === \"GET\" && pathname === \"/engram/v1/quality\") {\n this.enforceTokenOp(\"quality_status\"); // boundary dispatch (issue #1525)\n const namespace = this.resolveNamespace(req, parsed.searchParams.get(\"namespace\") ?? undefined);\n this.respondJson(res, 200, await this.service.quality(namespace, this.resolveRequestPrincipal(req)));\n return;\n }\n\n if (req.method === \"GET\" && pathname === \"/engram/v1/trust-zones/status\") {\n this.enforceTokenOp(\"trust_zones_status\"); // boundary dispatch (issue #1525)\n this.respondJson(\n res,\n 200,\n await this.service.trustZoneStatus(this.resolveNamespace(req, parsed.searchParams.get(\"namespace\") ?? undefined), this.resolveRequestPrincipal(req)),\n );\n return;\n }\n\n // Procedural memory stats (issue #567 PR 5/5). Read-only; namespace is\n // scoped via the same resolver used by recall/trust-zones so cross-\n // tenant reads aren't possible (CLAUDE.md rule 42).\n if (req.method === \"GET\" && pathname === \"/engram/v1/procedural/stats\") {\n this.enforceTokenOp(\"procedural_stats\"); // boundary dispatch (issue #1525)\n const namespaceParam = parsed.searchParams.get(\"namespace\");\n this.respondJson(\n res,\n 200,\n await this.service.procedureStats(\n {\n namespace: this.resolveNamespace(\n req,\n namespaceParam && namespaceParam.length > 0\n ? namespaceParam\n : undefined,\n ),\n },\n this.resolveRequestPrincipal(req),\n ),\n );\n return;\n }\n\n if (req.method === \"GET\" && pathname === \"/engram/v1/trust-zones/records\") {\n this.enforceTokenOp(\"trust_zones_records\"); // boundary dispatch (issue #1525)\n const limit = parseStrictIntegerQuery(parsed.searchParams.get(\"limit\"), \"limit\", 25, 1);\n const offset = parseStrictIntegerQuery(parsed.searchParams.get(\"offset\"), \"offset\", 0, 0);\n const response = await this.service.trustZoneBrowse({\n query: parsed.searchParams.get(\"q\") ?? undefined,\n zone: parseTrustZoneFilter(parsed.searchParams.get(\"zone\")),\n kind: parseTrustZoneKindFilter(parsed.searchParams.get(\"kind\")),\n sourceClass: parseTrustZoneSourceClassFilter(parsed.searchParams.get(\"sourceClass\")),\n namespace: this.resolveNamespace(req, parsed.searchParams.get(\"namespace\") ?? undefined),\n limit,\n offset,\n }, this.resolveRequestPrincipal(req));\n this.respondJson(res, 200, response);\n return;\n }\n\n if (req.method === \"POST\" && pathname === \"/engram/v1/review-disposition\") {\n this.enforceTokenOp(\"review_disposition\"); // boundary dispatch (issue #1525)\n const body = await this.readValidatedBody(req, \"reviewDisposition\");\n this.ensureWriteRateLimitAvailable(req);\n const response = await this.service.reviewDisposition({\n memoryId: body.memoryId,\n status: body.status,\n reasonCode: body.reasonCode,\n namespace: this.resolveNamespace(req, body.namespace),\n authenticatedPrincipal: this.resolveRequestPrincipal(req),\n });\n if (this.shouldCountWriteRateLimit(response as unknown as { dryRun?: boolean; idempotencyReplay?: boolean })) {\n this.recordWriteRateLimitHit(req);\n }\n this.respondJson(res, 200, response);\n return;\n }\n\n if (req.method === \"POST\" && pathname === \"/engram/v1/trust-zones/promote\") {\n this.enforceTokenOp(\"trust_zones_promote\"); // boundary dispatch (issue #1525)\n const body = await this.readValidatedBody(req, \"trustZonePromote\");\n const dryRun = body.dryRun === true;\n if (!dryRun) {\n this.ensureWriteRateLimitAvailable(req);\n }\n const response = await this.service.trustZonePromote({\n recordId: body.recordId,\n targetZone: body.targetZone,\n promotionReason: body.promotionReason,\n recordedAt: body.recordedAt,\n summary: body.summary,\n dryRun,\n namespace: this.resolveNamespace(req, body.namespace),\n authenticatedPrincipal: this.resolveRequestPrincipal(req),\n });\n if (this.shouldCountWriteRateLimit(response as unknown as { dryRun?: boolean; idempotencyReplay?: boolean })) {\n this.recordWriteRateLimitHit(req);\n }\n this.respondJson(res, response.dryRun ? 200 : 201, response);\n return;\n }\n\n if (req.method === \"POST\" && pathname === \"/engram/v1/trust-zones/demo-seed\") {\n this.enforceTokenOp(\"trust_zones_demo_seed\"); // boundary dispatch (issue #1525)\n const body = await this.readValidatedBody(req, \"trustZoneDemoSeed\");\n const dryRun = body.dryRun === true;\n if (!dryRun) {\n this.ensureWriteRateLimitAvailable(req);\n }\n const response = await this.service.trustZoneDemoSeed({\n scenario: body.scenario,\n recordedAt: body.recordedAt,\n dryRun,\n namespace: this.resolveNamespace(req, body.namespace),\n authenticatedPrincipal: this.resolveRequestPrincipal(req),\n });\n if (this.shouldCountWriteRateLimit(response as unknown as { dryRun?: boolean; idempotencyReplay?: boolean })) {\n this.recordWriteRateLimitHit(req);\n }\n this.respondJson(res, response.dryRun ? 200 : 201, response);\n return;\n }\n\n // Citation usage tracking (issue #379)\n if (req.method === \"POST\" && pathname === \"/v1/citations/observed\") {\n this.enforceTokenOp(\"citations_observed\"); // boundary dispatch (issue #1525)\n const body = await this.readJsonBody(req);\n if (!body || typeof body !== \"object\" || Array.isArray(body)) {\n throw new HttpError(400, \"request body must be a JSON object\", \"invalid_body\");\n }\n const payload = body as Record<string, unknown>;\n const sessionId = typeof payload.sessionId === \"string\" ? payload.sessionId : undefined;\n const namespace = typeof payload.namespace === \"string\" ? payload.namespace : undefined;\n const citationsRaw = payload.citations;\n if (!citationsRaw || typeof citationsRaw !== \"object\" || Array.isArray(citationsRaw)) {\n throw new HttpError(400, \"citations must be a JSON object with entries and rolloutIds\", \"invalid_citations\");\n }\n const citObj = citationsRaw as Record<string, unknown>;\n const entries: CitationEntry[] = [];\n if (Array.isArray(citObj.entries)) {\n for (const raw of citObj.entries) {\n if (raw && typeof raw === \"object\" && !Array.isArray(raw)) {\n const e = raw as Record<string, unknown>;\n if (\n typeof e.path === \"string\" &&\n typeof e.lineStart === \"number\" &&\n typeof e.lineEnd === \"number\"\n ) {\n entries.push({\n path: e.path,\n lineStart: e.lineStart,\n lineEnd: e.lineEnd,\n note: typeof e.note === \"string\" ? e.note : \"\",\n });\n }\n }\n }\n }\n const rolloutIds: string[] = [];\n if (Array.isArray(citObj.rolloutIds)) {\n for (const id of citObj.rolloutIds) {\n if (typeof id === \"string\" && id.length > 0) {\n rolloutIds.push(id);\n }\n }\n }\n\n // Record usage: for each citation entry, try to increment usage on the\n // matching memory. The service exposes recordAccess for this purpose.\n // Pass authenticatedPrincipal so namespace ACL checks use the same\n // identity resolution as other write endpoints (Finding #1, issue #379).\n let matched = 0;\n let submitted = 0;\n if (typeof this.service.recordCitationUsage === \"function\") {\n const result = await this.service.recordCitationUsage({\n sessionId,\n namespace: this.resolveNamespace(req, namespace),\n authenticatedPrincipal: this.resolveRequestPrincipal(req),\n entries,\n rolloutIds,\n });\n submitted = result.submitted;\n matched = result.matched;\n }\n\n this.respondJson(res, 200, {\n ok: true,\n submitted,\n matched,\n entriesReceived: entries.length,\n rolloutIdsReceived: rolloutIds.length,\n });\n return;\n }\n\n // ── Contradiction Review (issue #520) ─────────────────────────────────────\n if (req.method === \"GET\" && pathname === \"/engram/v1/review/contradictions\") {\n this.enforceTokenOp(\"review_list\"); // boundary dispatch (issue #1525)\n const VALID_FILTERS = new Set([\"all\", \"unresolved\", \"contradicts\", \"independent\", \"duplicates\", \"needs-user\"]);\n const rawFilter = parsed.searchParams.get(\"filter\") ?? \"unresolved\";\n if (!VALID_FILTERS.has(rawFilter)) {\n this.respondJson(res, 400, { error: `Invalid filter '${rawFilter}'. Valid: ${[...VALID_FILTERS].join(\", \")}` });\n return;\n }\n const namespace = this.resolveNamespace(req, parsed.searchParams.get(\"namespace\") ?? undefined);\n const limit = parseStrictIntegerQuery(parsed.searchParams.get(\"limit\"), \"limit\", 50, 1);\n const principal = this.resolveRequestPrincipal(req);\n const resolved = await this.service.getReadableStorageForNamespace(namespace, principal);\n const reviewNamespace = this.service.configRef.namespacesEnabled ? resolved.namespace : undefined;\n const includeUnscopedForNamespace = Boolean(\n reviewNamespace && isDefaultReviewNamespace(this.service.configRef.defaultNamespace, namespace, reviewNamespace),\n );\n const result = listPairs(this.service.memoryDir, {\n filter: rawFilter as \"all\" | \"unresolved\" | \"contradicts\" | \"independent\" | \"duplicates\" | \"needs-user\",\n namespace: reviewNamespace,\n includeUnscopedForNamespace,\n limit,\n });\n this.respondJson(res, 200, result);\n return;\n }\n\n if (req.method === \"GET\" && pathname.startsWith(\"/engram/v1/review/contradictions/\")) {\n this.enforceTokenOp(\"contradiction_detail\"); // boundary dispatch (issue #1525)\n const pairId = pathname.split(\"/\").pop() ?? \"\";\n const pair = readPair(this.service.memoryDir, pairId);\n if (!pair) {\n this.respondJson(res, 404, { error: \"pair_not_found\" });\n return;\n }\n // Per-token namespace enforcement (issues #1850 round 2 / round 4): the\n // pair is fetched BY ID, so its namespace comes from the record — NOT a\n // query param that resolveNamespace() already gates. A namespace-scoped\n // bearer that knows a pair id must not read contradiction data in a\n // namespace outside its allow-list. Fail closed (403) before the\n // principal-storage check so the token's declared scope is the\n // outermost gate. Legacy pairs carry no namespace (undefined), which\n // downstream storage maps to the server DEFAULT — route the record\n // namespace through the SAME effective-namespace chokepoint\n // (enforceNamespaceAllowList maps undefined → default) so a scoped token\n // whose allow-list INCLUDES the default can read/resolve a legacy pair,\n // while one that does NOT is still denied. No-op for unrestricted tokens.\n enforceNamespaceAllowList(\n tokenCapabilityStore.getStore(),\n pair.namespace,\n this.service.configRef?.defaultNamespace,\n );\n try {\n await this.service.getReadableStorageForNamespace(pair.namespace, this.resolveRequestPrincipal(req));\n } catch {\n this.respondJson(res, 404, { error: \"pair_not_found\" });\n return;\n }\n this.respondJson(res, 200, pair);\n return;\n }\n\n if (req.method === \"POST\" && pathname === \"/engram/v1/review/resolve\") {\n this.enforceTokenOp(\"review_resolve\"); // boundary dispatch (issue #1525)\n const body = await this.readJsonBody(req) as Record<string, unknown>;\n const pairId = typeof body.pairId === \"string\" ? body.pairId : \"\";\n const verb = typeof body.verb === \"string\" ? body.verb : \"\";\n if (!pairId || !verb) {\n this.respondJson(res, 400, { error: \"pairId and verb are required\" });\n return;\n }\n if (!isValidResolutionVerb(verb)) {\n this.respondJson(res, 400, { error: `Invalid verb: ${verb}. Must be one of: keep-a, keep-b, merge, both-valid, needs-more-context` });\n return;\n }\n // Per-token namespace enforcement (issues #1850 round 2 / round 4): the\n // resolution target is selected BY pairId, so the affected namespace\n // comes from the record — NOT a request param that resolveNamespace()\n // already gates. A namespace-scoped bearer must not mutate a\n // contradiction pair in a namespace outside its allow-list. Load the\n // pair to learn its namespace, enforce the token's scope, and fail\n // closed (403) BEFORE dispatching the (mutating) resolution. Legacy\n // pairs carry no namespace (undefined), which downstream storage maps to\n // the server DEFAULT — use the SAME effective-namespace chokepoint\n // (enforceNamespaceAllowList maps undefined → default) as the detail\n // route so a scoped token whose allow-list INCLUDES the default can\n // resolve a legacy pair. A missing pair falls through to\n // executeResolution's existing not-found result. No-op for unrestricted\n // tokens.\n const targetPair = readPair(this.service.memoryDir, pairId);\n if (targetPair) {\n enforceNamespaceAllowList(\n tokenCapabilityStore.getStore(),\n targetPair.namespace,\n this.service.configRef?.defaultNamespace,\n );\n }\n const principal = this.resolveRequestPrincipal(req);\n const result = await executeResolution(this.service.memoryDir, this.service.storageRef, pairId, verb, {\n mergedMemoryId: typeof body.mergedMemoryId === \"string\" ? body.mergedMemoryId : undefined,\n mergedContent: typeof body.mergedContent === \"string\" ? body.mergedContent : undefined,\n storageForNamespace: async (namespace) => {\n const resolved = await this.service.getWritableStorageForNamespace(namespace, principal);\n return resolved.storage;\n },\n // Catalog write touch (issue #1499 sweep): a contradiction merge writes a\n // new memory directly to the resolved namespace storage, bypassing the\n // extraction write path. Record it so QMD maintenance / writtenSince\n // don't miss the write. Best-effort and failure-tolerant.\n onMergedMemoryWritten: (namespace, storageDir) => {\n // #1522: catalog touch handled at the storage chokepoint.\n },\n });\n this.respondJson(res, 200, result);\n return;\n }\n\n // Graph snapshot (issue #691 PR 2/5) — read-only adjacency view used by\n // the admin-pane scaffold shipped in PR 1/5. All filters are query\n // params so the surface stays cacheable; invalid values yield 400 with\n // a descriptive body (CLAUDE.md rule 51 — never silently default).\n if (req.method === \"GET\" && pathname === \"/engram/v1/graph/snapshot\") {\n this.enforceTokenOp(\"graph_snapshot\"); // boundary dispatch (issue #1525)\n const limitRaw = parsed.searchParams.get(\"limit\");\n let limit: number | undefined;\n if (limitRaw !== null && limitRaw.length > 0) {\n const parsedLimit = Number(limitRaw);\n if (\n !Number.isFinite(parsedLimit)\n || !Number.isInteger(parsedLimit)\n || parsedLimit <= 0\n ) {\n this.respondJson(res, 400, {\n error: \"invalid_limit\",\n code: \"invalid_limit\",\n message: \"limit must be a positive integer\",\n });\n return;\n }\n limit = parsedLimit;\n }\n const sinceRaw = parsed.searchParams.get(\"since\");\n let since: string | undefined;\n if (sinceRaw !== null && sinceRaw.length > 0) {\n // Validate up-front so the access service can stay focused on the\n // pure snapshot logic (parser also runs there as a defense in\n // depth, but rejecting at the boundary preserves the\n // \"invalid_since\" error code instead of leaking a generic 500).\n if (!Number.isFinite(Date.parse(sinceRaw))) {\n this.respondJson(res, 400, {\n error: \"invalid_since\",\n code: \"invalid_since\",\n message: \"since must be a parseable ISO timestamp\",\n });\n return;\n }\n since = sinceRaw;\n }\n const focusNodeIdRaw = parsed.searchParams.get(\"focusNodeId\");\n const focusNodeId = focusNodeIdRaw && focusNodeIdRaw.length > 0\n ? focusNodeIdRaw\n : undefined;\n const categoriesRaw = parsed.searchParams.get(\"categories\");\n let categories: string[] | undefined;\n if (categoriesRaw !== null && categoriesRaw.length > 0) {\n categories = categoriesRaw\n .split(\",\")\n .map((value) => value.trim())\n .filter((value) => value.length > 0);\n if (categories.length === 0) {\n this.respondJson(res, 400, {\n error: \"invalid_categories\",\n code: \"invalid_categories\",\n message:\n \"categories must be a comma-separated list with at least one non-empty value\",\n });\n return;\n }\n }\n const namespaceParam = parsed.searchParams.get(\"namespace\");\n const namespace = this.resolveNamespace(\n req,\n namespaceParam && namespaceParam.length > 0 ? namespaceParam : undefined,\n );\n try {\n const snapshot = await this.service.graphSnapshot(\n {\n namespace,\n ...(limit !== undefined ? { limit } : {}),\n ...(since !== undefined ? { since } : {}),\n ...(focusNodeId !== undefined ? { focusNodeId } : {}),\n ...(categories !== undefined ? { categories } : {}),\n },\n this.resolveRequestPrincipal(req),\n );\n this.respondJson(res, 200, snapshot);\n } catch (err) {\n // As with recallXray above: surface only the deliberately-prefixed\n // graphSnapshot validation Error.message, never String(err) of an\n // arbitrary throw (CodeQL js/stack-trace-exposure). Validation errors are\n // always Error instances; anything else is rethrown as a 500.\n if (err instanceof Error && err.message.startsWith(\"graphSnapshot:\")) {\n this.respondJson(res, 400, {\n error: \"invalid_request\",\n code: \"invalid_request\",\n message: err.message,\n });\n return;\n }\n throw err;\n }\n return;\n }\n\n if (req.method === \"POST\" && pathname === \"/engram/v1/contradiction-scan\") {\n this.enforceTokenOp(\"contradiction_scan_run\"); // boundary dispatch (issue #1525)\n const body = await this.readJsonBody(req) as Record<string, unknown>;\n const { runContradictionScan } = await import(\"./contradiction/contradiction-scan.js\");\n const principal = this.resolveRequestPrincipal(req);\n const result = await runContradictionScan({\n storage: this.service.storageRef,\n config: this.service.configRef,\n memoryDir: this.service.memoryDir,\n embeddingLookupFactory: this.service.embeddingLookupFactoryRef,\n storageForNamespace: (namespace) =>\n this.service.getWritableStorageForNamespace(namespace, principal),\n localLlm: this.service.localLlmRef,\n fallbackLlm: this.service.fallbackLlmRef,\n namespace: this.resolveNamespace(req, typeof body.namespace === \"string\" ? body.namespace : undefined),\n });\n this.respondJson(res, 200, result);\n return;\n }\n\n // ── Graph mutation event stream (issue #691 PR 5/5) ──────────────────────\n //\n // GET /engram/v1/graph/events\n //\n // Server-Sent Events stream that emits graph mutation events in real time.\n // Event types: node-added, node-updated, edge-added, edge-updated, edge-removed.\n //\n // Auth: same Bearer token scheme as every other endpoint (checked above).\n //\n // The SSE handler subscribes to the in-process graph event bus for the\n // resolved memory dir. Events are batched within a 200 ms window so a\n // burst of writes (e.g. extraction of a large turn) doesn't overwhelm\n // the admin UI canvas with individual re-renders.\n //\n // The client receives a `data: <json>\\n\\n` line per batch. Each batch\n // payload is { events: GraphEvent[] }.\n //\n // The stream sends a heartbeat `data: {\"type\":\"heartbeat\"}\\n\\n` every\n // 25 s so load balancers and proxies don't time out idle connections.\n if (req.method === \"GET\" && pathname === \"/engram/v1/graph/events\") {\n this.enforceTokenOp(\"graph_events\"); // boundary dispatch (issue #1525)\n await this.handleGraphEventsSSE(req, res);\n return;\n }\n\n // ── Chat endpoints (issue #1583) ────────────────────────────────────────\n if (req.method === \"POST\" && pathname === \"/engram/v1/chat/message\") {\n this.enforceTokenOp(\"chat_message\"); // boundary dispatch (issue #1525)\n const body = await this.readJsonBody(req) as Record<string, unknown>;\n // Issue #1850 round 5 (finding 2): a resumed chat session is an\n // id-loaded record whose namespace bypassed the token allow-list. Gate\n // its stored namespace before posting (fail closed; no-op unrestricted).\n const resumeChatSessionId = typeof body.chatSessionId === \"string\" ? body.chatSessionId : undefined;\n if (resumeChatSessionId) {\n await enforceChatSessionNamespace(this.service, resumeChatSessionId);\n } else {\n // NEW chat session (no chatSessionId): processChatMessage will mint a\n // fresh session under the effective namespace. The HTTP chat handler\n // does not forward a request namespace, so the new session inherits\n // the server DEFAULT — route that effective namespace through the\n // SAME chokepoint as the resume path (enforceNamespaceAllowList maps\n // undefined → default) so a namespace-scoped token CANNOT start a\n // chat in a namespace outside its allow-list (its server default may\n // be unlisted, or the server may carry no configured default). Fail\n // closed; no-op for unrestricted/legacy tokens (issue #1850 round 7).\n enforceNamespaceAllowList(\n tokenCapabilityStore.getStore(),\n undefined,\n this.service.configRef?.defaultNamespace,\n );\n }\n await handleChatMessage(\n req, res, body,\n { service: this.service, config: this.service.configRef?.chat, memoryDir: this.service.memoryDir },\n this.resolveRequestPrincipal(req),\n );\n return;\n }\n const chatEventsMatch = /^\\/engram\\/v1\\/chat\\/events\\/([^/]+)$/.exec(pathname);\n if (req.method === \"GET\" && chatEventsMatch) {\n this.enforceTokenOp(\"chat_events\"); // boundary dispatch (issue #1525)\n // Issue #1850 round 5 (finding 2): the SSE target is an id-loaded chat\n // session whose namespace bypassed the token allow-list. Gate its stored\n // namespace before streaming (fail closed; no-op unrestricted).\n await enforceChatSessionNamespace(this.service, chatEventsMatch[1] ?? \"\");\n await handleChatEventsSSE(\n req, res, chatEventsMatch[1] ?? \"\",\n {\n service: this.service,\n config: this.service.configRef?.chat,\n memoryDir: this.service.memoryDir,\n // Register the chat-SSE disconnect cleanup with this server's\n // stop() set so an HTTP shutdown forcibly releases the heartbeat\n // and transcript subscription even when a lingering client never\n // emits 'close' (cursor Medium review; mirrors handleGraphEventsSSE\n // which registers in sseCleanupFns at access-http.ts:2604).\n registerSseCleanup: (cleanup) => {\n this.sseCleanupFns.add(cleanup);\n return () => { this.sseCleanupFns.delete(cleanup); };\n },\n },\n this.resolveRequestPrincipal(req),\n );\n return;\n }\n\n // ── Peer Registry endpoints (issue #679) ─────────────────────────────────\n // GET /engram/v1/console/state — operator console engine-state snapshot (issue #688 PR 2/3).\n // Read-only; namespace-aware via resolveRequestPrincipal so cross-tenant\n // reads are not possible (CLAUDE.md rule 42).\n if (req.method === \"GET\" && pathname === \"/engram/v1/console/state\") {\n this.enforceTokenOp(\"console_state\"); // boundary dispatch (issue #1525)\n const namespace = this.resolveNamespace(req, parsed.searchParams.get(\"namespace\") ?? undefined);\n const snapshot = await this.service.consoleState(namespace, this.resolveRequestPrincipal(req));\n this.respondJson(res, 200, snapshot);\n return;\n }\n\n // GET /engram/v1/peers — list all peers\n // GET /engram/v1/peers/:id — get one peer\n // PUT /engram/v1/peers/:id — upsert (create/update)\n // DELETE /engram/v1/peers/:id — delete identity only (idempotent)\n // DELETE /engram/v1/peers/:id?forget=true — destructive full purge (issue #679 completion)\n // GET /engram/v1/peers/:id/profile — get peer profile\n if (req.method === \"GET\" && pathname === \"/engram/v1/peers\") {\n this.enforceTokenOp(\"peer_list\"); // boundary dispatch (issue #1525)\n const result = await this.service.peerList();\n this.respondJson(res, 200, result);\n return;\n }\n\n const peerProfileMatch = /^\\/engram\\/v1\\/peers\\/([^/]+)\\/profile$/.exec(pathname);\n if (peerProfileMatch) {\n this.enforceTokenOp(\"peer_profile_get\"); // boundary dispatch (issue #1525)\n if (req.method !== \"GET\") {\n this.respondJson(res, 405, { error: \"method_not_allowed\", code: \"method_not_allowed\" });\n return;\n }\n const peerId = decodePeerIdSegment(peerProfileMatch[1] ?? \"\");\n const result = await this.service.peerProfileGet(peerId);\n if (!result.found) {\n this.respondJson(res, 404, { error: \"peer_profile_not_found\", code: \"peer_profile_not_found\" });\n return;\n }\n this.respondJson(res, 200, result);\n return;\n }\n\n const peerIdMatch = /^\\/engram\\/v1\\/peers\\/([^/]+)$/.exec(pathname);\n if (peerIdMatch) {\n const peerId = decodePeerIdSegment(peerIdMatch[1] ?? \"\");\n\n if (req.method === \"GET\") {\n this.enforceTokenOp(\"peer_get\"); // boundary dispatch (issue #1525)\n const result = await this.service.peerGet(peerId);\n if (!result.found) {\n this.respondJson(res, 404, { error: \"peer_not_found\", code: \"peer_not_found\" });\n return;\n }\n this.respondJson(res, 200, result);\n return;\n }\n\n if (req.method === \"PUT\") {\n this.enforceTokenOp(\"peer_set\"); // boundary dispatch (issue #1525)\n const body = await this.readJsonBody(req) as Record<string, unknown>;\n // Reject malformed types up front rather than silently dropping them\n // to undefined and letting peerSet fall back to defaults\n // (CLAUDE.md rule 51: no silent defaults on bad input).\n if (\"kind\" in body && body.kind !== undefined && typeof body.kind !== \"string\") {\n throw new EngramAccessInputError(\"kind must be a string when provided\");\n }\n if (\n \"displayName\" in body &&\n body.displayName !== undefined &&\n typeof body.displayName !== \"string\"\n ) {\n throw new EngramAccessInputError(\"displayName must be a string when provided\");\n }\n if (\"notes\" in body && body.notes !== undefined && typeof body.notes !== \"string\") {\n throw new EngramAccessInputError(\"notes must be a string when provided\");\n }\n const result = await this.service.peerSet({\n id: peerId,\n kind: typeof body.kind === \"string\" ? body.kind : undefined,\n displayName: typeof body.displayName === \"string\" ? body.displayName : undefined,\n notes: typeof body.notes === \"string\" ? body.notes : undefined,\n });\n this.respondJson(res, result.created ? 201 : 200, result);\n return;\n }\n\n if (req.method === \"DELETE\") {\n this.enforceTokenOp(\"peer_delete\"); // boundary dispatch (issue #1525)\n // `?forget=true` triggers the destructive full-purge path (issue #679\n // completion). The caller must also pass `confirm=yes` in the request\n // body; absent confirmation yields 400. Plain DELETE (no ?forget) keeps\n // the existing soft-delete behaviour (identity.md only).\n const forgetParam = parsed.searchParams.get(\"forget\");\n if (forgetParam === \"true\") {\n const body = await this.readJsonBody(req) as Record<string, unknown>;\n const confirm = typeof body.confirm === \"string\" ? body.confirm : \"\";\n if (confirm !== \"yes\") {\n this.respondJson(res, 400, {\n error: \"confirm_required\",\n code: \"confirm_required\",\n message: \"DELETE ?forget=true requires { confirm: 'yes' } in the request body\",\n });\n return;\n }\n const result = await this.service.peerForget(peerId, { confirm: \"yes\" });\n this.respondJson(res, 200, result);\n return;\n }\n const result = await this.service.peerDelete(peerId);\n this.respondJson(res, 200, result);\n return;\n }\n\n this.respondJson(res, 405, { error: \"method_not_allowed\", code: \"method_not_allowed\" });\n return;\n }\n\n // ── Dreams telemetry (issue #678 PR 3+4) ──────────────────────────────────\n\n if (req.method === \"GET\" && pathname === \"/engram/v1/dreams/status\") {\n this.enforceTokenOp(\"dreams_status\"); // boundary dispatch (issue #1525)\n const { normalizeDreamsStatusWindowHours } = await import(\"./maintenance/dreams-ledger.js\");\n const windowHoursRaw = parsed.searchParams.get(\"windowHours\");\n let windowHours: number;\n try {\n windowHours = normalizeDreamsStatusWindowHours(\n windowHoursRaw !== null ? Number(windowHoursRaw) : undefined,\n );\n } catch {\n this.respondJson(res, 400, { error: \"windowHours must be a positive integer\" });\n return;\n }\n const namespaceParam = parsed.searchParams.get(\"namespace\");\n const namespace = this.resolveNamespace(req, namespaceParam && namespaceParam.length > 0 ? namespaceParam : undefined);\n const result = await this.service.dreamsStatus({\n windowHours,\n namespace,\n principal: this.resolveRequestPrincipal(req),\n });\n this.respondJson(res, 200, result);\n return;\n }\n\n if (req.method === \"POST\" && pathname === \"/engram/v1/dreams/run\") {\n this.enforceTokenOp(\"dreams_run\"); // boundary dispatch (issue #1525)\n const body = await this.readJsonBody(req) as Record<string, unknown>;\n const VALID_PHASES = [\"lightSleep\", \"rem\", \"deepSleep\"] as const;\n const phase = typeof body.phase === \"string\" ? body.phase : undefined;\n if (!phase || !(VALID_PHASES as readonly string[]).includes(phase)) {\n this.respondJson(res, 400, {\n error: `phase is required and must be one of: ${VALID_PHASES.join(\", \")}`,\n });\n return;\n }\n if (\n \"dryRun\" in body &&\n body.dryRun !== undefined &&\n typeof body.dryRun !== \"boolean\"\n ) {\n this.respondJson(res, 400, {\n error: \"dryRun must be a boolean when provided\",\n });\n return;\n }\n if (\n \"namespace\" in body &&\n body.namespace !== undefined &&\n typeof body.namespace !== \"string\"\n ) {\n this.respondJson(res, 400, {\n error: \"namespace must be a string when provided\",\n });\n return;\n }\n const dryRun = body.dryRun === true;\n const namespace = this.resolveNamespace(req, typeof body.namespace === \"string\" ? body.namespace : undefined);\n if (!dryRun) {\n this.ensureWriteRateLimitAvailable(req);\n }\n const result = await this.service.dreamsRun({\n phase: phase as import(\"./types.js\").DreamsPhase,\n dryRun,\n namespace,\n authenticatedPrincipal: this.resolveRequestPrincipal(req),\n });\n if (this.shouldCountWriteRateLimit(result as { dryRun?: boolean; idempotencyReplay?: boolean })) {\n this.recordWriteRateLimitHit(req);\n }\n this.respondJson(res, 200, result);\n return;\n }\n\n // ── Admin console surfaces (issue #1502) ──────────────────────────────\n //\n // All five routes live under /engram/v1/admin/* which the access-surface\n // catalog treats as infrastructure (no boundary migration required; the\n // static-completeness fitness test excludes this prefix). They still\n // require bearer auth (enforced above) and delegate to core APIs via the\n // pure admin-surfaces module — the dashboard never re-resolves scope or\n // re-lists namespaces.\n if (pathname.startsWith(\"/engram/v1/admin/scope/inspect\")) {\n if (req.method !== \"GET\" && req.method !== \"POST\") {\n this.respondJson(res, 405, { error: \"method_not_allowed\", code: \"method_not_allowed\" });\n return;\n }\n this.requireOperatorToken();\n const principal = this.resolveRequestPrincipal(req);\n let sessionKey: string | undefined;\n let namespaceOverride: string | undefined;\n let operation: string | undefined;\n if (req.method === \"GET\") {\n sessionKey = parsed.searchParams.get(\"session\") ?? undefined;\n namespaceOverride = parsed.searchParams.get(\"namespace\") ?? undefined;\n operation = parsed.searchParams.get(\"operation\") ?? undefined;\n } else {\n const body = await this.readJsonBody(req) as Record<string, unknown>;\n sessionKey = typeof body.sessionKey === \"string\" ? body.sessionKey : undefined;\n namespaceOverride = typeof body.namespace === \"string\" ? body.namespace : undefined;\n operation = typeof body.operation === \"string\" ? body.operation : undefined;\n }\n const inspection = await this.service.adminInspectScope({\n sessionKey: sessionKey && sessionKey.length > 0 ? sessionKey : undefined,\n namespace: namespaceOverride && namespaceOverride.length > 0 ? namespaceOverride : undefined,\n principalOverride: principal,\n operation: operation as \"recall\" | \"observe\" | \"memory_store\" | \"maintenance\" | \"dashboard\" | undefined,\n });\n this.respondJson(res, 200, inspection);\n return;\n }\n if (pathname === \"/engram/v1/admin/namespaces\") {\n if (req.method !== \"GET\") {\n this.respondJson(res, 405, { error: \"method_not_allowed\", code: \"method_not_allowed\" });\n return;\n }\n this.requireOperatorToken();\n const kind = optionalNamespaceKindQueryParam(parsed.searchParams.get(\"kind\"));\n const discoveredBy = parsed.searchParams.get(\"discoveredBy\");\n const result = await this.service.adminListNamespaces({\n ...(kind ? { kind } : {}),\n ...(discoveredBy\n ? { discoveredBy: discoveredBy as \"config\" | \"write\" | \"read\" | \"scan\" | \"migration\" }\n : {}),\n });\n this.respondJson(res, 200, result);\n return;\n }\n if (pathname === \"/engram/v1/admin/maintenance-health\") {\n if (req.method !== \"GET\") {\n this.respondJson(res, 405, { error: \"method_not_allowed\", code: \"method_not_allowed\" });\n return;\n }\n this.requireOperatorToken();\n const report = await this.service.adminMaintenanceHealth();\n this.respondJson(res, 200, report);\n return;\n }\n if (pathname === \"/engram/v1/admin/transcript-audit\") {\n if (req.method !== \"GET\") {\n this.respondJson(res, 405, { error: \"method_not_allowed\", code: \"method_not_allowed\" });\n return;\n }\n this.requireOperatorToken();\n const report = await this.service.adminTranscriptAudit();\n this.respondJson(res, 200, report);\n return;\n }\n if (pathname === \"/engram/v1/admin/promote\") {\n if (req.method !== \"POST\") {\n this.respondJson(res, 405, { error: \"method_not_allowed\", code: \"method_not_allowed\" });\n return;\n }\n this.requireOperatorToken();\n const body = await this.readJsonBody(req) as Record<string, unknown>;\n if (typeof body.sourceMemoryId !== \"string\" || body.sourceMemoryId.trim().length === 0) {\n this.respondJson(res, 400, {\n error: \"invalid_request\",\n code: \"invalid_request\",\n message: \"sourceMemoryId is required\",\n });\n return;\n }\n if (typeof body.reason !== \"string\" || body.reason.trim().length === 0) {\n this.respondJson(res, 400, {\n error: \"invalid_request\",\n code: \"invalid_request\",\n message: \"reason is required for promotion\",\n });\n return;\n }\n if (!Array.isArray(body.targets) || body.targets.length === 0) {\n this.respondJson(res, 400, {\n error: \"invalid_request\",\n code: \"invalid_request\",\n message: \"targets must be a non-empty array\",\n });\n return;\n }\n const VALID_TARGETS = [\"teamProject\", \"serverShared\", \"userProject\", \"userGlobal\", \"explicit\"];\n const targets = [];\n for (const entry of body.targets) {\n if (typeof entry !== \"object\" || entry === null || typeof entry.kind !== \"string\") {\n this.respondJson(res, 400, {\n error: \"invalid_request\",\n code: \"invalid_request\",\n message: \"each target must be an object with a 'kind' string\",\n });\n return;\n }\n if (!VALID_TARGETS.includes(entry.kind)) {\n this.respondJson(res, 400, {\n error: \"invalid_request\",\n code: \"invalid_request\",\n message: `target.kind must be one of: ${VALID_TARGETS.join(\", \")}`,\n });\n return;\n }\n targets.push({\n kind: entry.kind as \"teamProject\" | \"serverShared\" | \"userProject\" | \"userGlobal\" | \"explicit\",\n namespace: typeof entry.namespace === \"string\" ? entry.namespace : undefined,\n });\n }\n try {\n // Rate-limit the promotion write, matching every other write route\n // (observe, trust-zone promotion, etc.). The check throws on limit\n // exceeded; the hit is recorded after the write succeeds.\n this.ensureWriteRateLimitAvailable(req);\n const result = await this.service.adminPromoteMemory({\n sourceMemoryId: body.sourceMemoryId,\n namespace: typeof body.namespace === \"string\" ? body.namespace : undefined,\n principal: this.resolveRequestPrincipal(req),\n sessionKey: typeof body.sessionKey === \"string\" ? body.sessionKey : undefined,\n targets,\n reason: body.reason,\n });\n // actor is derived from the authenticated principal inside adminPromoteMemory;\n this.recordWriteRateLimitHit(req);\n this.respondJson(res, 200, result);\n } catch (err) {\n if (err instanceof EngramAccessInputError) {\n this.respondJson(res, 400, {\n error: \"invalid_request\",\n code: \"invalid_request\",\n message: err.message,\n });\n return;\n }\n throw err;\n }\n return;\n }\n\n this.respondJson(res, 404, { error: \"not_found\", code: \"not_found\" });\n }\n\n private createRequestAbortSignal(req: IncomingMessage, res: ServerResponse): AbortSignal {\n const controller = new AbortController();\n const abort = () => {\n if (!controller.signal.aborted) controller.abort();\n };\n req.once(\"aborted\", abort);\n res.once(\"close\", () => {\n if (!res.writableEnded) abort();\n });\n return controller.signal;\n }\n\n /**\n * SSE handler for /engram/v1/graph/events.\n *\n * Lifecycle:\n * 1. Write SSE headers (Content-Type: text/event-stream).\n * 2. Register this response in `sseClients`.\n * 3. Resolve the namespace from the request and subscribe to THAT\n * namespace's graph event bus (Codex P1: in multi-namespace\n * deployments each namespace has its own bus keyed by its storage\n * dir — subscribing to the global root leaks events across tenants).\n * 4. On each event, add to a 200 ms batch; flush batch as a single SSE frame.\n * 5. Send heartbeat every 25 s.\n * 6. On client disconnect (req \"close\"), clean up timers and unsubscribe.\n * 7. Register the cleanup callback in `sseCleanupFns` so `stop()` can\n * release the heartbeat interval and bus subscription even when the\n * client never disconnects (Cursor review thread `access-http.ts:232`).\n */\n private async handleGraphEventsSSE(req: IncomingMessage, res: ServerResponse): Promise<void> {\n // Resolve namespace from the ?namespace= query parameter (same pattern\n // as graphSnapshot and other read endpoints). Falls back to the\n // default namespace when absent.\n const parsed = new URL(req.url ?? \"/\", `http://${hostToUrlAuthority(this.host)}`);\n const namespaceParam = parsed.searchParams.get(\"namespace\");\n const namespace = this.resolveNamespace(req, namespaceParam && namespaceParam.length > 0 ? namespaceParam : undefined);\n // Resolve to the per-namespace storage directory so the bus subscription\n // is scoped to the correct tenant (CLAUDE.md rule 42).\n // Pass the request principal so namespace ACL is enforced — without it,\n // resolveReadableNamespace throws when namespacesEnabled=true (Cursor\n // thread PRRT_kwDORJXyws59snoR / Codex thread PRRT_kwDORJXyws59soGJ).\n const principal = this.resolveRequestPrincipal(req);\n const memoryDir = await this.service.getMemoryDirForNamespace(namespace, principal);\n\n res.writeHead(200, {\n \"content-type\": \"text/event-stream; charset=utf-8\",\n \"cache-control\": \"no-cache, no-store, must-revalidate\",\n \"connection\": \"keep-alive\",\n \"x-accel-buffering\": \"no\", // prevent nginx buffering\n \"transfer-encoding\": \"chunked\",\n });\n\n // Send initial \"connected\" frame so the client knows the stream is live.\n const writeSSE = (payload: unknown): void => {\n try {\n res.write(`data: ${JSON.stringify(payload)}\\n\\n`);\n } catch {\n // client already gone — cleanup will fire via \"close\"\n }\n };\n\n writeSSE({ type: \"connected\" });\n\n this.sseClients.add(res);\n\n // --- 200 ms batch throttle -----------------------------------------------\n const flushBatch = (): void => {\n const batch = this.ssePendingBatches.get(res);\n if (!batch || batch.length === 0) return;\n this.ssePendingBatches.delete(res);\n this.sseBatchTimers.delete(res);\n writeSSE({ type: \"batch\", events: batch });\n };\n\n const unsubscribe = subscribeGraphEvents(memoryDir, (event: GraphEvent) => {\n let batch = this.ssePendingBatches.get(res);\n if (!batch) {\n batch = [];\n this.ssePendingBatches.set(res, batch);\n }\n batch.push(event);\n if (!this.sseBatchTimers.has(res)) {\n this.sseBatchTimers.set(res, setTimeout(flushBatch, 200));\n }\n });\n\n // --- 25 s heartbeat -------------------------------------------------------\n const heartbeatInterval = setInterval(() => {\n writeSSE({ type: \"heartbeat\" });\n }, 25_000);\n\n // --- Cleanup on client disconnect -----------------------------------------\n const cleanup = (): void => {\n clearInterval(heartbeatInterval);\n const timer = this.sseBatchTimers.get(res);\n if (timer !== undefined) {\n clearTimeout(timer);\n this.sseBatchTimers.delete(res);\n }\n this.ssePendingBatches.delete(res);\n unsubscribe();\n this.sseClients.delete(res);\n this.sseCleanupFns.delete(cleanup);\n try { res.end(); } catch { /* ignore */ }\n };\n\n // Register so stop() can invoke cleanup even when the client is still\n // connected (releases the heartbeat interval and bus subscription\n // before the HTTP server is torn down).\n this.sseCleanupFns.add(cleanup);\n\n req.once(\"close\", cleanup);\n req.once(\"error\", cleanup);\n }\n\n private async handleMcpRequest(\n req: IncomingMessage,\n res: ServerResponse,\n abortSignal: AbortSignal,\n ): Promise<void> {\n // Reject requests that advertise an unknown MCP protocol version in\n // the streamable-HTTP `MCP-Protocol-Version` header. Absent or\n // valid → proceed. Unknown → 400 with a JSON-RPC-shaped error so\n // the client surfaces a clear message. The supported set is\n // exported by @remnic/core's access-mcp module to keep the\n // version policy in a single place.\n const headerVersion = req.headers[\"mcp-protocol-version\"];\n if (typeof headerVersion === \"string\" && headerVersion.length > 0) {\n if (!(MCP_SUPPORTED_PROTOCOL_VERSIONS as readonly string[]).includes(headerVersion)) {\n this.respondJson(res, 400, {\n jsonrpc: \"2.0\",\n id: null,\n error: {\n code: -32000,\n message: `unsupported MCP-Protocol-Version: ${headerVersion}; supported: ${MCP_SUPPORTED_PROTOCOL_VERSIONS.join(\", \")}`,\n },\n });\n return;\n }\n }\n const body = await this.readJsonBody(req);\n\n const request = body as {\n jsonrpc?: string;\n id?: string | number | null;\n method?: string;\n params?: Record<string, unknown>;\n };\n\n const toolName = typeof request.params?.name === \"string\" ? request.params.name : \"\";\n const toolArgs = request.params?.arguments;\n const dreamsRunDryRun =\n (toolName === \"engram.dreams_run\" || toolName === \"remnic.dreams_run\") &&\n toolArgs !== null &&\n typeof toolArgs === \"object\" &&\n !Array.isArray(toolArgs) &&\n (toolArgs as { dryRun?: unknown }).dryRun === true;\n const memoryActionApplyDryRun =\n (toolName === \"engram.memory_action_apply\" || toolName === \"remnic.memory_action_apply\") &&\n toolArgs !== null &&\n typeof toolArgs === \"object\" &&\n !Array.isArray(toolArgs) &&\n (toolArgs as { dryRun?: unknown }).dryRun === true;\n const toolArgsSubcommand =\n toolArgs !== null && typeof toolArgs === \"object\" && !Array.isArray(toolArgs) && \"subcommand\" in toolArgs\n ? toolArgs.subcommand\n : undefined;\n const codingDecisionWrite =\n (toolName === \"engram.coding_decision\" || toolName === \"remnic.coding_decision\") &&\n (toolArgsSubcommand === \"record\" || toolArgsSubcommand === \"supersede\");\n const codingArchitectureWrite =\n (toolName === \"engram.coding_architecture\" || toolName === \"remnic.coding_architecture\") &&\n toolArgsSubcommand === \"refresh\";\n // codegraph parity tools (issue #1554): only mutating tools count as\n // writes — index, delete_project, ingest_traces, and manage_adr\n // (record|supersede). Read-only tools (search_graph, get_schema,\n // list_projects, etc.) must NOT hit the write quota.\n const CODEGRAPH_WRITE_TOOLS = new Set([\n \"engram.codegraph_index\", \"remnic.codegraph_index\",\n \"engram.codegraph_delete_project\", \"remnic.codegraph_delete_project\",\n \"engram.codegraph_ingest_traces\", \"remnic.codegraph_ingest_traces\",\n ]);\n const isCodegraphManageAdr =\n toolName === \"engram.codegraph_manage_adr\" || toolName === \"remnic.codegraph_manage_adr\";\n const codegraphWrite =\n CODEGRAPH_WRITE_TOOLS.has(toolName) ||\n (isCodegraphManageAdr && (toolArgsSubcommand === \"record\" || toolArgsSubcommand === \"supersede\"));\n const supportPassportQuotaLimitedWrite = this.isSupportPassportQuotaLimitedWriteTool(toolName);\n const isMcpWrite =\n request.method === \"tools/call\" &&\n (\n toolName === \"engram.memory_store\" ||\n toolName === \"remnic.memory_store\" ||\n toolName === \"engram.suggestion_submit\" ||\n toolName === \"remnic.suggestion_submit\" ||\n toolName === \"engram.observe\" ||\n toolName === \"remnic.observe\" ||\n toolName === \"engram.lcm_compaction_flush\" ||\n toolName === \"remnic.lcm_compaction_flush\" ||\n toolName === \"engram.extraction_force_flush\" ||\n toolName === \"remnic.extraction_force_flush\" ||\n toolName === \"engram.lcm_compaction_record\" ||\n toolName === \"remnic.lcm_compaction_record\" ||\n toolName === \"engram.capsule_export\" ||\n toolName === \"remnic.capsule_export\" ||\n toolName === \"engram.capsule_import\" ||\n toolName === \"remnic.capsule_import\" ||\n toolName === \"engram.entity_synthesis_run\" || toolName === \"remnic.entity_synthesis_run\" ||\n (\n !dreamsRunDryRun &&\n (toolName === \"engram.dreams_run\" || toolName === \"remnic.dreams_run\")\n ) ||\n (\n !memoryActionApplyDryRun &&\n (\n toolName === \"engram.memory_action_apply\" ||\n toolName === \"remnic.memory_action_apply\"\n )\n ) ||\n (\n toolName === \"engram.memory_correct_apply\" ||\n toolName === \"remnic.memory_correct_apply\" ||\n toolName === \"engram.memory_correct_plan\" ||\n toolName === \"remnic.memory_correct_plan\"\n ) ||\n codingDecisionWrite ||\n codingArchitectureWrite ||\n codegraphWrite ||\n supportPassportQuotaLimitedWrite\n );\n const observeSelfEnforcesQuota =\n toolName === \"engram.observe\" || toolName === \"remnic.observe\";\n const extractionForceFlushWrite =\n toolName === \"engram.extraction_force_flush\" || toolName === \"remnic.extraction_force_flush\";\n let writeRateLimitRecorded = false;\n let supportPassportQuota: WriteRateLimitReservation | undefined;\n const recordCommittedMcpWrite = extractionForceFlushWrite\n ? () => {\n if (writeRateLimitRecorded) return;\n writeRateLimitRecorded = true;\n this.recordWriteRateLimitHit(req);\n }\n : supportPassportQuotaLimitedWrite\n ? () => {\n if (writeRateLimitRecorded) return;\n writeRateLimitRecorded = true;\n supportPassportQuota?.commit();\n supportPassportQuota = undefined;\n }\n : undefined;\n if (isMcpWrite && !observeSelfEnforcesQuota) {\n if (supportPassportQuotaLimitedWrite) supportPassportQuota = this.reserveWriteRateLimitSlot(req);\n else this.ensureWriteRateLimitAvailable(req);\n }\n\n const sessionId = (() => {\n const raw = req.headers[\"mcp-session-id\"];\n return typeof raw === \"string\" ? raw.trim() : undefined;\n })();\n const mcpCorrelationId = correlationIdStore.getStore() ?? randomUUID();\n const requestIdentity = this.resolveRequestIdentity(req);\n // Per-token namespace enforcement on the MCP dispatch path (issue #1850\n // finding 1): MCP `tools/call` previously never applied the namespace\n // allow-list, so a namespace-scoped bearer could reach another tenant via\n // tool args or the adapter `namespaceOverride`. Run the SAME effective-\n // namespace chokepoint the REST surface runs. The effective namespace is\n // the explicit tool arg, else the adapter override, else the server\n // default (op.run with no namespace reaches the default tenant). Only\n // namespace-scoped tools are gated — namespace-agnostic tools (peer/\n // wearables) stay ungated, matching the REST surface. Fail closed (403)\n // BEFORE op.run; no-op for unrestricted tokens.\n if (request.method === \"tools/call\" && this.mcpServer.toolAcceptsNamespace(toolName)) {\n const mcpExplicitNamespace =\n toolArgs !== null && typeof toolArgs === \"object\" && !Array.isArray(toolArgs)\n && typeof (toolArgs as Record<string, unknown>).namespace === \"string\"\n && ((toolArgs as Record<string, unknown>).namespace as string).length > 0\n ? ((toolArgs as Record<string, unknown>).namespace as string)\n : undefined;\n enforceNamespaceAllowList(\n tokenCapabilityStore.getStore(),\n mcpExplicitNamespace ?? requestIdentity.namespace,\n this.service.configRef?.defaultNamespace,\n );\n }\n const response = await this.mcpServer.handleRequest(request, {\n principalOverride: requestIdentity.principal,\n namespaceOverride: requestIdentity.namespace,\n sessionKeyOverride: requestIdentity.sessionKey,\n sessionId,\n correlationId: mcpCorrelationId,\n enforceWriteQuota: observeSelfEnforcesQuota\n ? () => this.ensureWriteRateLimitAvailable(req)\n : undefined,\n recordWriteCommit: recordCommittedMcpWrite,\n sourceConnector: this.resolveConnector(req),\n abortSignal,\n }).catch((error) => {\n supportPassportQuota?.release();\n throw error;\n });\n\n if (isMcpWrite && response !== null) {\n const result = (response as Record<string, unknown>).result as Record<string, unknown> | undefined;\n const isError = result?.isError === true;\n const structured = result?.structuredContent as\n | { dryRun?: boolean; idempotencyReplay?: boolean; ok?: boolean }\n | undefined;\n // Rejected codegraph calls carry { ok: false } in structuredContent\n // (confirm_required, package_missing, runtime_unavailable, ...). The\n // MCP layer sets isError:false for these, so without this guard they\n // would consume the write quota despite no mutation occurring\n // (issue #1554 review thread: don't bill rejected calls as writes).\n const isRejectedCodegraph = structured?.ok === false;\n // A write tool that succeeded without structuredContent (e.g.\n // memory_correct_apply, which returns a CorrectionOutcome) still\n // consumed a write — count it. Tools WITH structuredContent use the\n // dryRun/idempotencyReplay guards.\n const counts = structured ? this.shouldCountWriteRateLimit(structured) : true;\n if (!writeRateLimitRecorded && !isError && !isRejectedCodegraph && counts) {\n if (supportPassportQuota) {\n supportPassportQuota.commit();\n supportPassportQuota = undefined;\n } else {\n this.recordWriteRateLimitHit(req);\n }\n writeRateLimitRecorded = true;\n }\n }\n supportPassportQuota?.release();\n // A mutating tool may have committed just before the client disconnected.\n // Record that side effect above, then honor cancellation before emitting\n // any response. Read-only calls reach this guard without accounting.\n if (abortSignal.aborted) {\n throw isAbortError(abortSignal.reason)\n ? abortSignal.reason\n : abortError(\"HTTP client disconnected\");\n }\n if (response === null) {\n res.statusCode = 202;\n res.end();\n return;\n }\n // If this was an initialize response, pop the session ID keyed by\n // correlation ID (unique per HTTP request, not client-chosen JSON-RPC id).\n const assignedSessionId = this.mcpServer.popInitSessionId(mcpCorrelationId);\n if (assignedSessionId) {\n res.setHeader(\"mcp-session-id\", assignedSessionId);\n }\n this.respondJson(res, 200, response);\n }\n\n protected respondJson(res: ServerResponse, status: number, payload: unknown): void {\n const body = JSON.stringify(payload, null, 2);\n res.statusCode = status;\n res.setHeader(\"content-type\", \"application/json; charset=utf-8\");\n res.setHeader(\"content-length\", String(Buffer.byteLength(body)));\n const cid = correlationIdStore.getStore();\n if (cid) {\n res.setHeader(\"x-request-id\", cid);\n }\n res.end(body);\n }\n\n private respondBinary(\n res: ServerResponse,\n status: number,\n body: Buffer,\n headers: Record<string, string> = {},\n ): void {\n res.statusCode = status;\n res.setHeader(\"content-type\", \"application/octet-stream\");\n res.setHeader(\"content-length\", String(body.length));\n for (const [key, value] of Object.entries(headers)) {\n res.setHeader(key, value);\n }\n const cid = correlationIdStore.getStore();\n if (cid) {\n res.setHeader(\"x-request-id\", cid);\n }\n res.end(body);\n }\n\n private async handleAdminConsole(\n req: IncomingMessage,\n res: ServerResponse,\n pathname: string,\n ): Promise<boolean> {\n if (req.method !== \"GET\") return false;\n if (pathname === \"/remnic/ui\" || pathname === \"/engram/ui\") {\n res.statusCode = 301;\n res.setHeader(\"location\", pathname + \"/\");\n res.end();\n return true;\n }\n if (pathname === \"/remnic/ui/relay\" || pathname === \"/engram/ui/relay\") {\n res.statusCode = 301;\n res.setHeader(\"location\", pathname + \"/\");\n res.end();\n return true;\n }\n if (pathname === \"/remnic/ui/\" || pathname === \"/engram/ui/\") {\n await this.respondAdminConsoleShell(req, res, pathname);\n return true;\n }\n if (pathname === \"/remnic/ui/relay/\" || pathname === \"/engram/ui/relay/\") {\n await this.respondAdminConsoleShell(req, res, pathname, \"relay/index.html\");\n return true;\n }\n if (pathname === \"/remnic/ui/app.js\" || pathname === \"/engram/ui/app.js\") {\n await this.respondStatic(res, path.join(this.adminConsolePublicDir, \"app.js\"), \"application/javascript; charset=utf-8\");\n return true;\n }\n const relayAsset = RELAY_ADMIN_CONSOLE_ASSETS.get(pathname.split(\"/\").at(-1) ?? \"\");\n const isRelayAsset = pathname.startsWith(\"/remnic/ui/relay/\") || pathname.startsWith(\"/engram/ui/relay/\");\n if (isRelayAsset && relayAsset && pathname.split(\"/\").length === 5) {\n const fileName = pathname.split(\"/\").at(-1);\n if (fileName) {\n await this.respondStatic(res, path.join(this.adminConsolePublicDir, \"relay\", fileName), relayAsset);\n return true;\n }\n }\n return false;\n }\n\n protected async respondAdminConsoleShell(\n req: IncomingMessage,\n res: ServerResponse,\n pathname: string,\n relativePath = \"index.html\",\n allowPrefill = true,\n ): Promise<void> {\n try {\n let body = await readFile(path.join(this.adminConsolePublicDir, relativePath), \"utf-8\");\n const matched = this.resolveAuthorizedEntry(req, pathname);\n const canPrefillToken =\n allowPrefill &&\n this.adminConsolePrefillToken &&\n matched !== null &&\n matched.capabilities === undefined &&\n this.timingSafeStringEqual(matched.token, this.adminConsolePrefillToken);\n if (canPrefillToken) {\n const serializedToken = serializeInlineScriptValue(this.adminConsolePrefillToken);\n const script = `<script>(function(token,script){const key=\"__REMNIC_ADMIN_CONSOLE_PREFILL_TOKEN__\";const clear=function(){token=\"\";try{delete window[key]}catch{window[key]=\"\"}};window.addEventListener(\"pagehide\",clear,{once:true});window.addEventListener(\"beforeunload\",clear,{once:true});try{if(new URLSearchParams(location.hash.slice(1)).has(\"secret\")){clear();return}Object.defineProperty(window,key,{configurable:true,get:function(){const value=token;clear();return value}})}finally{if(script){script.textContent=\"\";script.remove()}}})(${serializedToken},document.currentScript);</script>`;\n body = body.includes(\"</head>\")\n ? body.replace(\"</head>\", `${script}</head>`)\n : `${script}${body}`;\n res.setHeader(\"cache-control\", \"private, no-store\");\n }\n res.setHeader(\"vary\", \"authorization\");\n res.statusCode = 200;\n res.setHeader(\"content-type\", \"text/html; charset=utf-8\");\n res.setHeader(\"content-length\", String(Buffer.byteLength(body)));\n res.end(body);\n } catch {\n this.respondJson(res, 404, { error: \"not_found\" });\n }\n }\n\n protected async respondStatic(res: ServerResponse, filePath: string, contentType: string): Promise<void> {\n try {\n const body = await readFile(filePath, \"utf-8\");\n res.statusCode = 200;\n res.setHeader(\"content-type\", contentType);\n res.setHeader(\"content-length\", String(Buffer.byteLength(body)));\n res.end(body);\n } catch {\n this.respondJson(res, 404, { error: \"not_found\" });\n }\n }\n\n protected async readJsonBody(\n req: IncomingMessage,\n maxBodyBytes = this.maxBodyBytes,\n ): Promise<Record<string, unknown>> {\n const encoding = (this.readOptionalHeader(req, \"content-encoding\") ?? \"identity\").toLowerCase();\n if (encoding !== \"identity\" && encoding !== \"gzip\") {\n throw new HttpError(415, \"unsupported_content_encoding\", \"unsupported_content_encoding\");\n }\n const chunks: Buffer[] = [];\n let total = 0;\n for await (const chunk of req) {\n const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);\n total += buffer.length;\n if (total > maxBodyBytes) {\n throw new HttpError(413, \"request_body_too_large\", \"request_body_too_large\");\n }\n chunks.push(buffer);\n }\n if (chunks.length === 0) return {};\n let body = Buffer.concat(chunks, total);\n if (encoding === \"gzip\") {\n try {\n body = gunzipSync(body, { maxOutputLength: maxBodyBytes });\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ERR_BUFFER_TOO_LARGE\") {\n throw new HttpError(413, \"request_body_too_large\", \"request_body_too_large\");\n }\n throw new HttpError(400, \"invalid_gzip_body\", \"invalid_gzip_body\");\n }\n if (body.byteLength > maxBodyBytes) {\n throw new HttpError(413, \"request_body_too_large\", \"request_body_too_large\");\n }\n }\n const raw = body.toString(\"utf-8\").trim();\n if (raw.length === 0) return {};\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch {\n throw new HttpError(400, \"invalid_json\", \"invalid_json\");\n }\n if (!parsed || typeof parsed !== \"object\" || Array.isArray(parsed)) {\n throw new HttpError(400, \"invalid_json_object\", \"invalid_json_object\");\n }\n return parsed as Record<string, unknown>;\n }\n\n private async readBinaryBody(req: IncomingMessage, maxBytes: number): Promise<Buffer> {\n const chunks: Buffer[] = [];\n let total = 0;\n for await (const chunk of req) {\n const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);\n total += buffer.length;\n if (total > maxBytes) {\n throw new HttpError(413, \"request_body_too_large\", \"request_body_too_large\");\n }\n chunks.push(buffer);\n }\n return Buffer.concat(chunks, total);\n }\n\n private readRequiredHeader(req: IncomingMessage, name: string): string {\n const value = this.readOptionalHeader(req, name);\n if (value === undefined || value.length === 0) {\n throw new EngramAccessInputError(`${name} header is required`);\n }\n return value;\n }\n\n private readOptionalHeader(req: IncomingMessage, name: string): string | undefined {\n const raw = req.headers[name.toLowerCase()];\n if (Array.isArray(raw)) return raw[0]?.trim() || undefined;\n return raw?.trim() || undefined;\n }\n\n private readRequiredDecodedHeader(req: IncomingMessage, name: string): string {\n const raw = this.readRequiredHeader(req, name);\n try {\n return decodeURIComponent(raw);\n } catch {\n throw new EngramAccessInputError(`${name} header is not valid percent-encoded input`);\n }\n }\n\n private readRequiredIntegerHeader(req: IncomingMessage, name: string): number {\n const raw = this.readRequiredHeader(req, name);\n const parsed = Number(raw);\n if (!Number.isInteger(parsed) || parsed < 0) {\n throw new EngramAccessInputError(`${name} header must be a non-negative integer`);\n }\n return parsed;\n }\n\n private readOptionalIntegerHeader(req: IncomingMessage, name: string): number | undefined {\n const raw = this.readOptionalHeader(req, name);\n if (raw === undefined) return undefined;\n const parsed = Number(raw);\n if (!Number.isInteger(parsed) || parsed < 0) {\n throw new EngramAccessInputError(`${name} header must be a non-negative integer`);\n }\n return parsed;\n }\n\n private readRequiredNumberHeader(req: IncomingMessage, name: string): number {\n const raw = this.readRequiredHeader(req, name);\n const parsed = Number(raw);\n if (!Number.isFinite(parsed) || parsed < 0) {\n throw new EngramAccessInputError(`${name} header must be a non-negative finite number`);\n }\n return parsed;\n }\n private parseOptionalBooleanHeader(\n req: IncomingMessage,\n name: string,\n defaultValue: boolean,\n ): boolean {\n const raw = this.readOptionalHeader(req, name);\n if (raw === undefined) return defaultValue;\n if (raw === \"true\") return true;\n if (raw === \"false\") return false;\n throw new EngramAccessInputError(`${name} header must be one of: true, false`);\n }\n private lifecycleFlushDeps(req: IncomingMessage, res: ServerResponse): LifecycleFlushHttpDeps {\n const readValidatedBody = ((schemaName: SchemaName) => this.readValidatedBody(req, schemaName)) as LifecycleFlushHttpDeps[\"readValidatedBody\"];\n return { service: this.service, defaultNamespace: this.service.configRef?.defaultNamespace,\n enforceTokenOp: (op) => this.enforceTokenOp(op),\n readValidatedBody,\n ensureWriteRateLimitAvailable: () => this.ensureWriteRateLimitAvailable(req),\n resolveNamespace: (namespace) => this.resolveNamespace(req, namespace),\n resolveRequestPrincipal: () => this.resolveRequestPrincipal(req),\n recordWriteRateLimitHit: () => this.recordWriteRateLimitHit(req),\n respondJson: (payload) => this.respondJson(res, 200, payload),\n };\n }\n private async readValidatedBody<S extends SchemaName>(\n req: IncomingMessage,\n schemaName: S,\n maxBodyBytes?: number,\n ): Promise<SchemaTypeFor<S>> {\n const raw = await this.readJsonBody(req, maxBodyBytes);\n const result = validateRequest(schemaName, raw);\n if (!result.success) {\n throw new HttpError(400, result.error.error, \"validation_error\", result.error.details);\n }\n return result.data as SchemaTypeFor<S>;\n }\n\n /**\n * Build the WWW-Authenticate challenge string for 401 responses.\n * When `resourceMetadataUrl` is configured, includes the RFC 9728\n * `resource_metadata` parameter so MCP clients (e.g. ChatGPT) can\n * discover the OAuth 2.0 protected-resource metadata document.\n * Otherwise the bare `Bearer` challenge is returned (unchanged).\n */\n private bearerChallenge(): string {\n if (this.resourceMetadataUrl) {\n return `Bearer resource_metadata=\"${this.resourceMetadataUrl}\"`;\n }\n return \"Bearer\";\n }\n\n private isAuthorized(req: IncomingMessage, pathname?: string): boolean {\n return this.resolveAuthorizedEntry(req, pathname) !== null;\n }\n\n /**\n * Per-request cache of the matched token entry (the entry whose token\n * matched the bearer credential, BEFORE any path-policy check). Pinning\n * the entry to the first read means authorization, capability\n * enforcement, and connector provenance all observe the SAME token-store\n * snapshot — a rotation between the auth check and the write handler can\n * no longer stamp the wrong connector (PR #1852 race).\n */\n private matchedEntryCache = new WeakMap<\n IncomingMessage,\n { token: string; connector?: string; capabilities?: TokenCapabilities } | null\n >();\n\n /**\n * Resolve the matched token entry for this request, caching the result so\n * every downstream consumer (authorization, capability enforcement,\n * connector provenance) sees the same snapshot entry (PR #1852).\n */\n private resolveMatchedEntry(\n req: IncomingMessage,\n pathname?: string,\n ): { token: string; connector?: string; capabilities?: TokenCapabilities } | null {\n if (this.matchedEntryCache.has(req)) {\n return this.matchedEntryCache.get(req) ?? null;\n }\n const entry = this.computeMatchedEntry(req, pathname);\n this.matchedEntryCache.set(req, entry);\n return entry;\n }\n\n /**\n * Find the entry whose token matches the request's bearer credential.\n * Static operator tokens (`authToken`/`authTokens`) and the string-token\n * getter carry no capabilities ⇒ unrestricted. Dynamic entry-based tokens\n * capture connector identity and capabilities. A corrupt or unreadable\n * token store returns null rather than propagating an error — provenance\n * must never block an already-authenticated request.\n */\n private computeMatchedEntry(\n req: IncomingMessage,\n pathname?: string,\n ): { token: string; connector?: string; capabilities?: TokenCapabilities } | null {\n if (\n !this.authToken &&\n this.authTokens.length === 0 &&\n !this.authTokensGetter &&\n !this.authTokenEntriesGetter\n ) {\n return null;\n }\n // Primary path: Authorization: Bearer <token> header.\n const raw = req.headers.authorization;\n let candidate: string | null = null;\n if (raw) {\n const separator = raw.indexOf(\" \");\n if (separator > 0) {\n const scheme = raw.slice(0, separator).toLowerCase();\n if (scheme === \"bearer\") {\n candidate = raw.slice(separator + 1).trim();\n }\n }\n }\n // Fallback: ?token= query parameter — ONLY accepted for the SSE\n // endpoint (/engram/v1/graph/events). EventSource cannot set request\n // headers, so SSE clients must pass the token via the query string.\n // Allowing this fallback on every endpoint would let a CSRF attacker\n // embed a credentialed URL anywhere — restricting it to SSE limits the\n // attack surface (Codex P2 review thread `access-http.ts:1406`; Cursor\n // review thread `access-http.ts:1412`). Authorization header always\n // wins; timing-safe compare used below.\n if (!candidate && pathname === \"/engram/v1/graph/events\") {\n try {\n const parsed = new URL(req.url ?? \"/\", `http://${hostToUrlAuthority(this.host)}`);\n const queryToken = parsed.searchParams.get(\"token\");\n if (queryToken && queryToken.length > 0) {\n candidate = queryToken;\n }\n } catch {\n // Malformed URL — don't authenticate\n }\n }\n if (!candidate) return null;\n const token = candidate;\n // Check primary token (static operator token — no capabilities ⇒ unrestricted)\n if (this.authToken && this.timingSafeStringEqual(token, this.authToken)) {\n return { token };\n }\n // Check static multi-connector tokens\n for (const valid of this.authTokens) {\n if (this.timingSafeStringEqual(token, valid)) return { token: valid };\n }\n // Entry-based dynamic tokens are AUTHORITATIVE when configured: the\n // dynamic-token decision ends here (no fall-through to the string\n // getter, which carries no identity and would bypass the policy).\n // Validation and connector identity come from the same snapshot entry,\n // so a scope policy can never observe a token fresher than the\n // identity it scopes (mint/revoke coherence). Capabilities ride on the\n // same entry so enforcement can never lag the token that validated.\n if (this.authTokenEntriesGetter) {\n try {\n for (const entry of this.authTokenEntriesGetter()) {\n if (!this.timingSafeStringEqual(token, entry.token)) continue;\n return { token: entry.token, connector: entry.connector, capabilities: entry.capabilities };\n }\n } catch {\n // Corrupt or unreadable tokens.json — no match.\n }\n return null;\n }\n // String-token getter (no identity, no policy) — only consulted when\n // no entry getter is configured.\n if (this.authTokensGetter) {\n for (const valid of this.authTokensGetter()) {\n if (this.timingSafeStringEqual(token, valid)) return { token: valid };\n }\n }\n return null;\n }\n\n /**\n * Resolve the presenting token's entry for an authorized request, or null.\n * Applies the path-policy gate (if configured) on top of the per-request\n * cached matched entry so the identity that is authorized is the same one\n * whose connector later stamps frontmatter. Static operator tokens and the\n * string-token getter carry no capabilities ⇒ unrestricted.\n */\n private resolveAuthorizedEntry(\n req: IncomingMessage,\n pathname?: string,\n ): { token: string; connector?: string; capabilities?: TokenCapabilities } | null {\n const matched = this.resolveMatchedEntry(req, pathname);\n if (!matched) return null;\n // Apply the path-policy gate for dynamic entry-based tokens.\n if (\"connector\" in matched && this.tokenPathPolicy) {\n // Fail closed: a policy without a connector identity denies.\n if (typeof matched.connector !== \"string\" || matched.connector.length === 0) return null;\n return this.tokenPathPolicy(matched.connector, pathname) ? matched : null;\n }\n return matched;\n }\n\n /**\n * Resolve the presenting token's capabilities for this request, or\n * undefined when the token is unrestricted (legacy / static operator /\n * explicit-unrestricted record). Reads from the per-request cached matched\n * entry so capabilities come from the same snapshot as authorization and\n * connector provenance (PR #1852).\n */\n private resolveTokenCapabilities(\n req: IncomingMessage,\n pathname?: string,\n ): TokenCapabilities | undefined {\n return this.resolveMatchedEntry(req, pathname)?.capabilities;\n }\n\n /**\n * Enforce the presenting token's ops allow-list for an HTTP route that\n * dispatches directly to the service (not through the boundary). Reads the\n * per-request capability context set in `handle`; unrestricted tokens\n * pass. Throws {@link EngramAccessForbiddenError} (→ 403) when a scoped\n * token calls a non-permitted op (issue #1837).\n */\n protected enforceTokenOp(op: OperationName): void {\n void getOperation(op); // preserve the registration side-effect assertion\n assertOperationAllowed(tokenCapabilityStore.getStore(), op);\n }\n\n private enforceTokenAnyOf(ops: readonly OperationName[]): void {\n for (const op of ops) void getOperation(op);\n const capabilities = tokenCapabilityStore.getStore();\n if (ops.some((op) => capabilityAllowsOp(capabilities, op))) return;\n throw new EngramAccessForbiddenError(\n `token is not permitted to call any required operation: ${ops.join(\", \")}`,\n );\n }\n \n /**\n * Operator/admin routes are unrestricted-only surfaces: a scoped\n * (least-privileged) token must NOT reach them (issue #1837). Legacy and\n * explicit-unrestricted tokens pass. Throws EngramAccessForbiddenError (→403).\n */\n private requireOperatorToken(): void {\n if (isCapabilityRestricted(tokenCapabilityStore.getStore())) {\n throw new EngramAccessForbiddenError(\n \"token is scoped and may not access operator/admin routes\",\n );\n }\n }\n /**\n * Resolve the connector identity for the request's bearer token (Phase 1\n * provenance). Reuses the per-request cached matched entry so a token\n * rotation between the auth check and the write handler cannot stamp the\n * wrong connector (PR #1852 race). Returns `undefined` for operator-\n * supplied static tokens or when no entry getter is configured — those\n * writes are operator-initiated.\n */\n private resolveConnector(req: IncomingMessage): string | undefined {\n return this.resolveMatchedEntry(req)?.connector;\n }\n\n private timingSafeStringEqual(a: string, b: string): boolean {\n const left = this.encodeSecret(a);\n const right = this.encodeSecret(b);\n if (!left || !right) return false;\n return timingSafeEqual(left, right);\n }\n\n private encodeSecret(value: string): Buffer | null {\n const encoded = Buffer.from(value, \"utf-8\");\n if (encoded.length > 1024) return null;\n const out = Buffer.alloc(2 + 1024);\n out.writeUInt16BE(encoded.length, 0);\n encoded.copy(out, 2);\n return out;\n }\n\n private writeResponseStatus(response: { dryRun: boolean; status: string }): number {\n if (response.dryRun === true) return 200;\n if (response.status === \"stored\" || response.status === \"queued_for_review\") return 201;\n return 200;\n }\n\n protected ensureWriteRateLimitAvailable(req?: IncomingMessage): void {\n if (!this.writeLimiter.hasCapacity(this.principalForRateLimit(req))) {\n throw new HttpError(429, \"write_rate_limited\", \"write_rate_limited\");\n }\n }\n\n protected recordWriteRateLimitHit(req?: IncomingMessage): void {\n this.writeLimiter.record(this.principalForRateLimit(req));\n }\n\n protected reserveWriteRateLimitSlot(req?: IncomingMessage): WriteRateLimitReservation {\n const reservation = this.writeLimiter.reserve(this.principalForRateLimit(req));\n if (!reservation) {\n throw new HttpError(429, \"write_rate_limited\", \"write_rate_limited\");\n }\n return reservation;\n }\n\n private principalForRateLimit(req?: IncomingMessage): string | undefined {\n if (!req) return undefined;\n // Fall back to the authenticated connector identity when no principal is\n // resolved, so per-connector bearer tokens are isolated from each other\n // even without a principal header/server principal (issue #2029 review).\n return this.resolveRequestPrincipal(req) ?? this.resolveConnector(req);\n }\n\n private shouldCountWriteRateLimit(response: { dryRun?: boolean; idempotencyReplay?: boolean }): boolean {\n return response.dryRun !== true && response.idempotencyReplay !== true;\n }\n\n /**\n * Map wearables validation errors (WearablesInputError — invalid\n * params, unknown/disabled sources, missing connector packages) to a\n * 400 response. Returns false for everything else so backend faults\n * keep flowing to the global 500 handler.\n */\n private respondWearablesError(res: ServerResponse, err: unknown): boolean {\n if (err instanceof WearablesInputError) {\n this.respondJson(res, 400, {\n error: \"invalid_request\",\n code: \"invalid_request\",\n message: err.message,\n });\n return true;\n }\n return false;\n }\n}\n","/**\n * Error thrown by meeting surfaces for caller-correctable problems: invalid\n * dates/ids, unknown commands/flags, or a missing record. Transport layers map\n * this to 400-class responses; anything else is a backend fault (500). Mirrors\n * `WearablesInputError` so the meetings surfaces follow the same house style.\n */\n\nexport class MeetingsInputError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"MeetingsInputError\";\n }\n}\n","/**\n * Meetings HTTP route glue (issue #1900) — the route bodies extracted from\n * access-http.ts so the surface file stays under its structural ceiling. The\n * thin inline hooks in access-http.ts keep the pathname/method match + the\n * `enforceTokenOp(\"meetings_*\")` boundary-dispatch marker (required by the\n * surface-catalog fitness test) and delegate the body here.\n *\n * `MeetingsInputError` (invalid dates/ids) maps to a 400; everything else\n * rethrows so backend faults keep flowing to the global 500 handler. Behaviour,\n * validation, and `meetings.enabled` gating live in MeetingsService — these\n * functions only translate transport shape.\n */\n\nimport type { IncomingMessage, ServerResponse } from \"node:http\";\nimport { EngramAccessInputError, type WearablesMeetingsScope } from \"../access-service.js\";\nimport { MeetingsInputError } from \"./errors.js\";\n\ntype RespondJson = (res: ServerResponse, status: number, payload: unknown) => void;\ntype ReadJsonBody = (req: IncomingMessage) => Promise<unknown>;\n\n/** Minimal meetings surface the HTTP glue drives (satisfied by EngramAccessService). */\nexport interface MeetingsHttpService {\n meetingsList(date?: string, scope?: WearablesMeetingsScope): Promise<unknown>;\n meetingsGet(id: string, scope?: WearablesMeetingsScope): Promise<unknown>;\n meetingsBuild(date: string, scope?: WearablesMeetingsScope): Promise<unknown>;\n}\n\nfunction respondMeetingsError(respondJson: RespondJson, res: ServerResponse, err: unknown): boolean {\n if (err instanceof MeetingsInputError) {\n respondJson(res, 400, { error: \"invalid_request\", code: \"invalid_request\", message: err.message });\n return true;\n }\n return false;\n}\n\n/**\n * Decode a meeting `:id` URL path segment, mapping malformed percent-encoded\n * input (e.g. `%E0%A4%A`) to a 400 `MeetingsInputError` rather than letting the\n * `URIError` bubble up to the global 500 handler — mirrors the access-http\n * `decode*Segment` helpers.\n */\nfunction decodeMeetingIdSegment(raw: string): string {\n try {\n return decodeURIComponent(raw);\n } catch {\n throw new MeetingsInputError(\"meeting id path segment is not valid percent-encoded input\");\n }\n}\n\n/**\n * Per-principal write-quota hooks the build route shares with every other\n * mutating REST route: `enforceQuota` throws a 429 when the principal is over\n * budget; `recordHit` accounts the successful write. Injected from access-http\n * so the quota state stays owned by the server (issue #1937).\n */\nexport interface MeetingsWriteQuotaHooks {\n enforceQuota(): void;\n recordHit(): void;\n}\n\nexport async function respondMeetingsList(\n res: ServerResponse,\n respondJson: RespondJson,\n service: MeetingsHttpService,\n date: string | undefined,\n scope?: WearablesMeetingsScope,\n): Promise<void> {\n try {\n respondJson(res, 200, await service.meetingsList(date, scope));\n } catch (err) {\n if (respondMeetingsError(respondJson, res, err)) return;\n throw err;\n }\n}\n\nexport async function respondMeetingsGet(\n res: ServerResponse,\n respondJson: RespondJson,\n service: MeetingsHttpService,\n rawId: string,\n scope?: WearablesMeetingsScope,\n): Promise<void> {\n try {\n respondJson(res, 200, await service.meetingsGet(decodeMeetingIdSegment(rawId), scope));\n } catch (err) {\n if (respondMeetingsError(respondJson, res, err)) return;\n throw err;\n }\n}\n\nexport async function respondMeetingsBuild(\n req: IncomingMessage,\n res: ServerResponse,\n respondJson: RespondJson,\n readJsonBody: ReadJsonBody,\n service: MeetingsHttpService,\n quota: MeetingsWriteQuotaHooks,\n scopeFor?: (bodyNamespace?: string, bodySessionKey?: string) => WearablesMeetingsScope,\n): Promise<void> {\n const body = (await readJsonBody(req)) as Record<string, unknown>;\n const raw = body.date;\n if (raw !== undefined && raw !== null && raw !== \"\" && typeof raw !== \"string\") {\n throw new EngramAccessInputError(`date must be a string (got ${JSON.stringify(raw)})`);\n }\n const date = raw === undefined || raw === null || raw === \"\" ? undefined : raw;\n if (date === undefined) {\n throw new EngramAccessInputError(\"date is required (YYYY-MM-DD)\");\n }\n // Build persists/deletes records, writes memories, and reindexes — a mutating\n // route, so it carries the same per-principal write quota as every other\n // write (capsule import/export, admin promote). Enforce before the write,\n // account the hit after it succeeds (issue #1937).\n quota.enforceQuota();\n const scope = scopeFor?.(\n typeof body.namespace === \"string\" ? body.namespace : undefined,\n typeof body.sessionKey === \"string\" ? body.sessionKey : undefined,\n );\n try {\n const result = await service.meetingsBuild(date, scope);\n quota.recordHit();\n respondJson(res, 200, result);\n } catch (err) {\n if (respondMeetingsError(respondJson, res, err)) return;\n throw err;\n }\n}\n","/**\n * Chat HTTP handler (issue #1583 PR 3; deferred items #1685 / #1687).\n *\n * Implements the HTTP backend for the admin console Chat pane:\n * - POST /engram/v1/chat/message — send a message, get a reply\n * - GET /engram/v1/chat/events/:chatSessionId — SSE stream for replies\n *\n * Auth: same Bearer token as every other admin endpoint (loopback bearer).\n * Per-session isolation: every request verifies the session's principal\n * matches the caller (rule 42/47).\n *\n * Deferred items wired here (issues #1685 / #1687):\n * - The HTTP message handler delegates to the shared `processChatMessage`\n * (Thread 18) so session/engine/transcript construction is identical to\n * the MCP surface, instead of re-implementing it.\n * - Concurrent identical POSTs are coalesced by an in-flight dedup keyed on\n * `memoryDir + chatSessionId + principal + message` so a double-submit\n * processes exactly once (issue #1687 Thread 18 / #1685). The memoryDir\n * scopes the key per store (AGENTS.md State Scoping); an absent principal\n * is encoded distinctly so it can never alias a real principal string.\n * - The SSE stream subscribes to live transcript appends and pushes new\n * entries to connected clients (issue #1685 item 2 / #1687 Thread 8).\n * Subscription is established before the transcript snapshot is read so no\n * concurrent append is missed (cursor Bugbot race fix); the burst drains\n * the buffer only after switching to live mode so no buffered entry is\n * dropped. The disconnect cleanup is registered immediately and guarded\n * by a `closed` flag so an early close cannot leak the heartbeat or write\n * to an ended response.\n *\n * This module is imported by access-http.ts with thin route registration —\n * the god-file ratchet (#1520) tracks access-http.ts LOC.\n */\n\nimport type { IncomingMessage, ServerResponse } from \"node:http\";\nimport { createHash } from \"node:crypto\";\n\nimport type { EngramAccessService } from \"../access-service.js\";\nimport type { ChatConfig, ChatTranscriptEntry, ChatTurnResult } from \"./chat-types.js\";\nimport { processChatMessage } from \"./chat-factory.js\";\nimport {\n loadChatSession,\n sessionBelongsToPrincipal,\n subscribeChatTranscript,\n} from \"./chat-session.js\";\n\nexport interface ChatHttpHandlerOptions {\n service: EngramAccessService;\n config: ChatConfig | undefined;\n memoryDir: string;\n /**\n * Optional hook the host server supplies so the SSE handler can register\n * its disconnect cleanup with the server's stop() set (cursor Medium\n * review). Returns an unregister function the handler calls on normal\n * client disconnect. When omitted, cleanup runs only on req 'close'.\n */\n registerSseCleanup?: (cleanup: () => void) => () => void;\n}\n\n// ---------------------------------------------------------------------------\n// In-flight request dedup (issue #1687 Thread 18 / #1685)\n// ---------------------------------------------------------------------------\n\n/**\n * Pending chat-message promises keyed by\n * `memoryDir:chatSessionId:principal:messageHash`. A concurrent identical\n * POST joins the in-flight promise instead of re-processing (no second LLM\n * call, no second transcript append). Entries are always removed via\n * `finally` so the map cannot leak across requests.\n *\n * The memoryDir is part of the key so two Remnic stores in one process\n * cannot share a promise (AGENTS.md State Scoping). Only requests targeting\n * an existing `chatSessionId` are coalesced: when no session id is supplied\n * each request legitimately mints its own session, so identical message\n * bodies are genuinely distinct turns.\n */\nconst chatInFlight = new Map<string, Promise<ChatTurnResult>>();\n\n/**\n * Encode the principal into a fingerprint component where an absent principal\n * occupies a distinct namespace from any real principal string (control-byte\n * prefix), so a no-principal request can never coalesce with a request whose\n * principal is literally `\"_\"` (or any other string) and reuse its authorized\n * promise (codex P2 review thread).\n */\nfunction principalFingerprintComponent(principal: string | undefined): string {\n return principal === undefined ? \"\\x00absent\" : `\\x01${principal}`;\n}\n\nfunction chatDedupFingerprint(memoryDir: string, chatSessionId: string, principal: string | undefined, message: string): string {\n // sha256 keeps the key bounded for long messages; the principal component\n // is distinct per principal (incl. absent) so two callers targeting the\n // same session id can never share a result — the wrong principal still\n // independently hits access_denied inside processChatMessage.\n const messageHash = createHash(\"sha256\").update(message, \"utf8\").digest(\"hex\").slice(0, 32);\n return `${memoryDir}:${chatSessionId}:${principalFingerprintComponent(principal)}:${messageHash}`;\n}\n\n/**\n * Run `processChatMessage` with concurrent-identical-request coalescing.\n * Distinct messages (or distinct sessions / principals / stores) never collide.\n */\nfunction processChatMessageDedup(opts: {\n service: EngramAccessService;\n config: ChatConfig | undefined;\n memoryDir: string;\n message: string;\n chatSessionId?: string;\n principal?: string;\n}): Promise<ChatTurnResult> {\n // No session id → no coalescing (each request creates its own session).\n if (!opts.chatSessionId) {\n return processChatMessage(opts);\n }\n const fp = chatDedupFingerprint(opts.memoryDir, opts.chatSessionId, opts.principal, opts.message);\n const existing = chatInFlight.get(fp);\n if (existing) return existing;\n const pending = processChatMessage(opts).finally(() => {\n chatInFlight.delete(fp);\n });\n chatInFlight.set(fp, pending);\n return pending;\n}\n\n// ---------------------------------------------------------------------------\n// POST /engram/v1/chat/message\n// ---------------------------------------------------------------------------\n\n/**\n * Handle POST /engram/v1/chat/message.\n *\n * Body: `{ message: string, chatSessionId?: string }`\n * Response: `{ reply: string, chatSessionId: string, pendingPlan?: {...} }`\n *\n * Boundary checks (chat-disabled / missing message / no-LLM) run before\n * delegation so each maps to a precise HTTP status without spinning up a\n * session. Session/engine work is delegated to `processChatMessage`\n * (Thread 18), wrapped in {@link processChatMessageDedup} for double-submit\n * protection.\n */\nexport async function handleChatMessage(\n req: IncomingMessage,\n res: ServerResponse,\n body: Record<string, unknown>,\n opts: ChatHttpHandlerOptions,\n principal?: string,\n): Promise<void> {\n if (!opts.config?.enabled) {\n respondJson(res, 404, { error: \"chat_disabled\", code: \"chat_disabled\" });\n return;\n }\n\n const message = typeof body.message === \"string\" ? body.message : \"\";\n if (!message) {\n respondJson(res, 400, { error: \"message is required\", code: \"input_error\" });\n return;\n }\n\n if (!opts.service.fallbackLlmRef && !opts.service.localLlmRef) {\n respondJson(res, 503, {\n error: \"No LLM model is available. Configure a local or cloud model.\",\n code: \"no_llm\",\n });\n return;\n }\n\n const chatSessionId = typeof body.chatSessionId === \"string\" ? body.chatSessionId : undefined;\n\n let result: ChatTurnResult;\n try {\n result = await processChatMessageDedup({\n service: opts.service,\n config: opts.config,\n memoryDir: opts.memoryDir,\n message,\n ...(chatSessionId ? { chatSessionId } : {}),\n ...(principal ? { principal } : {}),\n });\n } catch (err) {\n // processChatMessage throws tagged errors for the session/LLM/engine\n // paths; map each back to its HTTP status. Dedup coalescing means a\n // concurrent duplicate shares the same rejection. A 'chat_session_expired'\n // means the session was swept by the TTL cleanup mid-turn (codex P2) —\n // tell the client to start a fresh session (410 Gone).\n const code = err instanceof Error ? err.message : String(err);\n if (code === \"chat_session_not_found\") {\n respondJson(res, 404, { error: \"chat_session_not_found\", code: \"chat_session_not_found\" });\n } else if (code === \"access_denied\") {\n respondJson(res, 403, { error: \"access_denied\", code: \"access_denied\" });\n } else if (code === \"chat_session_expired\") {\n respondJson(res, 410, { error: \"chat_session_expired\", code: \"chat_session_expired\" });\n } else if (code === \"chat_disabled\") {\n respondJson(res, 404, { error: \"chat_disabled\", code: \"chat_disabled\" });\n } else if (code === \"no_llm_available\" || code === \"engine_unavailable\") {\n respondJson(res, 503, {\n error: \"No LLM model is available. Configure a local or cloud model.\",\n code: \"no_llm\",\n });\n } else {\n respondJson(res, 500, { error: \"internal_error\", code: \"internal_error\" });\n }\n return;\n }\n\n // Build the public response field-by-field. Never serialize the engine\n // result wholesale: an engine failure may carry internal error metadata.\n const wireResult = {\n reply: result.reply,\n chatSessionId: result.chatSessionId,\n ...(result.pendingPlan\n ? {\n pendingPlan: {\n planId: result.pendingPlan.planId,\n preview: result.pendingPlan.preview,\n },\n }\n : {}),\n ...(result.skippedTools\n ? { skippedTools: result.skippedTools.filter((name): name is string => typeof name === \"string\") }\n : {}),\n };\n respondJson(res, 200, wireResult);\n}\n\n// ---------------------------------------------------------------------------\n// GET /engram/v1/chat/events/:chatSessionId (SSE)\n// ---------------------------------------------------------------------------\n\n/**\n * Handle GET /engram/v1/chat/events/:chatSessionId.\n *\n * SSE stream. Sends the existing transcript as an initial burst, then keeps\n * the connection open and **pushes new transcript entries live** as they are\n * appended (issue #1685 item 2 / #1687 Thread 8) via the per-session pub/sub\n * in `chat-session.ts`. A heartbeat is emitted every 25 s so proxies do not\n * time out. A `retry:` directive asks reconnecting clients to wait 5 s, and\n * because the initial burst always replays the full transcript (entries carry\n * a strictly-monotonic `seq`), clients dedupe on reconnect — the stream is\n * reconnect-safe.\n *\n * Race-free ordering (cursor Bugbot): the subscription is established BEFORE\n * the transcript snapshot is read; entries appended concurrently during the\n * snapshot read are buffered, then the buffer is drained AFTER switching to\n * live mode (so an append landing between the drain and the mode switch is\n * never dropped — cursor review). Every write goes through a `closed`-guarded\n * helper so a disconnect during the burst cannot write to an ended response\n * (cursor/kilo review). The disconnect cleanup is registered immediately and\n * guarded by `closed` so an early close cannot leak the heartbeat.\n */\nexport async function handleChatEventsSSE(\n req: IncomingMessage,\n res: ServerResponse,\n chatSessionId: string,\n opts: ChatHttpHandlerOptions,\n principal?: string,\n): Promise<void> {\n if (!opts.config?.enabled) {\n respondJson(res, 404, { error: \"chat_disabled\", code: \"chat_disabled\" });\n return;\n }\n\n // Liveness flag + handle, both closed over by the disconnect cleanup. The\n // cleanup is idempotent (guarded by `closed`) so a repeat close is harmless.\n let heartbeat: NodeJS.Timeout | undefined;\n let closed = false;\n // Every SSE write goes through this helper so a closed connection is never\n // written to (cursor Low review). Returns false when the write was skipped.\n const writeSse = (chunk: string): boolean => {\n if (closed) return false;\n try {\n res.write(chunk);\n return true;\n } catch {\n return false;\n }\n };\n\n // Subscribe BEFORE reading the transcript so a concurrent append between\n // the snapshot read and subscription is never missed (cursor Bugbot race).\n // During the initial burst entries are buffered; after the burst the\n // listener switches to writing straight to the response. A `closed` check\n // short-circuits pushes to a connection that is already gone.\n const pending: ChatTranscriptEntry[] = [];\n let bursting = true;\n const unsubscribe = subscribeChatTranscript(opts.memoryDir, chatSessionId, (entry) => {\n if (closed) return;\n if (bursting) {\n pending.push(entry);\n return;\n }\n writeSse(`data: ${JSON.stringify(entry)}\\n\\n`);\n });\n\n // Register disconnect cleanup IMMEDIATELY so a close during loadChatSession\n // or the burst still releases the subscription (cursor Bugbot). The flag\n // gates every later write so the handler never touches an ended response\n // (kilo review thread) and never sets up a heartbeat for a dead socket\n // (cursor review thread).\n const doCleanup = (): void => {\n closed = true;\n clearInterval(heartbeat);\n unsubscribe();\n try { res.end(); } catch { /* already ended */ }\n };\n // Register with the host server's stop() cleanup set (cursor Medium) so an\n // HTTP shutdown forcibly releases the subscription + heartbeat even when a\n // lingering client never emits 'close'. Unregistered again on normal close.\n const unregisterServerCleanup = opts.registerSseCleanup?.(doCleanup) ?? ((): void => {});\n req.on(\"close\", () => {\n doCleanup();\n unregisterServerCleanup();\n });\n\n const session = await loadChatSession(opts.memoryDir, chatSessionId);\n // If the client disconnected during the load, cleanup already ran — bail\n // out before touching the response (prevents \"headers after end\").\n if (closed) return;\n if (!session) {\n // No SSE stream is established — release the server stop() registration\n // alongside the subscription so sseCleanupFns does not retain a stale\n // callback for this JSON error response (cursor Medium: error-path leak).\n unsubscribe();\n unregisterServerCleanup();\n respondJson(res, 404, { error: \"chat_session_not_found\", code: \"chat_session_not_found\" });\n return;\n }\n if (!sessionBelongsToPrincipal(session, principal)) {\n unsubscribe();\n unregisterServerCleanup();\n respondJson(res, 403, { error: \"access_denied\", code: \"access_denied\" });\n return;\n }\n\n // SSE headers.\n res.writeHead(200, {\n \"content-type\": \"text/event-stream\",\n \"cache-control\": \"no-cache\",\n connection: \"keep-alive\",\n });\n\n // Ask reconnecting clients to wait 5 s before retrying (reconnect-safe:\n // the initial burst below replays the full transcript on rejoin).\n writeSse(\"retry: 5000\\n\\n\");\n\n // Send the transcript snapshot as the initial burst, recording delivered\n // seqs so buffered concurrent appends are not double-delivered.\n const deliveredSeqs = new Set<number>();\n for (const entry of session.transcript) {\n writeSse(`data: ${JSON.stringify(entry)}\\n\\n`);\n deliveredSeqs.add(entry.seq);\n }\n\n // Switch to live push FIRST, THEN drain buffered appends. Ordering matters:\n // if an append lands between the drain and the mode switch it would be\n // buffered (bursting still true) and never re-drained (cursor Medium). With\n // live mode on, appends during the drain write straight through and the\n // buffer is emptied once.\n bursting = false;\n for (const entry of pending) {\n if (!deliveredSeqs.has(entry.seq)) {\n writeSse(`data: ${JSON.stringify(entry)}\\n\\n`);\n }\n }\n\n // Heartbeat. Unref'd so a lingering connection never blocks process\n // exit (rule 47 — no shared mutable objects keep the loop alive). Cleared\n // by the close handler above when the client disconnects. Guard against\n // arming after a disconnect during the burst/drain: the close handler\n // already ran doCleanup (clearing any prior handle and unregistering the\n // server callback), so an interval armed here would be untracked and never\n // cleared — bail out instead (codex P2).\n if (closed) return;\n heartbeat = setInterval(() => {\n writeSse(`data: ${JSON.stringify({ type: \"heartbeat\" })}\\n\\n`);\n }, 25_000);\n heartbeat.unref?.();\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nfunction respondJson(res: ServerResponse, status: number, body: unknown): void {\n const json = JSON.stringify(body);\n res.writeHead(status, {\n \"content-type\": \"application/json; charset=utf-8\",\n \"content-length\": Buffer.byteLength(json, \"utf8\"),\n });\n res.end(json);\n}\n","import type { IncomingMessage, ServerResponse } from \"node:http\";\nimport path from \"node:path\";\n\nimport { EngramAccessForbiddenError } from \"../access-errors.js\";\nimport type { EngramAccessService } from \"../access-service.js\";\nimport { enforceNamespaceAllowList, tokenCapabilityStore } from \"../access-token-capabilities.js\";\nimport type { WriteRateLimitReservation } from \"../write-rate-limiter.js\";\nimport { handleSupportPassportOwnerHttp } from \"./access-http.js\";\nimport { buildSupportPassportPublicRequestHandler } from \"./public-http.js\";\n\nconst SUPPORT_PASSPORT_QUOTA_LIMITED_WRITE_TOOLS = new Set([\n \"engram.support_passport_draft_create\",\n \"remnic.support_passport_draft_create\",\n \"engram.support_passport_drafts_generate\",\n \"remnic.support_passport_drafts_generate\",\n \"engram.support_passport_card_replace\",\n \"remnic.support_passport_card_replace\",\n \"engram.support_passport_card_approve\",\n \"remnic.support_passport_card_approve\",\n \"engram.support_passport_card_reject\",\n \"remnic.support_passport_card_reject\",\n \"engram.support_passport_card_withdraw\",\n \"remnic.support_passport_card_withdraw\",\n \"engram.support_passport_grant_create\",\n \"remnic.support_passport_grant_create\",\n \"engram.support_passport_grant_revoke\",\n \"remnic.support_passport_grant_revoke\",\n]);\nconst SUPPORT_PASSPORT_ADMIN_CONSOLE_ASSETS = new Map<string, string>([\n [\"what-helps-me.css\", \"text/css; charset=utf-8\"],\n [\"model.js\", \"application/javascript; charset=utf-8\"],\n [\"app.js\", \"application/javascript; charset=utf-8\"],\n]);\n\nexport abstract class SupportPassportAccessHttpBase {\n private supportPassportPublicHandler: ReturnType<typeof buildSupportPassportPublicRequestHandler> | undefined;\n protected abstract readonly service: EngramAccessService;\n protected abstract readonly adminConsolePublicDir: string;\n protected abstract resolveRequestPrincipal(req: IncomingMessage): string | undefined;\n protected abstract readJsonBody(req: IncomingMessage, maxBodyBytes?: number): Promise<Record<string, unknown>>;\n protected abstract respondJson(res: ServerResponse, status: number, payload: unknown): void;\n protected abstract reserveWriteRateLimitSlot(req?: IncomingMessage): WriteRateLimitReservation;\n protected abstract respondAdminConsoleShell(\n req: IncomingMessage,\n res: ServerResponse,\n pathname: string,\n relativePath?: string,\n allowPrefill?: boolean,\n ): Promise<void>;\n protected abstract respondStatic(res: ServerResponse, filePath: string, contentType: string): Promise<void>;\n\n protected handleSupportPassportOwnerRequest(\n req: IncomingMessage,\n res: ServerResponse,\n pathname: string,\n hasQuery: boolean,\n abortSignal: AbortSignal\n ): Promise<boolean> {\n return handleSupportPassportOwnerHttp({\n req,\n res,\n pathname,\n hasQuery,\n service: this.service,\n principal: this.resolveRequestPrincipal(req),\n abortSignal,\n readJsonBody: () => this.readJsonBody(req),\n respondJson: (status, payload) => {\n res.setHeader(\"cache-control\", \"private, no-store\");\n res.setHeader(\"vary\", \"Authorization\");\n this.respondJson(res, status, payload);\n },\n reserveWriteRateLimitSlot: () => this.reserveWriteRateLimitSlot(req),\n });\n }\n\n protected handleSupportPassportPublicRequest(req: IncomingMessage, res: ServerResponse): Promise<boolean> {\n this.supportPassportPublicHandler ??= buildSupportPassportPublicRequestHandler(this.service, {\n trustedProxyAddresses: this.service.configRef?.supportPassport?.trustedProxyAddresses ?? [],\n });\n return this.supportPassportPublicHandler(req, res, {\n authorized: false,\n tokenAuthorized: false,\n });\n }\n\n protected async enforceSupportPassportAuthorizationProbe(req: IncomingMessage): Promise<void> {\n const principal = this.resolveRequestPrincipal(req)?.trim();\n if (!principal) {\n throw new EngramAccessForbiddenError(\"A trusted principal is required for support passport access.\");\n }\n const owner = await this.service.getWritableStorageForNamespace(undefined, principal);\n enforceNamespaceAllowList(\n tokenCapabilityStore.getStore(),\n owner.namespace,\n this.service.configRef.defaultNamespace\n );\n }\n\n protected isSupportPassportQuotaLimitedWriteTool(toolName: string): boolean {\n return SUPPORT_PASSPORT_QUOTA_LIMITED_WRITE_TOOLS.has(toolName);\n }\n\n protected async handleSupportPassportUi(\n req: IncomingMessage,\n res: ServerResponse,\n pathname: string\n ): Promise<boolean> {\n if (req.method !== \"GET\") return false;\n const isSupportPassportPath =\n pathname === \"/remnic/ui/what-helps-me\" ||\n pathname === \"/engram/ui/what-helps-me\" ||\n pathname.startsWith(\"/remnic/ui/what-helps-me/\") ||\n pathname.startsWith(\"/engram/ui/what-helps-me/\");\n if (!isSupportPassportPath) return false;\n if (!this.service.supportPassportEnabled) {\n this.respondJson(res, 404, { error: \"not_found\" });\n return true;\n }\n if (pathname === \"/remnic/ui/what-helps-me\" || pathname === \"/engram/ui/what-helps-me\") {\n const search = new URL(req.url ?? pathname, \"http://placeholder\").search;\n res.statusCode = 301;\n res.setHeader(\"location\", `${pathname}/${search}`);\n res.end();\n return true;\n }\n if (pathname === \"/remnic/ui/what-helps-me/\" || pathname === \"/engram/ui/what-helps-me/\") {\n const helperRequest = new URL(req.url ?? pathname, \"http://placeholder\").searchParams.has(\"grant\");\n res.setHeader(\"content-security-policy\", \"frame-ancestors 'none'\");\n res.setHeader(\"x-frame-options\", \"DENY\");\n await this.respondAdminConsoleShell(req, res, pathname, \"what-helps-me/index.html\", !helperRequest);\n return true;\n }\n const fileName = pathname.split(\"/\").at(-1) ?? \"\";\n const assetType = SUPPORT_PASSPORT_ADMIN_CONSOLE_ASSETS.get(fileName);\n if (assetType && pathname.split(\"/\").length === 5) {\n await this.respondStatic(res, path.join(this.adminConsolePublicDir, \"what-helps-me\", fileName), assetType);\n return true;\n }\n this.respondJson(res, 404, { error: \"not_found\" });\n return true;\n }\n}\n","import type { IncomingMessage, ServerResponse } from \"node:http\";\n\nimport { EngramAccessInputError } from \"../access-service.js\";\nimport type { OperationName } from \"../access-boundary.js\";\nimport { SupportPassportAccessHttpBase } from \"../support-passport/access-http-base.js\";\nimport type {\n ReviewDeckActionRequest,\n ReviewDeckUndoRequest,\n} from \"./review-deck.js\";\n\nconst LIST_PATHS = [\"/remnic/v1/review/deck\", \"/engram/v1/review/deck\"] as const;\nconst ACTION_PATHS = [\"/remnic/v1/review/deck/action\", \"/engram/v1/review/deck/action\"] as const;\nconst UNDO_PATHS = [\"/remnic/v1/review/deck/undo\", \"/engram/v1/review/deck/undo\"] as const;\nconst LIMIT_MIN = 1;\nconst LIMIT_MAX = 100;\nconst CURSOR_RE = /^[^\\s%]{1,2048}$/;\n\nfunction requiredString(body: Record<string, unknown>, field: string): string {\n const value = body[field];\n if (typeof value !== \"string\" || value.trim().length === 0) {\n throw new EngramAccessInputError(`${field} is required`);\n }\n return value.trim();\n}\n\nfunction parseLimit(raw: string | null): number {\n if (raw === null || raw.length === 0) {\n throw new EngramAccessInputError(\"limit is required and must be an integer\");\n }\n if (!/^(?:0|[1-9]\\d*)$/.test(raw)) {\n throw new EngramAccessInputError(\"limit must be an integer\");\n }\n const value = Number(raw);\n if (!Number.isInteger(value) || value < LIMIT_MIN || value > LIMIT_MAX) {\n throw new EngramAccessInputError(`limit must be an integer from ${LIMIT_MIN} to ${LIMIT_MAX}`);\n }\n return value;\n}\n\nfunction parseCursor(raw: string | null): string | undefined {\n if (raw === null) return undefined;\n if (!CURSOR_RE.test(raw)) {\n throw new EngramAccessInputError(\"cursor is malformed\");\n }\n return raw;\n}\n\nfunction parseActionBody(body: Record<string, unknown>): ReviewDeckActionRequest {\n const action = body.action;\n if (action !== \"keep\" && action !== \"not_true\" && action !== \"prepare_fix\") {\n throw new EngramAccessInputError(\"action must be one of: keep, not_true, prepare_fix\");\n }\n const itemId = requiredString(body, \"itemId\");\n const revision = requiredString(body, \"revision\");\n const idempotencyKey = requiredString(body, \"idempotencyKey\");\n if (action === \"prepare_fix\") {\n const correctionText = requiredString(body, \"correctionText\");\n return { schemaVersion: 1, itemId, revision, action, correctionText, idempotencyKey };\n }\n return { schemaVersion: 1, itemId, revision, action, idempotencyKey };\n}\n\nfunction parseUndoBody(body: Record<string, unknown>): ReviewDeckUndoRequest {\n return {\n schemaVersion: 1,\n receiptId: requiredString(body, \"receiptId\"),\n expectedRevision: requiredString(body, \"expectedRevision\"),\n idempotencyKey: requiredString(body, \"idempotencyKey\"),\n };\n}\n\nexport abstract class ReviewDeckAccessHttpBase extends SupportPassportAccessHttpBase {\n protected abstract enforceTokenOp(op: OperationName): void;\n protected abstract resolveNamespace(req: IncomingMessage, bodyNamespace?: string): string | undefined;\n protected abstract readonly maxBodyBytes: number;\n\n protected async handleReviewDeckRequest(\n req: IncomingMessage,\n res: ServerResponse,\n pathname: string,\n abortSignal?: AbortSignal,\n ): Promise<boolean> {\n const method = req.method;\n const isList = method === \"GET\" && (pathname === LIST_PATHS[0] || pathname === LIST_PATHS[1]);\n const isAction = method === \"POST\" && (pathname === ACTION_PATHS[0] || pathname === ACTION_PATHS[1]);\n const isUndo = method === \"POST\" && (pathname === UNDO_PATHS[0] || pathname === UNDO_PATHS[1]);\n if (!isList && !isAction && !isUndo) return false;\n if (!this.service.reviewDeckEnabled) {\n this.respondJson(res, 404, { error: \"not_found\", code: \"not_found\" });\n return true;\n }\n\n const parsed = new URL(req.url ?? \"/\", \"http://127.0.0.1\");\n const namespace = this.resolveNamespace(req, parsed.searchParams.get(\"namespace\") ?? undefined);\n const principal = this.resolveRequestPrincipal(req);\n\n if (isList) {\n this.enforceTokenOp(\"review_deck_list\");\n const page = await this.service.reviewDeckList({\n namespace,\n principal,\n cursor: parseCursor(parsed.searchParams.get(\"cursor\")),\n limit: parseLimit(parsed.searchParams.get(\"limit\")),\n });\n this.respondJson(res, 200, page);\n return true;\n }\n\n if (isAction) this.enforceTokenOp(\"review_deck_action\");\n else this.enforceTokenOp(\"review_deck_undo\");\n const writeQuota = this.reserveWriteRateLimitSlot(req);\n try {\n const body = await this.readJsonBody(req, this.maxBodyBytes);\n const result = isAction\n ? await this.service.reviewDeckAction(parseActionBody(body), {\n namespace,\n principal,\n signal: abortSignal,\n })\n : await this.service.reviewDeckUndo(parseUndoBody(body), {\n namespace,\n principal,\n signal: abortSignal,\n });\n writeQuota.commit();\n this.respondJson(res, 200, result);\n } catch (error) {\n writeQuota.release();\n throw error;\n }\n return true;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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