@remnic/core 9.65.6 → 9.65.8
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 +15 -13
- package/dist/access-admin-ops-surface.js +54 -54
- package/dist/access-audit.js +2 -2
- package/dist/access-authorization-probe.d.ts +15 -13
- package/dist/access-authorization-probe.js +55 -55
- package/dist/access-boundary.d.ts +15 -13
- package/dist/access-boundary.js +54 -54
- package/dist/access-cli.js +156 -148
- package/dist/access-cli.js.map +1 -1
- package/dist/access-coding-context-resolution.d.ts +2 -1
- package/dist/access-extraction-force-flush.d.ts +15 -13
- package/dist/access-extraction-force-flush.js +54 -54
- package/dist/access-health-types.d.ts +2 -1
- package/dist/access-http-lcm-compaction.d.ts +15 -13
- package/dist/access-http-lifecycle-flush.d.ts +15 -13
- package/dist/access-http-offline-stream.d.ts +15 -13
- package/dist/access-http-query.d.ts +3 -2
- package/dist/access-http-query.js +56 -56
- package/dist/access-http.d.ts +17 -20
- package/dist/access-http.js +75 -73
- package/dist/access-identity-continuity-surface.d.ts +13 -11
- package/dist/access-identity-continuity-surface.js +54 -54
- package/dist/access-lcm-surface.d.ts +15 -13
- package/dist/access-lcm-surface.js +54 -54
- package/dist/access-mcp-output-schemas.js +1 -1
- package/dist/access-mcp.d.ts +15 -13
- package/dist/access-mcp.js +66 -64
- package/dist/access-memory-search-fanout.d.ts +3 -2
- package/dist/{access-namespace-preflight-D_6mo8ms.d.ts → access-namespace-preflight-CpAOrS-9.d.ts} +1 -1
- package/dist/access-namespace-preflight.d.ts +4 -3
- package/dist/access-namespace-preflight.js +54 -54
- package/dist/access-observe-write-surface.d.ts +15 -13
- package/dist/access-observe-write-surface.js +54 -54
- package/dist/access-offline-manifest.d.ts +13 -11
- package/dist/access-offline-manifest.js +6 -6
- package/dist/access-operations-batch.js +58 -58
- package/dist/access-operations.d.ts +21 -19
- package/dist/access-operations.js +63 -61
- package/dist/access-recall-concurrency.d.ts +15 -13
- package/dist/access-recall-concurrency.js +54 -54
- package/dist/access-recall-response.d.ts +15 -13
- package/dist/access-recall-response.js +54 -54
- package/dist/access-recall-surface.d.ts +15 -13
- package/dist/access-recall-surface.js +54 -54
- package/dist/access-schema.d.ts +83 -83
- package/dist/access-schema.js +3 -3
- package/dist/{access-service-sbiNS5UB.d.ts → access-service-Diu61Cfv.d.ts} +72 -72
- package/dist/access-service-helpers.d.ts +15 -13
- package/dist/access-service.d.ts +15 -13
- package/dist/access-service.js +54 -54
- package/dist/access-surface-catalog.d.ts +15 -13
- package/dist/access-surface-catalog.js +66 -56
- package/dist/access-surface-catalog.js.map +1 -1
- package/dist/access-wearables-meetings-surface.d.ts +6 -3
- package/dist/action-confidence.d.ts +2 -1
- package/dist/active-context-config.d.ts +27 -0
- package/dist/active-context-config.js +14 -0
- package/dist/active-context-transform.d.ts +267 -0
- package/dist/active-context-transform.js +31 -0
- package/dist/active-memory-bridge.d.ts +2 -1
- package/dist/active-recall.d.ts +2 -1
- package/dist/active-recall.js +13 -12
- package/dist/active-recall.js.map +1 -1
- package/dist/adapters/index.js +4 -4
- package/dist/adapters/registry.js +2 -2
- package/dist/ambient-provenance.d.ts +2 -1
- package/dist/artifact-search.d.ts +2 -1
- package/dist/{auto-sync-XVMLL2RH.js → auto-sync-2YPITIWN.js} +6 -6
- package/dist/behavior-learner.d.ts +2 -1
- package/dist/behavior-signals.d.ts +2 -1
- package/dist/bootstrap.d.ts +13 -11
- package/dist/briefing-window.d.ts +5 -2
- package/dist/briefing.d.ts +5 -2
- package/dist/briefing.js +25 -25
- package/dist/buffer-surprise-report.d.ts +2 -1
- package/dist/buffer-turn-helpers.d.ts +2 -1
- package/dist/buffer.d.ts +5 -2
- package/dist/buffer.js +6 -6
- package/dist/bulk-import/index.d.ts +4 -3
- package/dist/calibration.d.ts +2 -1
- package/dist/capabilities.d.ts +2 -1
- package/dist/{capsule-crypto-GWVG7LGC.js → capsule-crypto-7FJQINUR.js} +2 -2
- package/dist/{catalog-DO_7zfkv.d.ts → catalog-9f-vEQLS.d.ts} +1 -1
- package/dist/causal-behavior.d.ts +4 -3
- package/dist/causal-behavior.js +2 -2
- package/dist/causal-chain.js +2 -2
- package/dist/causal-consolidation.d.ts +2 -1
- package/dist/causal-consolidation.js +28 -28
- package/dist/causal-retrieval.js +2 -2
- package/dist/causal-trajectory-graph.d.ts +2 -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-RKNJBZ55.js → chunk-2QSZNTDO.js} +4 -4
- package/dist/{chunk-X2DWBWOX.js → chunk-3A2NJP2U.js} +2 -2
- package/dist/chunk-3BCULS4U.js +1093 -0
- package/dist/chunk-3BCULS4U.js.map +1 -0
- package/dist/{chunk-JGG5HVI2.js → chunk-3PKAS6VL.js} +2 -2
- package/dist/{chunk-LSYD7GHZ.js → chunk-3SZD4CYO.js} +3 -3
- package/dist/chunk-43HUVDTD.js +114 -0
- package/dist/chunk-43HUVDTD.js.map +1 -0
- package/dist/{chunk-5TG4MU2U.js → chunk-4F4AQFWL.js} +8 -8
- package/dist/{chunk-D35XLYQ7.js → chunk-4QEYREAV.js} +12 -12
- package/dist/{chunk-46WM6JX2.js → chunk-4ZWCQJNM.js} +5 -5
- package/dist/{chunk-DVYRD4HY.js → chunk-5ACCD4L7.js} +30 -1
- package/dist/chunk-5ACCD4L7.js.map +1 -0
- package/dist/{chunk-W6J4POB6.js → chunk-5DHKCO52.js} +2 -2
- package/dist/{chunk-IRXMJLTW.js → chunk-5HK3CJAR.js} +2 -2
- package/dist/{chunk-NLUCDKLT.js → chunk-5RWZH6PH.js} +2 -2
- package/dist/{chunk-H7BZBSP6.js → chunk-645WOU5I.js} +4 -4
- package/dist/{chunk-AYAZWXJI.js → chunk-76DIF5KT.js} +2 -2
- package/dist/{chunk-OPPBTPUU.js → chunk-7KQB4EBS.js} +4 -4
- package/dist/{chunk-I2HTKOOP.js → chunk-7VZFRUQU.js} +3 -3
- package/dist/{chunk-DPNXADEI.js → chunk-7WOWGRAU.js} +11 -7
- package/dist/chunk-7WOWGRAU.js.map +1 -0
- package/dist/{chunk-JCWY73FK.js → chunk-AHPIFKNG.js} +2 -2
- package/dist/{chunk-FC7TIRFS.js → chunk-AX7UXCHJ.js} +6 -1
- package/dist/chunk-AX7UXCHJ.js.map +1 -0
- package/dist/{chunk-3I22VWB3.js → chunk-AZMLH5UT.js} +2 -2
- package/dist/chunk-B32WYRXX.js +77 -0
- package/dist/chunk-B32WYRXX.js.map +1 -0
- package/dist/{chunk-JOEJG4SD.js → chunk-BEC4YBNA.js} +4 -4
- package/dist/chunk-BWGCOLEL.js +61 -0
- package/dist/chunk-BWGCOLEL.js.map +1 -0
- package/dist/{chunk-BXXOPKT5.js → chunk-CAMNRAJF.js} +2 -2
- package/dist/{chunk-C24UZSFW.js → chunk-CEH2AFXG.js} +6 -6
- package/dist/{chunk-YOXVZJFM.js → chunk-CFVTRUR3.js} +2 -2
- package/dist/{chunk-SVSRPG6M.js → chunk-CPA5NBHN.js} +2 -2
- package/dist/{chunk-7BEPVIH3.js → chunk-CRML27CO.js} +3 -3
- package/dist/{chunk-AXGFOFNY.js → chunk-DA7ITC5Z.js} +2 -2
- package/dist/{chunk-5W7MKXMU.js → chunk-DEACDKE3.js} +144 -78
- package/dist/chunk-DEACDKE3.js.map +1 -0
- package/dist/{chunk-FEO2CDXR.js → chunk-DPCXDG7G.js} +2 -2
- package/dist/{chunk-HZNYJN77.js → chunk-F3NVYTTA.js} +2 -2
- package/dist/{chunk-7SSRXEZJ.js → chunk-F7XUD3PL.js} +2 -2
- package/dist/{chunk-LDBFXD4F.js → chunk-FP7YTTVO.js} +3 -1
- package/dist/chunk-FP7YTTVO.js.map +1 -0
- package/dist/{chunk-XZBXINXZ.js → chunk-GIC6BASP.js} +4 -4
- package/dist/{chunk-PP7R754B.js → chunk-GPFZFCRN.js} +1 -1
- package/dist/{chunk-53MZQEBD.js → chunk-GTO56JY5.js} +2 -2
- package/dist/{chunk-RAIUTAZZ.js → chunk-H2YSH3DG.js} +2 -2
- package/dist/{chunk-HWVNYNIV.js → chunk-HMZKGHMD.js} +2 -2
- package/dist/{chunk-ZXUZ54Z5.js → chunk-HRHO3ZNG.js} +2 -2
- package/dist/{chunk-SDEPLF7V.js → chunk-IBJ6U753.js} +2 -2
- package/dist/chunk-JCCWJHOP.js +240 -0
- package/dist/chunk-JCCWJHOP.js.map +1 -0
- package/dist/{chunk-T3JQTCCO.js → chunk-JI7U6AS3.js} +4 -4
- package/dist/{chunk-TR7DGXGI.js → chunk-JOZUBF4A.js} +5 -5
- package/dist/{chunk-YWBOOBDP.js → chunk-JYSN42VN.js} +71 -71
- package/dist/{chunk-ZPUIRTIZ.js → chunk-KOLJJN5G.js} +12 -75
- package/dist/chunk-KOLJJN5G.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-YUTTMSC7.js → chunk-KZIF6XHX.js} +93 -30
- package/dist/chunk-KZIF6XHX.js.map +1 -0
- package/dist/chunk-LB7WCZHY.js +553 -0
- package/dist/chunk-LB7WCZHY.js.map +1 -0
- package/dist/{chunk-RIAM7DND.js → chunk-LDKPDODJ.js} +2 -2
- package/dist/{chunk-227UFSEQ.js → chunk-LEPOP46W.js} +4 -4
- package/dist/{chunk-2JHRCWHT.js → chunk-LKYIOCWL.js} +107 -107
- package/dist/{chunk-XAWIL7TC.js → chunk-LOXHYCVS.js} +2 -2
- package/dist/{chunk-OMZLBT4B.js → chunk-LPNCR4QK.js} +48 -27
- package/dist/chunk-LPNCR4QK.js.map +1 -0
- package/dist/{chunk-OLBZ2WGG.js → chunk-LTBKKSCX.js} +2 -2
- package/dist/{chunk-O4BAGJDN.js → chunk-MDD2RINF.js} +2 -2
- package/dist/{chunk-H63EDPFJ.js → chunk-MI2OTWV5.js} +15 -2
- package/dist/{chunk-H63EDPFJ.js.map → chunk-MI2OTWV5.js.map} +1 -1
- package/dist/{chunk-LBFFNDFM.js → chunk-MINHJ55X.js} +1 -1
- package/dist/chunk-MINHJ55X.js.map +1 -0
- package/dist/{chunk-ROEAEANL.js → chunk-MY2BC6UE.js} +15 -15
- package/dist/{chunk-RACZB5HT.js → chunk-N37X5RU7.js} +4 -4
- package/dist/{chunk-AG46P24C.js → chunk-NNBZS3DY.js} +4 -4
- package/dist/{chunk-PGW64IFQ.js → chunk-NPFUNWNX.js} +2 -2
- package/dist/{chunk-MFOSZUIT.js → chunk-NPIBN2VL.js} +2 -2
- package/dist/{chunk-IF4EY26E.js → chunk-OA2O2GJ4.js} +3 -3
- package/dist/{chunk-6FUMA6AA.js → chunk-ODU2CNNX.js} +2 -2
- package/dist/{chunk-PNAGNVGK.js → chunk-OXRRJXPR.js} +42 -37
- package/dist/chunk-OXRRJXPR.js.map +1 -0
- package/dist/{chunk-TWBQQ3FT.js → chunk-P36Z4JRA.js} +2 -2
- package/dist/{chunk-OUKBMQ2O.js → chunk-PD66CVSD.js} +2 -2
- package/dist/{chunk-MVIYRRVJ.js → chunk-PMVPCZJZ.js} +5 -5
- package/dist/{chunk-US4IRASK.js → chunk-PU56CXZA.js} +6 -6
- package/dist/{chunk-IDQ6DKXC.js → chunk-S5XOSTYM.js} +3 -3
- package/dist/{chunk-DYO24BNB.js → chunk-SEEJOGQX.js} +5 -5
- package/dist/{chunk-7OZSHBWK.js → chunk-SNOIKAHM.js} +2 -2
- package/dist/{chunk-SR7JIRAR.js → chunk-T6ILXUAH.js} +2 -2
- package/dist/{chunk-2RXUZVPU.js → chunk-T7XP6IZE.js} +2 -2
- package/dist/{chunk-KBOG7FJV.js → chunk-TFR3HG4K.js} +3 -3
- package/dist/{chunk-XUZ5CIEE.js → chunk-TUHBYJXL.js} +1 -1
- package/dist/{chunk-7K5Q6COX.js → chunk-TVVEYCNW.js} +4 -4
- package/dist/{chunk-ZK4BFABK.js → chunk-U7EW2W4W.js} +13 -13
- package/dist/{chunk-4K7IW3F7.js → chunk-UD7UNYRD.js} +34 -3
- package/dist/chunk-UD7UNYRD.js.map +1 -0
- package/dist/{chunk-VFYRYFLL.js → chunk-UEBDCMOO.js} +2 -2
- package/dist/{chunk-JFWZRUKP.js → chunk-UENKPWCS.js} +4 -4
- package/dist/{chunk-AAXJNINV.js → chunk-UL4MKZHI.js} +2 -2
- package/dist/chunk-ULM7JCDH.js +154 -0
- package/dist/chunk-ULM7JCDH.js.map +1 -0
- package/dist/{chunk-R2MZCYA6.js → chunk-UNUMFURP.js} +3 -3
- package/dist/{chunk-5GIZM4RX.js → chunk-UPFNQJC7.js} +2 -2
- package/dist/{chunk-W4BMEGQA.js → chunk-UTQUEHC7.js} +2 -2
- package/dist/{chunk-I32NKXE2.js → chunk-V4IDF3EZ.js} +2 -2
- package/dist/{chunk-6LS5OX3U.js → chunk-W2BAGGEW.js} +50 -18
- package/dist/chunk-W2BAGGEW.js.map +1 -0
- package/dist/chunk-W2UOAATB.js +521 -0
- package/dist/chunk-W2UOAATB.js.map +1 -0
- package/dist/{chunk-QMZY3GG6.js → chunk-WNXYT4MK.js} +3 -3
- package/dist/{chunk-UVYI6VIX.js → chunk-X7Y7WX73.js} +1 -1
- package/dist/{chunk-T42L3S6A.js → chunk-XBGHAAKR.js} +2 -2
- package/dist/{chunk-RQ2EQRRR.js → chunk-XNWXSGHS.js} +80 -7
- package/dist/chunk-XNWXSGHS.js.map +1 -0
- package/dist/{chunk-THG4GYIE.js → chunk-YEUXERJ6.js} +5 -5
- package/dist/{chunk-BIJAWZYW.js → chunk-YMOPYG3K.js} +6 -6
- package/dist/{chunk-M4AHBM72.js → chunk-Z3YEGSR4.js} +2 -2
- package/dist/{cli-Bfgo0n1L.d.ts → cli-O3F-ht3i.d.ts} +5 -5
- package/dist/cli.d.ts +17 -15
- package/dist/cli.js +106 -104
- package/dist/coding/pre-action-gate.d.ts +2 -1
- package/dist/coding/pre-action-gate.js +2 -2
- package/dist/compounding/engine.d.ts +5 -2
- package/dist/compounding/engine.js +26 -26
- package/dist/compounding/preference-consolidator.d.ts +4 -3
- package/dist/compression-optimizer.d.ts +2 -1
- package/dist/config-security.js +2 -2
- package/dist/config.d.ts +2 -1
- package/dist/config.js +13 -12
- package/dist/connectors/codex-materialize-runner.d.ts +2 -1
- package/dist/connectors/codex-materialize-runner.js +25 -25
- package/dist/connectors/codex-materialize.d.ts +2 -1
- package/dist/connectors/index.d.ts +2 -1
- package/dist/connectors/index.js +25 -25
- package/dist/consolidation-provenance-check.d.ts +5 -2
- package/dist/consolidation-provenance-check.js +2 -2
- package/dist/consolidation-undo.d.ts +5 -2
- package/dist/context-summary.d.ts +43 -0
- package/dist/context-summary.js +14 -0
- package/dist/context-summary.js.map +1 -0
- package/dist/contradiction/index.d.ts +6 -3
- package/dist/contradiction/index.js +5 -5
- package/dist/converge-config.d.ts +2 -1
- package/dist/convergence-refresh.d.ts +5 -2
- package/dist/convergence-refresh.js +28 -28
- package/dist/conversation-index/backend.d.ts +2 -1
- package/dist/conversation-index/backend.js +2 -2
- package/dist/conversation-index/chunker.d.ts +2 -1
- package/dist/conversation-index/faiss-adapter.d.ts +2 -1
- package/dist/conversation-index/indexer.d.ts +2 -1
- package/dist/conversation-index/search.d.ts +2 -1
- package/dist/corpus-watermark.d.ts +2 -1
- package/dist/corpus-watermark.js +27 -27
- package/dist/cross-lingual-recall.d.ts +2 -1
- package/dist/day-summary.d.ts +2 -1
- package/dist/delinearize.d.ts +2 -1
- package/dist/dependency-propagation-config.d.ts +2 -1
- package/dist/{dependency-propagation-delivery-D23_x-s5.d.ts → dependency-propagation-delivery-CL6RWXTA.d.ts} +1 -1
- package/dist/direct-answer-wiring.d.ts +2 -1
- package/dist/direct-answer.d.ts +2 -1
- package/dist/embedding-fallback.d.ts +2 -1
- package/dist/enrichment/index.d.ts +2 -1
- package/dist/entity-origin-fields.d.ts +2 -1
- package/dist/entity-retrieval.d.ts +5 -2
- package/dist/entity-retrieval.js +26 -26
- package/dist/entity-schema.d.ts +2 -1
- package/dist/episodic-context.d.ts +2 -1
- package/dist/eval-trajectory-contracts.d.ts +257 -0
- package/dist/eval-trajectory-contracts.js +56 -0
- package/dist/eval-trajectory-contracts.js.map +1 -0
- package/dist/eval-trajectory-store.d.ts +40 -0
- package/dist/eval-trajectory-store.js +19 -0
- package/dist/eval-trajectory-store.js.map +1 -0
- package/dist/eval-trajectory.d.ts +68 -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 +13 -11
- package/dist/explicit-capture.js +6 -6
- package/dist/external-wiki-access.d.ts +15 -13
- package/dist/external-wiki-access.js +55 -55
- package/dist/external-wiki-collection-registration.d.ts +2 -1
- package/dist/external-wiki-collection.d.ts +2 -1
- package/dist/external-wiki-mcp-tools.d.ts +15 -13
- package/dist/extraction-error-classification.d.ts +2 -1
- package/dist/extraction-faithfulness.d.ts +2 -1
- package/dist/extraction-judge-telemetry.d.ts +2 -1
- package/dist/extraction-judge-training.d.ts +2 -1
- package/dist/extraction-judge.d.ts +2 -1
- package/dist/extraction-liveness.d.ts +2 -1
- package/dist/extraction-normalization.d.ts +2 -1
- package/dist/extraction-prompt.d.ts +2 -1
- package/dist/extraction-source-grounding-rules.d.ts +2 -1
- package/dist/extraction-source-grounding.d.ts +2 -1
- package/dist/extraction.d.ts +2 -1
- package/dist/extraction.js +33 -33
- package/dist/fallback-llm.d.ts +2 -1
- package/dist/{forget-SZ2BXDGF.js → forget-2AE4MDK3.js} +3 -3
- package/dist/graph-dashboard-diff.d.ts +2 -1
- package/dist/graph-dashboard-key.d.ts +2 -1
- package/dist/graph-dashboard-parser.d.ts +2 -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 +2 -1
- package/dist/graph-path-reconstruction.d.ts +2 -1
- package/dist/graph-path-scoring.d.ts +2 -1
- package/dist/graph-snapshot.d.ts +2 -1
- package/dist/graph-snapshot.js +3 -3
- package/dist/graph.d.ts +2 -1
- package/dist/graph.js +3 -3
- package/dist/harmonic-retrieval.js +1 -1
- package/dist/importance.d.ts +2 -1
- package/dist/importers/index.d.ts +2 -1
- package/dist/in-flight-reads.d.ts +2 -1
- package/dist/{index--QhGIXF2.d.ts → index-C7Xep6S9.d.ts} +2 -2
- package/dist/index.d.ts +706 -701
- package/dist/index.js +271 -200
- package/dist/intent.d.ts +2 -1
- package/dist/lcm/engine.d.ts +3 -2
- package/dist/lcm/engine.js +3 -2
- package/dist/lcm/index.d.ts +4 -2
- package/dist/lcm/index.js +6 -5
- package/dist/lcm/summarizer.d.ts +4 -6
- package/dist/lcm/summarizer.js +2 -1
- package/dist/lcm/tools.d.ts +4 -3
- package/dist/lifecycle.d.ts +2 -1
- package/dist/live-connectors-runner.d.ts +2 -1
- package/dist/local-llm.d.ts +2 -1
- package/dist/local-model-endpoint.d.ts +2 -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 +2 -1
- package/dist/maintenance/memory-governance.js +26 -26
- package/dist/maintenance/rebuild-memory-lifecycle-ledger.d.ts +5 -2
- package/dist/maintenance/rebuild-memory-lifecycle-ledger.js +25 -25
- package/dist/maintenance/rebuild-memory-projection.d.ts +5 -2
- package/dist/maintenance/rebuild-memory-projection.js +27 -27
- package/dist/{maintenance-PFvY1Pw_.d.ts → maintenance-CJ-xqFp0.d.ts} +4 -3
- package/dist/mcp-memory-inspector-app.d.ts +15 -13
- package/dist/mcp-read-only-tools.js +1 -1
- package/dist/memory-action-policy.d.ts +18 -2
- package/dist/memory-action-policy.js +3 -1
- package/dist/memory-cache.d.ts +2 -1
- package/dist/memory-controller.d.ts +2 -1
- package/dist/memory-controller.js +2 -2
- package/dist/memory-lifecycle-ledger-utils.d.ts +2 -1
- package/dist/memory-projection-store.d.ts +2 -1
- package/dist/memory-provenance.d.ts +2 -1
- package/dist/memory-snapshot.d.ts +2 -1
- package/dist/memory-subject-cli.d.ts +15 -13
- package/dist/memory-subject.d.ts +15 -13
- package/dist/memory-subject.js +3 -3
- package/dist/memory-worth-outcomes.d.ts +50 -3
- package/dist/memory-worth-outcomes.js +5 -3
- package/dist/models-json.d.ts +2 -1
- package/dist/namespaces/migrate.d.ts +6 -3
- package/dist/namespaces/migrate.js +26 -26
- package/dist/namespaces/principal.d.ts +2 -1
- package/dist/namespaces/search.d.ts +2 -1
- package/dist/namespaces/search.js +11 -11
- package/dist/namespaces/storage.d.ts +6 -3
- package/dist/namespaces/storage.js +25 -25
- package/dist/native-knowledge.d.ts +2 -1
- package/dist/offline-sync-impression-drain.d.ts +2 -1
- package/dist/offline-sync-impression-drain.js +2 -2
- package/dist/operator-doctor-corpus.d.ts +2 -1
- package/dist/operator-doctor-corpus.js +28 -28
- package/dist/operator-doctor-replica.d.ts +2 -1
- package/dist/operator-toolkit.d.ts +6 -3
- package/dist/operator-toolkit.js +45 -44
- package/dist/orchestration/compression-guideline-coordinator.d.ts +5 -2
- package/dist/orchestration/maintenance.d.ts +7 -4
- package/dist/orchestration/maintenance.js +34 -32
- package/dist/{orchestrator-4wzJrPVm.d.ts → orchestrator-BsntWxLy.d.ts} +8 -8
- package/dist/orchestrator.d.ts +13 -11
- package/dist/orchestrator.js +156 -148
- package/dist/patterns-cli.d.ts +2 -1
- package/dist/{pipeline-CgXgdIrF.d.ts → pipeline-CVoysPm2.d.ts} +1 -1
- package/dist/policy-runtime.d.ts +2 -1
- package/dist/proactive-contention.d.ts +2 -1
- package/dist/provenance.d.ts +2 -1
- package/dist/{public-http-BP3VQDl5.d.ts → public-http-CuOxlTC2.d.ts} +1 -1
- package/dist/{qmd-BppGGxsi.d.ts → qmd-DWMAGA5l.d.ts} +1 -1
- package/dist/qmd-preflight.d.ts +3 -2
- package/dist/qmd-recall-cache.d.ts +2 -1
- package/dist/qmd.d.ts +3 -2
- package/dist/qmd.js +4 -4
- package/dist/recall-concurrency-config.d.ts +2 -1
- package/dist/recall-disclosure-escalation.d.ts +2 -1
- package/dist/recall-explain-renderer.d.ts +2 -1
- package/dist/recall-explain-renderer.js +3 -3
- package/dist/recall-memory-map.d.ts +2 -1
- package/dist/recall-planner-llm.d.ts +2 -1
- package/dist/recall-state.d.ts +2 -1
- package/dist/recall-tag-filter.d.ts +2 -1
- package/dist/recall-timings.d.ts +2 -1
- package/dist/recall-xray-cli.d.ts +2 -1
- package/dist/recall-xray-cli.js +4 -4
- package/dist/recall-xray-renderer.d.ts +2 -1
- package/dist/recall-xray-renderer.js +3 -3
- package/dist/recall-xray.d.ts +2 -1
- package/dist/recall-xray.js +2 -2
- package/dist/reconcile/cursor.d.ts +2 -1
- package/dist/reconcile/manifest.d.ts +2 -1
- package/dist/reconcile/manifest.js +3 -3
- package/dist/reconcile/plan.d.ts +2 -1
- package/dist/replay/normalizers/chatgpt.d.ts +2 -1
- package/dist/replay/normalizers/claude.d.ts +2 -1
- package/dist/replay/normalizers/openclaw.d.ts +2 -1
- package/dist/replay/normalizers/shared.d.ts +2 -1
- package/dist/replay/runner.d.ts +2 -1
- package/dist/replay/types.d.ts +2 -1
- package/dist/replica-divergence.d.ts +2 -1
- package/dist/replica-peers-config.d.ts +2 -1
- package/dist/{resolution-4552BNRV.js → resolution-XWBPKYFB.js} +6 -6
- package/dist/resolution-XWBPKYFB.js.map +1 -0
- package/dist/resolve-auth-token.d.ts +2 -1
- package/dist/resume-bundles.js +14 -13
- package/dist/retrieval-agents.d.ts +3 -2
- package/dist/retrieval-tiers.d.ts +2 -1
- package/dist/routing/engine.d.ts +2 -1
- package/dist/routing/store.d.ts +2 -1
- package/dist/salvage-envelope.d.ts +2 -1
- package/dist/salvage-envelope.js +5 -5
- package/dist/schemas.d.ts +124 -124
- package/dist/{scope-profiles-ChZUtxDU.d.ts → scope-profiles-CPWkW_dI.d.ts} +1 -1
- package/dist/search/embed-helper.d.ts +2 -1
- package/dist/search/factory.d.ts +2 -1
- package/dist/search/factory.js +10 -10
- package/dist/search/index.d.ts +2 -1
- package/dist/search/index.js +15 -15
- package/dist/search/lancedb-backend.d.ts +2 -1
- package/dist/search/lancedb-backend.js +2 -2
- package/dist/search/meilisearch-backend.d.ts +2 -1
- package/dist/search/meilisearch-backend.js +2 -2
- package/dist/search/noop-backend.d.ts +2 -1
- package/dist/search/orama-backend.d.ts +2 -1
- package/dist/search/orama-backend.js +2 -2
- package/dist/search/port.d.ts +2 -1
- package/dist/search/remote-backend.d.ts +2 -1
- package/dist/{semantic-consolidation-mSPwQSmF.d.ts → semantic-consolidation-CNFVBXFc.d.ts} +1 -1
- package/dist/semantic-consolidation.d.ts +3 -2
- package/dist/semantic-consolidation.js +31 -31
- package/dist/semantic-rule-promotion.js +25 -25
- package/dist/semantic-rule-verifier.d.ts +2 -1
- package/dist/semantic-rule-verifier.js +25 -25
- package/dist/{service-BICWLwSP.d.ts → service-Bb-JIdQ0.d.ts} +2 -2
- package/dist/session-observer-bands.d.ts +2 -1
- package/dist/session-observer-state.d.ts +2 -1
- package/dist/shared-context/manager.d.ts +8 -7
- package/dist/signal.d.ts +2 -1
- package/dist/source-agent-qualifier.d.ts +2 -1
- package/dist/source-agent-qualifier.js +29 -29
- package/dist/{storage-B7urx1K3.d.ts → storage-CukrlNKk.d.ts} +4 -1
- package/dist/storage.d.ts +5 -2
- package/dist/storage.js +24 -24
- package/dist/subject-config.d.ts +2 -1
- package/dist/subject-config.js +4 -4
- package/dist/summarizer.d.ts +2 -1
- package/dist/summary-snapshot.d.ts +2 -1
- package/dist/support-passport/index.d.ts +18 -16
- package/dist/support-passport/index.js +57 -57
- package/dist/temporal-supersession.d.ts +3 -2
- package/dist/temporal-timeline-recall.d.ts +2 -1
- package/dist/temporal-validity.d.ts +2 -1
- package/dist/threading.d.ts +2 -1
- package/dist/tier-migration.d.ts +5 -2
- package/dist/tier-routing.d.ts +2 -1
- package/dist/topics.d.ts +2 -1
- package/dist/transcript.d.ts +2 -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/transfer/types.d.ts +78 -78
- package/dist/trust-score-stage.d.ts +2 -1
- package/dist/trust-score.d.ts +2 -1
- package/dist/{types-ETU5N6nB.d.ts → types-djxQlxJ7.d.ts} +3 -2
- package/dist/types.d.ts +2 -1
- package/dist/types.js +1 -1
- package/dist/utility-runtime.d.ts +2 -1
- package/dist/verified-recall.js +25 -25
- package/dist/who-knows-cli.d.ts +15 -13
- package/dist/who-knows-cli.js +26 -26
- package/dist/who-knows.d.ts +15 -13
- package/dist/who-knows.js +25 -25
- package/dist/write-envelope.d.ts +2 -1
- package/dist/write-envelope.js +4 -4
- package/package.json +22 -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/active-context-config.ts +98 -0
- package/src/active-context-transform.test.ts +533 -0
- package/src/active-context-transform.ts +981 -0
- package/src/config.ts +3 -5
- package/src/context-summary.ts +182 -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 +6 -11
- package/src/lcm/summarizer.ts +14 -93
- 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-action-policy.ts +28 -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/storage/context-transform-ledger.ts +39 -0
- package/src/storage/secure-line-reader.ts +50 -1
- package/src/storage.ts +4 -1
- package/src/types.ts +2 -3
- 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-6LS5OX3U.js.map +0 -1
- package/dist/chunk-DPNXADEI.js.map +0 -1
- package/dist/chunk-DVYRD4HY.js.map +0 -1
- package/dist/chunk-FC7TIRFS.js.map +0 -1
- package/dist/chunk-LBFFNDFM.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/chunk-ZPUIRTIZ.js.map +0 -1
- /package/dist/{capsule-crypto-GWVG7LGC.js.map → active-context-config.js.map} +0 -0
- /package/dist/{graph-edge-decay-FXGELBFA.js.map → active-context-transform.js.map} +0 -0
- /package/dist/{auto-sync-XVMLL2RH.js.map → auto-sync-2YPITIWN.js.map} +0 -0
- /package/dist/{resolution-4552BNRV.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-RKNJBZ55.js.map → chunk-2QSZNTDO.js.map} +0 -0
- /package/dist/{chunk-X2DWBWOX.js.map → chunk-3A2NJP2U.js.map} +0 -0
- /package/dist/{chunk-JGG5HVI2.js.map → chunk-3PKAS6VL.js.map} +0 -0
- /package/dist/{chunk-LSYD7GHZ.js.map → chunk-3SZD4CYO.js.map} +0 -0
- /package/dist/{chunk-5TG4MU2U.js.map → chunk-4F4AQFWL.js.map} +0 -0
- /package/dist/{chunk-D35XLYQ7.js.map → chunk-4QEYREAV.js.map} +0 -0
- /package/dist/{chunk-46WM6JX2.js.map → chunk-4ZWCQJNM.js.map} +0 -0
- /package/dist/{chunk-W6J4POB6.js.map → chunk-5DHKCO52.js.map} +0 -0
- /package/dist/{chunk-IRXMJLTW.js.map → chunk-5HK3CJAR.js.map} +0 -0
- /package/dist/{chunk-NLUCDKLT.js.map → chunk-5RWZH6PH.js.map} +0 -0
- /package/dist/{chunk-H7BZBSP6.js.map → chunk-645WOU5I.js.map} +0 -0
- /package/dist/{chunk-AYAZWXJI.js.map → chunk-76DIF5KT.js.map} +0 -0
- /package/dist/{chunk-OPPBTPUU.js.map → chunk-7KQB4EBS.js.map} +0 -0
- /package/dist/{chunk-I2HTKOOP.js.map → chunk-7VZFRUQU.js.map} +0 -0
- /package/dist/{chunk-JCWY73FK.js.map → chunk-AHPIFKNG.js.map} +0 -0
- /package/dist/{chunk-3I22VWB3.js.map → chunk-AZMLH5UT.js.map} +0 -0
- /package/dist/{chunk-JOEJG4SD.js.map → chunk-BEC4YBNA.js.map} +0 -0
- /package/dist/{chunk-BXXOPKT5.js.map → chunk-CAMNRAJF.js.map} +0 -0
- /package/dist/{chunk-C24UZSFW.js.map → chunk-CEH2AFXG.js.map} +0 -0
- /package/dist/{chunk-YOXVZJFM.js.map → chunk-CFVTRUR3.js.map} +0 -0
- /package/dist/{chunk-SVSRPG6M.js.map → chunk-CPA5NBHN.js.map} +0 -0
- /package/dist/{chunk-7BEPVIH3.js.map → chunk-CRML27CO.js.map} +0 -0
- /package/dist/{chunk-AXGFOFNY.js.map → chunk-DA7ITC5Z.js.map} +0 -0
- /package/dist/{chunk-FEO2CDXR.js.map → chunk-DPCXDG7G.js.map} +0 -0
- /package/dist/{chunk-HZNYJN77.js.map → chunk-F3NVYTTA.js.map} +0 -0
- /package/dist/{chunk-7SSRXEZJ.js.map → chunk-F7XUD3PL.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-53MZQEBD.js.map → chunk-GTO56JY5.js.map} +0 -0
- /package/dist/{chunk-RAIUTAZZ.js.map → chunk-H2YSH3DG.js.map} +0 -0
- /package/dist/{chunk-HWVNYNIV.js.map → chunk-HMZKGHMD.js.map} +0 -0
- /package/dist/{chunk-ZXUZ54Z5.js.map → chunk-HRHO3ZNG.js.map} +0 -0
- /package/dist/{chunk-SDEPLF7V.js.map → chunk-IBJ6U753.js.map} +0 -0
- /package/dist/{chunk-T3JQTCCO.js.map → chunk-JI7U6AS3.js.map} +0 -0
- /package/dist/{chunk-TR7DGXGI.js.map → chunk-JOZUBF4A.js.map} +0 -0
- /package/dist/{chunk-YWBOOBDP.js.map → chunk-JYSN42VN.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-RIAM7DND.js.map → chunk-LDKPDODJ.js.map} +0 -0
- /package/dist/{chunk-227UFSEQ.js.map → chunk-LEPOP46W.js.map} +0 -0
- /package/dist/{chunk-2JHRCWHT.js.map → chunk-LKYIOCWL.js.map} +0 -0
- /package/dist/{chunk-XAWIL7TC.js.map → chunk-LOXHYCVS.js.map} +0 -0
- /package/dist/{chunk-OLBZ2WGG.js.map → chunk-LTBKKSCX.js.map} +0 -0
- /package/dist/{chunk-O4BAGJDN.js.map → chunk-MDD2RINF.js.map} +0 -0
- /package/dist/{chunk-ROEAEANL.js.map → chunk-MY2BC6UE.js.map} +0 -0
- /package/dist/{chunk-RACZB5HT.js.map → chunk-N37X5RU7.js.map} +0 -0
- /package/dist/{chunk-AG46P24C.js.map → chunk-NNBZS3DY.js.map} +0 -0
- /package/dist/{chunk-PGW64IFQ.js.map → chunk-NPFUNWNX.js.map} +0 -0
- /package/dist/{chunk-MFOSZUIT.js.map → chunk-NPIBN2VL.js.map} +0 -0
- /package/dist/{chunk-IF4EY26E.js.map → chunk-OA2O2GJ4.js.map} +0 -0
- /package/dist/{chunk-6FUMA6AA.js.map → chunk-ODU2CNNX.js.map} +0 -0
- /package/dist/{chunk-TWBQQ3FT.js.map → chunk-P36Z4JRA.js.map} +0 -0
- /package/dist/{chunk-OUKBMQ2O.js.map → chunk-PD66CVSD.js.map} +0 -0
- /package/dist/{chunk-MVIYRRVJ.js.map → chunk-PMVPCZJZ.js.map} +0 -0
- /package/dist/{chunk-US4IRASK.js.map → chunk-PU56CXZA.js.map} +0 -0
- /package/dist/{chunk-IDQ6DKXC.js.map → chunk-S5XOSTYM.js.map} +0 -0
- /package/dist/{chunk-DYO24BNB.js.map → chunk-SEEJOGQX.js.map} +0 -0
- /package/dist/{chunk-7OZSHBWK.js.map → chunk-SNOIKAHM.js.map} +0 -0
- /package/dist/{chunk-SR7JIRAR.js.map → chunk-T6ILXUAH.js.map} +0 -0
- /package/dist/{chunk-2RXUZVPU.js.map → chunk-T7XP6IZE.js.map} +0 -0
- /package/dist/{chunk-KBOG7FJV.js.map → chunk-TFR3HG4K.js.map} +0 -0
- /package/dist/{chunk-XUZ5CIEE.js.map → chunk-TUHBYJXL.js.map} +0 -0
- /package/dist/{chunk-7K5Q6COX.js.map → chunk-TVVEYCNW.js.map} +0 -0
- /package/dist/{chunk-ZK4BFABK.js.map → chunk-U7EW2W4W.js.map} +0 -0
- /package/dist/{chunk-VFYRYFLL.js.map → chunk-UEBDCMOO.js.map} +0 -0
- /package/dist/{chunk-JFWZRUKP.js.map → chunk-UENKPWCS.js.map} +0 -0
- /package/dist/{chunk-AAXJNINV.js.map → chunk-UL4MKZHI.js.map} +0 -0
- /package/dist/{chunk-R2MZCYA6.js.map → chunk-UNUMFURP.js.map} +0 -0
- /package/dist/{chunk-5GIZM4RX.js.map → chunk-UPFNQJC7.js.map} +0 -0
- /package/dist/{chunk-W4BMEGQA.js.map → chunk-UTQUEHC7.js.map} +0 -0
- /package/dist/{chunk-I32NKXE2.js.map → chunk-V4IDF3EZ.js.map} +0 -0
- /package/dist/{chunk-QMZY3GG6.js.map → chunk-WNXYT4MK.js.map} +0 -0
- /package/dist/{chunk-UVYI6VIX.js.map → chunk-X7Y7WX73.js.map} +0 -0
- /package/dist/{chunk-T42L3S6A.js.map → chunk-XBGHAAKR.js.map} +0 -0
- /package/dist/{chunk-THG4GYIE.js.map → chunk-YEUXERJ6.js.map} +0 -0
- /package/dist/{chunk-BIJAWZYW.js.map → chunk-YMOPYG3K.js.map} +0 -0
- /package/dist/{chunk-M4AHBM72.js.map → chunk-Z3YEGSR4.js.map} +0 -0
- /package/dist/{forget-SZ2BXDGF.js.map → forget-2AE4MDK3.js.map} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/access-mcp.ts","../src/chat/chat-system-prompt.ts","../src/chat/chat-tools.ts","../src/chat/chat-engine.ts","../src/chat/chat-llm.ts","../src/chat/chat-executor.ts","../src/chat/chat-session.ts","../src/chat/chat-factory.ts","../src/meetings/mcp-tools.ts","../src/wearables/mcp-tools.ts","../src/location/mcp-tools.ts","../src/support-passport/mcp-tools.ts"],"sourcesContent":["import { randomUUID } from \"node:crypto\";\nimport {\n MCP_ADMIN_OPS_MIGRATED_OPERATIONS, MCP_ADMIN_OPS_TOOLS,\n MCP_GIT_CONTEXT_SCHEMA_PROPS_IGNORED,\n} from \"./access-mcp-admin-tools.js\";\nimport { readFile } from \"node:fs/promises\";\nimport type { Readable, Writable } from \"node:stream\";\n// Importing access-operations registers the pilot boundary operations\n// (memory_get / memory_search / memory_store) as a side effect; callTool\n// dispatches migrated tools through the registry (issue #1525).\nimport { type OperationName, getOperation } from \"./access-boundary.js\";\nimport { assertOperationAllowed, capabilityAllowsOp, enforceNamespaceAllowList, tokenCapabilityStore } from \"./access-token-capabilities.js\";\nimport {\n type ActionConfidenceRequest,\n type CapsuleExportRequest,\n type CapsuleImportRequest,\n type CapsuleListRequest,\n type DaySummaryRequest,\n type SchemaName,\n type SchemaTypeFor,\n type SuggestionSubmitRequest,\n validateRequest,\n} from \"./access-schema.js\";\nimport { EngramAccessInputError, type EngramAccessRecallResponse, type EngramAccessService } from \"./access-service.js\";\nimport \"./access-operations.js\";\nimport { validateBriefingFormat } from \"./briefing.js\";\nimport { processChatMessage } from \"./chat/chat-factory.js\";\nimport { enforceChatSessionNamespace } from \"./chat/chat-session.js\";\nimport { type CitationMetadata, buildCitationGuidance } from \"./citations.js\";\nimport { projectTagProjectId } from \"./coding/coding-namespace.js\";\nimport {\n REMNIC_CHATGPT_MEMORY_INSPECTOR_MIME_TYPE,\n REMNIC_CHATGPT_MEMORY_INSPECTOR_TOOL,\n REMNIC_CHATGPT_MEMORY_INSPECTOR_WIDGET_HTML,\n REMNIC_CHATGPT_MEMORY_INSPECTOR_WIDGET_URI,\n type RemnicChatGptMemoryInspectorInput,\n buildChatGptMemoryInspectorActionRequest,\n buildChatGptMemoryInspectorResult,\n} from \"./mcp-memory-inspector-app.js\";\nimport { resolvePrincipal } from \"./namespaces/principal.js\";\nimport { readEnvVar } from \"./runtime/env.js\";\nimport type { RecallDisclosure, RecallPlanMode } from \"./types.js\";\nimport { expandTildePath } from \"./utils/path.js\";\nimport { applyToolOutputSchemas } from \"./access-mcp-output-schemas.js\";\nimport { MCP_READ_ONLY_TOOL_SUFFIXES } from \"./mcp-read-only-tools.js\";\nimport { MEETINGS_MCP_TOOLS } from \"./meetings/mcp-tools.js\";\nimport { WEARABLES_MCP_TOOLS } from \"./wearables/mcp-tools.js\";\nimport { WHO_KNOWS_MCP_TOOLS } from \"./who-knows.js\"; import { LOCATION_MCP_TOOLS } from \"./location/mcp-tools.js\";\nimport { PROMOTION_CANDIDATES_MCP_TOOLS } from \"./memory-subject.js\";\nimport { EXTERNAL_WIKI_MCP_TOOLS } from \"./external-wiki-mcp-tools.js\";\nimport { abortError, isAbortError } from \"./abort-error.js\";\nimport { SUPPORT_PASSPORT_MCP_MIGRATED_OPERATIONS, SUPPORT_PASSPORT_MCP_TOOLS } from \"./support-passport/mcp-tools.js\";\ntype JsonRpcId = string | number | null;\n\ntype JsonRpcRequest = {\n jsonrpc?: string;\n id?: JsonRpcId;\n method?: string;\n params?: Record<string, unknown>;\n};\n\nfunction throwMcpAbort(signal: AbortSignal | undefined, message: string): void {\n if (!signal?.aborted) return;\n if (isAbortError(signal.reason)) throw signal.reason;\n throw abortError(message);\n}\n\ntype McpRequestOptions = {\n principalOverride?: string;\n namespaceOverride?: string;\n sessionKeyOverride?: string;\n sessionId?: string;\n correlationId?: string;\n /**\n * Write-quota enforcer forwarded into observe's idempotency lock\n * (issue #1649). Only the MCP-over-HTTP transport supplies this (it owns\n * the write-rate-limit window); the standalone MCP server has no quota.\n */\n enforceWriteQuota?: () => void | Promise<void>;\n /**\n * Called once when a lifecycle write reaches its durable commit boundary.\n * HTTP transports use this to account writes even when post-commit work\n * fails or the client disconnects before a response is available.\n */\n recordWriteCommit?: () => void;\n /**\n * Server-resolved connector identity (Phase 1 provenance). Set by the HTTP\n * auth boundary from the matched token entry's connector; threaded into\n * the operation context so write handlers stamp it onto frontmatter.\n */\n sourceConnector?: string;\n /** HTTP request lifetime; absent for the standalone stdio transport. */\n abortSignal?: AbortSignal;\n};\n\nexport type McpTool = {\n name: string;\n title?: string;\n description: string;\n inputSchema: Record<string, unknown>;\n outputSchema?: Record<string, unknown>;\n annotations?: Record<string, unknown>;\n _meta?: Record<string, unknown>;\n};\n\ntype McpResource = {\n uri: string;\n name: string;\n title?: string;\n description?: string;\n mimeType: string;\n _meta?: Record<string, unknown>;\n};\n\n/**\n * MCP protocol versions this server understands, ordered newest → oldest.\n * Exported so the HTTP transport can validate the `MCP-Protocol-Version`\n * header and reject requests advertising an unknown version.\n */\nexport const MCP_SUPPORTED_PROTOCOL_VERSIONS: readonly string[] = [\"2025-06-18\", \"2025-03-26\", \"2024-11-05\"];\nconst MCP_DEFAULT_PROTOCOL_VERSION: string = MCP_SUPPORTED_PROTOCOL_VERSIONS[0] ?? \"2025-06-18\";\nconst LEGACY_MCP_PREFIX = \"engram.\";\nconst CANONICAL_MCP_PREFIX = \"remnic.\";\n\nfunction toCanonicalToolName(name: string): string {\n return name.startsWith(LEGACY_MCP_PREFIX) ? `${CANONICAL_MCP_PREFIX}${name.slice(LEGACY_MCP_PREFIX.length)}` : name;\n}\nfunction toLegacyToolName(name: string): string {\n return name.startsWith(CANONICAL_MCP_PREFIX)\n ? `${LEGACY_MCP_PREFIX}${name.slice(CANONICAL_MCP_PREFIX.length)}`\n : name;\n}\n\n/**\n * Suffix-based allowlist matcher. Returns true for tools whose canonical\n * suffix (after stripping `remnic.` or `engram.`) is in\n * {@link MCP_READ_ONLY_TOOL_SUFFIXES}. Unprefixed names are treated as\n * unannotated.\n */\nfunction isReadOnlyToolName(name: string): boolean {\n for (const prefix of [CANONICAL_MCP_PREFIX, LEGACY_MCP_PREFIX]) {\n if (name.startsWith(prefix)) {\n return MCP_READ_ONLY_TOOL_SUFFIXES[name.slice(prefix.length)] === true;\n }\n }\n return false;\n}\n\nfunction withToolAliases(tool: McpTool, emitLegacyTools = true): McpTool[] {\n const canonicalName = toCanonicalToolName(tool.name);\n const canonicalTool = canonicalName === tool.name ? tool : { ...tool, name: canonicalName };\n if (canonicalName === tool.name) return [canonicalTool];\n // Issue #1427: when legacy aliases are opted out, advertise only the\n // canonical `remnic.*` name and drop the `engram.*` duplicate. Tool *calls*\n // still accept both names (the dispatch canonicalizes), so suppressing the\n // alias only trims `tools/list`, not callability.\n return emitLegacyTools ? [canonicalTool, tool] : [canonicalTool];\n}\n\nexport const MCP_MIGRATED_OPERATIONS: Readonly<Record<string, OperationName>> = {\n \"engram.memory_get\": \"memory_get\",\n \"engram.memory_search\": \"memory_search\",\n \"engram.external_wiki_search\": \"external_wiki_search\",\n \"engram.memory_store\": \"memory_store\",\n \"engram.coding_decision\": \"coding_decision\",\n \"engram.coding_architecture\": \"coding_architecture\",\n // codegraph parity tools (issue #1554) — each maps to its boundary op.\n \"engram.codegraph_index\": \"codegraph_index\",\n \"engram.codegraph_list_projects\": \"codegraph_list_projects\",\n \"engram.codegraph_delete_project\": \"codegraph_delete_project\",\n \"engram.codegraph_index_status\": \"codegraph_index_status\",\n \"engram.codegraph_search_graph\": \"codegraph_search_graph\",\n \"engram.codegraph_trace_path\": \"codegraph_trace_path\",\n \"engram.codegraph_detect_changes\": \"codegraph_detect_changes\",\n \"engram.codegraph_query_graph\": \"codegraph_query_graph\",\n \"engram.codegraph_get_schema\": \"codegraph_get_schema\",\n \"engram.codegraph_get_snippet\": \"codegraph_get_snippet\",\n \"engram.codegraph_get_architecture\": \"codegraph_get_architecture\",\n \"engram.codegraph_search_code\": \"codegraph_search_code\",\n \"engram.codegraph_manage_adr\": \"codegraph_manage_adr\",\n \"engram.codegraph_ingest_traces\": \"codegraph_ingest_traces\",\n \"engram.coding_delta\": \"coding_delta\",\n // Correction Contract (issue #1580) — one plan/apply pipeline.\n \"engram.memory_correct_plan\": \"memory_correct_plan\",\n \"engram.memory_correct_apply\": \"memory_correct_apply\",\n // Fully migrated through the strict-schema boundary (#1668).\n \"engram.recall\": \"recall\",\n \"engram.recall_explain\": \"recall_explain\",\n \"engram.set_coding_context\": \"set_coding_context\", \"engram.recall_tier_explain\": \"recall_tier_explain\",\n \"engram.recall_xray\": \"recall_xray\", \"engram.who_knows\": \"who_knows\", \"engram.promotion_candidates\": \"promotion_candidates\",\n \"engram.wearables_status\": \"wearables_status\", \"engram.wearables_sync\": \"wearables_sync\",\n \"engram.location_status\": \"location_status\", \"engram.location_check\": \"location_check\", \"engram.location_sync\": \"location_sync\",\n \"engram.location_backfill\": \"location_backfill\", \"engram.location_day\": \"location_day\",\n \"engram.transcript_day\": \"transcript_day\", \"engram.transcript_search\": \"transcript_search\",\n \"engram.transcript_memories\": \"transcript_memories\", \"engram.meetings_list\": \"meetings_list\", \"engram.meetings_get\": \"meetings_get\", \"engram.meetings_build\": \"meetings_build\",\n \"engram.action_confidence\": \"action_confidence\",\n \"engram.chatgpt_memory_inspector\": \"chatgpt_memory_inspector\",\n \"engram.day_summary\": \"day_summary\",\n \"engram.capsule_export\": \"capsule_export\",\n \"engram.capsule_import\": \"capsule_import\",\n \"engram.capsule_list\": \"capsule_list\",\n \"engram.memory_governance_run\": \"memory_governance_run\",\n \"engram.entity_synthesis_run\": \"entity_synthesis_run\",\n \"engram.procedure_mining_run\": \"procedure_mining_run\",\n \"engram.pattern_reinforcement_run\": \"pattern_reinforcement_run\",\n \"engram.procedural_stats\": \"procedural_stats\", \"engram.procedure_library_maintenance\": \"procedure_library_maintenance\",\n \"engram.memory_timeline\": \"memory_timeline\",\n \"engram.suggestion_submit\": \"suggestion_submit\",\n \"engram.entity_get\": \"entity_get\",\n \"engram.review_queue_list\": \"review_queue_list\",\n \"engram.observe\": \"observe\",\n \"engram.lcm_search\": \"lcm_search\",\n \"engram.lcm_compaction_flush\": \"lcm_compaction_flush\",\n \"engram.extraction_force_flush\": \"extraction_force_flush\",\n \"engram.lcm_compaction_record\": \"lcm_compaction_record\",\n \"engram.continuity_audit_generate\": \"continuity_audit_generate\",\n \"engram.continuity_incident_open\": \"continuity_incident_open\",\n \"engram.continuity_incident_close\": \"continuity_incident_close\",\n \"engram.continuity_incident_list\": \"continuity_incident_list\",\n \"engram.continuity_loop_add_or_update\": \"continuity_loop_add_or_update\",\n \"engram.continuity_loop_review\": \"continuity_loop_review\",\n \"engram.identity_anchor_get\": \"identity_anchor_get\",\n \"engram.identity_anchor_update\": \"identity_anchor_update\",\n \"engram.memory_identity\": \"memory_identity\",\n \"engram.work_task\": \"work_task\",\n \"engram.work_project\": \"work_project\",\n \"engram.work_board\": \"work_board\",\n \"engram.shared_context_write_output\": \"shared_context_write_output\",\n \"engram.shared_feedback_record\": \"shared_feedback_record\",\n \"engram.shared_priorities_append\": \"shared_priorities_append\",\n \"engram.shared_context_cross_signals_run\": \"shared_context_cross_signals_run\",\n \"engram.shared_context_curate_daily\": \"shared_context_curate_daily\",\n \"engram.compounding_weekly_synthesize\": \"compounding_weekly_synthesize\",\n \"engram.compounding_promote_candidate\": \"compounding_promote_candidate\",\n \"engram.compression_guidelines_optimize\": \"compression_guidelines_optimize\",\n \"engram.compression_guidelines_activate\": \"compression_guidelines_activate\",\n \"engram.memory_profile\": \"memory_profile\",\n \"engram.memory_entities_list\": \"memory_entities_list\",\n \"engram.memory_questions\": \"memory_questions\",\n \"engram.memory_last_recall\": \"memory_last_recall\",\n \"engram.memory_intent_debug\": \"memory_intent_debug\",\n \"engram.memory_qmd_debug\": \"memory_qmd_debug\",\n \"engram.memory_graph_explain\": \"memory_graph_explain\",\n \"engram.graph_snapshot\": \"graph_snapshot\",\n \"engram.memory_feedback\": \"memory_feedback\",\n \"engram.memory_promote\": \"memory_promote\",\n \"engram.memory_outcome\": \"memory_outcome\",\n \"engram.memory_action_apply\": \"memory_action_apply\",\n \"engram.context_checkpoint\": \"context_checkpoint\",\n \"engram.briefing\": \"briefing\",\n \"engram.review_list\": \"review_list\",\n \"engram.review_resolve\": \"review_resolve\",\n \"engram.contradiction_scan_run\": \"contradiction_scan_run\",\n \"engram.memory_summarize_hourly\": \"memory_summarize_hourly\",\n \"engram.conversation_index_update\": \"conversation_index_update\",\n \"engram.profiling_report\": \"profiling_report\",\n \"engram.graph_edge_decay_run\": \"graph_edge_decay_run\",\n \"engram.live_connectors_run\": \"live_connectors_run\",\n \"engram.peer_list\": \"peer_list\",\n \"engram.peer_get\": \"peer_get\",\n \"engram.peer_set\": \"peer_set\",\n \"engram.peer_delete\": \"peer_delete\",\n \"engram.peer_profile_get\": \"peer_profile_get\",\n \"engram.peer_forget\": \"peer_forget\",\n \"engram.console_state\": \"console_state\",\n \"engram.dreams_status\": \"dreams_status\",\n \"engram.dreams_run\": \"dreams_run\",\n ...SUPPORT_PASSPORT_MCP_MIGRATED_OPERATIONS, ...MCP_ADMIN_OPS_MIGRATED_OPERATIONS,\n \"engram.memory_chat\": \"chat_message\",\n};\n\nfunction resolveChatGptInspectorRecallSessionKey(\n explicitSessionKey: string | undefined,\n authenticatedPrincipal: string | undefined\n): string | undefined {\n if (explicitSessionKey) return explicitSessionKey;\n if (!authenticatedPrincipal) return undefined;\n return `remnic:chatgpt-memory-inspector:${randomUUID()}`;\n}\n\nconst STRICT_MCP_SCHEMA_KEYS: Partial<Record<SchemaName, readonly string[]>> = {\n daySummary: [\"memories\", \"sessionKey\", \"namespace\", \"timeZone\", \"cwd\", \"projectTag\"],\n memoryStore: [\n \"schemaVersion\",\n \"idempotencyKey\",\n \"dryRun\",\n \"sessionKey\",\n \"content\",\n \"category\",\n \"confidence\",\n \"namespace\",\n \"tags\",\n \"entityRef\",\n \"ttl\",\n \"sourceReason\",\n \"cwd\",\n \"projectTag\",\n ],\n suggestionSubmit: [\n \"schemaVersion\",\n \"idempotencyKey\",\n \"dryRun\",\n \"sessionKey\",\n \"content\",\n \"category\",\n \"confidence\",\n \"namespace\",\n \"tags\",\n \"entityRef\",\n \"ttl\",\n \"sourceReason\",\n \"cwd\",\n \"projectTag\",\n ],\n capsuleExport: [\n \"name\",\n \"namespace\",\n \"since\",\n \"includeKinds\",\n \"peerIds\",\n \"includeTranscripts\",\n \"encrypt\",\n \"cwd\",\n \"projectTag\",\n ],\n capsuleImport: [\"archivePath\", \"namespace\", \"mode\", \"passphrase\", \"cwd\", \"projectTag\"],\n capsuleList: [\"namespace\", \"sessionKey\", \"cwd\", \"projectTag\"],\n};\n\n// Tools whose envelope parses through the canonical zod wire schema (issue\n// #2482) — the SAME validation the HTTP transport runs. Every other migrated\n// tool passes raw args; its boundary op schema validates them.\nconst MCP_WIRE_SCHEMAS: Partial<Record<string, SchemaName>> = {\n memory_store: \"memoryStore\",\n suggestion_submit: \"suggestionSubmit\",\n action_confidence: \"actionConfidence\",\n day_summary: \"daySummary\",\n capsule_export: \"capsuleExport\",\n capsule_import: \"capsuleImport\",\n capsule_list: \"capsuleList\",\n observe: \"observe\",\n recall: \"recall\",\n lcm_compaction_flush: \"lcmCompactionFlush\",\n extraction_force_flush: \"extractionForceFlush\",\n lcm_compaction_record: \"lcmCompactionRecord\",\n};\n\n// Shared JSON-schema fragments for the client-injected git/project context\n// fields (#1434). Declared once to avoid drift across tool definitions.\n// `_SCOPED` is for write tools that resolve a project namespace from these\n// fields; `_IGNORED` is for tools that merely tolerate them for MCP client\n// compatibility (clients like Pi MCPorter auto-inject `cwd` on every call).\nconst MCP_GIT_CONTEXT_SCHEMA_PROPS_SCOPED: Record<string, unknown> = {\n cwd: {\n type: \"string\",\n description:\n \"Optional working directory. When no explicit namespace is given, resolves the project namespace this write is stored in (mirrors recall/observe).\",\n },\n projectTag: {\n type: \"string\",\n description:\n \"Optional project tag for non-git project scoping. When no explicit namespace is given, routes this write to the tagged project namespace.\",\n },\n};\n\nfunction parseMcpRequest<N extends SchemaName>(schemaName: N, args: Record<string, unknown>): SchemaTypeFor<N> {\n const allowedKeys = STRICT_MCP_SCHEMA_KEYS[schemaName];\n if (allowedKeys) {\n const allowed = new Set(allowedKeys);\n const unexpected = Object.keys(args).filter((key) => !allowed.has(key));\n if (unexpected.length > 0) {\n throw new EngramAccessInputError(\n `request validation failed: (root): Unrecognized key(s) in object: ${unexpected.join(\", \")}`\n );\n }\n }\n const validation = validateRequest<SchemaTypeFor<N>>(schemaName, args);\n if (validation.success) return validation.data;\n const details = validation.error.details.map((detail) => `${detail.field}: ${detail.message}`).join(\"; \");\n throw new EngramAccessInputError(\n details.length > 0 ? `${validation.error.error}: ${details}` : validation.error.error\n );\n}\n\n/**\n * Strict optional-string MCP argument: absent/null/\"\" → undefined,\n * non-string → loud error (CLAUDE.md rule 51 — no silent coercion).\n */\nfunction optionalNonEmptyString(value: unknown, label: string): string | undefined {\n if (value === undefined || value === null || value === \"\") return undefined;\n if (typeof value !== \"string\") {\n throw new Error(`${label} expects a string; got ${JSON.stringify(value)}`);\n }\n return value;\n}\n\n/**\n * Strict optional positive-integer MCP argument. Accepts JSON numbers\n * and numeric strings (loosely-typed MCP clients send both); rejects\n * everything else including booleans, which `Number()` would silently\n * coerce.\n */\nfunction optionalPositiveInteger(value: unknown, label: string): number | undefined {\n if (value === undefined || value === null || value === \"\") return undefined;\n if (typeof value !== \"number\" && typeof value !== \"string\") {\n throw new Error(`${label} expects a positive integer; got ${JSON.stringify(value)}`);\n }\n const parsed = typeof value === \"number\" ? value : Number(value);\n if (!Number.isFinite(parsed) || parsed <= 0 || !Number.isInteger(parsed)) {\n throw new Error(`${label} expects a positive integer; got ${JSON.stringify(value)}`);\n }\n return parsed;\n}\n\nfunction getObjectProperties(value: unknown): Record<string, unknown> | undefined {\n return value && typeof value === \"object\" && !Array.isArray(value) ? (value as Record<string, unknown>) : undefined;\n}\n\nasync function getMcpServerVersion(): Promise<string> {\n const envVersion = readEnvVar(\"OPENCLAW_ENGRAM_VERSION\")?.trim() || readEnvVar(\"npm_package_version\")?.trim();\n if (envVersion) return envVersion;\n try {\n const pkgPath = new URL(\"../package.json\", import.meta.url);\n const raw = await readFile(pkgPath, \"utf-8\");\n const parsed = JSON.parse(raw) as { version?: string };\n return parsed.version?.trim() || \"unknown\";\n } catch {\n return \"unknown\";\n }\n}\n\nexport class EngramMcpServer {\n private buffer = Buffer.alloc(0);\n private flushTask: Promise<void> | null = null;\n private readonly tools: McpTool[];\n private readonly resources: McpResource[];\n private readonly resourceTextByUri: Map<string, string>;\n private readonly authenticatedPrincipal?: string;\n /**\n * MCP client info keyed by server-assigned session ID. On each `initialize`\n * handshake the server generates a UUID, stores the client's clientInfo\n * against it, and returns the ID as `Mcp-Session-Id` in the response\n * metadata. Subsequent requests from the same client include this header,\n * allowing per-session clientInfo lookup without cross-session leaks.\n */\n private clientInfoBySession = new Map<string, { name: string; version?: string }>();\n /**\n * Session IDs generated during initialize, keyed by caller-supplied correlation\n * ID (unique per HTTP request) to avoid collisions when multiple clients send\n * initialize with the same JSON-RPC id concurrently.\n */\n private initSessionIds = new Map<string, string>();\n\n /**\n * Whether oai-mem-citation guidance is explicitly enabled via config.\n */\n private readonly citationsEnabled: boolean;\n /** Whether to auto-enable citations for Codex adapter connections. */\n private readonly citationsAutoDetect: boolean;\n /**\n * Whether to advertise legacy `engram.*` tool aliases alongside the canonical\n * `remnic.*` names (issue #1427). Defaults to true for backward compatibility;\n * set false to halve the advertised `tools/list` surface.\n */\n private readonly emitLegacyTools: boolean;\n /**\n * Whether the `coding_decision` tool should appear in `tools/list`. Gated on\n * `codingKnowledge.enabled && codingKnowledge.decisionRecords` (issue #1548\n * Track A PR 2, rule 39). When false the tools array is byte-identical to\n * pre-feature.\n */\n private readonly codingDecisionVisible: boolean;\n /**\n * Whether the `coding_architecture` tool should appear in `tools/list`.\n * Gated on `codingKnowledge.enabled && codingKnowledge.architectureCard`\n * (issue #1548 Track A PR 3, rule 39).\n */\n private readonly architectureCardVisible: boolean;\n /**\n * Whether the 14 codegraph parity tools should appear in `tools/list`\n * (issue #1554). Config-only -- runtime availability is checked at call\n * time. When false the tools array is byte-identical to pre-feature.\n */\n private readonly codegraphVisible: boolean;\n private readonly sessionDeltaVisible: boolean;\n /**\n * Whether the two correction tools (memory_correct_plan / memory_correct_apply)\n * should appear in `tools/list` (issue #1580). Gated on `correction.enabled`\n * (default true — plan is read-only; safe on). When false the tools array is\n * byte-identical to pre-feature.\n */\n private readonly correctionVisible: boolean;\n\n /**\n * Whether the `memory_chat` tool should appear in `tools/list` (issue\n * #1583). Gated on `chat.enabled`. When false the tools array is\n * byte-identical to pre-feature (rule 39).\n */\n private readonly chatVisible: boolean;\n\n constructor(\n private readonly service: EngramAccessService,\n options: {\n principal?: string;\n citationsEnabled?: boolean;\n citationsAutoDetect?: boolean;\n emitLegacyTools?: boolean;\n codingDecisionVisible?: boolean;\n architectureCardVisible?: boolean;\n codegraphVisible?: boolean;\n sessionDeltaVisible?: boolean;\n correctionVisible?: boolean;\n chatVisible?: boolean;\n } = {}\n ) {\n this.citationsEnabled = options.citationsEnabled === true;\n this.citationsAutoDetect = options.citationsAutoDetect !== false;\n this.emitLegacyTools = options.emitLegacyTools !== false;\n this.codingDecisionVisible = options.codingDecisionVisible === true;\n this.architectureCardVisible = options.architectureCardVisible === true;\n this.codegraphVisible = options.codegraphVisible === true;\n this.sessionDeltaVisible = options.sessionDeltaVisible === true;\n // correction defaults to visible (enabled by default — plan is read-only).\n this.correctionVisible = options.correctionVisible !== false;\n this.chatVisible = options.chatVisible === true;\n this.authenticatedPrincipal =\n options.principal?.trim() || readEnvVar(\"OPENCLAW_ENGRAM_ACCESS_PRINCIPAL\")?.trim() || undefined;\n this.resources = [\n {\n uri: REMNIC_CHATGPT_MEMORY_INSPECTOR_WIDGET_URI,\n name: \"remnic-memory-inspector\",\n title: \"Remnic Memory Inspector\",\n description:\n \"Apps-compatible widget for inspecting retrieved Remnic memories, provenance, safety, and correction/scoping affordances.\",\n mimeType: REMNIC_CHATGPT_MEMORY_INSPECTOR_MIME_TYPE,\n _meta: {\n ui: {\n csp: {\n connectDomains: [],\n resourceDomains: [],\n },\n prefersBorder: true,\n },\n \"openai/widgetDescription\":\n \"Inspect retrieved Remnic memories, provenance, safety, and correction/scoping affordances.\",\n },\n },\n ];\n this.resourceTextByUri = new Map([\n [REMNIC_CHATGPT_MEMORY_INSPECTOR_WIDGET_URI, REMNIC_CHATGPT_MEMORY_INSPECTOR_WIDGET_HTML],\n ]);\n this.tools = [\n {\n name: \"engram.recall\",\n description: \"Recall Engram context for a query.\",\n inputSchema: {\n type: \"object\",\n properties: {\n query: { type: \"string\" },\n sessionKey: { type: \"string\" },\n namespace: { type: \"string\" },\n topK: { type: \"number\" },\n mode: { type: \"string\", enum: [\"auto\", \"no_recall\", \"minimal\", \"full\", \"graph_mode\"] },\n includeDebug: { type: \"boolean\" },\n // Recall disclosure depth (issue #677). Default `chunk` when\n // omitted. Section/raw payload shaping ships in PR 2; this PR\n // wires the field end-to-end so clients can already pass it\n // without it being silently dropped.\n disclosure: { type: \"string\", enum: [\"chunk\", \"section\", \"raw\"] },\n cwd: { type: \"string\", description: \"Working directory for auto git-context resolution.\" },\n projectTag: {\n type: \"string\",\n description: \"Project tag for non-git project scoping (e.g. 'acme-webshop').\",\n },\n asOf: {\n type: \"string\",\n description:\n \"Historical recall pin (issue #680). ISO 8601 timestamp; when set, the recall returns the corpus as it existed at this instant.\",\n },\n tags: {\n type: \"array\",\n items: { type: \"string\" },\n description: \"Filter recall results to memories whose frontmatter tags match (issue #689).\",\n },\n tagMatch: {\n type: \"string\",\n enum: [\"any\", \"all\"],\n description:\n \"Tag-filter match mode. 'any' (default) admits results with at least one filter tag; 'all' requires every filter tag.\",\n },\n },\n required: [\"query\"],\n additionalProperties: false,\n },\n },\n {\n name: \"engram.recall_explain\",\n description: \"Return the last recall snapshot for a session or the most recent one.\",\n inputSchema: {\n type: \"object\",\n properties: {\n sessionKey: { type: \"string\" },\n namespace: { type: \"string\" },\n },\n additionalProperties: false,\n },\n },\n {\n name: \"engram.set_coding_context\",\n description:\n \"Attach a coding-agent context (project / branch) to a session so recall routes to a project- / branch-scoped namespace (issue #569). For MCP clients that do not ship cwd automatically (Cursor, generic agents, etc.). Also aliased as remnic.set_coding_context. Pass codingContext: null to clear. Alternatively, pass just a projectTag for non-git project scoping (e.g. OpenClaw channels).\",\n inputSchema: {\n type: \"object\",\n properties: {\n sessionKey: {\n type: \"string\",\n description: \"Session identifier the context should attach to.\",\n },\n codingContext: {\n anyOf: [\n { type: \"null\" },\n {\n type: \"object\",\n properties: {\n projectId: { type: \"string\", description: \"Stable project id (origin:<hex> or root:<hex>).\" },\n branch: { type: [\"string\", \"null\"], description: \"Current branch, or null in detached HEAD.\" },\n rootPath: { type: \"string\", description: \"Absolute path to the repo root.\" },\n defaultBranch: {\n type: [\"string\", \"null\"],\n description: \"Default branch (usually main/master), or null when unknown.\",\n },\n },\n required: [\"projectId\", \"branch\", \"rootPath\", \"defaultBranch\"],\n additionalProperties: false,\n },\n ],\n description: \"The context to attach, or null to clear. Omit when using projectTag instead.\",\n },\n projectTag: {\n type: \"string\",\n description:\n \"Arbitrary project tag for non-git project scoping (e.g. 'acme-webshop'). \" +\n \"Creates a coding context with projectId 'tag:<projectTag>'. \" +\n \"Use instead of codingContext when the session isn't tied to a specific git repo.\",\n },\n },\n required: [\"sessionKey\"],\n additionalProperties: false,\n },\n },\n {\n name: \"engram.recall_tier_explain\",\n description:\n \"Return a structured tier-explain payload for the last direct-answer-eligible recall (issue #518). Orthogonal to engram.recall_explain, which returns a graph-path explanation.\",\n inputSchema: {\n type: \"object\",\n properties: {\n sessionKey: {\n type: \"string\",\n description: \"Optional session key. Omit to read the most recent snapshot.\",\n },\n namespace: {\n type: \"string\",\n description: \"Optional namespace to scope the returned snapshot.\",\n },\n },\n additionalProperties: false,\n },\n },\n {\n // Registered as `engram.recall_xray`; `withToolAliases` below\n // emits the canonical `remnic.recall_xray` alias automatically\n // (dual-naming invariant for every new MCP tool).\n name: \"engram.recall_xray\",\n description:\n \"Run a recall with X-ray capture enabled and return the unified per-result attribution snapshot (tier + audit + MMR + filters in one view). Issue #570.\",\n inputSchema: {\n type: \"object\",\n properties: {\n query: {\n type: \"string\",\n description: \"Query to recall against. Required; non-empty.\",\n },\n sessionKey: {\n type: \"string\",\n description: \"Optional session key to scope the recall.\",\n },\n namespace: {\n type: \"string\",\n description:\n \"Optional namespace. Enforced against the caller's principal; a mismatch yields snapshotFound:false.\",\n },\n budget: {\n type: \"integer\",\n minimum: 1,\n description: \"Optional positive-integer override for the recall character budget.\",\n },\n disclosure: {\n type: \"string\",\n enum: [\"chunk\", \"section\", \"raw\"],\n description:\n \"Optional disclosure depth for X-ray telemetry (issue #677). When set, populates the per-disclosure token-spend summary on each result.\",\n },\n },\n required: [\"query\"],\n additionalProperties: false,\n },\n },\n ...WEARABLES_MCP_TOOLS, ...MEETINGS_MCP_TOOLS, ...WHO_KNOWS_MCP_TOOLS, ...PROMOTION_CANDIDATES_MCP_TOOLS, ...LOCATION_MCP_TOOLS,\n ...(service.supportPassportEnabled ? SUPPORT_PASSPORT_MCP_TOOLS : []),\n {\n name: \"engram.action_confidence\",\n description:\n \"Advisory ask/draft/act/refuse/escalate decision helper for interruption budgeting. Read-only; never mutates memory.\",\n inputSchema: {\n type: \"object\",\n properties: {\n intendedAction: { type: \"string\" },\n confidence: { type: \"number\", minimum: 0, maximum: 1 },\n risk: {\n type: \"string\",\n enum: [\"low\", \"medium\", \"high\", \"irreversible\", \"restricted\"],\n },\n contextReadiness: {\n type: \"string\",\n enum: [\"none\", \"partial\", \"sufficient\"],\n },\n currentContextScopes: {\n type: \"array\",\n items: { type: \"string\" },\n },\n userRules: {\n type: \"array\",\n items: {\n type: \"object\",\n properties: {\n kind: {\n type: \"string\",\n enum: [\"ask-before\", \"do-not-use-outside-this-context\", \"never\", \"requires-escalation\"],\n },\n description: { type: \"string\" },\n matched: { type: \"boolean\" },\n },\n required: [\"kind\"],\n additionalProperties: false,\n },\n },\n retrievedMemories: {\n type: \"array\",\n items: {\n type: \"object\",\n properties: {\n source: { type: \"string\" },\n created: { type: \"string\" },\n updated: { type: \"string\" },\n scope: { type: \"string\" },\n userContextScopes: {\n type: \"array\",\n items: { type: \"string\" },\n },\n retrievalReason: { type: \"string\" },\n confidence: { type: \"number\", minimum: 0, maximum: 1 },\n stale: { type: \"boolean\" },\n corrected: { type: \"boolean\" },\n correctionState: {\n type: \"string\",\n enum: [\"none\", \"correction\", \"superseded\", \"disputed\", \"forgotten\"],\n },\n safeToUse: { type: \"boolean\" },\n safety: {\n type: \"string\",\n enum: [\"safe\", \"requires-review\", \"blocked\"],\n },\n safetyReasons: {\n type: \"array\",\n items: { type: \"string\" },\n },\n },\n additionalProperties: false,\n },\n },\n },\n additionalProperties: false,\n },\n },\n {\n name: REMNIC_CHATGPT_MEMORY_INSPECTOR_TOOL,\n title: \"Show Remnic Memory Inspector\",\n description:\n \"Use this when the user wants a ChatGPT Apps-compatible UI for inspecting Remnic recall, provenance, safety, and correction/forget/scoping affordances. Read-only; correction and forget actions are proposed as follow-up prompts.\",\n inputSchema: {\n type: \"object\",\n properties: {\n query: {\n type: \"string\",\n description: \"Memory question to inspect.\",\n },\n sessionKey: {\n type: \"string\",\n description: \"Optional Remnic session key for scoped recall.\",\n },\n namespace: {\n type: \"string\",\n description: \"Optional Remnic namespace to inspect.\",\n },\n currentContextScopes: {\n type: \"array\",\n items: { type: \"string\" },\n description: \"Optional current user-context scopes, such as repo, work, personal, client, or private.\",\n },\n allowUnverifiedPreview: {\n type: \"boolean\",\n description:\n \"If true, the inspector may show recalled preview text when X-ray provenance is missing or unavailable. Explicitly blocked memories remain redacted.\",\n },\n },\n required: [\"query\"],\n additionalProperties: false,\n },\n outputSchema: {\n type: \"object\",\n properties: {\n app: { type: \"object\" },\n query: { type: \"string\" },\n sessionKey: { type: \"string\" },\n namespace: { type: \"string\" },\n safeRecallPreview: { type: \"string\" },\n memoryCount: { type: \"number\" },\n memoryIds: { type: \"array\", items: { type: \"string\" } },\n memories: { type: \"array\", items: { type: \"object\" } },\n actionConfidence: { type: \"object\" },\n affordances: { type: \"array\", items: { type: \"object\" } },\n guidance: { type: \"object\" },\n },\n required: [\n \"app\",\n \"query\",\n \"namespace\",\n \"safeRecallPreview\",\n \"memoryCount\",\n \"memoryIds\",\n \"memories\",\n \"actionConfidence\",\n \"affordances\",\n \"guidance\",\n ],\n additionalProperties: false,\n },\n annotations: {\n readOnlyHint: true,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n },\n _meta: {\n ui: {\n resourceUri: REMNIC_CHATGPT_MEMORY_INSPECTOR_WIDGET_URI,\n visibility: [\"model\", \"app\"],\n },\n \"openai/outputTemplate\": REMNIC_CHATGPT_MEMORY_INSPECTOR_WIDGET_URI,\n \"openai/toolInvocation/invoking\": \"Inspecting Remnic memory...\",\n \"openai/toolInvocation/invoked\": \"Remnic memory inspector ready.\",\n },\n },\n {\n name: \"engram.day_summary\",\n description:\n \"Generate a structured end-of-day summary. When memories is omitted or empty, auto-gathers today's facts and hourly summaries from storage.\",\n inputSchema: {\n type: \"object\",\n properties: {\n memories: { type: \"string\" },\n sessionKey: { type: \"string\" },\n namespace: { type: \"string\" },\n timeZone: { type: \"string\" },\n ...MCP_GIT_CONTEXT_SCHEMA_PROPS_IGNORED,\n },\n required: [],\n additionalProperties: false,\n },\n },\n ...MCP_ADMIN_OPS_TOOLS,\n {\n name: \"engram.memory_get\",\n description: \"Fetch one Remnic memory by id.\",\n inputSchema: {\n type: \"object\",\n properties: {\n memoryId: { type: \"string\" },\n namespace: { type: \"string\" },\n // Issue #1582 — when memoryId is a `[m:xxxx]` handle, sessionKey\n // scopes resolution to this session's recent recall history.\n // Advertising it here lets the transport inject its session key\n // (toolAcceptsArgument) so MCP callers can cite handles (codex review).\n sessionKey: { type: \"string\" },\n },\n required: [\"memoryId\"],\n additionalProperties: false,\n },\n },\n {\n name: \"engram.memory_timeline\",\n description: \"Fetch one Remnic memory timeline by id.\",\n inputSchema: {\n type: \"object\",\n properties: {\n memoryId: { type: \"string\" },\n namespace: { type: \"string\" },\n limit: { type: \"number\" },\n },\n required: [\"memoryId\"],\n additionalProperties: false,\n },\n },\n {\n name: \"engram.memory_store\",\n description: \"Store an explicit Remnic memory through the access layer.\",\n inputSchema: {\n type: \"object\",\n properties: {\n schemaVersion: { type: \"number\" },\n idempotencyKey: { type: \"string\" },\n dryRun: { type: \"boolean\" },\n sessionKey: { type: \"string\" },\n content: { type: \"string\" },\n category: { type: \"string\" },\n confidence: { type: \"number\" },\n namespace: { type: \"string\" },\n tags: { type: \"array\", items: { type: \"string\" } },\n entityRef: { type: \"string\" },\n ttl: { type: \"string\" },\n sourceReason: { type: \"string\" },\n ...MCP_GIT_CONTEXT_SCHEMA_PROPS_SCOPED,\n },\n required: [\"content\"],\n additionalProperties: false,\n },\n },\n {\n name: \"engram.suggestion_submit\",\n description: \"Queue a suggested Remnic memory for review.\",\n inputSchema: {\n type: \"object\",\n properties: {\n schemaVersion: { type: \"number\" },\n idempotencyKey: { type: \"string\" },\n dryRun: { type: \"boolean\" },\n sessionKey: { type: \"string\" },\n content: { type: \"string\" },\n category: { type: \"string\" },\n confidence: { type: \"number\" },\n namespace: { type: \"string\" },\n tags: { type: \"array\", items: { type: \"string\" } },\n entityRef: { type: \"string\" },\n ttl: { type: \"string\" },\n sourceReason: { type: \"string\" },\n ...MCP_GIT_CONTEXT_SCHEMA_PROPS_SCOPED,\n },\n required: [\"content\"],\n additionalProperties: false,\n },\n },\n {\n name: \"engram.entity_get\",\n description: \"Fetch one Engram entity by name.\",\n inputSchema: {\n type: \"object\",\n properties: {\n name: { type: \"string\" },\n namespace: { type: \"string\" },\n },\n required: [\"name\"],\n additionalProperties: false,\n },\n },\n {\n name: \"engram.review_queue_list\",\n description: \"Fetch the latest Engram review queue artifact bundle.\",\n inputSchema: {\n type: \"object\",\n properties: {\n runId: { type: \"string\" },\n namespace: { type: \"string\" },\n },\n additionalProperties: false,\n },\n },\n {\n name: \"engram.observe\",\n description: \"Feed conversation messages into Engram's memory pipeline (LCM archive + extraction).\",\n inputSchema: {\n type: \"object\",\n properties: {\n sessionKey: { type: \"string\", description: \"Conversation session identifier\" },\n messages: {\n type: \"array\",\n items: {\n type: \"object\",\n properties: {\n role: { type: \"string\", enum: [\"user\", \"assistant\"] },\n content: { type: \"string\" },\n sourceFormat: {\n type: \"string\",\n enum: [\"openai\", \"anthropic\", \"openclaw\", \"pi\", \"lossless-claw\", \"remnic\"],\n },\n rawContent: {\n description: \"Optional native provider content blocks for structured message-part capture.\",\n },\n parts: {\n type: \"array\",\n description: \"Optional normalized Remnic LCM message parts.\",\n items: {\n type: \"object\",\n properties: {\n ordinal: { type: [\"number\", \"null\"], minimum: 0 },\n kind: {\n type: \"string\",\n enum: [\n \"text\",\n \"tool_call\",\n \"tool_result\",\n \"patch\",\n \"file_read\",\n \"file_write\",\n \"step_start\",\n \"step_finish\",\n \"snapshot\",\n \"retry\",\n ],\n },\n payload: { type: \"object\", additionalProperties: true },\n toolName: { type: [\"string\", \"null\"] },\n tool_name: { type: [\"string\", \"null\"] },\n filePath: { type: [\"string\", \"null\"] },\n file_path: { type: [\"string\", \"null\"] },\n createdAt: { type: [\"string\", \"null\"] },\n created_at: { type: [\"string\", \"null\"] },\n },\n required: [\"kind\", \"payload\"],\n additionalProperties: false,\n },\n },\n },\n required: [\"role\", \"content\"],\n additionalProperties: false,\n },\n description: \"Conversation messages to observe\",\n },\n idempotencyKey: {\n type: \"string\",\n description:\n \"Optional idempotency key (issue #1649). Deduplicates a retried observe POST server-side so the batch is ingested once even when the HTTP response is lost. Reusing the key with a different payload is rejected.\",\n },\n namespace: { type: \"string\" },\n skipExtraction: { type: \"boolean\" },\n cwd: { type: \"string\", description: \"Working directory for auto git-context resolution.\" },\n projectTag: {\n type: \"string\",\n description: \"Project tag for non-git project scoping (e.g. 'acme-webshop').\",\n },\n },\n required: [\"sessionKey\", \"messages\"],\n additionalProperties: false,\n },\n },\n {\n name: \"engram.lcm_search\",\n description: \"Search the LCM conversation archive for matching content.\",\n inputSchema: {\n type: \"object\",\n properties: {\n query: { type: \"string\", description: \"Search query\" },\n sessionKey: { type: \"string\", description: \"Optional session filter\" },\n sessionPrefix: { type: \"string\", description: \"Optional session prefix filter\" },\n namespace: { type: \"string\" },\n limit: { type: \"number\", description: \"Max results to return\" },\n },\n required: [\"query\"],\n additionalProperties: false,\n },\n },\n {\n name: \"engram.lcm_compaction_flush\",\n description: \"Flush pending LCM observe work and incremental summaries before a host compacts session context.\",\n inputSchema: {\n type: \"object\",\n properties: {\n sessionKey: { type: \"string\", description: \"Conversation session identifier\" },\n namespace: { type: \"string\" },\n cwd: { type: \"string\", description: \"Working directory for auto git-context resolution.\" },\n projectTag: { type: \"string\", description: \"Project tag for non-git project scoping.\" },\n },\n required: [\"sessionKey\"],\n additionalProperties: false,\n },\n },\n {\n name: \"engram.extraction_force_flush\",\n description: \"Force-drain a session extraction buffer before a lifecycle boundary.\",\n inputSchema: {\n type: \"object\",\n properties: {\n sessionKey: { type: \"string\", description: \"Conversation session identifier\" },\n namespace: { type: \"string\" },\n cwd: { type: \"string\", description: \"Working directory for auto git-context resolution.\" },\n projectTag: { type: \"string\", description: \"Project tag for non-git project scoping.\" },\n deadlineMs: { type: \"number\", minimum: 0 },\n },\n required: [\"sessionKey\"],\n additionalProperties: false,\n },\n },\n {\n name: \"engram.lcm_compaction_record\",\n description: \"Record a host compaction event with before/after token counts in the LCM archive.\",\n inputSchema: {\n type: \"object\",\n properties: {\n sessionKey: { type: \"string\", description: \"Conversation session identifier\" },\n namespace: { type: \"string\" },\n tokensBefore: { type: \"integer\", minimum: 0 },\n tokensAfter: { type: \"integer\", minimum: 0 },\n },\n required: [\"sessionKey\", \"tokensBefore\", \"tokensAfter\"],\n additionalProperties: false,\n },\n },\n // ── Continuity / Identity tools ─────────────────────────────────────\n {\n name: \"engram.continuity_audit_generate\",\n description: \"Generate a deterministic identity continuity audit report (weekly/monthly).\",\n inputSchema: {\n type: \"object\",\n properties: {\n period: { type: \"string\", enum: [\"weekly\", \"monthly\"] },\n key: {\n type: \"string\",\n description: \"Period key (weekly: YYYY-Www, monthly: YYYY-MM). Defaults to current.\",\n },\n },\n additionalProperties: false,\n },\n },\n {\n name: \"engram.continuity_incident_open\",\n description: \"Create a new continuity incident record in append-only storage.\",\n inputSchema: {\n type: \"object\",\n properties: {\n symptom: { type: \"string\", description: \"Observed continuity failure symptom.\" },\n namespace: { type: \"string\" },\n triggerWindow: { type: \"string\", description: \"Time window when incident occurred.\" },\n suspectedCause: { type: \"string\" },\n },\n required: [\"symptom\"],\n additionalProperties: false,\n },\n },\n {\n name: \"engram.continuity_incident_close\",\n description: \"Close an open continuity incident with verification details.\",\n inputSchema: {\n type: \"object\",\n properties: {\n id: { type: \"string\", description: \"Incident ID to close.\" },\n namespace: { type: \"string\" },\n fixApplied: { type: \"string\", description: \"What fix was applied.\" },\n verificationResult: { type: \"string\", description: \"How closure was verified.\" },\n preventiveRule: { type: \"string\", description: \"Optional preventive follow-up rule.\" },\n },\n required: [\"id\", \"fixApplied\", \"verificationResult\"],\n additionalProperties: false,\n },\n },\n {\n name: \"engram.continuity_incident_list\",\n description: \"List continuity incidents, optionally filtered by state.\",\n inputSchema: {\n type: \"object\",\n properties: {\n state: { type: \"string\", enum: [\"open\", \"closed\", \"all\"] },\n namespace: { type: \"string\" },\n limit: { type: \"number\", description: \"Max incidents (default 25, max 200).\" },\n },\n additionalProperties: false,\n },\n },\n {\n name: \"engram.continuity_loop_add_or_update\",\n description: \"Add or update a continuity improvement loop entry.\",\n inputSchema: {\n type: \"object\",\n properties: {\n id: { type: \"string\", description: \"Stable loop identifier.\" },\n cadence: { type: \"string\", enum: [\"daily\", \"weekly\", \"monthly\", \"quarterly\"] },\n purpose: { type: \"string\", description: \"What this recurring loop improves.\" },\n status: { type: \"string\", enum: [\"active\", \"paused\", \"retired\"] },\n killCondition: { type: \"string\", description: \"Clear condition for retiring this loop.\" },\n namespace: { type: \"string\" },\n lastReviewed: { type: \"string\", description: \"ISO timestamp for last review.\" },\n notes: { type: \"string\" },\n },\n required: [\"id\", \"cadence\", \"purpose\", \"status\", \"killCondition\"],\n additionalProperties: false,\n },\n },\n {\n name: \"engram.continuity_loop_review\",\n description: \"Update review metadata for an existing continuity improvement loop.\",\n inputSchema: {\n type: \"object\",\n properties: {\n id: { type: \"string\", description: \"Loop ID to review.\" },\n namespace: { type: \"string\" },\n status: { type: \"string\", enum: [\"active\", \"paused\", \"retired\"] },\n notes: { type: \"string\" },\n reviewedAt: { type: \"string\", description: \"ISO timestamp for review event.\" },\n },\n required: [\"id\"],\n additionalProperties: false,\n },\n },\n {\n name: \"engram.identity_anchor_get\",\n description: \"Read the identity continuity anchor document (recovery-safe identity context).\",\n inputSchema: {\n type: \"object\",\n properties: {\n namespace: { type: \"string\" },\n },\n additionalProperties: false,\n },\n },\n {\n name: \"engram.identity_anchor_update\",\n description: \"Conservatively merge identity anchor sections without overwriting existing material.\",\n inputSchema: {\n type: \"object\",\n properties: {\n namespace: { type: \"string\" },\n identityTraits: { type: \"string\", description: \"Updates for 'Identity Traits' section.\" },\n communicationPreferences: {\n type: \"string\",\n description: \"Updates for 'Communication Preferences' section.\",\n },\n operatingPrinciples: { type: \"string\", description: \"Updates for 'Operating Principles' section.\" },\n continuityNotes: { type: \"string\", description: \"Updates for 'Continuity Notes' section.\" },\n },\n additionalProperties: false,\n },\n },\n {\n name: \"engram.memory_identity\",\n description: \"Read the agent's identity reflections from the workspace IDENTITY.md file.\",\n inputSchema: {\n type: \"object\",\n properties: {\n namespace: { type: \"string\" },\n },\n additionalProperties: false,\n },\n },\n // ── Work Layer tools ─────────────────────────────────────────────────\n {\n name: \"engram.work_task\",\n description:\n \"Manage work-layer tasks (create, get, list, update, transition, delete). Excluded from memory extraction.\",\n inputSchema: {\n type: \"object\",\n properties: {\n action: { type: \"string\", enum: [\"create\", \"get\", \"list\", \"update\", \"transition\", \"delete\"] },\n id: { type: \"string\" },\n title: { type: \"string\" },\n description: { type: \"string\" },\n status: { type: \"string\", enum: [\"todo\", \"in_progress\", \"blocked\", \"done\", \"cancelled\"] },\n priority: { type: \"string\", enum: [\"low\", \"medium\", \"high\"] },\n owner: { type: \"string\" },\n assignee: { type: \"string\" },\n projectId: { type: \"string\" },\n tags: { type: \"array\", items: { type: \"string\" } },\n dueAt: { type: \"string\" },\n },\n required: [\"action\"],\n additionalProperties: false,\n },\n },\n {\n name: \"engram.work_project\",\n description:\n \"Manage work-layer projects (create, get, list, update, delete, link_task). Excluded from memory extraction.\",\n inputSchema: {\n type: \"object\",\n properties: {\n action: { type: \"string\", enum: [\"create\", \"get\", \"list\", \"update\", \"delete\", \"link_task\"] },\n id: { type: \"string\" },\n name: { type: \"string\" },\n description: { type: \"string\" },\n status: { type: \"string\", enum: [\"active\", \"on_hold\", \"completed\", \"archived\"] },\n owner: { type: \"string\" },\n tags: { type: \"array\", items: { type: \"string\" } },\n taskId: { type: \"string\", description: \"Task ID for link_task.\" },\n projectId: { type: \"string\", description: \"Project ID for link_task.\" },\n },\n required: [\"action\"],\n additionalProperties: false,\n },\n },\n {\n name: \"engram.work_board\",\n description: \"Export/import work-layer board snapshots and markdown.\",\n inputSchema: {\n type: \"object\",\n properties: {\n action: { type: \"string\", enum: [\"export_markdown\", \"export_snapshot\", \"import_snapshot\"] },\n projectId: { type: \"string\" },\n snapshotJson: { type: \"string\", description: \"Snapshot JSON for import_snapshot.\" },\n linkToMemory: { type: \"boolean\", description: \"If true, output can be retained as long-term memory.\" },\n },\n required: [\"action\"],\n additionalProperties: false,\n },\n },\n // ── Shared Context / Compounding tools ────────────────────────────\n {\n name: \"engram.shared_context_write_output\",\n description: \"Write agent work product into shared-context directory for cross-agent coordination.\",\n inputSchema: {\n type: \"object\",\n properties: {\n agentId: { type: \"string\", description: \"Agent ID producing this output.\" },\n title: { type: \"string\", description: \"Short title for the output.\" },\n content: { type: \"string\", description: \"Markdown content to write.\" },\n },\n required: [\"agentId\", \"title\", \"content\"],\n additionalProperties: false,\n },\n },\n {\n name: \"engram.shared_feedback_record\",\n description: \"Append approval/rejection decision into shared-context feedback inbox for compounding learning.\",\n inputSchema: {\n type: \"object\",\n properties: {\n agent: { type: \"string\", description: \"Agent name that produced the output.\" },\n decision: { type: \"string\", enum: [\"approved\", \"approved_with_feedback\", \"rejected\"] },\n reason: { type: \"string\" },\n date: { type: \"string\", description: \"ISO timestamp. Defaults to now.\" },\n learning: { type: \"string\" },\n outcome: { type: \"string\" },\n severity: { type: \"string\", enum: [\"low\", \"medium\", \"high\"] },\n confidence: { type: \"number\", description: \"Confidence 0-1.\" },\n workflow: { type: \"string\" },\n tags: { type: \"array\", items: { type: \"string\" } },\n evidenceWindowStart: { type: \"string\" },\n evidenceWindowEnd: { type: \"string\" },\n refs: { type: \"array\", items: { type: \"string\" } },\n },\n required: [\"agent\", \"decision\", \"reason\"],\n additionalProperties: false,\n },\n },\n {\n name: \"engram.shared_priorities_append\",\n description: \"Append priorities text into shared-context inbox for curator merge.\",\n inputSchema: {\n type: \"object\",\n properties: {\n agentId: { type: \"string\" },\n text: { type: \"string\", description: \"Priority notes (markdown).\" },\n },\n required: [\"agentId\", \"text\"],\n additionalProperties: false,\n },\n },\n {\n name: \"engram.shared_context_cross_signals_run\",\n description: \"Generate cross-signal markdown + JSON artifacts from agent outputs and feedback.\",\n inputSchema: {\n type: \"object\",\n properties: {\n date: { type: \"string\", description: \"YYYY-MM-DD. Defaults to today.\" },\n },\n additionalProperties: false,\n },\n },\n {\n name: \"engram.shared_context_curate_daily\",\n description: \"Generate daily roundtable summary (deterministic baseline aggregation).\",\n inputSchema: {\n type: \"object\",\n properties: {\n date: { type: \"string\", description: \"YYYY-MM-DD. Defaults to today.\" },\n },\n additionalProperties: false,\n },\n },\n {\n name: \"engram.compounding_weekly_synthesize\",\n description:\n \"Generate weekly compounding outputs: reports, mistake registry, rubrics, and promotion candidates.\",\n inputSchema: {\n type: \"object\",\n properties: {\n weekId: { type: \"string\", description: \"ISO week ID (YYYY-Www). Defaults to current week.\" },\n },\n additionalProperties: false,\n },\n },\n {\n name: \"engram.compounding_promote_candidate\",\n description: \"Promote a compounding candidate from weekly report into durable rule/principle memory.\",\n inputSchema: {\n type: \"object\",\n properties: {\n weekId: { type: \"string\" },\n candidateId: { type: \"string\" },\n dryRun: { type: \"boolean\", description: \"Preview without writing.\" },\n },\n required: [\"weekId\", \"candidateId\"],\n additionalProperties: false,\n },\n },\n // ── Compression Guidelines tools ────────────────────────────────────\n {\n name: \"engram.compression_guidelines_optimize\",\n description: \"Run compression guideline optimizer, optionally persisting new guidelines.\",\n inputSchema: {\n type: \"object\",\n properties: {\n dryRun: { type: \"boolean\" },\n eventLimit: { type: \"number\" },\n },\n additionalProperties: false,\n },\n },\n {\n name: \"engram.compression_guidelines_activate\",\n description: \"Promote staged compression guideline draft to active (after review).\",\n inputSchema: {\n type: \"object\",\n properties: {\n expectedContentHash: { type: \"string\" },\n expectedGuidelineVersion: { type: \"number\" },\n },\n additionalProperties: false,\n },\n },\n ...EXTERNAL_WIKI_MCP_TOOLS,\n {\n name: \"engram.memory_search\",\n description:\n \"Direct semantic search over memory files using the QMD index. Returns matching memories with relevance scores.\",\n inputSchema: {\n type: \"object\",\n properties: {\n query: { type: \"string\" },\n namespace: { type: \"string\" },\n maxResults: { type: \"number\" },\n collection: {\n type: \"string\",\n description:\n \"QMD collection. With namespaces enabled, omitted, base, and 'global' searches stay scoped to readable namespaces; namespace-derived collections require matching namespace access.\",\n },\n mode: { type: \"string\", enum: [\"search\", \"hybrid\", \"bm25\", \"vector\"], description: \"Ranking mode; omitted uses the backend default. Not supported with 'collection' on a flat corpus.\" },\n },\n required: [\"query\"],\n additionalProperties: false,\n },\n },\n {\n name: \"engram.memory_profile\",\n description:\n \"Read the user's behavioral profile — a living document of their preferences, habits, and personality.\",\n inputSchema: {\n type: \"object\",\n properties: { namespace: { type: \"string\" } },\n additionalProperties: false,\n },\n },\n {\n name: \"engram.memory_entities_list\",\n description: \"List all tracked entities (people, projects, tools, companies).\",\n inputSchema: {\n type: \"object\",\n properties: { namespace: { type: \"string\" } },\n additionalProperties: false,\n },\n },\n {\n name: \"engram.memory_questions\",\n description: \"List open questions the system is curious about from past conversations.\",\n inputSchema: {\n type: \"object\",\n properties: { namespace: { type: \"string\" } },\n additionalProperties: false,\n },\n },\n {\n name: \"engram.memory_last_recall\",\n description: \"Return the last recall snapshot for a session (debug introspection).\",\n inputSchema: {\n type: \"object\",\n properties: { sessionKey: { type: \"string\" } },\n additionalProperties: false,\n },\n },\n {\n name: \"engram.memory_intent_debug\",\n description: \"Return the last intent classification debug snapshot.\",\n inputSchema: {\n type: \"object\",\n properties: { namespace: { type: \"string\" } },\n additionalProperties: false,\n },\n },\n {\n name: \"engram.memory_qmd_debug\",\n description: \"Return QMD search index debug information from the last recall.\",\n inputSchema: {\n type: \"object\",\n properties: { namespace: { type: \"string\" } },\n additionalProperties: false,\n },\n },\n {\n name: \"engram.memory_graph_explain\",\n description: \"Explain the last entity graph recall — which entities were activated and why.\",\n inputSchema: {\n type: \"object\",\n properties: { namespace: { type: \"string\" } },\n additionalProperties: false,\n },\n },\n {\n // Graph snapshot for the admin pane (issue #691 PR 2/5). Returns\n // a read-only `{ nodes, edges, generatedAt }` view of the\n // multi-graph adjacency, with the same filter knobs as the HTTP\n // surface so connectors / CLI clients can hit either endpoint\n // interchangeably.\n name: \"engram.graph_snapshot\",\n description:\n \"Return a read-only graph snapshot (nodes + edges) for the admin pane. Filters: limit (default 500, max 5000), since (ISO timestamp), focusNodeId (restricts to neighborhood), categories (allow-list of memory categories).\",\n inputSchema: {\n type: \"object\",\n properties: {\n namespace: { type: \"string\" },\n limit: { type: \"number\", description: \"Maximum number of edges to return (default 500, max 5000).\" },\n since: { type: \"string\", description: \"Inclusive lower bound on edge timestamp (ISO-8601).\" },\n focusNodeId: {\n type: \"string\",\n description: \"When set, restrict the snapshot to the focus node and its neighbors.\",\n },\n categories: {\n type: \"array\",\n items: { type: \"string\" },\n description: \"Optional category allow-list (e.g. ['fact', 'decision']).\",\n },\n },\n additionalProperties: false,\n },\n },\n {\n name: \"engram.memory_feedback\",\n description: \"Record relevance feedback (thumbs up/down) for a specific memory.\",\n inputSchema: {\n type: \"object\",\n properties: {\n memoryId: { type: \"string\" },\n vote: { type: \"string\", enum: [\"up\", \"down\"] },\n note: { type: \"string\" },\n },\n required: [\"memoryId\", \"vote\"],\n additionalProperties: false,\n },\n },\n {\n name: \"engram.memory_promote\",\n description: \"Promote a memory's lifecycle state (e.g. from draft to active).\",\n inputSchema: {\n type: \"object\",\n properties: {\n memoryId: { type: \"string\" },\n namespace: { type: \"string\" },\n sessionKey: { type: \"string\" },\n },\n required: [\"memoryId\"],\n additionalProperties: false,\n },\n },\n // Memory Worth outcome signal (issue #560 PR 3). Callers record whether\n // a session that used a given memory ultimately succeeded or failed;\n // the counter is persisted in the memory's frontmatter (mw_success /\n // mw_fail) and will feed the recall-time filter added in PR 4.\n {\n name: \"engram.memory_outcome\",\n description:\n \"Record a Memory Worth outcome (success/failure) for a memory. Increments mw_success or mw_fail in the memory's frontmatter for use by the recall filter.\",\n inputSchema: {\n type: \"object\",\n properties: {\n memoryId: { type: \"string\" },\n outcome: { type: \"string\", enum: [\"success\", \"failure\"] },\n namespace: { type: \"string\" },\n sessionKey: { type: \"string\" },\n timestamp: { type: \"string\", description: \"Optional ISO-8601 timestamp of the observation.\" },\n },\n required: [\"memoryId\", \"outcome\"],\n additionalProperties: false,\n },\n },\n {\n name: \"engram.memory_action_apply\",\n description: \"Record a memory-action application event for policy-learning telemetry.\",\n inputSchema: {\n type: \"object\",\n properties: {\n action: {\n type: \"string\",\n enum: [\n \"store_episode\",\n \"store_note\",\n \"update_note\",\n \"create_artifact\",\n \"summarize_node\",\n \"discard\",\n \"link_graph\",\n ],\n },\n category: { type: \"string\" },\n content: { type: \"string\" },\n outcome: { type: \"string\", enum: [\"applied\", \"skipped\", \"failed\"] },\n reason: { type: \"string\" },\n memoryId: { type: \"string\" },\n sessionKey: { type: \"string\" },\n linkTargetId: { type: \"string\" },\n linkType: { type: \"string\" },\n linkStrength: { type: \"number\" },\n artifactType: { type: \"string\" },\n execute: { type: \"boolean\" },\n sourcePrompt: { type: \"string\" },\n namespace: { type: \"string\" },\n dryRun: { type: \"boolean\" },\n },\n required: [\"action\"],\n additionalProperties: false,\n },\n },\n {\n name: \"engram.context_checkpoint\",\n description: \"Save a structured context checkpoint for a session (preserves conversation state to disk).\",\n inputSchema: {\n type: \"object\",\n properties: {\n sessionKey: { type: \"string\" },\n context: { type: \"string\", description: \"Context content to checkpoint\" },\n namespace: { type: \"string\" },\n },\n required: [\"sessionKey\", \"context\"],\n additionalProperties: false,\n },\n },\n // ── Daily Context Briefing (#370) ───────────────────────────────────\n // Uses the legacy \"engram.*\" prefix like every other tool in this array;\n // withToolAliases (applied via .flatMap below) generates the canonical\n // \"remnic.briefing\" alias automatically.\n ...(service.briefingEnabled\n ? [\n {\n name: \"engram.briefing\",\n description:\n \"Generate a daily context briefing by cross-referencing active entities, recent facts, open commitments, and optional calendar events.\",\n inputSchema: {\n type: \"object\",\n properties: {\n since: { type: \"string\", description: \"Lookback window (e.g. 'yesterday', '3d', '1w', '24h').\" },\n focus: {\n type: \"string\",\n description:\n \"Optional focus filter (e.g. 'person:Jane Doe', 'project:remnic-core', 'topic:retrieval').\",\n },\n namespace: { type: \"string\" },\n format: { type: \"string\", enum: [\"markdown\", \"json\"] },\n maxFollowups: {\n type: \"number\",\n description: \"Maximum LLM-suggested follow-ups (0 disables that section).\",\n },\n },\n additionalProperties: false,\n },\n },\n ]\n : []),\n // ── Contradiction Review (issue #520) ────────────────────────────────\n {\n name: \"engram.review_list\",\n description: \"List contradiction review items pending user resolution.\",\n inputSchema: {\n type: \"object\",\n properties: {\n filter: {\n type: \"string\",\n enum: [\"all\", \"unresolved\", \"contradicts\", \"independent\", \"duplicates\", \"needs-user\"],\n description: \"Filter by verdict type. Default: unresolved.\",\n },\n namespace: { type: \"string\" },\n limit: { type: \"number\", description: \"Max items to return (default 50).\" },\n },\n additionalProperties: false,\n },\n },\n {\n name: \"engram.review_resolve\",\n description: \"Resolve a contradiction pair with a chosen verb.\",\n inputSchema: {\n type: \"object\",\n properties: {\n pairId: { type: \"string\", description: \"The contradiction pair ID to resolve.\" },\n verb: {\n type: \"string\",\n enum: [\"keep-a\", \"keep-b\", \"merge\", \"both-valid\", \"needs-more-context\"],\n description: \"Resolution action.\",\n },\n mergedMemoryId: { type: \"string\", description: \"Existing merged memory ID to use when verb is merge.\" },\n mergedContent: { type: \"string\", description: \"Content for a new merged memory when verb is merge.\" },\n },\n required: [\"pairId\", \"verb\"],\n additionalProperties: false,\n },\n },\n {\n name: \"engram.contradiction_scan_run\",\n description: \"Run an on-demand contradiction scan over the memory corpus.\",\n inputSchema: {\n type: \"object\",\n properties: {\n namespace: { type: \"string\" },\n },\n additionalProperties: false,\n },\n },\n {\n name: \"engram.memory_summarize_hourly\",\n description: \"Generate hourly summaries for recent conversations.\",\n inputSchema: {\n type: \"object\",\n properties: {},\n additionalProperties: false,\n },\n },\n {\n name: \"engram.conversation_index_update\",\n description: \"Chunk transcript history into conversation-index documents.\",\n inputSchema: {\n type: \"object\",\n properties: {\n sessionKey: { type: \"string\" },\n hours: { type: \"number\", description: \"How many hours of transcript history to include.\" },\n embed: { type: \"boolean\", description: \"If true, run QMD embed after update for this invocation.\" },\n },\n additionalProperties: false,\n },\n },\n {\n name: \"engram.profiling_report\",\n description:\n \"Return timing and performance data for Remnic recall and extraction pipelines. Requires profilingEnabled: true.\",\n inputSchema: {\n type: \"object\",\n properties: {\n format: {\n type: \"string\",\n enum: [\"ascii\", \"json\"],\n description: \"Output format. Defaults to ascii.\",\n },\n limit: {\n type: \"integer\",\n minimum: 1,\n maximum: 20,\n description: \"Number of recent traces to include. Defaults to 5.\",\n },\n },\n additionalProperties: false,\n },\n },\n {\n name: \"engram.graph_edge_decay_run\",\n description:\n \"Run the graph-edge-confidence decay maintenance pass (issue #681 PR 2/3). Respects graphEdgeDecayEnabled; writes a structured telemetry record to state/graph-edge-decay-status.json.\",\n inputSchema: {\n type: \"object\",\n properties: {\n dryRun: { type: \"boolean\" },\n },\n additionalProperties: false,\n },\n },\n {\n name: \"engram.live_connectors_run\",\n description:\n \"Run due live connectors once. Used by the live-connector cron and available for operator-triggered sync checks.\",\n inputSchema: {\n type: \"object\",\n properties: {\n force: {\n type: \"boolean\",\n description: \"When true, run enabled connectors even if their poll interval has not elapsed.\",\n },\n },\n additionalProperties: false,\n },\n },\n // ── Peer Registry tools (issue #679 PR 4/5) ─────────────────────────\n {\n name: \"engram.peer_list\",\n description:\n \"List all registered peers in the peer registry (issue #679). Returns an array of peer identity records sorted alphabetically by id.\",\n inputSchema: {\n type: \"object\",\n properties: {},\n additionalProperties: false,\n },\n },\n {\n name: \"engram.peer_get\",\n description:\n \"Get a single peer by id. Returns the peer's identity record or { found: false } when not found (issue #679).\",\n inputSchema: {\n type: \"object\",\n properties: {\n id: { type: \"string\", description: \"Peer id to look up.\" },\n },\n required: [\"id\"],\n additionalProperties: false,\n },\n },\n {\n name: \"engram.peer_set\",\n description:\n \"Create or update a peer identity record (issue #679). On first write, creates the peer with the given kind (default 'human'). On subsequent writes, updates displayName and/or notes; kind and createdAt are immutable.\",\n inputSchema: {\n type: \"object\",\n properties: {\n id: { type: \"string\", description: \"Peer id — must match PEER_ID_PATTERN.\" },\n kind: {\n type: \"string\",\n enum: [\"self\", \"human\", \"agent\", \"integration\"],\n description: \"Kind of peer. Required on first write; ignored on updates.\",\n },\n displayName: { type: \"string\", description: \"Human-readable display name.\" },\n notes: { type: \"string\", description: \"Optional free-form markdown notes.\" },\n },\n required: [\"id\"],\n additionalProperties: false,\n },\n },\n {\n name: \"engram.peer_delete\",\n description:\n \"Delete a peer's identity record (issue #679). Idempotent — succeeds even if the peer does not exist. The peer directory is preserved so profile and interaction-log data are not destroyed.\",\n inputSchema: {\n type: \"object\",\n properties: {\n id: { type: \"string\", description: \"Peer id to delete.\" },\n },\n required: [\"id\"],\n additionalProperties: false,\n },\n },\n {\n name: \"engram.peer_profile_get\",\n description:\n \"Get the evolving cognitive profile for a peer (issue #679). Returns the profile written by the async reasoner (PR 2/5), or { found: false } if no profile has been generated yet.\",\n inputSchema: {\n type: \"object\",\n properties: {\n id: { type: \"string\", description: \"Peer id whose profile to retrieve.\" },\n },\n required: [\"id\"],\n additionalProperties: false,\n },\n },\n {\n name: \"engram.peer_forget\",\n description:\n \"DESTRUCTIVELY purge the entire peer directory (identity.md + profile.md + interactions.log.md and any companion files). \" +\n \"Requires confirm: 'yes'. Idempotent — safe to call twice. \" +\n \"Use engram.peer_delete when you only want to remove the identity record and preserve profile data.\",\n inputSchema: {\n type: \"object\",\n properties: {\n id: { type: \"string\", description: \"Peer id to purge.\" },\n confirm: {\n type: \"string\",\n enum: [\"yes\"],\n description: \"Must be exactly 'yes' to proceed. Guard against accidental invocation.\",\n },\n },\n required: [\"id\", \"confirm\"],\n additionalProperties: false,\n },\n },\n // ── Operator Console state (issue #688 PR 2/3) ─────────────────────────\n {\n name: \"engram.console_state\",\n description:\n \"Return a point-in-time ConsoleStateSnapshot of the engine's runtime state — buffer, extraction queue, dedup decisions, maintenance ledger tail, QMD probe, and daemon info (issue #688). Read-only; never mutates state.\",\n inputSchema: {\n type: \"object\",\n properties: {\n namespace: {\n type: \"string\",\n description: \"Optional namespace to scope the snapshot.\",\n },\n },\n additionalProperties: false,\n },\n },\n // ── Dreams telemetry (issue #678 PR 3+4) ─────────────────────────────\n {\n name: \"engram.dreams_status\",\n description:\n \"Return per-phase Dreams pipeline telemetry for the last N hours (default 24). Reports run count, total duration, and items processed for each phase: lightSleep, rem, deepSleep.\",\n inputSchema: {\n type: \"object\",\n properties: {\n windowHours: {\n type: \"number\",\n description: \"How many hours to look back (default 24, minimum 1).\",\n },\n namespace: {\n type: \"string\",\n description: \"Optional namespace to read Dreams telemetry from.\",\n },\n },\n additionalProperties: false,\n },\n },\n {\n name: \"engram.dreams_run\",\n description:\n \"Manually invoke a single Dreams pipeline phase (lightSleep, rem, or deepSleep). Returns the same telemetry shape as a scheduled run. Pass dryRun: true to preview without committing writes.\",\n inputSchema: {\n type: \"object\",\n properties: {\n phase: {\n type: \"string\",\n enum: [\"lightSleep\", \"rem\", \"deepSleep\"],\n description: \"Which phase to run.\",\n },\n dryRun: {\n type: \"boolean\",\n description: \"When true, report what would change without committing writes (default false).\",\n },\n namespace: {\n type: \"string\",\n description: \"Optional namespace to run the phase in.\",\n },\n },\n required: [\"phase\"],\n additionalProperties: false,\n },\n },\n ].flatMap((tool) => withToolAliases(tool, this.emitLegacyTools));\n if (this.codingDecisionVisible) {\n const codingDecisionTools = withToolAliases(\n {\n name: \"engram.coding_decision\",\n description:\n \"List, get, record, or supersede decision records in the session's coding namespace (issue #1548 Track A). Subcommands: list, get, record, supersede.\",\n inputSchema: {\n type: \"object\",\n properties: {\n subcommand: {\n type: \"string\",\n enum: [\"list\", \"get\", \"record\", \"supersede\"],\n description: \"Which decision-record operation to run.\",\n },\n sessionKey: {\n type: \"string\",\n description: \"Session identifier whose coding context scopes the operation.\",\n },\n namespace: {\n type: \"string\",\n description: \"Optional explicit namespace (overrides coding-context overlay).\",\n },\n id: { type: \"string\", description: \"Decision record id (required for get and supersede).\" },\n title: { type: \"string\", description: \"Decision title (required for record and supersede).\" },\n status: {\n type: \"string\",\n enum: [\"proposed\", \"accepted\", \"superseded\", \"rejected\"],\n description: \"Decision status (record only; defaults to proposed).\",\n },\n context: { type: \"string\", description: \"Context/background for the decision.\" },\n decision: { type: \"string\", description: \"The decision itself (required for record and supersede).\" },\n consequences: { type: \"string\", description: \"Consequences of the decision.\" },\n entityRefs: {\n type: \"array\",\n items: { type: \"string\" },\n description: \"Entity references the decision relates to.\",\n },\n supersedesId: {\n type: \"string\",\n description: \"Id of the record this decision supersedes (supersede only).\",\n },\n },\n required: [\"subcommand\"],\n additionalProperties: false,\n },\n },\n this.emitLegacyTools\n );\n this.tools = [...this.tools, ...codingDecisionTools];\n }\n if (this.architectureCardVisible) {\n const architectureTools = withToolAliases(\n {\n name: \"engram.coding_architecture\",\n description:\n \"Get or refresh the architecture card for the session's coding namespace (issue #1548 Track A PR 3). Subcommands: get, refresh.\",\n inputSchema: {\n type: \"object\",\n properties: {\n subcommand: {\n type: \"string\",\n enum: [\"get\", \"refresh\"],\n description: \"Which architecture-card operation to run.\",\n },\n sessionKey: {\n type: \"string\",\n description: \"Session identifier whose coding context scopes the operation.\",\n },\n namespace: {\n type: \"string\",\n description: \"Optional explicit namespace (overrides coding-context overlay).\",\n },\n },\n required: [\"subcommand\"],\n additionalProperties: false,\n },\n },\n this.emitLegacyTools\n );\n this.tools = [...this.tools, ...architectureTools];\n }\n if (this.codegraphVisible) {\n // The 14 codegraph parity tools (issue #1554). Each delegates to its\n // boundary operation; the MCP dispatch injects the `tool` field from\n // the operation name. The inputSchema is intentionally permissive —\n // the boundary's zod schema owns validation (rule 51).\n const codegraphToolDefs: Array<{ suffix: string; description: string; required?: string[] }> = [\n { suffix: \"index\", description: \"Index a repository into the code graph.\", required: [\"repoRoot\"] },\n { suffix: \"list_projects\", description: \"List code graph projects for the principal.\" },\n {\n suffix: \"delete_project\",\n description: \"Delete a code graph project (requires confirm: true).\",\n required: [\"confirm\"],\n },\n { suffix: \"index_status\", description: \"Get the indexing status for a project.\" },\n { suffix: \"search_graph\", description: \"Search the code graph for symbols.\", required: [\"query\"] },\n {\n suffix: \"trace_path\",\n description: \"Trace call/dependency paths from a starting symbol.\",\n required: [\"start\"],\n },\n { suffix: \"detect_changes\", description: \"Detect changed symbols since a git ref.\", required: [\"head\"] },\n {\n suffix: \"query_graph\",\n description: \"Run a structured query against the code graph.\",\n required: [\"structuredQuery\"],\n },\n { suffix: \"get_schema\", description: \"Get the code graph schema statistics.\" },\n { suffix: \"get_snippet\", description: \"Get a source code snippet for a symbol.\", required: [\"qualifiedName\"] },\n { suffix: \"get_architecture\", description: \"Get the composed architecture card + graph stats.\" },\n {\n suffix: \"search_code\",\n description: \"Search the code graph for code (functions, classes, methods).\",\n required: [\"query\"],\n },\n {\n suffix: \"manage_adr\",\n description: \"Manage ADRs via Track A decision records (list, get, record, supersede).\",\n required: [\"subcommand\"],\n },\n {\n suffix: \"ingest_traces\",\n description: \"Ingest call-site traces to upgrade edge confidence.\",\n required: [\"traces\"],\n },\n ];\n for (const def of codegraphToolDefs) {\n const tools = withToolAliases(\n {\n name: `engram.codegraph_${def.suffix}`,\n description: def.description,\n inputSchema: {\n type: \"object\",\n properties: {\n sessionKey: {\n type: \"string\",\n description: \"Session identifier whose coding context scopes the operation.\",\n },\n project: { type: \"string\", description: \"Explicit project id (defaults to session coding context).\" },\n principal: { type: \"string\", description: \"Authenticated principal override.\" },\n query: { type: \"string\" },\n limit: { type: \"number\" },\n start: { type: \"string\" },\n direction: { type: \"string\", enum: [\"inbound\", \"outbound\", \"both\"] },\n depth: { type: \"number\" },\n qualifiedName: { type: \"string\" },\n path: { type: \"string\" },\n structuredQuery: { type: \"object\" },\n head: { type: \"string\" },\n repoRoot: { type: \"string\" },\n mode: { type: \"string\", enum: [\"auto\", \"full\", \"incremental\"] },\n confirm: { type: \"boolean\" },\n subcommand: { type: \"string\", enum: [\"list\", \"get\", \"record\", \"supersede\"] },\n id: { type: \"string\" },\n title: { type: \"string\" },\n status: { type: \"string\", enum: [\"proposed\", \"accepted\", \"superseded\", \"rejected\"] },\n context: { type: \"string\" },\n decision: { type: \"string\" },\n consequences: { type: \"string\" },\n entityRefs: { type: \"array\", items: { type: \"string\" } },\n supersedesId: { type: \"string\" },\n traces: { type: \"array\", items: { type: \"object\" } },\n },\n required: def.required ?? [],\n additionalProperties: false,\n },\n },\n this.emitLegacyTools\n );\n this.tools = [...this.tools, ...tools];\n }\n }\n if (this.sessionDeltaVisible) {\n const deltaTools = withToolAliases(\n {\n name: \"engram.coding_delta\",\n description:\n \"Get the session delta (commits + touched files since last seen) for the session's coding namespace (issue #1548 Track A PR 4). Subcommand: get.\",\n inputSchema: {\n type: \"object\",\n properties: {\n subcommand: {\n type: \"string\",\n enum: [\"get\"],\n description: \"Which delta operation to run.\",\n },\n sessionKey: {\n type: \"string\",\n description: \"Session identifier whose coding context scopes the operation.\",\n },\n namespace: {\n type: \"string\",\n description: \"Optional explicit namespace (overrides coding-context overlay).\",\n },\n },\n required: [\"subcommand\"],\n additionalProperties: false,\n },\n },\n this.emitLegacyTools\n );\n this.tools = [...this.tools, ...deltaTools];\n }\n if (this.correctionVisible) {\n // Correction Contract (issue #1580) — one plan/apply pipeline for every\n // memory correction. Both tools dispatch through the boundary operations\n // (memory_correct_plan / memory_correct_apply) which delegate to the\n // CorrectionService.\n const planTool = withToolAliases(\n {\n name: \"engram.memory_correct_plan\",\n description:\n \"Plan a memory correction from a plain-language statement (issue #1580). Returns a CorrectionPlan with a diff preview; apply via memory_correct_apply.\",\n inputSchema: {\n type: \"object\",\n properties: {\n text: {\n type: \"string\",\n description: 'The natural-language correction (e.g. \"we migrated to MySQL in March\").',\n },\n targetIds: {\n type: \"array\",\n items: { type: \"string\" },\n description: \"Optional explicit target memory ids. When omitted, the planner searches.\",\n },\n sessionKey: { type: \"string\", description: \"Session identifier for namespace resolution.\" },\n namespace: { type: \"string\", description: \"Optional explicit namespace (validated by policy).\" },\n },\n required: [\"text\"],\n additionalProperties: false,\n },\n },\n this.emitLegacyTools\n );\n const applyTool = withToolAliases(\n {\n name: \"engram.memory_correct_apply\",\n description:\n \"Apply a planned memory correction by planId (issue #1580). Requires confirm: true when correction.applyRequiresConfirm is on (default).\",\n inputSchema: {\n type: \"object\",\n properties: {\n planId: { type: \"string\", description: \"The plan id returned by memory_correct_plan.\" },\n confirm: { type: \"boolean\", description: \"Must be true to apply (safety guard, rule 48).\" },\n sessionKey: { type: \"string\", description: \"Session identifier for namespace resolution.\" },\n namespace: { type: \"string\", description: \"Optional explicit namespace (validated by policy).\" },\n },\n required: [\"planId\"],\n additionalProperties: false,\n },\n },\n this.emitLegacyTools\n );\n this.tools = [...this.tools, ...planTool, ...applyTool];\n }\n if (this.chatVisible) {\n const chatTools = withToolAliases(\n {\n name: \"engram.memory_chat\",\n description:\n \"Conversational memory inspection and correction (issue #1583). Send a message to chat about what Remnic remembers, inspect memories, or request corrections. Returns {reply, chatSessionId, pendingPlan?}.\",\n inputSchema: {\n type: \"object\",\n properties: {\n message: {\n type: \"string\",\n description:\n \"The user's message — a question about memories, a correction request, or a confirmation (yes/apply) to proceed with a pending plan.\",\n },\n chatSessionId: {\n type: \"string\",\n description: \"Optional existing chat session id to resume. Omit to start a new session.\",\n },\n },\n required: [\"message\"],\n additionalProperties: false,\n },\n },\n this.emitLegacyTools\n );\n this.tools = [...this.tools, ...chatTools];\n }\n // Apply `readOnlyHint` annotations to the conservative read-only\n // allowlist. Done as a final pass so every spread (chat, codegraph,\n // coding_*, correction, etc.) inherits the annotation without\n // scattering the same logic across every `withToolAliases` call site.\n // Suffix-based matching covers both the `remnic.*` and `engram.*`\n // naming forms emitted by `withToolAliases`.\n this.tools = this.tools.map((tool) =>\n isReadOnlyToolName(tool.name) && tool.annotations?.readOnlyHint !== true\n ? { ...tool, annotations: { ...(tool.annotations ?? {}), readOnlyHint: true } }\n : tool\n );\n // Apply `outputSchema` declarations from the registry. Like the\n // readOnlyHint pass above, this is a final suffix-based pass so every\n // tool (including both `remnic.*` and `engram.*` aliases) gets a\n // schema. Tools that already declare an outputSchema (e.g.\n // chatgpt_memory_inspector) are left untouched.\n this.tools = applyToolOutputSchemas(this.tools, CANONICAL_MCP_PREFIX, LEGACY_MCP_PREFIX);\n }\n\n /** Get clientInfo for a specific MCP session. Returns undefined for non-MCP requests. */\n getClientInfo(sessionId?: string): { name: string; version?: string } | undefined {\n if (sessionId) {\n return this.clientInfoBySession.get(sessionId);\n }\n return undefined;\n }\n\n /** Pop the session ID generated during an initialize handshake, keyed by correlation ID. */\n popInitSessionId(correlationId: string): string | undefined {\n const sid = this.initSessionIds.get(correlationId);\n if (sid !== undefined) this.initSessionIds.delete(correlationId);\n return sid;\n }\n\n async handleRequest(request: JsonRpcRequest, options?: McpRequestOptions): Promise<Record<string, unknown> | null> {\n const id = request.id ?? null;\n const method = request.method ?? \"\";\n\n if (method === \"notifications/initialized\") return null;\n if (method === \"ping\") {\n return { jsonrpc: \"2.0\", id, result: {} };\n }\n if (method === \"initialize\") {\n const params = request.params ?? {};\n // MCP initialize REQUIRES params.protocolVersion (string). Reject a\n // missing/mistyped field with JSON-RPC invalid params instead of\n // silently negotiating (repo rule: never reinterpret invalid input).\n // An unsupported-but-well-formed version gets the spec-mandated\n // counter-offer below instead: the server answers with the newest\n // version it supports and the client decides whether to proceed.\n if (typeof params.protocolVersion !== \"string\" || params.protocolVersion.length === 0) {\n return {\n jsonrpc: \"2.0\",\n id,\n error: {\n code: -32602,\n message: `initialize requires params.protocolVersion (string); supported versions: ${MCP_SUPPORTED_PROTOCOL_VERSIONS.join(\", \")}`,\n },\n };\n }\n const rawClientInfo = params.clientInfo as { name?: string; version?: string } | undefined;\n // Generate a server-side session ID for this MCP session.\n // The caller should send this back as Mcp-Session-Id on subsequent requests.\n const newSessionId = randomUUID();\n if (rawClientInfo && typeof rawClientInfo.name === \"string\") {\n const info = { name: rawClientInfo.name, version: rawClientInfo.version as string | undefined };\n this.clientInfoBySession.set(newSessionId, info);\n // Evict oldest sessions if map exceeds limit\n if (this.clientInfoBySession.size > 1000) {\n const firstKey = this.clientInfoBySession.keys().next().value;\n if (firstKey) this.clientInfoBySession.delete(firstKey);\n }\n }\n const version = await getMcpServerVersion();\n // Store session ID keyed by correlation ID (unique per HTTP request) so\n // concurrent initializes with the same JSON-RPC id don't collide.\n const corrId = options?.correlationId;\n if (corrId) this.initSessionIds.set(corrId, newSessionId);\n return {\n jsonrpc: \"2.0\",\n id,\n result: {\n protocolVersion: MCP_SUPPORTED_PROTOCOL_VERSIONS.includes(params.protocolVersion)\n ? params.protocolVersion\n : MCP_DEFAULT_PROTOCOL_VERSION,\n capabilities: {\n tools: {},\n resources: {},\n },\n serverInfo: {\n name: \"remnic\",\n version,\n },\n },\n };\n }\n if (method === \"tools/list\") {\n // Issue #1850 round 5 (finding 3): a scoped/deny-all token must not\n // enumerate the full tool surface — filter advertised tools by the\n // token's ops allow-list via the same map callTool uses. Unrestricted\n // tokens (ops axis absent) see everything; unmapped tool ⇒ \"\" ⇒ hidden.\n const caps = tokenCapabilityStore.getStore();\n const tools = caps?.ops === undefined\n ? this.tools\n : this.tools.filter((t) => capabilityAllowsOp(caps, MCP_MIGRATED_OPERATIONS[toLegacyToolName(t.name)] ?? \"\"));\n return { jsonrpc: \"2.0\", id, result: { tools } };\n }\n if (method === \"resources/list\") {\n return {\n jsonrpc: \"2.0\",\n id,\n result: {\n resources: this.resources,\n },\n };\n }\n if (method === \"resources/templates/list\") {\n return {\n jsonrpc: \"2.0\",\n id,\n result: {\n resourceTemplates: [],\n },\n };\n }\n if (method === \"resources/read\") {\n const params = request.params ?? {};\n const uri = typeof params.uri === \"string\" ? params.uri : \"\";\n const resource = this.resources.find((entry) => entry.uri === uri);\n if (!resource) {\n return {\n jsonrpc: \"2.0\",\n id,\n error: {\n code: -32602,\n message: `Unknown resource URI: ${uri}`,\n },\n };\n }\n const text = this.resourceTextByUri.get(resource.uri);\n if (text === undefined) {\n return {\n jsonrpc: \"2.0\",\n id,\n error: {\n code: -32603,\n message: `Resource content unavailable: ${resource.uri}`,\n },\n };\n }\n return {\n jsonrpc: \"2.0\",\n id,\n result: {\n contents: [\n {\n uri: resource.uri,\n mimeType: resource.mimeType,\n text,\n _meta: resource._meta,\n },\n ],\n },\n };\n }\n if (method === \"tools/call\") {\n const params = request.params ?? {};\n const name = typeof params.name === \"string\" ? params.name : \"\";\n\n try {\n let argumentsObject: Record<string, unknown> = {};\n if (\"arguments\" in params && params.arguments !== undefined) {\n if (params.arguments === null || typeof params.arguments !== \"object\" || Array.isArray(params.arguments)) {\n throw new EngramAccessInputError(\"tools/call arguments must be an object when provided\");\n }\n argumentsObject = params.arguments as Record<string, unknown>;\n }\n if (\n !(\"namespace\" in argumentsObject) &&\n options?.namespaceOverride &&\n this.toolAcceptsArgument(name, \"namespace\")\n ) {\n argumentsObject = { ...argumentsObject, namespace: options.namespaceOverride };\n }\n const skipSessionKeyOverride =\n toLegacyToolName(name) === \"engram.lcm_search\" &&\n typeof argumentsObject.sessionPrefix === \"string\" &&\n argumentsObject.sessionPrefix.length > 0;\n if (\n !(\"sessionKey\" in argumentsObject) &&\n !skipSessionKeyOverride &&\n options?.sessionKeyOverride &&\n this.toolAcceptsArgument(name, \"sessionKey\")\n ) {\n argumentsObject = { ...argumentsObject, sessionKey: options.sessionKeyOverride };\n }\n const effectivePrincipal = options?.principalOverride ?? this.authenticatedPrincipal;\n // Forward the MCP session scope (namespace/sessionKey overrides) so\n // tools like memory_chat bind the caller active scope (Thread 17).\n const mcpScope = {\n ...(options?.namespaceOverride ? { namespace: options.namespaceOverride } : {}),\n ...(options?.sessionKeyOverride ? { sessionKey: options.sessionKeyOverride } : {}),\n };\n // Abort before dispatch so a disconnected request never starts work.\n // Once a mutating tool has returned, cancellation is deferred to the\n // HTTP transport so it can account for the committed write first.\n throwMcpAbort(options?.abortSignal, \"MCP request aborted before operation start\");\n const result = await this.callTool(\n name,\n argumentsObject,\n effectivePrincipal,\n options?.sessionId,\n mcpScope,\n options?.enforceWriteQuota,\n options?.recordWriteCommit,\n options?.sourceConnector,\n options?.abortSignal,\n );\n if (isReadOnlyToolName(name)) {\n throwMcpAbort(options?.abortSignal, \"MCP request aborted before response\");\n }\n const structuredContent = result;\n return {\n jsonrpc: \"2.0\",\n id,\n result: {\n content: [{ type: \"text\", text: JSON.stringify(result ?? null, null, 2) }],\n ...(structuredContent == null ? {} : { structuredContent }),\n isError: false,\n },\n };\n } catch (err) {\n // Cancellation is transport control flow, not a JSON-RPC tool error.\n // Preserve the original AbortError so HTTP can silently end a dead socket.\n if (isAbortError(err)) throw err;\n const message = err instanceof Error ? err.message : String(err);\n return {\n jsonrpc: \"2.0\",\n id,\n result: {\n content: [{ type: \"text\", text: message }],\n isError: true,\n },\n };\n }\n }\n\n return {\n jsonrpc: \"2.0\",\n id,\n error: {\n code: -32601,\n message: `Method not found: ${method}`,\n },\n };\n }\n\n async runStdio(input: Readable, output: Writable): Promise<void> {\n input.on(\"data\", (chunk) => {\n this.buffer = Buffer.concat([this.buffer, Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)]);\n this.scheduleFlush(output);\n });\n await new Promise<void>((resolve, reject) => {\n input.on(\"end\", resolve);\n input.on(\"error\", reject);\n });\n while (this.flushTask) {\n await this.flushTask;\n }\n }\n\n private scheduleFlush(output: Writable): void {\n if (this.flushTask) return;\n const task = this.flushBuffer(output)\n .catch((err) => {\n this.writeMessage(output, {\n jsonrpc: \"2.0\",\n id: null,\n error: {\n code: -32700,\n message: err instanceof Error ? err.message : String(err),\n },\n });\n })\n .finally(() => {\n if (this.flushTask === task) {\n this.flushTask = null;\n }\n if (this.buffer.length > 0) {\n this.scheduleFlush(output);\n }\n });\n this.flushTask = task;\n }\n\n private async flushBuffer(output: Writable): Promise<void> {\n while (true) {\n const headerEnd = this.buffer.indexOf(\"\\r\\n\\r\\n\");\n if (headerEnd < 0) return;\n const headerText = this.buffer.slice(0, headerEnd).toString(\"utf-8\");\n const headers = headerText.split(\"\\r\\n\");\n const contentLengthHeader = headers.find((line) => line.toLowerCase().startsWith(\"content-length:\"));\n if (!contentLengthHeader) {\n this.buffer = Buffer.alloc(0);\n return;\n }\n const contentLength = Number.parseInt(contentLengthHeader.split(\":\")[1]?.trim() ?? \"0\", 10);\n if (!Number.isFinite(contentLength) || contentLength < 0) {\n this.buffer = Buffer.alloc(0);\n return;\n }\n const messageStart = headerEnd + 4;\n const messageEnd = messageStart + contentLength;\n if (this.buffer.length < messageEnd) return;\n const body = this.buffer.slice(messageStart, messageEnd).toString(\"utf-8\");\n this.buffer = this.buffer.slice(messageEnd);\n\n let parsed: JsonRpcRequest;\n try {\n parsed = JSON.parse(body) as JsonRpcRequest;\n } catch {\n this.writeMessage(output, {\n jsonrpc: \"2.0\",\n id: null,\n error: {\n code: -32700,\n message: \"Parse error\",\n },\n });\n continue;\n }\n const response = await this.handleRequest(parsed);\n if (response) {\n this.writeMessage(output, response);\n }\n }\n }\n\n private writeMessage(output: Writable, payload: Record<string, unknown>): void {\n const body = JSON.stringify(payload);\n const message = `Content-Length: ${Buffer.byteLength(body, \"utf-8\")}\\r\\n\\r\\n${body}`;\n output.write(message);\n }\n\n private toolAcceptsArgument(name: string, key: string): boolean {\n // Match by canonical name so argument validation resolves whether the\n // caller used the `engram.*` or `remnic.*` name and regardless of whether\n // legacy aliases are advertised (issue #1427) — a tool stays callable under\n // both names even when only the canonical alias appears in `tools/list`.\n const target = toCanonicalToolName(name);\n const tool = this.tools.find((entry) => toCanonicalToolName(entry.name) === target);\n const inputSchema = getObjectProperties(tool?.inputSchema);\n const properties = getObjectProperties(inputSchema?.properties);\n if (properties && Object.prototype.hasOwnProperty.call(properties, key)) {\n return true;\n }\n return inputSchema?.additionalProperties === true;\n }\n\n /**\n * Whether a tool accepts a `namespace` argument — i.e. it is a\n * namespace-scoped operation whose effective namespace MUST be gated by the\n * per-token allow-list. Exposed (public) so the HTTP MCP transport can run\n * the SAME effective-namespace enforcement the REST surface runs, without\n * duplicating the tool-schema introspection (issue #1850). Namespace-\n * agnostic tools (peer/wearables/etc.) return false and stay ungated,\n * matching the REST surface where those routes never call resolveNamespace.\n */\n toolAcceptsNamespace(name: string): boolean {\n return this.toolAcceptsArgument(name, \"namespace\");\n }\n\n /**\n * Determine whether oai-mem-citation guidance should be appended to recall.\n * Returns true when explicitly enabled via config OR when auto-detect is\n * active and the current MCP session belongs to a Codex adapter client.\n *\n * When no sessionId is provided (e.g., stdio transport where there are no\n * HTTP headers carrying mcp-session-id), fall back to checking if there is\n * exactly one known session whose clientInfo matches the Codex pattern.\n * This covers the common stdio case where a single client connection exists.\n */\n private shouldEmitCitations(mcpSessionId?: string): boolean {\n if (this.citationsEnabled) return true;\n if (!this.citationsAutoDetect) return false;\n\n // Direct session lookup (HTTP transport with mcp-session-id header).\n if (mcpSessionId) {\n const info = this.clientInfoBySession.get(mcpSessionId);\n if (!info) return false;\n return this.isCodexClient(info);\n }\n\n // Stdio fallback: no session ID available. If there is exactly one session\n // registered (the typical stdio pattern), check that session's clientInfo.\n if (this.clientInfoBySession.size === 1) {\n const [info] = [...this.clientInfoBySession.values()];\n if (info) return this.isCodexClient(info);\n }\n\n return false;\n }\n\n /** Check whether a clientInfo record identifies a Codex adapter client. */\n private isCodexClient(info: { name: string; version?: string }): boolean {\n const lowerName = info.name.toLowerCase();\n return lowerName === \"codex-mcp-client\" || lowerName.includes(\"codex\");\n }\n\n /**\n * Build citation metadata for each recall result that has a path.\n * Line range defaults to 1-1 when not determinable from the summary.\n */\n private buildRecallCitations(response: EngramAccessRecallResponse): CitationMetadata[] {\n return response.results\n .filter((r) => r.path && r.path.length > 0)\n .map((r) => ({\n memoryId: r.id,\n path: r.path,\n lineStart: 1,\n lineEnd: 1,\n noteDefault: r.preview?.slice(0, 60) || r.id,\n }));\n }\n\n private async callTool(\n name: string,\n args: Record<string, unknown>,\n effectivePrincipal?: string,\n mcpSessionId?: string,\n scope?: { namespace?: string; sessionKey?: string },\n enforceWriteQuota?: () => void | Promise<void>,\n recordWriteCommit?: () => void,\n sourceConnector?: string,\n abortSignal?: AbortSignal,\n ): Promise<unknown> {\n const migrated = MCP_MIGRATED_OPERATIONS[toLegacyToolName(name)];\n if (!migrated) {\n throw new Error(`unknown tool: ${name}`);\n }\n const op = getOperation(migrated);\n if (!op) {\n throw new EngramAccessInputError(`access-boundary: operation not registered: ${migrated}`);\n }\n let envelope: Record<string, unknown>;\n const wireSchema = MCP_WIRE_SCHEMAS[migrated];\n if (wireSchema) {\n envelope = parseMcpRequest(wireSchema, args) as Record<string, unknown>;\n } else if (migrated.startsWith(\"codegraph_\")) {\n envelope = { ...args, tool: migrated.slice(\"codegraph_\".length) };\n } else if (migrated === \"chat_message\") {\n // memory_chat bypasses op.run(); gate op + resumed-session namespace like the HTTP route (#1850 r6).\n assertOperationAllowed(tokenCapabilityStore.getStore(), migrated);\n const message = typeof args.message === \"string\" ? args.message : \"\";\n if (!message) throw new EngramAccessInputError(\"message is required\");\n const chatSessionId = typeof args.chatSessionId === \"string\" ? args.chatSessionId : undefined;\n if (chatSessionId) {\n await enforceChatSessionNamespace(this.service, chatSessionId);\n } else {\n // NEW chat session (no chatSessionId): processChatMessage mints a fresh\n // session under the EFFECTIVE namespace (scope.namespace OR server\n // default). Unlike the HTTP chat handler (which forwards no namespace),\n // the MCP scope CAN carry one (Thread 17), so route it through the SAME\n // effective-namespace chokepoint as the HTTP new-chat path\n // (enforceNamespaceAllowList maps undefined → default) — a namespace-\n // scoped token CANNOT start a chat in a namespace outside its allow-\n // list, including an unconfigured/forbidden server default. Fail closed;\n // no-op for unrestricted/legacy tokens (issue #1850 round 8).\n enforceNamespaceAllowList(\n tokenCapabilityStore.getStore(),\n scope?.namespace,\n this.service.configRef?.defaultNamespace,\n );\n }\n const chatResult = await processChatMessage({\n service: this.service,\n config: this.service.configRef?.chat,\n memoryDir: this.service.memoryDir,\n message,\n ...(chatSessionId ? { chatSessionId } : {}),\n ...(effectivePrincipal ? { principal: effectivePrincipal } : {}),\n ...(scope?.namespace ? { namespace: scope.namespace } : {}),\n ...(scope?.sessionKey ? { sessionKey: scope.sessionKey } : {}),\n });\n if (chatResult && typeof chatResult === \"object\" && \"error\" in chatResult) {\n const { error: _stripped, ...wireResult } = chatResult as unknown as Record<string, unknown>;\n return wireResult;\n }\n return chatResult;\n } else {\n envelope = args;\n }\n // recall citation guidance (MCP-specific post-processing).\n if (migrated === \"recall\") {\n const result = (await op.run(envelope, {\n service: this.service,\n authenticatedPrincipal: effectivePrincipal,\n ...(sourceConnector ? { sourceConnector } : {}),\n ...(abortSignal ? { abortSignal } : {}),\n })) as { result: unknown };\n throwMcpAbort(abortSignal, \"MCP recall aborted before postprocessing\");\n const response = result.result as Record<string, unknown>;\n if (this.shouldEmitCitations(mcpSessionId)) {\n const citations = this.buildRecallCitations(response as unknown as EngramAccessRecallResponse);\n const guidance = buildCitationGuidance(citations);\n if (guidance.length > 0) {\n return {\n ...response,\n context: (((response as Record<string, unknown>).context as string) ?? \"\") + guidance,\n citations,\n };\n }\n }\n return response;\n }\n const output = (await op.run(envelope, {\n service: this.service,\n authenticatedPrincipal: effectivePrincipal,\n ...(enforceWriteQuota || recordWriteCommit\n ? { hooks: { ...(enforceWriteQuota ? { enforceWriteQuota } : {}), ...(recordWriteCommit ? { recordWriteCommit } : {}) } }\n : {}),\n ...(sourceConnector ? { sourceConnector } : {}),\n ...(abortSignal ? { abortSignal } : {}),\n })) as { result: unknown };\n return output.result;\n }\n}\n","/**\n * Sealed system prompt for the chat engine (issue #1583).\n *\n * The prompt encodes the core rules that every turn enforces:\n * - Always cite memory ids/handles and source quotes when asserting what's\n * remembered.\n * - NEVER apply a mutation without explicit user confirmation in the\n * conversation.\n * - Render plans as the diff the Correction Contract returns.\n * - Prefer \"I found nothing\" over speculation.\n *\n * The engine supplements the prompt with a tool-citation guard at runtime\n * (the model must ground assertions in tool results from the current turn).\n */\n\n/**\n * Build the system prompt for the chat engine. Parameterised by whether the\n * correction (mutation) tools are available — when #1580 is not yet merged,\n * correction_plan/apply are omitted and the prompt reflects that.\n */\nexport function buildChatSystemPrompt(opts: {\n correctionAvailable: boolean;\n}): string {\n const lines: string[] = [\n \"You are Remnic Chat — a conversational memory inspector and corrector.\",\n \"You help the user understand, explore, and fix what Remnic remembers.\",\n \"\",\n \"## Core rules\",\n \"\",\n \"1. GROUND EVERY ASSERTION. When you state what Remnic remembers, you MUST\",\n \" cite the memory id or handle, include the source quote, and the date.\",\n \" If no tool result in this turn supports the claim, say\",\n \" \\\"I found nothing\\\" instead of guessing.\",\n \"\",\n \"2. NO MUTATION WITHOUT CONFIRMATION. You may propose a correction plan\",\n \" (correction_plan), but you must NEVER apply it (correction_apply) until\",\n \" the user explicitly confirms in the conversation.\",\n \"\",\n \"3. RENDER PLANS AS DIFFS. When you surface a correction plan, render it\",\n \" as the diff preview the plan returns — before/after, affected memory\",\n \" ids, and the supersession reason.\",\n \"\",\n \"4. BE HONEST ABOUT LIMITS. If a tool returns no results, say so. If you\",\n \" are unsure, say so. Never fabricate memory content.\",\n \"\",\n \"5. RESPECT SCOPE. You operate within the caller's namespace and principal.\",\n \" Do not attempt to access memories outside the caller's scope.\",\n ];\n\n if (opts.correctionAvailable) {\n lines.push(\n \"\",\n \"## Mutation protocol\",\n \"\",\n \"When the user asks to change or forget memories:\",\n \"1. Call correction_plan to generate a diff preview.\",\n \"2. Present the diff to the user and ask them to reply 'apply' to confirm.\",\n \"3. Only after explicit confirmation, call correction_apply.\",\n \"\",\n \"For bulk/destructive requests ('forget everything about X'), always go\",\n \"through correction_plan first — there is no direct-delete tool.\",\n );\n } else {\n lines.push(\n \"\",\n \"## Mutation status\",\n \"\",\n \"Correction (mutation) tools are not yet available in this build.\",\n \"You can inspect and search memories but cannot apply corrections.\",\n \"When the user asks to change memories, explain that correction tools\",\n \"require the Correction Contract (#1580) which is pending.\",\n );\n }\n\n return lines.join(\"\\n\");\n}\n","/**\n * Chat tools — the ONLY tools available to the chat engine (issue #1583).\n *\n * Each tool is a thin adapter over an existing access-service method (rule 22\n * — zero new business logic here). Mutating tools (correction_apply,\n * memory_promote) are marked and go through the confirmation protocol in the\n * engine before reaching the executor.\n */\n\nimport type { ChatToolSchema } from \"./chat-types.js\";\n\n// ---------------------------------------------------------------------------\n// Tool identifiers\n// ---------------------------------------------------------------------------\n\nexport type ChatToolName =\n | \"memory_search\"\n | \"memory_get\"\n | \"memory_timeline\"\n | \"recall_explain\"\n | \"entity_get\"\n | \"stats\"\n | \"correction_plan\"\n | \"correction_apply\"\n | \"memory_promote\"\n | \"review_list\"\n | \"scope_inspect\";\n\n/** Tools that mutate memory — require confirmation before execution. */\nexport const MUTATING_TOOLS: ReadonlySet<ChatToolName> = new Set([\n \"correction_apply\",\n \"memory_promote\",\n]);\n\n// ---------------------------------------------------------------------------\n// Tool schema definitions (sent to the LLM as the function-calling schema)\n// ---------------------------------------------------------------------------\n\nconst MEMORY_SEARCH_SCHEMA: ChatToolSchema = {\n type: \"function\",\n function: {\n name: \"memory_search\",\n description:\n \"Semantic search across stored memories. Returns matching memory paths, scores, and snippets. Use this to find what Remnic remembers about a topic.\",\n parameters: {\n type: \"object\",\n properties: {\n query: { type: \"string\", description: \"The search query.\" },\n maxResults: { type: \"number\", description: \"Maximum results (default 8).\" },\n },\n required: [\"query\"],\n additionalProperties: false,\n },\n },\n};\n\nconst MEMORY_GET_SCHEMA: ChatToolSchema = {\n type: \"function\",\n function: {\n name: \"memory_get\",\n description:\n \"Fetch a single memory by its id. Returns the full memory content, category, tags, and source attribution.\",\n parameters: {\n type: \"object\",\n properties: {\n memoryId: { type: \"string\", description: \"The memory id to fetch.\" },\n },\n required: [\"memoryId\"],\n additionalProperties: false,\n },\n },\n};\n\nconst MEMORY_TIMELINE_SCHEMA: ChatToolSchema = {\n type: \"function\",\n function: {\n name: \"memory_timeline\",\n description:\n \"Read the lifecycle timeline of a single memory — creation, updates, consolidations, and tier transitions.\",\n parameters: {\n type: \"object\",\n properties: {\n memoryId: { type: \"string\", description: \"The memory id.\" },\n limit: { type: \"number\", description: \"Maximum rows (default 200).\" },\n },\n required: [\"memoryId\"],\n additionalProperties: false,\n },\n },\n};\n\nconst RECALL_EXPLAIN_SCHEMA: ChatToolSchema = {\n type: \"function\",\n function: {\n name: \"recall_explain\",\n description:\n \"Explain why Remnic would recall certain memories for a given query. Returns tier scoring and matching details. Use this to answer 'why did you remember this?'\",\n parameters: {\n type: \"object\",\n properties: {\n query: { type: \"string\", description: \"Optional query to explain recall for. When omitted, explains the most recent recall.\" },\n },\n required: [],\n additionalProperties: false,\n },\n },\n};\n\nconst ENTITY_GET_SCHEMA: ChatToolSchema = {\n type: \"function\",\n function: {\n name: \"entity_get\",\n description:\n \"Fetch the compiled entity record for a named entity (person, project, tool, etc.). Returns traits, timeline, and associated memories.\",\n parameters: {\n type: \"object\",\n properties: {\n name: { type: \"string\", description: \"Entity name.\" },\n },\n required: [\"name\"],\n additionalProperties: false,\n },\n },\n};\n\nconst STATS_SCHEMA: ChatToolSchema = {\n type: \"function\",\n function: {\n name: \"stats\",\n description:\n \"Return aggregate memory statistics — memory count, entity count, profile summary, and open questions. Use this for high-level 'what do you know?' questions.\",\n parameters: {\n type: \"object\",\n properties: {},\n additionalProperties: false,\n },\n },\n};\n\nconst CORRECTION_PLAN_SCHEMA: ChatToolSchema = {\n type: \"function\",\n function: {\n name: \"correction_plan\",\n description:\n \"Generate a correction plan (diff preview) for a requested memory change. This does NOT apply the change — it previews what would happen. The user must confirm before correction_apply runs.\",\n parameters: {\n type: \"object\",\n properties: {\n request: {\n type: \"string\",\n description:\n \"Natural-language description of the correction, e.g. 'we finished the MySQL migration in March' or 'forget the outdated database credentials'.\",\n },\n },\n required: [\"request\"],\n additionalProperties: false,\n },\n },\n};\n\nconst CORRECTION_APPLY_SCHEMA: ChatToolSchema = {\n type: \"function\",\n function: {\n name: \"correction_apply\",\n description:\n \"Apply a previously generated correction plan. The engine intercepts this call and requires explicit user confirmation before it executes.\",\n parameters: {\n type: \"object\",\n properties: {\n planId: { type: \"string\", description: \"The plan id from correction_plan.\" },\n },\n required: [\"planId\"],\n additionalProperties: false,\n },\n },\n};\n\nconst MEMORY_PROMOTE_SCHEMA: ChatToolSchema = {\n type: \"function\",\n function: {\n name: \"memory_promote\",\n description:\n \"Promote a memory's tier (e.g. from cold to hot). The engine requires user confirmation before executing.\",\n parameters: {\n type: \"object\",\n properties: {\n memoryId: { type: \"string\", description: \"The memory id to promote.\" },\n },\n required: [\"memoryId\"],\n additionalProperties: false,\n },\n },\n};\n\nconst REVIEW_LIST_SCHEMA: ChatToolSchema = {\n type: \"function\",\n function: {\n name: \"review_list\",\n description:\n \"List items in the contradiction/quality review queue. Returns pairs of potentially conflicting memories awaiting resolution.\",\n parameters: {\n type: \"object\",\n properties: {\n runId: { type: \"string\", description: \"Optional governance run id.\" },\n },\n additionalProperties: false,\n },\n },\n};\n\nconst SCOPE_INSPECT_SCHEMA: ChatToolSchema = {\n type: \"function\",\n function: {\n name: \"scope_inspect\",\n description:\n \"Inspect the current scope/namespace resolution — which namespace the chat session operates in and how it was resolved.\",\n parameters: {\n type: \"object\",\n properties: {},\n additionalProperties: false,\n },\n },\n};\n\n/**\n * All read-only tool schemas, always available when chat is enabled.\n */\nconst READONLY_SCHEMAS: ChatToolSchema[] = [\n MEMORY_SEARCH_SCHEMA,\n MEMORY_GET_SCHEMA,\n MEMORY_TIMELINE_SCHEMA,\n RECALL_EXPLAIN_SCHEMA,\n ENTITY_GET_SCHEMA,\n STATS_SCHEMA,\n REVIEW_LIST_SCHEMA,\n];\n\n/**\n * Build the tool schema list for the LLM. The correction tools are only\n * included when the Correction Contract (#1580) is available; scope_inspect\n * is only included when the scope resolver (#1494) is available.\n */\nexport function buildChatToolSchemas(opts: {\n correctionAvailable: boolean;\n scopeInspectAvailable: boolean;\n}): ChatToolSchema[] {\n const tools = [...READONLY_SCHEMAS];\n if (opts.correctionAvailable) {\n tools.push(CORRECTION_PLAN_SCHEMA, CORRECTION_APPLY_SCHEMA, MEMORY_PROMOTE_SCHEMA);\n }\n if (opts.scopeInspectAvailable) {\n tools.push(SCOPE_INSPECT_SCHEMA);\n }\n return tools;\n}\n","/**\n * Chat engine — the bounded tool-loop agent (issue #1583).\n *\n * Loop: user message → LLM (with tool schema) → execute tool calls → feed\n * results back → final reply. Max `chat.maxToolCallsPerTurn` tool calls per\n * user turn; budget exhausted → reply with partial results + what was\n * skipped (rule 34 — never a silent stall).\n *\n * Confirmation protocol (the safety core): mutating tools\n * (correction_apply, memory_promote) are two-phase in the engine itself,\n * independent of the LLM's judgment. The engine intercepts a mutation tool\n * call, checks the session's confirmedPlanIds set; absent → the engine\n * returns the plan preview to the user with a confirmation prompt; the\n * user's affirmative (exact-match: yes/y/apply/confirm — deterministic, not\n * LLM-interpreted) marks it confirmed for ONE apply.\n */\n\nimport { randomUUID } from \"node:crypto\";\n\nimport type {\n ChatLlmAdapter,\n ChatLlmMessage,\n ChatSessionState,\n ChatToolResult,\n ChatToolSchema,\n ChatTurnResult,\n} from \"./chat-types.js\";\nimport { buildChatSystemPrompt } from \"./chat-system-prompt.js\";\nimport {\n buildChatToolSchemas,\n MUTATING_TOOLS,\n type ChatToolName,\n} from \"./chat-tools.js\";\n\n// ---------------------------------------------------------------------------\n// Tool executor — delegates each tool to access-service (rule 22)\n// ---------------------------------------------------------------------------\n\n/**\n * The executor interface the engine calls for each tool. Each implementation\n * is a thin adapter over the corresponding access-service method — zero new\n * business logic lives in the engine.\n */\nexport interface ChatToolExecutor {\n memorySearch(query: string, maxResults?: number): Promise<string>;\n memoryGet(memoryId: string): Promise<string>;\n memoryTimeline(memoryId: string, limit?: number): Promise<string>;\n recallExplain(query: string): Promise<string>;\n entityGet(name: string): Promise<string>;\n stats(): Promise<string>;\n reviewList(runId?: string): Promise<string>;\n scopeInspect(): Promise<string>;\n /**\n * Generate a correction plan. Returns a JSON string with a planId and\n * a diff preview. When the Correction Contract (#1580) is not merged,\n * this is a stub that returns a not-available marker.\n */\n correctionPlan(request: string): Promise<{ planId: string; preview: string }>;\n /**\n * Apply a correction plan. Returns a JSON result string.\n */\n correctionApply(planId: string): Promise<string>;\n /**\n * Promote a memory's tier. Returns a JSON result string.\n */\n memoryPromote(memoryId: string): Promise<string>;\n}\n\n// ---------------------------------------------------------------------------\n// Engine options\n// ---------------------------------------------------------------------------\n\nexport interface ChatEngineOptions {\n llm: ChatLlmAdapter;\n executor: ChatToolExecutor;\n maxToolCallsPerTurn: number;\n model?: string;\n /** Whether the Correction Contract (#1580) plan/apply is available. */\n correctionAvailable: boolean;\n /** Whether the scope resolver (#1494) is available. */\n scopeInspectAvailable: boolean;\n}\n\n// ---------------------------------------------------------------------------\n// Confirmation keywords — deterministic, not LLM-interpreted\n// ---------------------------------------------------------------------------\n\n// Exact-match confirmations. Unrecognized text keeps the conservative\n// no-apply default, so this stays a small fixed set (issue #2198).\nconst CONFIRMATION_KEYWORDS: Record<string, true> = {\n yes: true,\n y: true,\n apply: true,\n confirm: true,\n \"はい\": true, // Japanese\n \"sí\": true, // Spanish\n ja: true, // German/Dutch\n \"نعم\": true, // Arabic\n};\n\nexport function isConfirmationMessage(text: string): boolean {\n return CONFIRMATION_KEYWORDS[text.trim().toLowerCase()] === true;\n}\n\n// ---------------------------------------------------------------------------\n// Engine\n// ---------------------------------------------------------------------------\n\nexport class ChatEngine {\n private readonly llm: ChatLlmAdapter;\n private readonly executor: ChatToolExecutor;\n private readonly maxToolCallsPerTurn: number;\n private readonly model?: string;\n private readonly correctionAvailable: boolean;\n private readonly scopeInspectAvailable: boolean;\n private readonly systemPrompt: string;\n private readonly toolSchemas: ChatToolSchema[];\n private readonly allowedToolNames: Set<string>;\n\n constructor(opts: ChatEngineOptions) {\n this.llm = opts.llm;\n this.executor = opts.executor;\n this.maxToolCallsPerTurn = opts.maxToolCallsPerTurn;\n this.model = opts.model;\n this.correctionAvailable = opts.correctionAvailable;\n this.scopeInspectAvailable = opts.scopeInspectAvailable;\n this.systemPrompt = buildChatSystemPrompt({\n correctionAvailable: opts.correctionAvailable,\n });\n this.toolSchemas = buildChatToolSchemas({\n correctionAvailable: opts.correctionAvailable,\n scopeInspectAvailable: opts.scopeInspectAvailable,\n });\n // Pre-compute the set of allowed tool names for fast lookup (cursor HIGH —\n // executeTool must not run a tool that's not in the active schema set).\n this.allowedToolNames = new Set(this.toolSchemas.map((t) => t.function.name));\n }\n\n /**\n * Process a single user message. The session state is mutated in place\n * (confirmedPlanIds, pendingPlanId) — the caller persists the transcript.\n */\n async processMessage(\n userMessage: string,\n session: ChatSessionState,\n ): Promise<ChatTurnResult> {\n // ── Confirmation fast-path ──────────────────────────────────────────\n // If there is a pending plan and the user's message is an exact-match\n // confirmation keyword, mark the plan confirmed and apply it directly\n // (bypassing the LLM — deterministic, not LLM-interpreted).\n if (\n isConfirmationMessage(userMessage) &&\n this.correctionAvailable\n ) {\n // Confirm + apply a pending correction plan.\n if (session.pendingPlanId) {\n const planId = session.pendingPlanId;\n session.confirmedPlanIds.add(planId);\n session.pendingPlanId = undefined;\n try {\n const applyResult = await this.executor.correctionApply(planId);\n // Consume the one-time confirmation on success so a later\n // tool-loop correction_apply cannot re-apply the same plan id\n // (cursor Medium: stale confirm allowed re-apply).\n session.confirmedPlanIds.delete(planId);\n return {\n reply: `Correction applied.\\n\\n${applyResult}`,\n chatSessionId: session.id,\n ...(session.pendingPromotionId ? {} : {}),\n };\n } catch (err) {\n // Roll back: the plan was NOT applied — restore the pending state\n // so the user can retry (cursor HIGH OlACo).\n session.confirmedPlanIds.delete(planId);\n session.pendingPlanId = planId;\n const msg = err instanceof Error ? err.message : String(err);\n return {\n reply: \"[error] Failed to apply the correction. Please try again or re-request the plan.\",\n chatSessionId: session.id,\n error: msg,\n };\n }\n }\n // Confirm + apply a pending memory promotion.\n if (session.pendingPromotionId) {\n const memoryId = session.pendingPromotionId;\n session.pendingPromotionId = undefined;\n try {\n const promoteResult = await this.executor.memoryPromote(memoryId);\n return {\n reply: `Memory promoted.\\n\\n${promoteResult}`,\n chatSessionId: session.id,\n };\n } catch (err) {\n // Roll back: the promotion was NOT applied — restore pending state.\n session.pendingPromotionId = memoryId;\n const msg = err instanceof Error ? err.message : String(err);\n return {\n reply: \"[error] Failed to promote the memory. Please try again.\",\n chatSessionId: session.id,\n error: msg,\n };\n }\n }\n }\n\n // ── Normal tool-loop ────────────────────────────────────────────────\n // Build the transcript context, filtering out:\n // - the system header (seq === 0)\n // - internal state markers (pending_plan:/pending_promotion:/plan_applied:)\n // - the last user entry if it matches userMessage (the caller already\n // appended it to the transcript before calling processMessage — adding\n // it again below would duplicate it in the prompt).\n const recentEntries = session.transcript\n .slice(-21)\n .filter((e) => e.role !== \"system\" || e.seq !== 0)\n .filter((e) => !(e.role === \"system\" && /^[a-z_]+:/.test(e.content)))\n .filter((e, _i, arr) => {\n // Drop the last user entry if it duplicates the current message.\n if (e.role === \"user\" && e.content === userMessage) {\n const lastUser = [...arr].reverse().find((x) => x.role === \"user\");\n return e !== lastUser;\n }\n return true;\n });\n const conversation: ChatLlmMessage[] = [\n { role: \"system\", content: this.systemPrompt },\n ...recentEntries.map((e) => ({\n role: e.role as \"user\" | \"assistant\" | \"tool\",\n content: e.content,\n ...(e.toolCallId ? { toolCallId: e.toolCallId } : {}),\n })),\n { role: \"user\", content: userMessage },\n ];\n\n let toolCallCount = 0;\n const skippedTools: string[] = [];\n let pendingPlan: { planId: string; preview: string } | undefined;\n\n for (;;) {\n let response;\n try {\n response = await this.llm.complete(conversation, {\n tools: this.toolSchemas,\n ...(this.model ? { model: this.model } : {}),\n });\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n return {\n reply: \"[error] The model request failed. Check your model configuration and retry.\",\n chatSessionId: session.id,\n error: msg,\n };\n }\n\n // LLM outage (rule 13) — tagged error reply.\n if (!response) {\n return {\n reply: \"[error] No LLM model is available. Configure a local or cloud model to use Remnic Chat.\",\n chatSessionId: session.id,\n error: \"no_llm_available\",\n };\n }\n\n // No tool calls → final reply.\n if (response.toolCalls.length === 0) {\n // Citation guard: if the reply asserts memory content without tool\n // results in this turn, append a citation-missing warning.\n let reply = response.content;\n if (toolCallCount === 0 && looksLikeMemoryAssertion(reply)) {\n reply += \"\\n\\n⚠️ The above assertion was not grounded in a tool result this turn. Please verify with memory_search or memory_get.\";\n }\n return {\n reply,\n chatSessionId: session.id,\n ...(pendingPlan ? { pendingPlan } : {}),\n ...(skippedTools.length > 0 ? { skippedTools } : {}),\n };\n }\n\n // Push the assistant response content once for this LLM turn (not per\n // tool call — avoids duplicate assistant messages in the conversation).\n conversation.push({ role: \"assistant\", content: response.content });\n\n // Execute each tool call (budget-limited).\n for (const tc of response.toolCalls) {\n if (toolCallCount >= this.maxToolCallsPerTurn) {\n skippedTools.push(tc.name);\n continue;\n }\n toolCallCount++;\n\n // ── Tool-schema gate (cursor HIGH OlCjs — must run before mutating-tool\n // interception so disabled tools like correction_apply/memory_promote\n // are rejected before any confirmation flow or executor call).\n if (!this.allowedToolNames.has(tc.name)) {\n conversation.push({\n role: \"tool\",\n content: JSON.stringify({ error: `Tool '${tc.name}' is not available in this configuration.` }),\n toolCallId: tc.id,\n });\n continue;\n }\n\n // ── Confirmation protocol for mutating tools ──────────────────\n if (MUTATING_TOOLS.has(tc.name as ChatToolName)) {\n if (tc.name === \"correction_apply\") {\n const planId = typeof tc.arguments.planId === \"string\" ? tc.arguments.planId : \"\";\n if (!session.confirmedPlanIds.has(planId)) {\n // Not confirmed — return the plan preview for user confirmation.\n // The plan was generated by a prior correction_plan call; fetch it.\n try {\n const plan = await this.executor.correctionPlan(\n `retrieve plan ${planId}`,\n );\n // Bind the REQUESTED planId so the confirmation fast-path applies\n // the exact plan shown (not an executor re-minted id).\n pendingPlan = { planId, preview: plan.preview };\n session.pendingPlanId = planId;\n conversation.push({\n role: \"tool\",\n content: JSON.stringify({\n intercepted: true,\n message: \"This mutation requires confirmation. The plan preview has been shown to the user.\",\n }),\n toolCallId: tc.id,\n });\n return {\n reply: formatPlanPreview(plan.preview),\n chatSessionId: session.id,\n pendingPlan,\n };\n } catch {\n conversation.push({\n role: \"tool\",\n content: JSON.stringify({ error: \"Plan not found or expired.\" }),\n toolCallId: tc.id,\n });\n continue;\n }\n }\n // Confirmed — consume the one-time confirmation.\n session.confirmedPlanIds.delete(planId);\n }\n }\n\n // ── memory_promote confirmation (mutating tool) ─────────────────\n // memory_promote is NEVER executed directly in the tool loop — it can\n // only be applied via the confirmation fast-path at the top of\n // processMessage (cursor HIGH: prevent bypass via repeated tool calls).\n if (tc.name === \"memory_promote\" && this.correctionAvailable) {\n const memoryId = typeof tc.arguments.memoryId === \"string\" ? tc.arguments.memoryId : \"\";\n session.pendingPromotionId = memoryId;\n conversation.push({\n role: \"tool\",\n content: JSON.stringify({\n intercepted: true,\n message: `Memory promotion requires confirmation. Reply 'apply' to promote memory '${memoryId}'.`,\n }),\n toolCallId: tc.id,\n });\n return {\n reply: `I want to promote memory \\`${memoryId}\\`. Reply **apply** to confirm this promotion, or **cancel** to discard it.`,\n chatSessionId: session.id,\n };\n }\n\n // ── Execute the tool ───────────────────────────────────────────\n let result: ChatToolResult;\n try {\n result = await this.executeTool(tc.name, tc.arguments, session);\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n result = { content: JSON.stringify({ error: msg }) };\n }\n\n // Feed the tool result back into the conversation.\n conversation.push({\n role: \"tool\",\n content: result.content,\n toolCallId: tc.id,\n });\n\n // If a correction_plan surfaced, track the pending plan.\n if (tc.name === \"correction_plan\" && this.correctionAvailable) {\n try {\n const parsed = JSON.parse(result.content) as { planId?: string; preview?: string };\n if (parsed.planId && parsed.preview) {\n pendingPlan = { planId: parsed.planId, preview: parsed.preview };\n session.pendingPlanId = parsed.planId;\n }\n } catch {\n // The plan result might be a stub — that's fine.\n }\n }\n }\n\n // If we hit the budget and there are still tool calls, report partial.\n if (skippedTools.length > 0) {\n // Ask the LLM for a final summary with what we have.\n conversation.push({\n role: \"user\",\n content: `[system] Tool budget exhausted (${this.maxToolCallsPerTurn} calls). ${skippedTools.length} tool(s) were skipped: ${skippedTools.join(\", \")}. Please summarize what you found.`,\n });\n // One more LLM call for the summary, then we're done.\n let summaryResponse;\n try {\n summaryResponse = await this.llm.complete(conversation, {\n tools: [], // No more tools — force a text reply.\n ...(this.model ? { model: this.model } : {}),\n });\n } catch {\n // Budget-exhaustion summary is best-effort — don't mask the partial\n // results with a transport error (kilo review, Thread 16).\n summaryResponse = null;\n }\n const summaryText = summaryResponse?.content ?? \"I reached my tool-call budget. Here is what I found so far, but some queries were skipped.\";\n return {\n reply: summaryText,\n chatSessionId: session.id,\n ...(pendingPlan ? { pendingPlan } : {}),\n skippedTools,\n };\n }\n }\n }\n\n /**\n * Execute a single tool by name, delegating to the executor.\n */\n private async executeTool(\n name: string,\n args: Record<string, unknown>,\n _session: ChatSessionState,\n ): Promise<ChatToolResult> {\n switch (name as ChatToolName) {\n case \"memory_search\": {\n const query = typeof args.query === \"string\" ? args.query : \"\";\n const maxResults = typeof args.maxResults === \"number\" ? args.maxResults : undefined;\n return { content: await this.executor.memorySearch(query, maxResults) };\n }\n case \"memory_get\": {\n const memoryId = typeof args.memoryId === \"string\" ? args.memoryId : \"\";\n return { content: await this.executor.memoryGet(memoryId) };\n }\n case \"memory_timeline\": {\n const memoryId = typeof args.memoryId === \"string\" ? args.memoryId : \"\";\n const limit = typeof args.limit === \"number\" ? args.limit : undefined;\n return { content: await this.executor.memoryTimeline(memoryId, limit) };\n }\n case \"recall_explain\": {\n const query = typeof args.query === \"string\" ? args.query : \"\";\n return { content: await this.executor.recallExplain(query) };\n }\n case \"entity_get\": {\n const entityName = typeof args.name === \"string\" ? args.name : \"\";\n return { content: await this.executor.entityGet(entityName) };\n }\n case \"stats\": {\n return { content: await this.executor.stats() };\n }\n case \"correction_plan\": {\n const request = typeof args.request === \"string\" ? args.request : \"\";\n const plan = await this.executor.correctionPlan(request);\n return { content: JSON.stringify(plan) };\n }\n case \"correction_apply\": {\n const planId = typeof args.planId === \"string\" ? args.planId : \"\";\n return { content: await this.executor.correctionApply(planId) };\n }\n case \"memory_promote\": {\n const memoryId = typeof args.memoryId === \"string\" ? args.memoryId : \"\";\n return { content: await this.executor.memoryPromote(memoryId) };\n }\n case \"review_list\": {\n const runId = typeof args.runId === \"string\" ? args.runId : undefined;\n return { content: await this.executor.reviewList(runId) };\n }\n case \"scope_inspect\": {\n return { content: await this.executor.scopeInspect() };\n }\n default:\n return { content: JSON.stringify({ error: `Unknown tool: ${name}` }) };\n }\n }\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Heuristic: does the reply look like it's asserting stored memory content\n * without citing a tool result? This is intentionally simple — flag, don't\n * police perfectly (per the issue's pitfall note).\n */\nfunction looksLikeMemoryAssertion(text: string): boolean {\n const lower = text.toLowerCase();\n // Phrases that indicate a memory assertion.\n const assertionPhrases = [\n \"you remember\",\n \"i remember\",\n \"according to my memory\",\n \"your memory\",\n \"stored memory\",\n \"remnic remembers\",\n \"remnic knows\",\n ];\n // Only flag if there's an assertion AND no citation marker.\n const hasAssertion = assertionPhrases.some((p) => lower.includes(p));\n const hasCitation = lower.includes(\"[id:\") || lower.includes(\"memory id\") || lower.includes(\"source:\");\n return hasAssertion && !hasCitation;\n}\n\n/**\n * Format a plan preview for display to the user.\n */\nfunction formatPlanPreview(preview: string): string {\n return [\n \"Here is the correction plan I generated:\",\n \"\",\n \"```diff\",\n preview,\n \"```\",\n \"\",\n \"Reply **apply** to confirm and apply this correction.\",\n \"Reply **cancel** to discard it.\",\n ].join(\"\\n\");\n}\n","/**\n * LLM adapter for the chat engine (issue #1583).\n *\n * The adapter exposes the production {@link ChatLlmAdapter} interface so the\n * engine is decoupled from the routing chain. Two implementations:\n *\n * - {@link createProductionChatLlmAdapter}: wraps the existing\n * FallbackLlmClient / LocalLlmClient routing chain so local Ollama/vLLM\n * models are fully supported (gotcha 1). Memory chat must not require\n * cloud.\n *\n * - {@link StubChatLlmAdapter}: test-only adapter that drives scripted\n * tool-call sequences. PR 1 tests use this to verify the engine loop,\n * confirmation protocol, budget exhaustion, and citation guard without\n * real LLM calls.\n */\n\nimport type { ChatLlmAdapter, ChatLlmMessage, ChatLlmResponse, ChatLlmToolCall, ChatToolSchema } from \"./chat-types.js\";\n\n// ---------------------------------------------------------------------------\n// Minimal LLM-client interface (duck-typed from FallbackLlmClient and\n// LocalLlmClient — both expose chatCompletion returning {content}|null).\n// ---------------------------------------------------------------------------\n\ninterface LlmLikeClient {\n chatCompletion(\n messages: Array<{ role: string; content: string }>,\n options?: { model?: string; signal?: AbortSignal; [k: string]: unknown },\n ): Promise<{ content: string; modelUsed?: string } | null>;\n}\n\n/**\n * Create a production LLM adapter from an existing routing-chain client\n * (FallbackLlmClient or LocalLlmClient).\n *\n * The adapter maps the chat engine's message format to the client's\n * chatCompletion signature, injects the tool schema as a system-level\n * instruction (OpenAI function-calling compat), and parses tool-call requests\n * from the model's response.\n */\nexport function createProductionChatLlmAdapter(\n client: LlmLikeClient,\n): ChatLlmAdapter {\n return {\n async complete(\n messages: ChatLlmMessage[],\n options: { tools: ChatToolSchema[]; model?: string; signal?: AbortSignal },\n ): Promise<ChatLlmResponse | null> {\n // Build the tool-calling instruction appended to the system message.\n const toolInstruction = formatToolInstruction(options.tools);\n const mapped = messages.map((m) => {\n if (m.role === \"system\") {\n return { role: m.role, content: m.content + \"\\n\\n\" + toolInstruction };\n }\n // Normalize tool results to a provider-safe role. The underlying\n // chat-completion clients do not implement native tool-call envelopes,\n // so a bare role:\"tool\" (without tool_call_id) is rejected by\n // OpenAI/Anthropic/Ollama endpoints. Surface the result as a user\n // message so the follow-up LLM turn always succeeds (P1).\n if (m.role === \"tool\") {\n const tag = m.toolCallId ? `[tool:${m.toolCallId}]` : \"[tool]\";\n return { role: \"user\", content: `${tag} ${m.content}` };\n }\n return { role: m.role, content: m.content };\n });\n const result = await client.chatCompletion(mapped, {\n ...(options.model ? { model: options.model } : {}),\n ...(options.signal ? { signal: options.signal } : {}),\n });\n if (!result) return null;\n const toolCalls = parseToolCalls(result.content);\n return {\n content: stripToolCallJson(result.content, toolCalls),\n toolCalls,\n };\n },\n };\n}\n\n/**\n * Format the available tools as a function-calling instruction for the LLM.\n * Models that support native function-calling can ignore this; models that\n * don't (most local models) use it to emit structured tool calls.\n */\nfunction formatToolInstruction(tools: ChatToolSchema[]): string {\n if (tools.length === 0) return \"\";\n const lines = [\n \"## Available tools\",\n \"\",\n \"You may call the following tools by emitting a JSON block on its own line:\",\n \"```json\",\n '{\"tool\": \"<name>\", \"arguments\": { ... }}',\n \"```\",\n \"\",\n \"Call one tool at a time. After receiving the tool result, continue your\",\n \"reasoning or emit another tool call. When you have a final answer, reply\",\n \"with text only (no tool-call JSON).\",\n \"\",\n \"Tools:\",\n ];\n for (const t of tools) {\n const params = JSON.stringify(t.function.parameters);\n lines.push(`- ${t.function.name}: ${t.function.description}`);\n lines.push(` Parameters: ${params}`);\n }\n return lines.join(\"\\n\");\n}\n\n/**\n * Parse a tool-call JSON block from the model's response content.\n * Tolerates leading/trailing text and code fences.\n */\nexport function parseToolCalls(content: string): ChatLlmToolCall[] {\n const calls: ChatLlmToolCall[] = [];\n // Match ```json ... ``` blocks and bare JSON objects with \"tool\" key.\n const patterns = [\n /```json\\s*\\n([\\s\\S]*?)\\n```/g,\n /```\\s*\\n([\\s\\S]*?)\\n```/g,\n ];\n const candidates: string[] = [];\n for (const pattern of patterns) {\n let match: RegExpExecArray | null;\n while ((match = pattern.exec(content)) !== null) {\n candidates.push(match[1]);\n }\n }\n // Also try bare JSON lines.\n for (const line of content.split(\"\\n\")) {\n const trimmed = line.trim();\n if (trimmed.startsWith(\"{\") && trimmed.includes('\"tool\"')) {\n candidates.push(trimmed);\n }\n }\n const seen = new Set<string>();\n for (const candidate of candidates) {\n try {\n const parsed = JSON.parse(candidate) as { tool?: string; arguments?: Record<string, unknown> };\n if (typeof parsed.tool === \"string\" && parsed.tool.length > 0) {\n const args = parsed.arguments ?? {};\n // De-duplicate: a fenced block and its inner bare line can both match.\n const key = parsed.tool + \":\" + JSON.stringify(args);\n if (seen.has(key)) continue;\n seen.add(key);\n calls.push({\n id: `call_${calls.length + 1}`,\n name: parsed.tool,\n arguments: args,\n });\n }\n } catch {\n // Not valid JSON — skip.\n }\n }\n return calls;\n}\n\n/**\n * Remove tool-call JSON blocks from the content, leaving only prose.\n */\nfunction stripToolCallJson(content: string, toolCalls: ChatLlmToolCall[]): string {\n if (toolCalls.length === 0) return content;\n let result = content;\n // Remove fenced blocks.\n result = result.replace(/```json\\s*\\n[\\s\\S]*?\\n```/g, \"\");\n result = result.replace(/```\\s*\\n[\\s\\S]*?\\n```/g, \"\");\n // Remove bare JSON tool-call lines.\n result = result\n .split(\"\\n\")\n .filter((line) => {\n const trimmed = line.trim();\n return !(trimmed.startsWith(\"{\") && trimmed.includes('\"tool\"'));\n })\n .join(\"\\n\");\n return result.trim();\n}\n\n// ---------------------------------------------------------------------------\n// Stub adapter — for tests (rule 33: production signature, scripted behaviour)\n// ---------------------------------------------------------------------------\n\n/**\n * A scripted step in the stub adapter. Each step is consumed in order for\n * each LLM call; the last step repeats if the engine loops beyond the\n * script length.\n */\nexport interface StubLlmStep {\n content?: string;\n toolCalls?: Array<{ name: string; arguments: Record<string, unknown> }>;\n}\n\nexport class StubChatLlmAdapter implements ChatLlmAdapter {\n private steps: StubLlmStep[];\n private callIndex = 0;\n\n constructor(steps: StubLlmStep[]) {\n this.steps = steps;\n }\n\n async complete(\n _messages: ChatLlmMessage[],\n _options: { tools: ChatToolSchema[]; model?: string; signal?: AbortSignal },\n ): Promise<ChatLlmResponse | null> {\n const step = this.steps[Math.min(this.callIndex, this.steps.length - 1)];\n this.callIndex++;\n const toolCalls: ChatLlmToolCall[] = (step.toolCalls ?? []).map((tc, i) => ({\n id: `call_${i + 1}`,\n name: tc.name,\n arguments: tc.arguments,\n }));\n return {\n content: step.content ?? \"\",\n toolCalls,\n };\n }\n\n /** Reset the call index (for test reuse). */\n reset(): void {\n this.callIndex = 0;\n }\n}\n\n/**\n * A stub adapter that always returns null (simulates LLM outage, rule 13).\n */\nexport class NullChatLlmAdapter implements ChatLlmAdapter {\n async complete(): Promise<null> {\n return null;\n }\n}\n","/**\n * Production chat-tool executor (issue #1583).\n *\n * Each method is a thin adapter over the corresponding EngramAccessService\n * method — zero new business logic (rule 22). The executor carries the\n * session's principal/namespace/sessionKey so every tool call flows through\n * access-service with the caller's identity (rule 42).\n *\n * Correction tools (correction_plan / correction_apply / memory_promote) are\n * stubbed behind the same interface until the Correction Contract (#1580)\n * merges. The stub returns a clear not-available marker so the engine and\n * surfaces degrade gracefully.\n */\n\nimport type { EngramAccessService } from \"../access-service.js\";\nimport type { ChatToolExecutor } from \"./chat-engine.js\";\n\nexport interface ChatExecutorBindings {\n service: EngramAccessService;\n principal?: string;\n namespace?: string;\n sessionKey?: string;\n}\n\n/**\n * Create a production executor bound to the caller's identity.\n */\nexport function createChatExecutor(bindings: ChatExecutorBindings): ChatToolExecutor {\n const { service, principal, namespace, sessionKey } = bindings;\n\n return {\n async memorySearch(query: string, maxResults?: number): Promise<string> {\n const result = await service.memorySearch({\n query,\n ...(namespace ? { namespace } : {}),\n ...(maxResults !== undefined ? { maxResults } : {}),\n ...(principal ? { principal } : {}),\n });\n return JSON.stringify(result);\n },\n\n async memoryGet(memoryId: string): Promise<string> {\n const result = await service.memoryGet(memoryId, namespace, principal, sessionKey);\n return JSON.stringify(result);\n },\n\n async memoryTimeline(memoryId: string, limit?: number): Promise<string> {\n const result = await service.memoryTimeline(memoryId, namespace, limit ?? 200, principal);\n return JSON.stringify(result);\n },\n\n async recallExplain(query: string): Promise<string> {\n const result = await service.recallExplain({\n ...(sessionKey ? { sessionKey } : {}),\n ...(namespace ? { namespace } : {}),\n ...(principal ? { authenticatedPrincipal: principal } : {}),\n ...(query ? { query } : {}),\n });\n return JSON.stringify(result);\n },\n\n async entityGet(name: string): Promise<string> {\n const result = await service.entityGet(name, namespace);\n return JSON.stringify(result);\n },\n\n async stats(): Promise<string> {\n const [profile, entities, questions] = await Promise.all([\n service.memoryProfile(namespace, principal),\n service.memoryEntitiesList(namespace, principal),\n service.memoryQuestions(namespace, principal),\n ]);\n return JSON.stringify({ profile, entities, questions });\n },\n\n async reviewList(runId?: string): Promise<string> {\n const result = await service.reviewQueue(runId, namespace, principal);\n return JSON.stringify(result);\n },\n\n async scopeInspect(): Promise<string> {\n return JSON.stringify({\n namespace: namespace ?? \"default\",\n principal: principal ?? \"default\",\n sessionKey: sessionKey ?? undefined,\n });\n },\n\n // ── Correction tools — stubbed until #1580 merges ──────────────────\n // When the Correction Contract lands, replace these stubs with calls to\n // the correction module's plan/apply interface. The engine, CLI, and\n // MCP tool all consume this interface, so the stub-to-real swap is a\n // single-file change here.\n\n async correctionPlan(request: string): Promise<{ planId: string; preview: string }> {\n // Stub: the Correction Contract (#1580) is not yet merged.\n // Return a not-available marker that the engine surfaces gracefully.\n return {\n planId: `stub-${Date.now()}`,\n preview: `[Correction Contract (#1580) not yet available]\\n\\nRequested correction: \"${request}\"\\n\\nThe plan/apply pipeline is pending. Inspection tools are fully functional.`,\n };\n },\n\n async correctionApply(planId: string): Promise<string> {\n // Stub: no-op until #1580 merges.\n return JSON.stringify({\n applied: false,\n planId,\n reason: \"Correction Contract (#1580) not yet available. No mutation was applied.\",\n });\n },\n\n async memoryPromote(memoryId: string): Promise<string> {\n // Delegate to the existing memoryPromote service method if available.\n try {\n const serviceWithPromote = service as EngramAccessService & {\n memoryPromote?: (memoryId: string, namespace?: string, principal?: string) => Promise<unknown>;\n };\n if (typeof serviceWithPromote.memoryPromote === \"function\") {\n const result = await serviceWithPromote.memoryPromote(memoryId, namespace, principal);\n return JSON.stringify(result);\n }\n } catch {\n // Fall through to stub.\n }\n return JSON.stringify({\n promoted: false,\n memoryId,\n reason: \"Memory promotion is not available in this build.\",\n });\n },\n };\n}\n","/**\n * Chat session state — transcript + pending-plan pointer persisted under\n * `<memoryDir>/state/chat/<chatSessionId>.jsonl` (issue #1583).\n *\n * Atomic appends (rule 54). Chat transcripts are excluded from memory\n * extraction — the work-task exclusion tag is stamped on creation so talking\n * *about* memories does not create memories of the conversation itself.\n */\n\nimport { mkdir, readFile, appendFile, readdir, stat, unlink, open } from \"node:fs/promises\";\nimport { constants as fsConstants } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { randomUUID } from \"node:crypto\";\nimport { enforceNamespaceAllowList, tokenCapabilityStore } from \"../access-token-capabilities.js\";\n\nimport type { ChatSessionState, ChatTranscriptEntry } from \"./chat-types.js\";\n\nconst CHAT_DIR_NAME = \"state/chat\";\n\n/**\n * Resolve the chat-session directory for a given memory dir.\n */\nexport function chatSessionDir(memoryDir: string): string {\n return join(memoryDir, CHAT_DIR_NAME);\n}\n\n/**\n * Resolve the transcript file path for a chat session id.\n */\n/**\n * Validate a chat session id is safe for filesystem use (no path traversal).\n * Accepts UUIDs and alphanumeric+dash identifiers only (P1 — path safety).\n */\nexport function isSafeChatSessionId(chatSessionId: string): boolean {\n return /^[A-Za-z0-9]{8,128}$/.test(chatSessionId.replace(/-/g, \"\"));\n}\n\nexport function chatSessionFile(memoryDir: string, chatSessionId: string): string {\n if (!isSafeChatSessionId(chatSessionId)) {\n throw new Error(\"Invalid chat session id\");\n }\n return join(chatSessionDir(memoryDir), `${chatSessionId}.jsonl`);\n}\n\n// ---------------------------------------------------------------------------\n// Monotonic transcript seq (issue #1687 review — strictly increasing)\n// ---------------------------------------------------------------------------\n\n/**\n * Last emitted transcript `seq`. Seeded from `Date.now()` on first use and\n * incremented when two appends land in the same millisecond, so `seq` is\n * strictly increasing within a process (review thread: `Date.now()` alone is\n * not monotonic — same-ms entries would share a seq and break the SSE\n * reconnect dedup-by-seq contract). Across process restarts the counter is\n * raised above the on-disk max by `loadChatSession` (issue #1718), so a\n * backward clock step (NTP, VM migration, manual change) cannot re-seed it\n * below lines already persisted for a resumed session.\n */\nlet lastTranscriptSeq = 0;\n\nfunction nextTranscriptSeq(): number {\n const now = Date.now();\n lastTranscriptSeq = now > lastTranscriptSeq ? now : lastTranscriptSeq + 1;\n return lastTranscriptSeq;\n}\n\n/**\n * Test-only: reset the module-level transcript seq counter so a regression\n * test can deterministically simulate a fresh process restart (issue #1718).\n */\nexport function __resetTranscriptSeqForTest(): void {\n lastTranscriptSeq = 0;\n}\n\n/**\n * Create a new chat session. The session binds the caller's principal and\n * sessionKey at creation (rule 42); every tool call flows through\n * access-service with that identity.\n */\nexport async function createChatSession(\n memoryDir: string,\n opts: { principal?: string; sessionKey?: string; namespace?: string },\n): Promise<ChatSessionState> {\n const id = randomUUID();\n const now = new Date().toISOString();\n const state: ChatSessionState = {\n id,\n principal: opts.principal,\n sessionKey: opts.sessionKey,\n namespace: opts.namespace,\n transcript: [],\n confirmedPlanIds: new Set(),\n createdAt: now,\n };\n // Ensure the directory exists.\n await mkdir(chatSessionDir(memoryDir), { recursive: true });\n // Write a metadata header line so the file is never empty and carries\n // the principal/scope binding (used for per-session isolation checks).\n await appendFile(\n chatSessionFile(memoryDir, id),\n JSON.stringify({\n seq: 0,\n ts: now,\n role: \"system\" as const,\n content: `Chat session created. Principal: ${opts.principal ?? \"default\"}. Namespace: ${opts.namespace ?? \"default\"}. work_task: Excluded from memory extraction`,\n // Structured binding fields so loadChatSession doesn't need to regex-parse\n // prose (robust against dotted principals like alice@example.com).\n ...(opts.principal ? { principal: opts.principal } : {}),\n ...(opts.namespace ? { namespace: opts.namespace } : {}),\n ...(opts.sessionKey ? { sessionKey: opts.sessionKey } : {}),\n }) + \"\\n\",\n \"utf8\",\n );\n return state;\n}\n\n/**\n * Load a chat session from disk, including its full transcript.\n * Returns `null` if the session file does not exist.\n *\n * Per-session isolation: the caller MUST verify that the loaded session's\n * principal matches the requesting principal before operating on it.\n */\nexport async function loadChatSession(\n memoryDir: string,\n chatSessionId: string,\n): Promise<ChatSessionState | null> {\n let raw: string;\n try {\n raw = await readFile(chatSessionFile(memoryDir, chatSessionId), \"utf8\");\n } catch {\n return null;\n }\n const lines = raw.split(\"\\n\").filter((l) => l.trim().length > 0);\n const transcript: ChatTranscriptEntry[] = [];\n let principal: string | undefined;\n let sessionKey: string | undefined;\n let namespace: string | undefined;\n let createdAt = \"\";\n let pendingPlanId: string | undefined;\n let pendingPromotionId: string | undefined;\n for (const line of lines) {\n try {\n const entry = JSON.parse(line) as ChatTranscriptEntry & Record<string, unknown>;\n transcript.push(entry);\n // Extract binding from the system header line.\n if (entry.role === \"system\" && entry.seq === 0) {\n // Prefer structured fields (robust against dotted principals).\n const metaPrincipal = typeof entry.principal === \"string\" ? entry.principal : undefined;\n const metaNamespace = typeof entry.namespace === \"string\" ? entry.namespace : undefined;\n const metaSessionKey = typeof entry.sessionKey === \"string\" ? entry.sessionKey : undefined;\n if (metaPrincipal) principal = metaPrincipal;\n else {\n // Greedy regex fallback for older session files (captures until \". Namespace\").\n const pMatch = entry.content.match(/Principal: (.+?)\\.\\s/);\n if (pMatch) principal = pMatch[1]?.trim() === \"default\" ? undefined : pMatch[1]?.trim();\n }\n if (metaNamespace) namespace = metaNamespace;\n else {\n const nsMatch = entry.content.match(/Namespace: (.+?)\\.\\s/);\n if (nsMatch) namespace = nsMatch[1]?.trim() === \"default\" ? undefined : nsMatch[1]?.trim();\n }\n if (metaSessionKey) sessionKey = metaSessionKey;\n createdAt = entry.ts;\n }\n // Scan for pending-plan / pending-promotion markers (append-only state).\n if (entry.role === \"system\") {\n const pm = entry.content.match(/^pending_plan:(.+)$/);\n if (pm) pendingPlanId = pm[1];\n const pp = entry.content.match(/^pending_promotion:(.+)$/);\n if (pp) pendingPromotionId = pp[1];\n const resolved = entry.content.match(/^(plan_applied|plan_cancelled|promotion_applied|promotion_cancelled):/);\n if (resolved) {\n // Only clear the matching pending — a plan resolution must not drop\n // an active promotion (and vice versa) (cursor Medium OlACs).\n if (entry.content.startsWith(\"plan_\")) {\n pendingPlanId = undefined;\n }\n if (entry.content.startsWith(\"promotion_\")) {\n pendingPromotionId = undefined;\n }\n }\n }\n } catch {\n // Skip malformed lines (rule 54 — atomic appends; partial lines are\n // tolerated, never crash the engine).\n }\n }\n // Issue #1718 — backward-clock-skew robustness: raise the module-level seq\n // counter so the next append is strictly greater than any line already on\n // disk for this session, regardless of clock direction across restarts\n // (NTP step, VM migration, manual change). Without this, a backward clock\n // skew would re-seed the counter below the on-disk max and the SSE\n // reconnect dedup-by-seq contract could drop freshly-appended entries as\n // duplicates. The transcript is already fully parsed above, so this is a\n // single pass over the in-memory array.\n for (const e of transcript) {\n if (typeof e.seq === \"number\" && e.seq + 1 > lastTranscriptSeq) {\n lastTranscriptSeq = e.seq + 1;\n }\n }\n return {\n id: chatSessionId,\n principal,\n sessionKey,\n namespace,\n transcript,\n confirmedPlanIds: new Set(),\n ...(pendingPlanId ? { pendingPlanId } : {}),\n ...(pendingPromotionId ? { pendingPromotionId } : {}),\n createdAt,\n };\n}\n\n/**\n * Structural shape {@link enforceChatSessionNamespace} reads from a service —\n * `memoryDir` to locate the session file and `configRef.defaultNamespace` to\n * resolve the effective namespace. Kept structural so the chat module need not\n * depend on the full {@link EngramAccessService} type.\n */\nexport interface ChatSessionNamespaceHost {\n memoryDir: string;\n configRef?: { defaultNamespace?: string } | undefined;\n}\n\n/**\n * The shared effective-namespace chokepoint for a resumed chat session\n * (issue #1850 round 6). A chat session is an id-loaded record whose stored\n * namespace bypassed the per-token allow-list; BOTH the HTTP dispatch\n * (`/engram/v1/chat/message`, `/engram/v1/chat/events/:id`) and the MCP\n * dispatch (`memory_chat` → processChatMessage) call this ONE function so\n * neither surface can dodge it. Loads the session and runs\n * `enforceNamespaceAllowList` (which maps undefined → the server default).\n * FAIL CLOSED: a scoped token whose allow-list does not cover the session's\n * effective namespace is rejected; no-op for unrestricted/legacy tokens. A\n * missing session is left to the downstream handler (404 /\n * chat_session_not_found) — only FOUND sessions carry a namespace to gate.\n */\nexport async function enforceChatSessionNamespace(\n service: ChatSessionNamespaceHost,\n chatSessionId: string,\n): Promise<void> {\n const session = await loadChatSession(service.memoryDir, chatSessionId);\n if (!session) return;\n enforceNamespaceAllowList(tokenCapabilityStore.getStore(), session.namespace, service.configRef?.defaultNamespace);\n}\n\n/**\n * Append a transcript entry to the session file (atomic append, rule 54).\n *\n * After the append resolves, in-process subscribers (open SSE connections —\n * issue #1687) are notified synchronously so live clients receive the new\n * entry without polling. Listener errors are swallowed so a misbehaving\n * subscriber can never break a transcript append (rule 54 — atomic + safe).\n */\nexport async function appendTranscriptEntry(\n memoryDir: string,\n chatSessionId: string,\n entry: Omit<ChatTranscriptEntry, \"seq\" | \"ts\">,\n): Promise<ChatTranscriptEntry> {\n const filePath = chatSessionFile(memoryDir, chatSessionId);\n const full: ChatTranscriptEntry = {\n ...entry,\n seq: nextTranscriptSeq(),\n ts: new Date().toISOString(),\n };\n // Atomic resurrection guard (codex P2): open with O_APPEND but WITHOUT\n // O_CREAT so a session already unlinked by a concurrent TTL sweep fails at\n // open-time (ENOENT) — there is no stat->appendFile TOCTOU. A headerless\n // recreation would load with no principal binding and be treated as public\n // by sessionBelongsToPrincipal. A concurrent unlink during the append is\n // caught by the post-append re-stat below so the turn fails visibly rather\n // than writing to an orphaned inode and returning 200.\n let fh;\n try {\n fh = await open(filePath, fsConstants.O_APPEND | fsConstants.O_WRONLY);\n } catch (err) {\n // Only ENOENT (session unlinked by a concurrent TTL sweep) maps to\n // chat_session_expired; real fs errors (EACCES, EMFILE, EISDIR, ...)\n // are rethrown so the caller surfaces the actual failure (codex P2).\n if (err instanceof Error && (err as NodeJS.ErrnoException).code === \"ENOENT\") {\n throw new Error(\"chat_session_expired\");\n }\n throw err;\n }\n try {\n await fh.appendFile(JSON.stringify(full) + \"\\n\", \"utf8\");\n } finally {\n await fh.close();\n }\n // Post-append re-check (codex P2): if a concurrent TTL sweep unlinked the\n // session between open() and here, the append landed on the orphaned inode\n // and the directory no longer references it. Re-stat the PATH (not the fd)\n // so the turn fails with chat_session_expired instead of returning 200 with\n // a reply the client cannot resume. A later sweep unlinking an over-TTL\n // session is a legitimate TTL action, not a silent loss.\n try {\n await stat(filePath);\n } catch (err) {\n // Only ENOENT (concurrent TTL unlink) is session expiry; other fs\n // errors (EACCES, EMFILE, ENOTDIR, ...) are rethrown (codex/kilo P2).\n if (err instanceof Error && (err as NodeJS.ErrnoException).code === \"ENOENT\") {\n throw new Error(\"chat_session_expired\");\n }\n throw err;\n }\n notifyTranscriptListeners(memoryDir, chatSessionId, full);\n return full;\n}\n\n// ---------------------------------------------------------------------------\n// In-process transcript pub/sub (issue #1687 SSE push)\n// ---------------------------------------------------------------------------\n\n/**\n * Per-session listener sets, keyed by `memoryDir + chatSessionId` so two\n * memory stores sharing a legacy/imported session id cannot leak transcript\n * entries to each other (AGENTS.md State Scoping — module-level singletons\n * are scoped per store). Kept module-level so appendTranscriptEntry can fan\n * out new entries to open SSE connections regardless of which caller\n * appended (HTTP, MCP, or CLI). Empty sets are pruned so the map never\n * grows unbounded (rule 47 — no leak).\n */\nconst transcriptListeners = new Map<string, Set<(entry: ChatTranscriptEntry) => void>>();\n\nfunction transcriptListenerKey(memoryDir: string, chatSessionId: string): string {\n return `${memoryDir}\\x00${chatSessionId}`;\n}\n\nfunction notifyTranscriptListeners(memoryDir: string, chatSessionId: string, entry: ChatTranscriptEntry): void {\n const set = transcriptListeners.get(transcriptListenerKey(memoryDir, chatSessionId));\n if (!set) return;\n for (const fn of set) {\n try {\n fn(entry);\n } catch {\n // A listener must never break the append path (rule 54).\n }\n }\n}\n\n/**\n * Subscribe to live transcript entries for a chat session in a given memory\n * store. Returns an unsubscribe function that removes the listener and\n * prunes the session's set when it becomes empty. Used by the SSE handler\n * to push new user/assistant entries to connected clients (issue #1687).\n *\n * The `memoryDir` scopes the subscription to its store so a process hosting\n * two Remnic services cannot cross-deliver transcript entries (AGENTS.md\n * State Scoping).\n */\nexport function subscribeChatTranscript(\n memoryDir: string,\n chatSessionId: string,\n listener: (entry: ChatTranscriptEntry) => void,\n): () => void {\n const key = transcriptListenerKey(memoryDir, chatSessionId);\n let set = transcriptListeners.get(key);\n if (!set) {\n set = new Set();\n transcriptListeners.set(key, set);\n }\n set.add(listener);\n return () => {\n const current = transcriptListeners.get(key);\n if (!current) return;\n current.delete(listener);\n if (current.size === 0) {\n transcriptListeners.delete(key);\n }\n };\n}\n\n/**\n * Append a pending-plan marker so a later turn can confirm the plan\n * (append-only state — loadChatSession scans for the latest unresolved one).\n */\nexport async function markPendingPlan(\n memoryDir: string,\n chatSessionId: string,\n planId: string,\n): Promise<void> {\n await appendTranscriptEntry(memoryDir, chatSessionId, {\n role: \"system\",\n content: `pending_plan:${planId}`,\n });\n}\n\n/**\n * Append a pending-promotion marker so a later turn can confirm the promotion.\n */\nexport async function markPendingPromotion(\n memoryDir: string,\n chatSessionId: string,\n memoryId: string,\n): Promise<void> {\n await appendTranscriptEntry(memoryDir, chatSessionId, {\n role: \"system\",\n content: `pending_promotion:${memoryId}`,\n });\n}\n\n/**\n * Record that a pending plan was applied or cancelled.\n */\nexport async function markPlanResolved(\n memoryDir: string,\n chatSessionId: string,\n planId: string,\n): Promise<void> {\n await appendTranscriptEntry(memoryDir, chatSessionId, {\n role: \"system\",\n content: `plan_applied:${planId}`,\n });\n}\n\n/**\n * Record that a pending promotion was applied or cancelled.\n */\nexport async function markPromotionResolved(\n memoryDir: string,\n chatSessionId: string,\n memoryId: string,\n): Promise<void> {\n await appendTranscriptEntry(memoryDir, chatSessionId, {\n role: \"system\",\n content: `promotion_applied:${memoryId}`,\n });\n}\n\n/**\n * Clean up expired chat sessions based on TTL.\n */\nexport async function cleanupExpiredChatSessions(\n memoryDir: string,\n ttlHours: number,\n): Promise<number> {\n const dir = chatSessionDir(memoryDir);\n let files: string[];\n try {\n files = await readdir(dir);\n } catch {\n return 0;\n }\n const now = Date.now();\n let removed = 0;\n for (const file of files) {\n if (!file.endsWith(\".jsonl\")) continue;\n try {\n const filePath = join(dir, file);\n const st = await stat(filePath);\n const ageHours = (now - st.mtimeMs) / (1000 * 60 * 60);\n // TTL of 0 = expire everything immediately. For positive TTLs the\n // boundary is inclusive; sub-millisecond APFS mtime skew is negligible\n // against an hour-scale threshold (rule 54 — deterministic cleanup).\n if (ttlHours <= 0 || ageHours >= ttlHours) {\n // Re-check mtime immediately before unlinking so a turn appended\n // mid-sweep (which refreshes mtime) is not deleted by the stale age\n // decision captured above (codex P2). ttlHours <= 0 (expire-all)\n // skips the re-check. The residual microsecond window is a\n // legitimate sweep of an over-TTL file.\n if (ttlHours > 0) {\n const fresh = await stat(filePath);\n const freshAge = (Date.now() - fresh.mtimeMs) / (1000 * 60 * 60);\n if (freshAge < ttlHours) continue;\n }\n await unlink(filePath);\n removed++;\n }\n } catch {\n // Best-effort cleanup; skip files we can't stat/unlink.\n }\n }\n return removed;\n}\n\n/**\n * Verify that a session belongs to the given principal (rule 42/47 —\n * per-session isolation, no cross-visibility).\n */\nexport function sessionBelongsToPrincipal(\n session: ChatSessionState,\n principal?: string,\n): boolean {\n // A session with no recorded principal is accessible to anyone (legacy/\n // single-user case). A session with a principal requires an exact match.\n if (!session.principal) return true;\n return session.principal === principal;\n}\n","/**\n * Chat engine factory + message processor (issue #1583).\n *\n * Wires the LLM adapter, executor, and engine from config + access-service.\n * Used by all three surfaces (CLI, HTTP, MCP) so they share identical\n * engine construction and session lifecycle.\n */\n\nimport type { EngramAccessService } from \"../access-service.js\";\nimport type { FallbackLlmClient } from \"../fallback-llm.js\";\nimport type { LocalLlmClient } from \"../local-llm.js\";\nimport type { ChatConfig, ChatTurnResult } from \"./chat-types.js\";\nimport { ChatEngine } from \"./chat-engine.js\";\nimport { createProductionChatLlmAdapter } from \"./chat-llm.js\";\nimport { createChatExecutor } from \"./chat-executor.js\";\nimport {\n createChatSession,\n loadChatSession,\n appendTranscriptEntry,\n sessionBelongsToPrincipal,\n markPendingPlan,\n markPlanResolved,\n markPendingPromotion,\n markPromotionResolved,\n} from \"./chat-session.js\";\n\nexport interface ChatEngineFactoryOptions {\n service: EngramAccessService;\n config: ChatConfig;\n fallbackLlm: FallbackLlmClient | null;\n localLlm: LocalLlmClient | null;\n principal?: string;\n namespace?: string;\n sessionKey?: string;\n}\n\n/**\n * Create a {@link ChatEngine} from the factory options. Returns `null` when\n * no LLM client is available. The engine uses the fallback LLM chain first\n * (cloud/gateway), then the local LLM chain — both fully supported (gotcha 1).\n */\nexport function createChatEngine(opts: ChatEngineFactoryOptions): ChatEngine | null {\n const llmClient = opts.fallbackLlm ?? opts.localLlm;\n if (!llmClient) return null;\n\n const adapter = createProductionChatLlmAdapter(llmClient as {\n chatCompletion(\n messages: Array<{ role: string; content: string }>,\n options?: { model?: string; signal?: AbortSignal },\n ): Promise<{ content: string } | null>;\n });\n\n const executor = createChatExecutor({\n service: opts.service,\n principal: opts.principal,\n namespace: opts.namespace,\n sessionKey: opts.sessionKey,\n });\n\n return new ChatEngine({\n llm: adapter,\n executor,\n maxToolCallsPerTurn: opts.config.maxToolCallsPerTurn,\n ...(opts.config.model ? { model: opts.config.model } : {}),\n correctionAvailable: false,\n scopeInspectAvailable: false,\n });\n}\n\n/**\n * Process a single chat message end-to-end. Shared by MCP and HTTP surfaces\n * so session lifecycle, transcript persistence, and error handling are\n * identical across transports.\n *\n * Throws when chat is disabled or no LLM is available.\n */\nexport async function processChatMessage(opts: {\n service: EngramAccessService;\n config: ChatConfig | undefined;\n memoryDir: string;\n message: string;\n chatSessionId?: string;\n principal?: string;\n /** Namespace/sessionKey forwarded from the MCP request scope (Thread 17). */\n namespace?: string;\n sessionKey?: string;\n}): Promise<ChatTurnResult> {\n if (!opts.config?.enabled) {\n throw new Error(\"chat_disabled\");\n }\n if (!opts.service.fallbackLlmRef && !opts.service.localLlmRef) {\n throw new Error(\"no_llm_available\");\n }\n\n // Load or create the session FIRST so the engine inherits the session's\n // namespace/sessionKey scope (rule 42 — every tool call flows with that\n // identity; the executor must not use a different scope than the session).\n let session;\n if (opts.chatSessionId) {\n session = await loadChatSession(opts.memoryDir, opts.chatSessionId);\n if (!session) throw new Error(\"chat_session_not_found\");\n if (!sessionBelongsToPrincipal(session, opts.principal)) {\n throw new Error(\"access_denied\");\n }\n } else {\n session = await createChatSession(opts.memoryDir, {\n principal: opts.principal,\n ...(opts.namespace ? { namespace: opts.namespace } : {}),\n ...(opts.sessionKey ? { sessionKey: opts.sessionKey } : {}),\n });\n }\n\n const engine = createChatEngine({\n service: opts.service,\n config: opts.config as ChatConfig,\n fallbackLlm: opts.service.fallbackLlmRef,\n localLlm: opts.service.localLlmRef,\n principal: opts.principal,\n ...(session.namespace ? { namespace: session.namespace } : {}),\n ...(session.sessionKey ? { sessionKey: session.sessionKey } : {}),\n });\n if (!engine) {\n throw new Error(\"engine_unavailable\");\n }\n\n await appendTranscriptEntry(opts.memoryDir, session.id, {\n role: \"user\",\n content: opts.message,\n });\n\n // Snapshot pending state BEFORE the turn so we only persist a marker when\n // state actually changed (Thread 15 — a normal turn must not clear an\n // active pending plan/promotion from an earlier turn).\n const priorPendingPlanId = session.pendingPlanId;\n const priorPendingPromotionId = session.pendingPromotionId;\n\n const result = await engine.processMessage(opts.message, session);\n\n await appendTranscriptEntry(opts.memoryDir, session.id, {\n role: \"assistant\",\n content: result.reply,\n });\n\n // Persist pending-plan/promotion state so a later turn can confirm it\n // (append-only — loadChatSession scans for the latest unresolved marker).\n if (result.pendingPlan?.planId) {\n await markPendingPlan(opts.memoryDir, session.id, result.pendingPlan.planId);\n } else if (session.pendingPromotionId && !priorPendingPromotionId) {\n // A promotion just became pending this turn.\n await markPendingPromotion(opts.memoryDir, session.id, session.pendingPromotionId);\n } else if (priorPendingPlanId && !session.pendingPlanId) {\n // A pending plan was consumed (applied) this turn.\n await markPlanResolved(opts.memoryDir, session.id, priorPendingPlanId);\n } else if (priorPendingPromotionId && !session.pendingPromotionId) {\n // A pending promotion was consumed (applied) this turn.\n await markPromotionResolved(opts.memoryDir, session.id, priorPendingPromotionId);\n }\n // else: no pending-state change this turn — do NOT append a marker.\n\n return result;\n}\n","/**\n * Meetings MCP tool definitions (issue #1900) — the three `engram.meetings_*`\n * tool-def objects, extracted from access-mcp.ts so the surface file stays under\n * its structural ceiling. Spread back into `this.tools` (`...MEETINGS_MCP_TOOLS`);\n * tools/list is verified at runtime. MCP_MIGRATED_OPERATIONS + callTool dispatch\n * stay inline in access-mcp.ts.\n */\n\nimport type { McpTool } from \"../access-mcp.js\";\n\nexport const MEETINGS_MCP_TOOLS: McpTool[] = [\n {\n name: \"engram.meetings_list\",\n description:\n \"List stored meeting records (issue #1900), across all days or one day. Returns per-day meeting summaries; empty when meetings.enabled is off.\",\n inputSchema: {\n type: \"object\",\n properties: {\n namespace: { type: \"string\", description: \"Caller namespace to scope this operation to (issue #2123).\" },\n sessionKey: { type: \"string\", description: \"Session key for principal/namespace resolution.\" },\n date: {\n type: \"string\",\n description: \"Optional day to list (YYYY-MM-DD). Omit for all days.\",\n },\n },\n additionalProperties: false,\n },\n },\n {\n name: \"engram.meetings_get\",\n description:\n \"Return one stored meeting record's markdown by id (mtg-YYYY-MM-DD-<hash>). Absent when not found or meetings.enabled is off.\",\n inputSchema: {\n type: \"object\",\n properties: {\n namespace: { type: \"string\", description: \"Caller namespace to scope this operation to (issue #2123).\" },\n sessionKey: { type: \"string\", description: \"Session key for principal/namespace resolution.\" },\n id: {\n type: \"string\",\n description: \"Meeting id (mtg-YYYY-MM-DD-<hash>). Required.\",\n },\n },\n required: [\"id\"],\n additionalProperties: false,\n },\n },\n {\n name: \"engram.meetings_build\",\n description:\n \"Detect + fuse + store a day's meetings from ingested audio + screen activity. No-op (enabled:false) when meetings.enabled is off.\",\n inputSchema: {\n type: \"object\",\n properties: {\n namespace: { type: \"string\", description: \"Caller namespace to scope this operation to (issue #2123).\" },\n sessionKey: { type: \"string\", description: \"Session key for principal/namespace resolution.\" },\n date: {\n type: \"string\",\n description: \"Day to build (YYYY-MM-DD). Required.\",\n },\n },\n required: [\"date\"],\n additionalProperties: false,\n },\n },\n];\n","/**\n * Wearables MCP tool definitions (issue #1900 / #2123) — the five\n * `engram.wearables_*` / `engram.transcript_*` tool-def objects, extracted from\n * access-mcp.ts so the surface file stays under its structural ceiling. Spread\n * back into `this.tools` (`...WEARABLES_MCP_TOOLS`); tools/list is verified at\n * runtime. MCP_MIGRATED_OPERATIONS + callTool dispatch stay inline in\n * access-mcp.ts. Each schema carries `namespace` + `sessionKey` so the MCP\n * scope-override injects the caller namespace (caller-derived symmetry, #2123).\n */\n\nimport type { McpTool } from \"../access-mcp.js\";\n\nexport const WEARABLES_MCP_TOOLS: McpTool[] = [\n {\n name: \"engram.wearables_status\",\n description:\n \"Status of wearable transcript sources (Limitless / Bee / Omi): configured sources, connector availability, last sync, stored transcript days.\",\n inputSchema: {\n type: \"object\",\n properties: {\n namespace: { type: \"string\", description: \"Caller namespace to scope this operation to (issue #2123).\" },\n sessionKey: { type: \"string\", description: \"Session key for principal/namespace resolution.\" },\n },\n additionalProperties: false,\n },\n },\n {\n name: \"engram.wearables_sync\",\n description:\n \"Pull, clean, and store wearable transcripts for one source or all enabled sources; optionally creates trust-gated memories per the source's memoryMode.\",\n inputSchema: {\n type: \"object\",\n properties: {\n namespace: { type: \"string\", description: \"Caller namespace to scope this operation to (issue #2123).\" },\n sessionKey: { type: \"string\", description: \"Session key for principal/namespace resolution.\" },\n source: {\n type: \"string\",\n description: \"Source id (e.g. limitless, bee, omi). Omit to sync every enabled source.\",\n },\n date: {\n type: \"string\",\n description: \"Sync exactly this day (YYYY-MM-DD). Overrides days.\",\n },\n days: {\n type: \"integer\",\n minimum: 1,\n maximum: 90,\n description: \"Lookback window in days ending today (default 2).\",\n },\n forceMemories: {\n type: \"boolean\",\n description: \"Re-run memory extraction even for unchanged days.\",\n },\n },\n additionalProperties: false,\n },\n },\n {\n name: \"engram.transcript_day\",\n description:\n \"Return the full stored wearable transcript(s) for a day, across all sources or one source, with cross-source overlap hints.\",\n inputSchema: {\n type: \"object\",\n properties: {\n namespace: { type: \"string\", description: \"Caller namespace to scope this operation to (issue #2123).\" },\n sessionKey: { type: \"string\", description: \"Session key for principal/namespace resolution.\" },\n date: {\n type: \"string\",\n description: \"Day to read (YYYY-MM-DD). Required.\",\n },\n source: {\n type: \"string\",\n description: \"Optional source id to scope to (e.g. limitless).\",\n },\n },\n required: [\"date\"],\n additionalProperties: false,\n },\n },\n {\n name: \"engram.transcript_search\",\n description:\n \"Search stored wearable transcripts. Results carry source + date so callers can pull the full day via engram.transcript_day.\",\n inputSchema: {\n type: \"object\",\n properties: {\n namespace: { type: \"string\", description: \"Caller namespace to scope this operation to (issue #2123).\" },\n sessionKey: { type: \"string\", description: \"Session key for principal/namespace resolution.\" },\n query: {\n type: \"string\",\n description: \"Search query. Required; non-empty.\",\n },\n source: {\n type: \"string\",\n description: \"Optional source id filter.\",\n },\n from: {\n type: \"string\",\n description: \"Optional inclusive start date (YYYY-MM-DD).\",\n },\n to: {\n type: \"string\",\n description: \"Optional inclusive end date (YYYY-MM-DD).\",\n },\n limit: {\n type: \"integer\",\n minimum: 1,\n maximum: 50,\n description: \"Maximum results (default 10).\",\n },\n },\n required: [\"query\"],\n additionalProperties: false,\n },\n },\n {\n name: \"engram.transcript_memories\",\n description:\n \"List memories created from wearable transcripts, filterable by source and/or day. Includes pending_review candidates awaiting approval.\",\n inputSchema: {\n type: \"object\",\n properties: {\n namespace: { type: \"string\", description: \"Caller namespace to scope this operation to (issue #2123).\" },\n sessionKey: { type: \"string\", description: \"Session key for principal/namespace resolution.\" },\n source: {\n type: \"string\",\n description: \"Optional source id filter (e.g. limitless).\",\n },\n date: {\n type: \"string\",\n description: \"Optional transcript day filter (YYYY-MM-DD).\",\n },\n limit: {\n type: \"integer\",\n minimum: 1,\n maximum: 200,\n description: \"Maximum results (default 50).\",\n },\n },\n additionalProperties: false,\n },\n }\n];\n","/**\n * Location MCP tool definitions (issue #2047) — the five\n * `engram.location_*` tool-def objects, extracted from access-mcp.ts so the\n * surface file stays at its structural ceiling (same pattern as\n * wearables/mcp-tools.ts). Spread back into `this.tools`\n * (`...LOCATION_MCP_TOOLS`); MCP_MIGRATED_OPERATIONS + boundary dispatch\n * stay inline in access-mcp.ts. Location is fleet-wide: no namespace arg\n * (day files live under the memory root, outside every namespace).\n */\n\nimport type { McpTool } from \"../access-mcp.js\";\n\nexport const LOCATION_MCP_TOOLS: McpTool[] = [\n {\n name: \"engram.location_status\",\n description:\n \"Location sync status: master gate, timezone, per-source provider registration, last sync, and recent stored day counts. Never returns secrets, addresses, coordinates, or place labels.\",\n inputSchema: {\n type: \"object\",\n properties: {},\n additionalProperties: false,\n },\n },\n {\n name: \"engram.location_check\",\n description:\n \"Probe every enabled location provider (auth/connectivity). Reports ok/detail per source; a disabled master gate or source reports a skip reason, never an error.\",\n inputSchema: {\n type: \"object\",\n properties: {},\n additionalProperties: false,\n },\n },\n {\n name: \"engram.location_sync\",\n description:\n \"Sync local-day place observations from every enabled location provider (default: location.syncDays ending yesterday). Same shared runner as the CLI and HTTP surfaces; a forced sync never bypasses the enabled gates or validation. Returns per-day, per-source synced/skipped/failed results.\",\n inputSchema: {\n type: \"object\",\n properties: {\n date: {\n type: \"string\",\n description: \"Optional exclusive-window end day (YYYY-MM-DD, inclusive); defaults to yesterday in location.timezone.\",\n },\n days: {\n type: \"integer\",\n minimum: 1,\n maximum: 90,\n description: \"Optional window size (1..90); defaults to location.syncDays.\",\n },\n },\n additionalProperties: false,\n },\n },\n {\n name: \"engram.location_backfill\",\n description:\n \"Sync an explicit historical day range (inclusive, capped at 90 days) for every enabled location provider. Same shared sync runner as location_sync; never makes an unbounded scan.\",\n inputSchema: {\n type: \"object\",\n properties: {\n from: { type: \"string\", description: \"Range start day (YYYY-MM-DD).\" },\n to: { type: \"string\", description: \"Range end day (YYYY-MM-DD, inclusive).\" },\n },\n required: [\"from\", \"to\"],\n additionalProperties: false,\n },\n },\n {\n name: \"engram.location_day\",\n description:\n \"Return one stored location day (place segments per source). Coordinates appear only when location.retainCoordinates is enabled; an unstored day returns found:false.\",\n inputSchema: {\n type: \"object\",\n properties: {\n date: { type: \"string\", description: \"Day to read (YYYY-MM-DD).\" },\n },\n required: [\"date\"],\n additionalProperties: false,\n },\n },\n];\n","import type { McpTool } from \"../access-mcp.js\";\nimport { SUPPORT_PASSPORT_SOURCE_MEMORY_ID_MAX_LENGTH } from \"./contracts.js\";\n\nconst CARD_CATEGORIES = [\n \"communication\",\n \"environment\",\n \"transitions\",\n \"sensory\",\n \"regulation\",\n \"interests\",\n \"other\",\n] as const;\n\nconst cardTextProperties = {\n title: { type: \"string\", minLength: 1, maxLength: 80 },\n statement: { type: \"string\", minLength: 1, maxLength: 500 },\n category: { type: \"string\", enum: CARD_CATEGORIES },\n reviewBy: { type: \"string\", format: \"date-time\" },\n};\n\nconst cardRevisionProperties = {\n cardId: { type: \"string\", minLength: 1, maxLength: 128 },\n expectedRevision: { type: \"string\", pattern: \"^[a-f0-9]{64}$\" },\n};\n\nconst cardMutationProperties = {\n ...cardRevisionProperties,\n reasonCode: { type: \"string\", minLength: 1, maxLength: 64, pattern: \"^[a-z0-9-]+$\" },\n};\n\nconst sourceMemoryIdProperty = {\n type: \"string\",\n minLength: 1,\n maxLength: SUPPORT_PASSPORT_SOURCE_MEMORY_ID_MAX_LENGTH,\n};\n\nexport const SUPPORT_PASSPORT_MCP_MIGRATED_OPERATIONS = {\n \"engram.support_passport_memory_preview\": \"support_passport_memory_preview\",\n \"engram.support_passport_cards_list\": \"support_passport_cards_list\",\n \"engram.support_passport_draft_create\": \"support_passport_draft_create\",\n \"engram.support_passport_drafts_generate\": \"support_passport_drafts_generate\",\n \"engram.support_passport_card_replace\": \"support_passport_card_replace\",\n \"engram.support_passport_card_approve\": \"support_passport_card_approve\",\n \"engram.support_passport_card_reject\": \"support_passport_card_reject\",\n \"engram.support_passport_card_withdraw\": \"support_passport_card_withdraw\",\n \"engram.support_passport_grant_create\": \"support_passport_grant_create\",\n \"engram.support_passport_grants_list\": \"support_passport_grants_list\",\n \"engram.support_passport_grant_revoke\": \"support_passport_grant_revoke\",\n} as const;\n\nexport const SUPPORT_PASSPORT_MCP_TOOLS: McpTool[] = [\n {\n name: \"engram.support_passport_memory_preview\",\n description: \"Preview one memory and get the exact revision required for model drafting consent.\",\n inputSchema: {\n type: \"object\",\n properties: { memoryId: sourceMemoryIdProperty },\n required: [\"memoryId\"],\n additionalProperties: false,\n },\n },\n {\n name: \"engram.support_passport_cards_list\",\n description: \"List your support cards.\",\n inputSchema: { type: \"object\", properties: {}, additionalProperties: false },\n },\n {\n name: \"engram.support_passport_draft_create\",\n description: \"Create one support card draft for your review.\",\n inputSchema: {\n type: \"object\",\n properties: cardTextProperties,\n required: [\"title\", \"statement\", \"category\", \"reviewBy\"],\n additionalProperties: false,\n },\n },\n {\n name: \"engram.support_passport_drafts_generate\",\n description: \"Draft support cards from only the memories you select and consent to send to your configured model.\",\n inputSchema: {\n type: \"object\",\n properties: {\n sourceMemoryIds: {\n type: \"array\",\n minItems: 1,\n maxItems: 20,\n uniqueItems: true,\n items: sourceMemoryIdProperty,\n },\n sourceMemoryRevisions: {\n type: \"array\",\n minItems: 1,\n maxItems: 20,\n uniqueItems: true,\n items: {\n type: \"object\",\n properties: {\n memoryId: sourceMemoryIdProperty,\n revision: { type: \"string\", pattern: \"^[a-f0-9]{64}$\" },\n },\n required: [\"memoryId\", \"revision\"],\n additionalProperties: false,\n },\n },\n consent: { const: true },\n },\n required: [\"sourceMemoryIds\", \"sourceMemoryRevisions\", \"consent\"],\n additionalProperties: false,\n },\n },\n {\n name: \"engram.support_passport_card_replace\",\n description: \"Create a replacement draft for one support card.\",\n inputSchema: {\n type: \"object\",\n properties: { ...cardTextProperties, ...cardRevisionProperties },\n required: [\"cardId\", \"title\", \"statement\", \"category\", \"reviewBy\", \"expectedRevision\"],\n additionalProperties: false,\n },\n },\n ...([\"approve\", \"reject\", \"withdraw\"] as const).map(\n (action): McpTool => ({\n name: `engram.support_passport_card_${action}`,\n description: `${action === \"withdraw\" ? \"Withdraw\" : action === \"approve\" ? \"Approve\" : \"Reject\"} one support card as its owner.`,\n inputSchema: {\n type: \"object\",\n properties: cardMutationProperties,\n required: [\"cardId\", \"expectedRevision\", \"reasonCode\"],\n additionalProperties: false,\n },\n })\n ),\n {\n name: \"engram.support_passport_grant_create\",\n description: \"Create one timed share link for selected approved support cards.\",\n inputSchema: {\n type: \"object\",\n properties: {\n cardIds: {\n type: \"array\",\n minItems: 1,\n maxItems: 8,\n uniqueItems: true,\n items: { type: \"string\", minLength: 1, maxLength: 128 },\n },\n cardRevisions: {\n type: \"array\",\n minItems: 1,\n maxItems: 8,\n uniqueItems: true,\n items: {\n type: \"object\",\n properties: {\n cardId: { type: \"string\", minLength: 1, maxLength: 128 },\n revision: { type: \"string\", pattern: \"^[a-f0-9]{64}$\" },\n },\n required: [\"cardId\", \"revision\"],\n additionalProperties: false,\n },\n },\n expiresAt: { type: \"string\", format: \"date-time\" },\n durationMs: { type: \"integer\", minimum: 300_000, maximum: 604_800_000 },\n },\n required: [\"cardIds\", \"cardRevisions\"],\n oneOf: [{ required: [\"expiresAt\"] }, { required: [\"durationMs\"] }],\n additionalProperties: false,\n },\n },\n {\n name: \"engram.support_passport_grants_list\",\n description: \"List your support passport share links without secrets.\",\n inputSchema: { type: \"object\", properties: {}, additionalProperties: false },\n },\n {\n name: \"engram.support_passport_grant_revoke\",\n description: \"Stop one support passport share link.\",\n inputSchema: {\n type: \"object\",\n properties: {\n grantId: { type: \"string\", minLength: 1, maxLength: 128 },\n expectedVersion: { type: \"integer\", minimum: 1 },\n },\n required: [\"grantId\", \"expectedVersion\"],\n additionalProperties: false,\n },\n },\n];\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,cAAAA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