@remnic/core 9.45.3 → 9.45.4
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/abort-error.d.ts +2 -1
- package/dist/abort-error.js +3 -1
- package/dist/access-admin-ops-surface.d.ts +14 -10
- package/dist/access-admin-ops-surface.js +84 -76
- package/dist/access-audit.js +2 -2
- package/dist/access-authorization-probe.d.ts +14 -10
- package/dist/access-authorization-probe.js +85 -77
- package/dist/access-boundary.d.ts +15 -11
- package/dist/access-boundary.js +84 -76
- package/dist/access-citation-namespace.js +2 -2
- package/dist/access-cli.js +193 -181
- package/dist/access-cli.js.map +1 -1
- package/dist/access-coding-context-resolution.d.ts +16 -0
- package/dist/access-coding-context-resolution.js +13 -0
- package/dist/access-coding-context-resolution.js.map +1 -0
- package/dist/access-extraction-force-flush.d.ts +14 -10
- package/dist/access-extraction-force-flush.js +84 -76
- package/dist/access-health-types.d.ts +2 -1
- package/dist/access-http-lcm-compaction.d.ts +16 -12
- package/dist/access-http-lcm-compaction.js +3 -3
- package/dist/access-http-lifecycle-flush.d.ts +14 -10
- package/dist/access-http-lifecycle-flush.js +2 -2
- package/dist/access-http-offline-stream.d.ts +123 -0
- package/dist/access-http-offline-stream.js +10 -0
- package/dist/access-http-offline-stream.js.map +1 -0
- package/dist/access-http-query.js +84 -76
- package/dist/access-http.d.ts +15 -10
- package/dist/access-http.js +105 -92
- package/dist/access-identity-continuity-surface.d.ts +9 -8
- package/dist/access-identity-continuity-surface.js +84 -76
- package/dist/access-lcm-surface.d.ts +14 -10
- package/dist/access-lcm-surface.js +84 -76
- package/dist/access-mcp-output-schemas.js +1 -1
- package/dist/access-mcp.d.ts +14 -10
- package/dist/access-mcp.js +95 -83
- package/dist/access-memory-search-fanout.d.ts +3 -2
- package/dist/{access-namespace-preflight-5yZ4g6F8.d.ts → access-namespace-preflight-CWUDwB4M.d.ts} +1 -1
- package/dist/access-namespace-preflight.d.ts +4 -3
- package/dist/access-namespace-preflight.js +84 -76
- package/dist/access-observe-helpers.d.ts +1 -0
- package/dist/access-observe-helpers.js +1 -1
- package/dist/access-observe-write-surface.d.ts +16 -10
- package/dist/access-observe-write-surface.js +84 -76
- package/dist/access-offline-manifest.d.ts +104 -0
- package/dist/access-offline-manifest.js +45 -0
- package/dist/access-offline-manifest.js.map +1 -0
- package/dist/access-operations-batch.js +86 -78
- package/dist/access-operations.d.ts +15 -11
- package/dist/access-operations.js +91 -80
- package/dist/access-recall-concurrency.d.ts +16 -26
- package/dist/access-recall-concurrency.js +86 -77
- package/dist/access-recall-response.d.ts +18 -14
- package/dist/access-recall-response.js +84 -76
- package/dist/access-recall-surface.d.ts +29 -24
- package/dist/access-recall-surface.js +84 -76
- package/dist/access-schema.js +3 -3
- package/dist/{access-service-CiJRsgAB.d.ts → access-service-CsU-ljFD.d.ts} +25 -16
- package/dist/access-service-helpers.d.ts +14 -10
- package/dist/access-service.d.ts +14 -10
- package/dist/access-service.js +84 -76
- package/dist/access-surface-catalog.d.ts +14 -10
- package/dist/access-surface-catalog.js +4 -0
- package/dist/access-surface-catalog.js.map +1 -1
- package/dist/access-wearables-meetings-surface.d.ts +4 -3
- package/dist/action-confidence.d.ts +2 -1
- package/dist/active-memory-bridge.d.ts +2 -1
- package/dist/active-recall.d.ts +2 -1
- package/dist/active-recall.js +10 -8
- package/dist/active-recall.js.map +1 -1
- package/dist/adapters/index.js +7 -7
- package/dist/adapters/registry.js +3 -3
- package/dist/{auto-sync-5OE5QOZB.js → auto-sync-UPTUVE4X.js} +6 -6
- package/dist/behavior-learner.d.ts +2 -1
- package/dist/behavior-learner.js +1 -1
- package/dist/behavior-signals.d.ts +2 -1
- package/dist/bootstrap.d.ts +9 -8
- package/dist/briefing.d.ts +3 -2
- package/dist/briefing.js +23 -22
- package/dist/buffer-surprise-report.d.ts +2 -1
- package/dist/buffer-turn-helpers.d.ts +2 -1
- package/dist/buffer.d.ts +3 -2
- package/dist/buffer.js +12 -11
- 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-merge-IDWJPCWK.js → capsule-merge-Q6AR3XL7.js} +67 -54
- package/dist/capsule-merge-Q6AR3XL7.js.map +1 -0
- package/dist/{catalog-scBmy0sO.d.ts → catalog-bctMURhN.d.ts} +1 -1
- package/dist/causal-behavior.d.ts +2 -1
- 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 +27 -26
- package/dist/causal-consolidation.js.map +1 -1
- package/dist/causal-retrieval.js +2 -2
- package/dist/causal-trajectory-graph.d.ts +2 -1
- package/dist/causal-trajectory.js +1 -1
- package/dist/{chunk-VUPTKTDV.js → chunk-2MRHJNWL.js} +3 -3
- package/dist/{chunk-JBPKEARU.js → chunk-2QSZNTDO.js} +7 -7
- package/dist/{chunk-5IVLTFOV.js → chunk-44N6ESJ4.js} +2 -2
- package/dist/{chunk-WOCNN776.js → chunk-4POAMKV6.js} +100 -41
- package/dist/chunk-4POAMKV6.js.map +1 -0
- package/dist/{chunk-HO3QBJEY.js → chunk-5546W5SI.js} +2 -2
- package/dist/{chunk-U7GW7NE7.js → chunk-5CEECY6P.js} +10 -10
- package/dist/{chunk-4UH4BTGK.js → chunk-5SNZSWWR.js} +82 -82
- package/dist/{chunk-6CZPDBJS.js → chunk-5U7ID3EZ.js} +3 -3
- package/dist/{chunk-GF22HWS2.js → chunk-6NNNURLK.js} +7 -7
- package/dist/chunk-773TRRGT.js +36 -0
- package/dist/chunk-773TRRGT.js.map +1 -0
- package/dist/chunk-7CITSYSH.js +242 -0
- package/dist/chunk-7CITSYSH.js.map +1 -0
- package/dist/{chunk-227UFSEQ.js → chunk-7RZJWZ46.js} +5 -5
- package/dist/{chunk-E5UK4VPE.js → chunk-7SHJHPTY.js} +5 -5
- package/dist/{chunk-UVIKWC7M.js → chunk-7YERSTN7.js} +17 -17
- package/dist/{chunk-DLVPUX7U.js → chunk-7YKVM5H3.js} +8 -6
- package/dist/chunk-7YKVM5H3.js.map +1 -0
- package/dist/{chunk-3CE77VAP.js → chunk-A4JMGKCD.js} +87 -74
- package/dist/chunk-A4JMGKCD.js.map +1 -0
- package/dist/chunk-A5KNZSNA.js +26 -0
- package/dist/chunk-A5KNZSNA.js.map +1 -0
- package/dist/{chunk-S2NCTZGJ.js → chunk-AJQ57VV3.js} +15 -15
- package/dist/chunk-AJQ57VV3.js.map +1 -0
- package/dist/{chunk-CUM2BBPN.js → chunk-AUMWZSE7.js} +19 -10
- package/dist/chunk-AUMWZSE7.js.map +1 -0
- package/dist/{chunk-XYTOI63Z.js → chunk-BGHFOD5A.js} +19 -11
- package/dist/chunk-BGHFOD5A.js.map +1 -0
- package/dist/{chunk-BUE5E2HL.js → chunk-BGLY7EEM.js} +5 -314
- package/dist/chunk-BGLY7EEM.js.map +1 -0
- package/dist/chunk-BIPBQQFI.js +44 -0
- package/dist/chunk-BIPBQQFI.js.map +1 -0
- package/dist/{chunk-S5SLVSVY.js → chunk-BQIFZ2MP.js} +5 -5
- package/dist/chunk-BTTPKDIL.js +34 -0
- package/dist/{chunk-PVGDJXVK.js.map → chunk-BTTPKDIL.js.map} +1 -1
- package/dist/{chunk-E53DSZEN.js → chunk-C26TE27X.js} +3 -3
- package/dist/{chunk-LZ4LDKHZ.js → chunk-CLB32OHM.js} +6 -6
- package/dist/{chunk-Q6IP2ARR.js → chunk-CSOYVTRX.js} +2 -2
- package/dist/{chunk-XOQSEF7X.js → chunk-CVILPI77.js} +6 -6
- package/dist/chunk-D3I2MCN7.js +29 -0
- package/dist/chunk-D3I2MCN7.js.map +1 -0
- package/dist/{chunk-A5OJCXZL.js → chunk-DSUAAZZX.js} +15 -4
- package/dist/chunk-DSUAAZZX.js.map +1 -0
- package/dist/{chunk-HREE4JHI.js → chunk-DYVMXPCF.js} +486 -287
- package/dist/chunk-DYVMXPCF.js.map +1 -0
- package/dist/{chunk-J7VGGECD.js → chunk-DZPFMQZ7.js} +1 -1
- package/dist/chunk-DZPFMQZ7.js.map +1 -0
- package/dist/{chunk-PDLBLTOK.js → chunk-EITZHSX6.js} +9 -9
- package/dist/{chunk-D3J5SLQK.js → chunk-EJHEWCGQ.js} +81 -20
- package/dist/chunk-EJHEWCGQ.js.map +1 -0
- package/dist/{chunk-WUNIWKY4.js → chunk-ELIL2A37.js} +6 -6
- package/dist/{chunk-E6PNLPGJ.js → chunk-FZP32336.js} +806 -470
- package/dist/chunk-FZP32336.js.map +1 -0
- package/dist/{chunk-HZFHQ4AQ.js → chunk-G7A5HLUS.js} +23 -17
- package/dist/chunk-G7A5HLUS.js.map +1 -0
- package/dist/{chunk-CINZGPSJ.js → chunk-GUMZC2BO.js} +2 -2
- package/dist/{chunk-H24WNPA2.js → chunk-GWFSVJ4P.js} +3 -3
- package/dist/{chunk-7XC2HX75.js → chunk-GYPQL6XN.js} +157 -16
- package/dist/chunk-GYPQL6XN.js.map +1 -0
- package/dist/{chunk-TSH56VPU.js → chunk-HAYSYUAB.js} +2 -2
- package/dist/{chunk-TDHTVMPG.js → chunk-HFPASSFV.js} +7 -2
- package/dist/chunk-HFPASSFV.js.map +1 -0
- package/dist/chunk-J2WC5LF4.js +395 -0
- package/dist/chunk-J2WC5LF4.js.map +1 -0
- package/dist/{chunk-PKNLM44P.js → chunk-JH6BPLOP.js} +9 -9
- package/dist/{chunk-KXB4VXHY.js → chunk-JIYDRBVZ.js} +2 -2
- package/dist/chunk-JV3C2MNQ.js +74 -0
- package/dist/chunk-JV3C2MNQ.js.map +1 -0
- package/dist/{chunk-AV5ZEH4M.js → chunk-KVJRXN2E.js} +2 -2
- package/dist/{chunk-JVLCVFQ4.js → chunk-KXEFRMCF.js} +3 -3
- package/dist/{chunk-WFTIGIIS.js → chunk-L6CQ7WIW.js} +5 -5
- package/dist/{chunk-EJUEXZHX.js → chunk-LLJMAULE.js} +2 -2
- package/dist/{chunk-N5Z4EVOR.js → chunk-LNEWDF2A.js} +36 -11
- package/dist/chunk-LNEWDF2A.js.map +1 -0
- package/dist/{chunk-AS7YMSL6.js → chunk-M23RF3LJ.js} +4 -4
- package/dist/{chunk-UYLMNVY6.js → chunk-MDISBSYA.js} +16 -9
- package/dist/chunk-MDISBSYA.js.map +1 -0
- package/dist/{chunk-3F2LKUMU.js → chunk-NIS256NW.js} +2 -2
- package/dist/{chunk-YIAA2X3D.js → chunk-NK5RGJ65.js} +3 -3
- package/dist/chunk-NLDVVWCL.js +84 -0
- package/dist/chunk-NLDVVWCL.js.map +1 -0
- package/dist/{chunk-OQ5PRDDS.js → chunk-NTOIP2E6.js} +6 -6
- package/dist/{chunk-HLPD7B7P.js → chunk-NUEQKLNB.js} +2 -2
- package/dist/{chunk-4J7G5SY4.js → chunk-NZBZ7IS2.js} +72 -24
- package/dist/chunk-NZBZ7IS2.js.map +1 -0
- package/dist/{chunk-3TBLDMJA.js → chunk-O4KMGRXE.js} +5 -2
- package/dist/chunk-O4KMGRXE.js.map +1 -0
- package/dist/{chunk-33PLLLL7.js → chunk-P7NGM24P.js} +6 -6
- package/dist/{chunk-7TWUCYER.js → chunk-PNRA7FAD.js} +7 -7
- package/dist/{chunk-5I4M26Q7.js → chunk-QBSFOKY6.js} +4 -4
- package/dist/{chunk-QJAQNXWI.js → chunk-QCECHYZL.js} +76 -79
- package/dist/chunk-QCECHYZL.js.map +1 -0
- package/dist/{chunk-P4DRWEYC.js → chunk-QVSBTCVP.js} +2 -2
- package/dist/{chunk-AAIUERNB.js → chunk-R5RFK3CB.js} +6 -6
- package/dist/{chunk-WDISJRMG.js → chunk-RMMVQQA6.js} +2 -2
- package/dist/{chunk-KWMXR7XS.js → chunk-S2V7RUCL.js} +8 -1
- package/dist/{chunk-KWMXR7XS.js.map → chunk-S2V7RUCL.js.map} +1 -1
- package/dist/{chunk-5SM35XZR.js → chunk-S5NZBKKQ.js} +2 -2
- package/dist/{chunk-VNA7W7QF.js → chunk-SVH57F5Z.js} +12 -4
- package/dist/chunk-SVH57F5Z.js.map +1 -0
- package/dist/{chunk-WIPEXG6R.js → chunk-SXIMQLGV.js} +2 -2
- package/dist/{chunk-RVLJEII5.js → chunk-SYUBB3WM.js} +256 -187
- package/dist/chunk-SYUBB3WM.js.map +1 -0
- package/dist/{chunk-OAEQLRCY.js → chunk-TN76AKO3.js} +5 -5
- package/dist/{chunk-QN25OCUF.js → chunk-TQ4GD737.js} +5 -5
- package/dist/{chunk-VCD4PSK2.js → chunk-TQZ4DVBC.js} +7 -4
- package/dist/chunk-TQZ4DVBC.js.map +1 -0
- package/dist/{chunk-7K5Q6COX.js → chunk-TVVEYCNW.js} +4 -4
- package/dist/{chunk-DNWXFTLD.js → chunk-TYISDI6B.js} +2 -2
- package/dist/{chunk-4LMA77JH.js → chunk-U2VLVBBH.js} +3 -3
- package/dist/{chunk-5ZE7QHTK.js → chunk-ULVR5KG7.js} +5 -5
- package/dist/{chunk-NVRYW264.js → chunk-UQWIKLQK.js} +18 -15
- package/dist/chunk-UQWIKLQK.js.map +1 -0
- package/dist/{chunk-YV32N67O.js → chunk-URS5GSM7.js} +1 -1
- package/dist/chunk-URS5GSM7.js.map +1 -0
- package/dist/{chunk-4B77XSG5.js → chunk-UV72DEZD.js} +5 -5
- package/dist/{chunk-S2BBISHU.js → chunk-VANZKHTN.js} +3 -3
- package/dist/chunk-VHFXP27N.js +250 -0
- package/dist/chunk-VHFXP27N.js.map +1 -0
- package/dist/{chunk-3Y224NYC.js → chunk-VYISFWVX.js} +2 -2
- package/dist/{chunk-TIHMZFIV.js → chunk-W3IC7QOY.js} +3 -3
- package/dist/{chunk-NRV4Y3PM.js → chunk-W4FBGYGK.js} +1 -1
- package/dist/{chunk-P2BM76KT.js → chunk-WAS4HV46.js} +174 -43
- package/dist/chunk-WAS4HV46.js.map +1 -0
- package/dist/{chunk-57QKLRBV.js → chunk-WB7JSQCP.js} +2 -1
- package/dist/chunk-WB7JSQCP.js.map +1 -0
- package/dist/chunk-WGP57SR3.js +68 -0
- package/dist/chunk-WGP57SR3.js.map +1 -0
- package/dist/{chunk-ECK75GDJ.js → chunk-WQIHRA5F.js} +43 -24
- package/dist/chunk-WQIHRA5F.js.map +1 -0
- package/dist/{chunk-MU7ZHSZE.js → chunk-WZFAPHIK.js} +2 -2
- package/dist/{chunk-T2TTP3KU.js → chunk-X4IDNPOS.js} +2 -2
- package/dist/{chunk-BLAKS3CP.js → chunk-XL3TATMJ.js} +3 -3
- package/dist/{chunk-W4XJFLAL.js → chunk-XPRJSHNI.js} +2 -2
- package/dist/{chunk-5TFP4CUL.js → chunk-XQ3HXAQH.js} +14 -11
- package/dist/chunk-XQ3HXAQH.js.map +1 -0
- package/dist/{chunk-VWAXN2BN.js → chunk-XSFHWBQO.js} +93 -31
- package/dist/chunk-XSFHWBQO.js.map +1 -0
- package/dist/{chunk-DL7ZD3JH.js → chunk-XTAUXTDO.js} +14 -9
- package/dist/chunk-XTAUXTDO.js.map +1 -0
- package/dist/{chunk-JE7EK33X.js → chunk-Y7HRYCNW.js} +2 -2
- package/dist/{chunk-E6EE5B67.js → chunk-YK6BDDHP.js} +4 -4
- package/dist/{chunk-ES36HTSC.js → chunk-YLHM5BQQ.js} +3 -3
- package/dist/{chunk-RN7DY3FC.js → chunk-YMAQDHQM.js} +31 -12
- package/dist/chunk-YMAQDHQM.js.map +1 -0
- package/dist/{chunk-ULARSG5Z.js → chunk-YN6ASZUG.js} +10 -8
- package/dist/{chunk-ULARSG5Z.js.map → chunk-YN6ASZUG.js.map} +1 -1
- package/dist/{chunk-IKKWIPYN.js → chunk-YYQAKIDJ.js} +37 -1
- package/dist/chunk-YYQAKIDJ.js.map +1 -0
- package/dist/{chunk-BJKPPZ6Z.js → chunk-ZFGZ6PZ2.js} +2 -2
- package/dist/{chunk-CJ2ZR7UA.js → chunk-ZI32MKDW.js} +267 -214
- package/dist/chunk-ZI32MKDW.js.map +1 -0
- package/dist/{chunk-64UDOIMI.js → chunk-ZLQ37WJX.js} +2 -2
- package/dist/chunk-ZMAYKGPN.js +351 -0
- package/dist/chunk-ZMAYKGPN.js.map +1 -0
- package/dist/{cli-BUGN3d6_.d.ts → cli-BBHDtG36.d.ts} +5 -5
- package/dist/cli.d.ts +16 -12
- package/dist/cli.js +138 -124
- package/dist/compounding/engine.d.ts +3 -2
- package/dist/compounding/engine.js +24 -23
- package/dist/compounding/preference-consolidator.d.ts +2 -1
- package/dist/compression-optimizer.d.ts +2 -1
- package/dist/config.d.ts +2 -1
- package/dist/config.js +10 -8
- package/dist/connectors/codex-materialize-runner.d.ts +2 -1
- package/dist/connectors/codex-materialize-runner.js +23 -22
- package/dist/connectors/codex-materialize.d.ts +2 -1
- package/dist/connectors/index.d.ts +2 -1
- package/dist/connectors/index.js +26 -25
- package/dist/consolidation-provenance-check.d.ts +3 -2
- package/dist/consolidation-provenance-check.js +4 -4
- package/dist/consolidation-undo.d.ts +3 -2
- package/dist/consolidation-undo.js +10 -7
- package/dist/consolidation-undo.js.map +1 -1
- package/dist/contradiction/index.d.ts +3 -2
- package/dist/converge-config.d.ts +2 -1
- package/dist/convergence-refresh.d.ts +4 -3
- package/dist/convergence-refresh.js +27 -26
- 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 +42 -41
- package/dist/day-summary.d.ts +2 -1
- package/dist/delinearize.d.ts +2 -1
- package/dist/direct-answer-wiring.d.ts +2 -1
- package/dist/direct-answer-wiring.js +2 -2
- package/dist/direct-answer.d.ts +2 -1
- package/dist/embedding-fallback.d.ts +2 -1
- package/dist/embedding-fallback.js +2 -2
- package/dist/enrichment/index.d.ts +2 -1
- package/dist/entity-retrieval-boundaries.js +1 -1
- package/dist/entity-retrieval.d.ts +3 -2
- package/dist/entity-retrieval.js +24 -23
- package/dist/entity-schema.d.ts +2 -1
- package/dist/explicit-capture.d.ts +9 -8
- package/dist/explicit-capture.js +11 -9
- package/dist/external-wiki-access.d.ts +127 -0
- package/dist/external-wiki-access.js +186 -0
- package/dist/external-wiki-access.js.map +1 -0
- package/dist/external-wiki-cli.d.ts +13 -0
- package/dist/external-wiki-cli.js +96 -0
- package/dist/external-wiki-cli.js.map +1 -0
- package/dist/external-wiki-collection-registration.d.ts +39 -0
- package/dist/external-wiki-collection-registration.js +79 -0
- package/dist/external-wiki-collection-registration.js.map +1 -0
- package/dist/external-wiki-collection.d.ts +50 -0
- package/dist/external-wiki-collection.js +387 -0
- package/dist/external-wiki-collection.js.map +1 -0
- package/dist/external-wiki-config.d.ts +13 -0
- package/dist/external-wiki-config.js +13 -0
- package/dist/external-wiki-config.js.map +1 -0
- package/dist/external-wiki-guard.d.ts +11 -0
- package/dist/external-wiki-guard.js +18 -0
- package/dist/external-wiki-guard.js.map +1 -0
- package/dist/external-wiki-mcp-tools.d.ts +123 -0
- package/dist/external-wiki-mcp-tools.js +8 -0
- package/dist/external-wiki-mcp-tools.js.map +1 -0
- package/dist/external-wiki-search.d.ts +42 -0
- package/dist/external-wiki-search.js +11 -0
- package/dist/external-wiki-search.js.map +1 -0
- package/dist/external-wiki.d.ts +43 -0
- package/dist/external-wiki.js +16 -0
- package/dist/external-wiki.js.map +1 -0
- 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-source-grounding-helpers.d.ts +5 -3
- package/dist/extraction-source-grounding-helpers.js +1 -1
- package/dist/extraction-source-grounding-rules.d.ts +2 -1
- package/dist/extraction-source-grounding-rules.js +2 -2
- package/dist/extraction-source-grounding.d.ts +2 -1
- package/dist/extraction-source-grounding.js +5 -5
- package/dist/extraction.d.ts +2 -1
- package/dist/extraction.js +45 -43
- package/dist/fallback-llm.d.ts +2 -1
- 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-reinforcement.d.ts +2 -1
- package/dist/graph-snapshot.d.ts +2 -1
- package/dist/graph.d.ts +2 -1
- package/dist/harmonic-retrieval.js +2 -2
- 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.d.ts +362 -350
- package/dist/index.js +291 -259
- package/dist/intent.d.ts +2 -1
- package/dist/lcm/engine.d.ts +2 -1
- package/dist/lcm/engine.js +3 -3
- package/dist/lcm/index.d.ts +2 -1
- package/dist/lcm/index.js +8 -8
- package/dist/lcm/tools.d.ts +2 -1
- 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-llm.js +2 -2
- package/dist/local-model-endpoint.d.ts +2 -1
- package/dist/maintenance/memory-governance.d.ts +2 -1
- package/dist/maintenance/memory-governance.js +24 -23
- package/dist/maintenance/rebuild-memory-lifecycle-ledger.d.ts +3 -2
- package/dist/maintenance/rebuild-memory-lifecycle-ledger.js +24 -23
- package/dist/maintenance/rebuild-memory-projection.d.ts +3 -2
- package/dist/maintenance/rebuild-memory-projection.js +26 -25
- package/dist/{maintenance-LbuS2rUA.d.ts → maintenance-D2mveyCd.d.ts} +3 -3
- package/dist/mcp-memory-inspector-app.d.ts +14 -10
- package/dist/mcp-read-only-tools.js +1 -1
- package/dist/memory-action-policy.d.ts +2 -1
- package/dist/memory-cache.d.ts +2 -1
- 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-worth-outcomes.d.ts +3 -2
- package/dist/models-json.d.ts +2 -1
- package/dist/namespaces/migrate.d.ts +4 -3
- package/dist/namespaces/migrate.js +40 -39
- package/dist/namespaces/principal.d.ts +2 -1
- package/dist/namespaces/search.d.ts +2 -1
- package/dist/namespaces/search.js +18 -18
- package/dist/namespaces/storage.d.ts +4 -3
- package/dist/namespaces/storage.js +23 -22
- 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 +11 -9
- package/dist/offline-sync.d.ts +29 -3
- package/dist/offline-sync.js +6 -2
- package/dist/operator-doctor-corpus.d.ts +2 -1
- package/dist/operator-doctor-corpus.js +45 -44
- package/dist/operator-doctor-replica.d.ts +2 -1
- package/dist/operator-doctor-replica.js +3 -3
- package/dist/operator-toolkit.d.ts +4 -3
- package/dist/operator-toolkit.js +59 -55
- package/dist/orchestration/compression-guideline-coordinator.d.ts +3 -2
- package/dist/orchestration/maintenance.d.ts +5 -4
- package/dist/orchestration/maintenance.js +36 -33
- package/dist/{orchestrator-rHiWt32X.d.ts → orchestrator-DJYlwiUv.d.ts} +14 -7
- package/dist/orchestrator.d.ts +9 -8
- package/dist/orchestrator.js +201 -189
- package/dist/page-versioning.js +3 -3
- package/dist/patterns-cli.d.ts +2 -1
- package/dist/{pipeline-W_97O8BV.d.ts → pipeline-CNjY4wk3.d.ts} +1 -1
- package/dist/policy-runtime.d.ts +2 -1
- package/dist/policy-runtime.js +1 -1
- package/dist/proactive-contention.d.ts +2 -1
- package/dist/provenance.d.ts +2 -1
- package/dist/provenance.js +2 -2
- package/dist/{qmd-LWtMofAf.d.ts → qmd-C0UDZidt.d.ts} +9 -7
- package/dist/qmd-preflight.d.ts +5 -4
- package/dist/qmd-preflight.js +2 -2
- package/dist/qmd-recall-cache.d.ts +2 -1
- package/dist/qmd.d.ts +4 -3
- package/dist/qmd.js +5 -5
- 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 +8 -1
- package/dist/recall-xray.js +2 -2
- package/dist/reconcile/cursor.d.ts +12 -2
- package/dist/reconcile/cursor.js +46 -7
- package/dist/reconcile/cursor.js.map +1 -1
- package/dist/reconcile/manifest.d.ts +9 -2
- package/dist/reconcile/manifest.js +15 -268
- package/dist/reconcile/manifest.js.map +1 -1
- package/dist/reconcile/plan.d.ts +4 -1
- package/dist/reconcile/plan.js +4 -4
- 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-divergence.js +2 -2
- package/dist/replica-peers-config.d.ts +2 -1
- package/dist/resolve-auth-token.d.ts +2 -1
- package/dist/resume-bundles.js +12 -10
- package/dist/retrieval-agents.d.ts +4 -3
- package/dist/retrieval-agents.js +2 -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/schemas.d.ts +32 -32
- package/dist/{scope-profiles-BiQKOE-p.d.ts → scope-profiles-BJzp2F5A.d.ts} +1 -1
- package/dist/search/embed-helper.d.ts +2 -1
- package/dist/search/embed-helper.js +3 -3
- package/dist/search/factory.d.ts +4 -2
- package/dist/search/factory.js +20 -18
- package/dist/search/index.d.ts +2 -1
- package/dist/search/index.js +22 -22
- package/dist/search/lancedb-backend.d.ts +2 -1
- package/dist/search/lancedb-backend.js +4 -4
- package/dist/search/meilisearch-backend.d.ts +2 -1
- package/dist/search/meilisearch-backend.js +4 -4
- package/dist/search/noop-backend.d.ts +2 -1
- package/dist/search/orama-backend.d.ts +2 -1
- package/dist/search/orama-backend.js +4 -4
- package/dist/search/port.d.ts +18 -1
- package/dist/search/port.js +1 -1
- package/dist/search/remote-backend.d.ts +2 -1
- package/dist/search/remote-backend.js +2 -2
- package/dist/secure-store/index.js +2 -2
- package/dist/{semantic-consolidation-dHYCyqgh.d.ts → semantic-consolidation-D4KAZO2G.d.ts} +1 -1
- package/dist/semantic-consolidation.d.ts +3 -2
- package/dist/semantic-consolidation.js +25 -24
- package/dist/semantic-rule-promotion.js +23 -22
- package/dist/semantic-rule-verifier.d.ts +2 -1
- package/dist/semantic-rule-verifier.js +24 -23
- package/dist/{service-DJG3KCQ4.d.ts → service-BeDxSqE-.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 +2 -1
- package/dist/shared-context/manager.js +2 -2
- package/dist/signal.d.ts +2 -1
- package/dist/source-agent-qualifier.d.ts +2 -1
- package/dist/source-agent-qualifier.js +42 -40
- package/dist/{storage-F9FVh-w9.d.ts → storage-DfjxusTE.d.ts} +24 -12
- package/dist/storage.d.ts +3 -2
- package/dist/storage.js +25 -24
- package/dist/summarizer.d.ts +2 -1
- package/dist/summarizer.js +5 -5
- package/dist/summary-snapshot.d.ts +2 -1
- 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 +3 -2
- package/dist/tier-routing.d.ts +2 -1
- package/dist/tool-scoped-memory.d.ts +5 -1
- package/dist/tool-scoped-memory.js +3 -1
- package/dist/topics.d.ts +2 -1
- package/dist/transcript.d.ts +2 -1
- package/dist/transfer/capsule-import.js +4 -4
- package/dist/transfer/types.d.ts +12 -12
- package/dist/trust-score-stage.d.ts +2 -1
- package/dist/trust-score.d.ts +2 -1
- package/dist/{types-rEwubvim.d.ts → types-yX_FwERf.d.ts} +8 -1
- 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 +24 -23
- package/dist/write-envelope.d.ts +2 -1
- package/package.json +2 -2
- package/src/abort-error.ts +17 -0
- package/src/access-admin-ops-surface.ts +1 -0
- package/src/access-boundary.ts +1 -0
- package/src/access-coding-context-resolution.ts +42 -0
- package/src/access-extraction-force-flush.ts +38 -2
- package/src/access-http-lcm-compaction.ts +5 -2
- package/src/access-http-offline-stream.ts +79 -0
- package/src/access-http.test.ts +310 -3
- package/src/access-http.ts +85 -21
- package/src/access-mcp-output-schemas.ts +36 -0
- package/src/access-mcp.test.ts +95 -1
- package/src/access-mcp.ts +7 -9
- package/src/access-observe-helpers.ts +64 -22
- package/src/access-observe-write-surface.ts +8 -0
- package/src/access-offline-manifest.ts +54 -0
- package/src/access-operations-batch.ts +3 -3
- package/src/access-operations.ts +13 -7
- package/src/access-recall-concurrency.ts +3 -27
- package/src/access-recall-surface.ts +3 -0
- package/src/access-service-health.test.ts +32 -7
- package/src/access-service-namespace.test.ts +55 -0
- package/src/access-service-observe-idempotency.test.ts +34 -2
- package/src/access-service-observe-lcm-parity.test.ts +138 -3
- package/src/access-service-observe-scope.test.ts +160 -1
- package/src/access-service-offline-file-content.test.ts +345 -1
- package/src/access-service.ts +86 -59
- package/src/access-surface-catalog.ts +4 -0
- package/src/admin/admin-surfaces.ts +2 -0
- package/src/binary-lifecycle/pipeline.test.ts +106 -1
- package/src/binary-lifecycle/pipeline.ts +3 -0
- package/src/coding/git-context.test.ts +47 -0
- package/src/coding/git-context.ts +129 -27
- package/src/config.test.ts +24 -0
- package/src/config.ts +9 -12
- package/src/connector-provenance.test.ts +101 -0
- package/src/consolidation-undo.ts +3 -0
- package/src/convergence-refresh.ts +14 -2
- package/src/correction/correction-access-wiring.ts +9 -7
- package/src/correction/correction-executor.test.ts +206 -2
- package/src/correction/correction-executor.ts +29 -20
- package/src/correction/correction-planner.test.ts +36 -0
- package/src/correction/correction-planner.ts +9 -15
- package/src/correction/correction-service.ts +3 -1
- package/src/correction/correction-storage-integration.test.ts +77 -0
- package/src/correction/correction-surfaces.test.ts +41 -28
- package/src/correction/passive-capture.test.ts +59 -0
- package/src/correction/passive-capture.ts +4 -1
- package/src/entity-retrieval-boundaries.ts +17 -4
- package/src/entity-retrieval.ts +27 -6
- package/src/external-wiki-access.test.ts +65 -0
- package/src/external-wiki-access.ts +31 -0
- package/src/external-wiki-cli.ts +92 -0
- package/src/external-wiki-collection-registration.test.ts +163 -0
- package/src/external-wiki-collection-registration.ts +101 -0
- package/src/external-wiki-collection.test.ts +502 -0
- package/src/external-wiki-collection.ts +503 -0
- package/src/external-wiki-config.test.ts +135 -0
- package/src/external-wiki-config.ts +100 -0
- package/src/external-wiki-guard.ts +83 -0
- package/src/external-wiki-mcp-tools.ts +23 -0
- package/src/external-wiki-search.test.ts +301 -0
- package/src/external-wiki-search.ts +362 -0
- package/src/external-wiki.test.ts +240 -0
- package/src/external-wiki.ts +453 -0
- package/src/extraction-scope-source-agent.test.ts +21 -0
- package/src/extraction-source-grounding-helpers.ts +243 -53
- package/src/extraction-source-grounding-rules.ts +133 -39
- package/src/extraction-source-grounding.test.ts +363 -33
- package/src/extraction-timeout.test.ts +1 -0
- package/src/extraction-watermark.test.ts +150 -7
- package/src/extraction.ts +8 -1
- package/src/index.ts +8 -0
- package/src/mcp-read-only-tools.ts +1 -0
- package/src/offline-sync.test.ts +194 -0
- package/src/offline-sync.ts +217 -13
- package/src/orchestration/external-wiki-recall-guard.test.ts +94 -0
- package/src/orchestration/extraction-persist.ts +19 -2
- package/src/orchestration/extraction-run-helpers.ts +37 -19
- package/src/orchestration/extraction-run.test.ts +171 -2
- package/src/orchestration/extraction-run.ts +11 -13
- package/src/orchestration/extraction-watermark.ts +106 -17
- package/src/orchestration/generic-recall-paths.ts +14 -0
- package/src/orchestration/orchestrator-helpers.ts +2 -0
- package/src/orchestration/orchestrator-init.ts +9 -0
- package/src/orchestration/recall-internal-deps.ts +6 -0
- package/src/orchestration/recall-internal.ts +154 -33
- package/src/orchestration/recall-rerank-coordinator.ts +60 -25
- package/src/orchestration/recall-search-pipeline.test.ts +75 -1
- package/src/orchestration/recall-search-pipeline.ts +50 -10
- package/src/orchestrator-convergence-refresh.test.ts +36 -2
- package/src/orchestrator.ts +13 -3
- package/src/page-versioning.ts +5 -19
- package/src/procedural/procedure-recall.ts +5 -1
- package/src/provenance-surfaces.test.ts +3 -0
- package/src/qmd-client.test.ts +78 -17
- package/src/qmd.test.ts +24 -0
- package/src/qmd.ts +224 -315
- package/src/recall-explain-renderer.ts +3 -0
- package/src/recall-rerank-coordinator.test.ts +61 -0
- package/src/recall-xray-renderer.test.ts +6 -0
- package/src/recall-xray.test.ts +88 -1
- package/src/recall-xray.ts +15 -0
- package/src/reconcile/cursor.test.ts +48 -0
- package/src/reconcile/cursor.ts +58 -11
- package/src/reconcile/manifest.test.ts +4 -0
- package/src/reconcile/manifest.ts +41 -51
- package/src/reconcile/plan.test.ts +4 -0
- package/src/reconcile/plan.ts +28 -16
- package/src/search/factory.ts +6 -6
- package/src/search/port.ts +25 -9
- package/src/secure-store/secure-fs.ts +20 -12
- package/src/secure-store/secure-store.test.ts +41 -2
- package/src/spaces/index.test.ts +61 -2
- package/src/spaces/index.ts +44 -18
- package/src/storage/entity-alias-config.ts +97 -0
- package/src/storage/entity-canonical-id-lock.ts +53 -23
- package/src/storage/entity-canonical-id-migration.ts +53 -22
- package/src/storage/entity-canonical-id-references.ts +3 -0
- package/src/storage/entity-id-safety.ts +7 -0
- package/src/storage/entity-store.ts +6 -2
- package/src/storage/memory-frontmatter-metadata.ts +4 -9
- package/src/storage/memory-migration-serialization.ts +10 -15
- package/src/storage/tombstone-blocked-capture-mutation.ts +52 -64
- package/src/storage/tombstone-blocked-capture-sync.ts +244 -199
- package/src/storage-deletion-revisions.test.ts +91 -0
- package/src/storage-fact-hash-index-defer.test.ts +446 -163
- package/src/storage.ts +534 -245
- package/src/tool-scoped-memory.ts +10 -0
- package/src/transfer/capsule-import.ts +13 -0
- package/src/transfer/capsule-merge.ts +13 -0
- package/src/trust-score-recall-paths.test.ts +75 -1
- package/src/types.ts +7 -3
- package/dist/capsule-merge-IDWJPCWK.js.map +0 -1
- package/dist/chunk-3CE77VAP.js.map +0 -1
- package/dist/chunk-3TBLDMJA.js.map +0 -1
- package/dist/chunk-4J7G5SY4.js.map +0 -1
- package/dist/chunk-57QKLRBV.js.map +0 -1
- package/dist/chunk-5TFP4CUL.js.map +0 -1
- package/dist/chunk-7XC2HX75.js.map +0 -1
- package/dist/chunk-A5OJCXZL.js.map +0 -1
- package/dist/chunk-BUE5E2HL.js.map +0 -1
- package/dist/chunk-CJ2ZR7UA.js.map +0 -1
- package/dist/chunk-CUM2BBPN.js.map +0 -1
- package/dist/chunk-D3J5SLQK.js.map +0 -1
- package/dist/chunk-DL7ZD3JH.js.map +0 -1
- package/dist/chunk-DLVPUX7U.js.map +0 -1
- package/dist/chunk-E6PNLPGJ.js.map +0 -1
- package/dist/chunk-ECK75GDJ.js.map +0 -1
- package/dist/chunk-HREE4JHI.js.map +0 -1
- package/dist/chunk-HZFHQ4AQ.js.map +0 -1
- package/dist/chunk-IKKWIPYN.js.map +0 -1
- package/dist/chunk-J7VGGECD.js.map +0 -1
- package/dist/chunk-N5Z4EVOR.js.map +0 -1
- package/dist/chunk-NVRYW264.js.map +0 -1
- package/dist/chunk-P2BM76KT.js.map +0 -1
- package/dist/chunk-PVGDJXVK.js +0 -21
- package/dist/chunk-QJAQNXWI.js.map +0 -1
- package/dist/chunk-RN7DY3FC.js.map +0 -1
- package/dist/chunk-RVLJEII5.js.map +0 -1
- package/dist/chunk-S2NCTZGJ.js.map +0 -1
- package/dist/chunk-TDHTVMPG.js.map +0 -1
- package/dist/chunk-UYLMNVY6.js.map +0 -1
- package/dist/chunk-VCD4PSK2.js.map +0 -1
- package/dist/chunk-VNA7W7QF.js.map +0 -1
- package/dist/chunk-VWAXN2BN.js.map +0 -1
- package/dist/chunk-WOCNN776.js.map +0 -1
- package/dist/chunk-XYTOI63Z.js.map +0 -1
- package/dist/chunk-YV32N67O.js.map +0 -1
- /package/dist/{auto-sync-5OE5QOZB.js.map → auto-sync-UPTUVE4X.js.map} +0 -0
- /package/dist/{chunk-VUPTKTDV.js.map → chunk-2MRHJNWL.js.map} +0 -0
- /package/dist/{chunk-JBPKEARU.js.map → chunk-2QSZNTDO.js.map} +0 -0
- /package/dist/{chunk-5IVLTFOV.js.map → chunk-44N6ESJ4.js.map} +0 -0
- /package/dist/{chunk-HO3QBJEY.js.map → chunk-5546W5SI.js.map} +0 -0
- /package/dist/{chunk-U7GW7NE7.js.map → chunk-5CEECY6P.js.map} +0 -0
- /package/dist/{chunk-4UH4BTGK.js.map → chunk-5SNZSWWR.js.map} +0 -0
- /package/dist/{chunk-6CZPDBJS.js.map → chunk-5U7ID3EZ.js.map} +0 -0
- /package/dist/{chunk-GF22HWS2.js.map → chunk-6NNNURLK.js.map} +0 -0
- /package/dist/{chunk-227UFSEQ.js.map → chunk-7RZJWZ46.js.map} +0 -0
- /package/dist/{chunk-E5UK4VPE.js.map → chunk-7SHJHPTY.js.map} +0 -0
- /package/dist/{chunk-UVIKWC7M.js.map → chunk-7YERSTN7.js.map} +0 -0
- /package/dist/{chunk-S5SLVSVY.js.map → chunk-BQIFZ2MP.js.map} +0 -0
- /package/dist/{chunk-E53DSZEN.js.map → chunk-C26TE27X.js.map} +0 -0
- /package/dist/{chunk-LZ4LDKHZ.js.map → chunk-CLB32OHM.js.map} +0 -0
- /package/dist/{chunk-Q6IP2ARR.js.map → chunk-CSOYVTRX.js.map} +0 -0
- /package/dist/{chunk-XOQSEF7X.js.map → chunk-CVILPI77.js.map} +0 -0
- /package/dist/{chunk-PDLBLTOK.js.map → chunk-EITZHSX6.js.map} +0 -0
- /package/dist/{chunk-WUNIWKY4.js.map → chunk-ELIL2A37.js.map} +0 -0
- /package/dist/{chunk-CINZGPSJ.js.map → chunk-GUMZC2BO.js.map} +0 -0
- /package/dist/{chunk-H24WNPA2.js.map → chunk-GWFSVJ4P.js.map} +0 -0
- /package/dist/{chunk-TSH56VPU.js.map → chunk-HAYSYUAB.js.map} +0 -0
- /package/dist/{chunk-PKNLM44P.js.map → chunk-JH6BPLOP.js.map} +0 -0
- /package/dist/{chunk-KXB4VXHY.js.map → chunk-JIYDRBVZ.js.map} +0 -0
- /package/dist/{chunk-AV5ZEH4M.js.map → chunk-KVJRXN2E.js.map} +0 -0
- /package/dist/{chunk-JVLCVFQ4.js.map → chunk-KXEFRMCF.js.map} +0 -0
- /package/dist/{chunk-WFTIGIIS.js.map → chunk-L6CQ7WIW.js.map} +0 -0
- /package/dist/{chunk-EJUEXZHX.js.map → chunk-LLJMAULE.js.map} +0 -0
- /package/dist/{chunk-AS7YMSL6.js.map → chunk-M23RF3LJ.js.map} +0 -0
- /package/dist/{chunk-3F2LKUMU.js.map → chunk-NIS256NW.js.map} +0 -0
- /package/dist/{chunk-YIAA2X3D.js.map → chunk-NK5RGJ65.js.map} +0 -0
- /package/dist/{chunk-OQ5PRDDS.js.map → chunk-NTOIP2E6.js.map} +0 -0
- /package/dist/{chunk-HLPD7B7P.js.map → chunk-NUEQKLNB.js.map} +0 -0
- /package/dist/{chunk-33PLLLL7.js.map → chunk-P7NGM24P.js.map} +0 -0
- /package/dist/{chunk-7TWUCYER.js.map → chunk-PNRA7FAD.js.map} +0 -0
- /package/dist/{chunk-5I4M26Q7.js.map → chunk-QBSFOKY6.js.map} +0 -0
- /package/dist/{chunk-P4DRWEYC.js.map → chunk-QVSBTCVP.js.map} +0 -0
- /package/dist/{chunk-AAIUERNB.js.map → chunk-R5RFK3CB.js.map} +0 -0
- /package/dist/{chunk-WDISJRMG.js.map → chunk-RMMVQQA6.js.map} +0 -0
- /package/dist/{chunk-5SM35XZR.js.map → chunk-S5NZBKKQ.js.map} +0 -0
- /package/dist/{chunk-WIPEXG6R.js.map → chunk-SXIMQLGV.js.map} +0 -0
- /package/dist/{chunk-OAEQLRCY.js.map → chunk-TN76AKO3.js.map} +0 -0
- /package/dist/{chunk-QN25OCUF.js.map → chunk-TQ4GD737.js.map} +0 -0
- /package/dist/{chunk-7K5Q6COX.js.map → chunk-TVVEYCNW.js.map} +0 -0
- /package/dist/{chunk-DNWXFTLD.js.map → chunk-TYISDI6B.js.map} +0 -0
- /package/dist/{chunk-4LMA77JH.js.map → chunk-U2VLVBBH.js.map} +0 -0
- /package/dist/{chunk-5ZE7QHTK.js.map → chunk-ULVR5KG7.js.map} +0 -0
- /package/dist/{chunk-4B77XSG5.js.map → chunk-UV72DEZD.js.map} +0 -0
- /package/dist/{chunk-S2BBISHU.js.map → chunk-VANZKHTN.js.map} +0 -0
- /package/dist/{chunk-3Y224NYC.js.map → chunk-VYISFWVX.js.map} +0 -0
- /package/dist/{chunk-TIHMZFIV.js.map → chunk-W3IC7QOY.js.map} +0 -0
- /package/dist/{chunk-NRV4Y3PM.js.map → chunk-W4FBGYGK.js.map} +0 -0
- /package/dist/{chunk-MU7ZHSZE.js.map → chunk-WZFAPHIK.js.map} +0 -0
- /package/dist/{chunk-T2TTP3KU.js.map → chunk-X4IDNPOS.js.map} +0 -0
- /package/dist/{chunk-BLAKS3CP.js.map → chunk-XL3TATMJ.js.map} +0 -0
- /package/dist/{chunk-W4XJFLAL.js.map → chunk-XPRJSHNI.js.map} +0 -0
- /package/dist/{chunk-JE7EK33X.js.map → chunk-Y7HRYCNW.js.map} +0 -0
- /package/dist/{chunk-E6EE5B67.js.map → chunk-YK6BDDHP.js.map} +0 -0
- /package/dist/{chunk-ES36HTSC.js.map → chunk-YLHM5BQQ.js.map} +0 -0
- /package/dist/{chunk-BJKPPZ6Z.js.map → chunk-ZFGZ6PZ2.js.map} +0 -0
- /package/dist/{chunk-64UDOIMI.js.map → chunk-ZLQ37WJX.js.map} +0 -0
|
@@ -173,6 +173,16 @@ export function withholdToolScopedFromSharedNamespace({
|
|
|
173
173
|
return false;
|
|
174
174
|
}
|
|
175
175
|
|
|
176
|
+
export function canRecallToolScopedMemory(
|
|
177
|
+
frontmatter: { sourceConnector?: string; toolScoped?: true },
|
|
178
|
+
requestingConnector?: string,
|
|
179
|
+
): boolean {
|
|
180
|
+
if (frontmatter.toolScoped !== true) return true;
|
|
181
|
+
const sourceConnector = frontmatter.sourceConnector?.trim();
|
|
182
|
+
const requester = requestingConnector?.trim();
|
|
183
|
+
return !sourceConnector || !requester || sourceConnector === requester;
|
|
184
|
+
}
|
|
185
|
+
|
|
176
186
|
export interface GlobalFactPromotionInputs {
|
|
177
187
|
scope: string | null | undefined;
|
|
178
188
|
content: string;
|
|
@@ -11,6 +11,7 @@ import {
|
|
|
11
11
|
repairContentAfterJournalMove,
|
|
12
12
|
requestEntityCanonicalIdReconcile,
|
|
13
13
|
} from "../storage/entity-canonical-id-references.js";
|
|
14
|
+
import { withRawEntityPageMutation } from "../storage/entity-canonical-id-lock.js";
|
|
14
15
|
import {
|
|
15
16
|
createVersion,
|
|
16
17
|
type VersioningConfig,
|
|
@@ -422,6 +423,7 @@ export async function importCapsule(
|
|
|
422
423
|
// between a legacy-preserving memory write and its colliding entity page,
|
|
423
424
|
// canonicalizing the memory onto the wrong claimant irreversibly.
|
|
424
425
|
let reconcileNeeded = false;
|
|
426
|
+
const applyRecords = async (): Promise<void> => {
|
|
425
427
|
for (const rec of sortedRecords) {
|
|
426
428
|
const targetRel = computeTargetPath(rec.path, mode, capsule.id);
|
|
427
429
|
// Use rootReal (realpath-resolved) to stay consistent with phase 1's
|
|
@@ -537,6 +539,17 @@ export async function importCapsule(
|
|
|
537
539
|
if (reconcileNeeded) {
|
|
538
540
|
await requestEntityCanonicalIdReconcile(journalStateDir);
|
|
539
541
|
}
|
|
542
|
+
};
|
|
543
|
+
const firstEntityId = capsuleEntityIds.values().next().value;
|
|
544
|
+
if (firstEntityId === undefined) {
|
|
545
|
+
await applyRecords();
|
|
546
|
+
} else {
|
|
547
|
+
await withRawEntityPageMutation(
|
|
548
|
+
rootReal,
|
|
549
|
+
path.join(rootReal, "entities", `${firstEntityId}.md`),
|
|
550
|
+
applyRecords,
|
|
551
|
+
);
|
|
552
|
+
}
|
|
540
553
|
|
|
541
554
|
// Sort skipped for stable output (see comment above).
|
|
542
555
|
skipped.sort((a, b) => a.path.localeCompare(b.path));
|
|
@@ -10,6 +10,7 @@ import {
|
|
|
10
10
|
repairContentAfterJournalMove,
|
|
11
11
|
requestEntityCanonicalIdReconcile,
|
|
12
12
|
} from "../storage/entity-canonical-id-references.js";
|
|
13
|
+
import { withRawEntityPageMutation } from "../storage/entity-canonical-id-lock.js";
|
|
13
14
|
import {
|
|
14
15
|
createVersion,
|
|
15
16
|
type VersioningConfig,
|
|
@@ -440,6 +441,7 @@ export async function mergeCapsule(
|
|
|
440
441
|
a.path.localeCompare(b.path),
|
|
441
442
|
);
|
|
442
443
|
|
|
444
|
+
const applyRecords = async (): Promise<void> => {
|
|
443
445
|
for (const rec of sortedRecords) {
|
|
444
446
|
const targetAbs = path.join(rootReal, fromPosixRelPath(rec.path));
|
|
445
447
|
const entry = manifestIndex.get(rec.path)!; // validated above
|
|
@@ -531,6 +533,17 @@ export async function mergeCapsule(
|
|
|
531
533
|
if (reconcileNeeded) {
|
|
532
534
|
await requestEntityCanonicalIdReconcile(journalStateDir);
|
|
533
535
|
}
|
|
536
|
+
};
|
|
537
|
+
const firstEntityId = capsuleEntityIds.values().next().value;
|
|
538
|
+
if (firstEntityId === undefined) {
|
|
539
|
+
await applyRecords();
|
|
540
|
+
} else {
|
|
541
|
+
await withRawEntityPageMutation(
|
|
542
|
+
rootReal,
|
|
543
|
+
path.join(rootReal, "entities", `${firstEntityId}.md`),
|
|
544
|
+
applyRecords,
|
|
545
|
+
);
|
|
546
|
+
}
|
|
534
547
|
|
|
535
548
|
// Sort output lists for determinism.
|
|
536
549
|
merged.sort((a, b) => a.sourcePath.localeCompare(b.sourcePath));
|
|
@@ -61,6 +61,7 @@ async function writeFact(
|
|
|
61
61
|
memoryDir: string,
|
|
62
62
|
body: string,
|
|
63
63
|
extraFrontmatterLines: string[] = [],
|
|
64
|
+
updatedAt = new Date().toISOString(),
|
|
64
65
|
): Promise<string> {
|
|
65
66
|
const today = new Date().toISOString().slice(0, 10);
|
|
66
67
|
const id = `fact-${Date.now()}-${Math.random().toString(36).slice(2)}`;
|
|
@@ -69,7 +70,7 @@ async function writeFact(
|
|
|
69
70
|
`id: ${id}`,
|
|
70
71
|
"category: fact",
|
|
71
72
|
`created: ${new Date().toISOString()}`,
|
|
72
|
-
`updated: ${
|
|
73
|
+
`updated: ${updatedAt}`,
|
|
73
74
|
"source: extraction",
|
|
74
75
|
"confidence: 0.8",
|
|
75
76
|
"confidenceTier: high",
|
|
@@ -152,6 +153,79 @@ test("TrustScore quarantine excludes a contradicted memory from injection but su
|
|
|
152
153
|
typeof quarantined!.trust!.quarantineReason === "string" && quarantined!.trust!.quarantineReason.length > 0,
|
|
153
154
|
"quarantined result carries a human-readable reason",
|
|
154
155
|
);
|
|
156
|
+
assert.ok(
|
|
157
|
+
snapshot!.appliedResults.some((result) => result.memoryId === goodId),
|
|
158
|
+
"the applied witness includes the memory that reached published recall",
|
|
159
|
+
);
|
|
160
|
+
assert.equal(
|
|
161
|
+
snapshot!.appliedResults.some((result) => result.memoryId === badId),
|
|
162
|
+
false,
|
|
163
|
+
"the applied witness excludes a candidate removed before the result-limit partition",
|
|
164
|
+
);
|
|
165
|
+
assert.equal(
|
|
166
|
+
snapshot!.headroomResults.some((result) => result.memoryId === badId),
|
|
167
|
+
false,
|
|
168
|
+
"the headroom witness excludes quarantined candidates",
|
|
169
|
+
);
|
|
170
|
+
} finally {
|
|
171
|
+
await orchestrator.destroy();
|
|
172
|
+
await rm(memoryDir, { recursive: true, force: true });
|
|
173
|
+
}
|
|
174
|
+
});
|
|
175
|
+
|
|
176
|
+
test("X-ray capture preserves recent-scan serving while recording post-trust applied and pre-trust headroom", async () => {
|
|
177
|
+
const { orchestrator, memoryDir } = await makeOrchestrator({
|
|
178
|
+
qmdMaxResults: 2,
|
|
179
|
+
});
|
|
180
|
+
const now = Date.now();
|
|
181
|
+
try {
|
|
182
|
+
const tailId = await writeFact(
|
|
183
|
+
memoryDir,
|
|
184
|
+
"Parity recall token: stable tail candidate.",
|
|
185
|
+
["mw_success: 5", "mw_fail: 0"],
|
|
186
|
+
new Date(now - 3_000).toISOString(),
|
|
187
|
+
);
|
|
188
|
+
const quarantinedId = await writeFact(
|
|
189
|
+
memoryDir,
|
|
190
|
+
"Parity recall token: contradicted applied candidate.",
|
|
191
|
+
['faithfulness: {"verdict":"contradicted"}'],
|
|
192
|
+
new Date(now - 2_000).toISOString(),
|
|
193
|
+
);
|
|
194
|
+
const servedId = await writeFact(
|
|
195
|
+
memoryDir,
|
|
196
|
+
"Parity recall token: verified served candidate.",
|
|
197
|
+
["mw_success: 5", "mw_fail: 0"],
|
|
198
|
+
new Date(now - 1_000).toISOString(),
|
|
199
|
+
);
|
|
200
|
+
|
|
201
|
+
const withoutCapture = await orchestrator.recall(
|
|
202
|
+
"parity recall token",
|
|
203
|
+
"sess-trust-parity",
|
|
204
|
+
{ mode: "full" },
|
|
205
|
+
);
|
|
206
|
+
const withCapture = await orchestrator.recall(
|
|
207
|
+
"parity recall token",
|
|
208
|
+
"sess-trust-parity",
|
|
209
|
+
{ mode: "full", xrayCapture: true },
|
|
210
|
+
);
|
|
211
|
+
const snapshot = orchestrator.getLastXraySnapshot();
|
|
212
|
+
|
|
213
|
+
assert.equal(withCapture, withoutCapture);
|
|
214
|
+
assert.match(withCapture, /verified served candidate/);
|
|
215
|
+
assert.doesNotMatch(withCapture, /contradicted applied candidate|stable tail candidate/);
|
|
216
|
+
assert.ok(snapshot);
|
|
217
|
+
assert.deepEqual(
|
|
218
|
+
snapshot.appliedResults.map((result) => result.memoryId),
|
|
219
|
+
[servedId],
|
|
220
|
+
);
|
|
221
|
+
assert.deepEqual(
|
|
222
|
+
snapshot.headroomResults.map((result) => result.memoryId),
|
|
223
|
+
[tailId],
|
|
224
|
+
);
|
|
225
|
+
assert.equal(
|
|
226
|
+
snapshot.appliedResults.some((result) => result.memoryId === quarantinedId),
|
|
227
|
+
false,
|
|
228
|
+
);
|
|
155
229
|
} finally {
|
|
156
230
|
await orchestrator.destroy();
|
|
157
231
|
await rm(memoryDir, { recursive: true, force: true });
|
package/src/types.ts
CHANGED
|
@@ -4,6 +4,7 @@ import type { ActivityConfig } from "./activity/types.js";
|
|
|
4
4
|
import type { WearablesConfig } from "./wearables/types.js";
|
|
5
5
|
import type { ExtractionLivenessConfig } from "./extraction-liveness.js";
|
|
6
6
|
import type { ReplicaPeersConfig } from "./replica-peers-config.js";
|
|
7
|
+
import type { ExternalWikiRoot } from "./external-wiki-config.js";
|
|
7
8
|
|
|
8
9
|
import type { BufferTurnOwner } from "./buffer-turn-helpers.js";
|
|
9
10
|
export type ReasoningEffort = "none" | "low" | "medium" | "high";
|
|
@@ -733,6 +734,7 @@ export interface PluginConfig extends BoundedJsonlStateConfig {
|
|
|
733
734
|
memoryOsPreset?: MemoryOsPresetName;
|
|
734
735
|
qmdEnabled: boolean;
|
|
735
736
|
qmdCollection: string;
|
|
737
|
+
wikiMergeIntoRecall: boolean;
|
|
736
738
|
qmdMaxResults: number;
|
|
737
739
|
qmdEmbeddingBacklogThreshold: number;
|
|
738
740
|
qmdColdTierEnabled?: boolean;
|
|
@@ -751,11 +753,8 @@ export interface PluginConfig extends BoundedJsonlStateConfig {
|
|
|
751
753
|
qmdChunkStrategy: "auto" | "regex";
|
|
752
754
|
qmdCandidateLimit?: number;
|
|
753
755
|
qmdQueryRerankEnabled: boolean;
|
|
754
|
-
// Daemon search plan; "hybrid" (default) = lex+vec+hyde. Issue #1335.
|
|
755
756
|
qmdSearchStrategy: "hybrid" | "lex-vec" | "lex";
|
|
756
|
-
// Subprocess fallback command; "query" (default) keeps LLM expansion. Issue #1335.
|
|
757
757
|
qmdSubprocessStrategy: "query" | "search";
|
|
758
|
-
// Per-call daemon search timeout in ms; default 8000. Issue #1335.
|
|
759
758
|
qmdDaemonTimeoutMs: number;
|
|
760
759
|
qmdIndexName?: string;
|
|
761
760
|
qmdForceCpu: boolean;
|
|
@@ -785,6 +784,7 @@ export interface PluginConfig extends BoundedJsonlStateConfig {
|
|
|
785
784
|
/** Optional absolute path to qmd binary. If unset, PATH/fallback discovery is used. */
|
|
786
785
|
qmdPath?: string;
|
|
787
786
|
memoryDir: string;
|
|
787
|
+
externalWikis: ExternalWikiRoot[];
|
|
788
788
|
debug: boolean;
|
|
789
789
|
identityEnabled: boolean;
|
|
790
790
|
identityContinuityEnabled: boolean;
|
|
@@ -2788,6 +2788,8 @@ export interface ImportanceScore {
|
|
|
2788
2788
|
}
|
|
2789
2789
|
|
|
2790
2790
|
export interface MemoryFrontmatter extends SourceConnectorProvenance {
|
|
2791
|
+
/** True when write-time classification ties this memory to its source connector's tools or commands. */
|
|
2792
|
+
toolScoped?: true;
|
|
2791
2793
|
id: string;
|
|
2792
2794
|
category: MemoryCategory;
|
|
2793
2795
|
created: string;
|
|
@@ -3329,6 +3331,8 @@ export interface ExtractionResult {
|
|
|
3329
3331
|
extractionFailure?: string;
|
|
3330
3332
|
/** Coarse class used by the retry/backoff + circuit-breaker layer (extraction hot loop). */
|
|
3331
3333
|
extractionFailureClass?: ExtractionFailureClass;
|
|
3334
|
+
/** Local prefilter reason; no provider extraction was attempted. */
|
|
3335
|
+
extractionSkippedReason?: "conversation_only_non_memory" | "mechanical_telemetry";
|
|
3332
3336
|
/** Trusted source connector resolved over boundedTurns; persisted verbatim by the orchestrator so it is not recomputed (#2183). */
|
|
3333
3337
|
sourceConnector?: string;
|
|
3334
3338
|
}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/transfer/capsule-merge.ts"],"sourcesContent":["import { lstat, mkdir, readFile, realpath, stat, unlink, writeFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { gunzipSync } from \"node:zlib\";\nimport { bumpMemoryCorpusVersionForDir } from \"../memory-corpus-version.js\";\nimport {\n HistoricalEntityCanonicalIdCache,\n canonicalizeEntityRefFrontmatter,\n readEntityRefFromFrontmatter,\n classifyEntityRefWritePath,\n repairContentAfterJournalMove,\n requestEntityCanonicalIdReconcile,\n} from \"../storage/entity-canonical-id-references.js\";\nimport {\n createVersion,\n type VersioningConfig,\n type VersioningLogger,\n} from \"../page-versioning.js\";\nimport {\n assertIsDirectoryNotSymlink,\n assertRealpathInsideRoot,\n fromPosixRelPath,\n isPathInsideRoot,\n sha256String,\n} from \"./fs-utils.js\";\nimport {\n parseExportBundle,\n type CapsuleBlock,\n type ExportManifestV2,\n type ExportMemoryRecordV1,\n} from \"./types.js\";\n\n/**\n * Three-way conflict-resolution mode for {@link mergeCapsule}.\n *\n * A \"conflict\" is defined as: the same memory-file path exists in both the\n * source archive and the target directory AND the content hash of the local\n * file differs from the archive's manifest entry for that path.\n *\n * Files that exist only in the archive (no local counterpart) are always\n * written regardless of mode — there is no conflict to resolve.\n *\n * Files that are byte-identical (same content hash in both locations) are\n * recorded as {@link MergeCapsuleResult.skipped} with reason `\"identical\"` and\n * are never re-written regardless of mode; this is a no-op optimisation rather\n * than a conflict.\n *\n * - `\"skip-conflicts\"` (default) — log the conflict, skip the conflicting\n * archive entries, but continue importing non-conflicting entries. The\n * resulting merge is the union of:\n * - all non-conflicting archive files (written to target)\n * - all pre-existing local files (left unchanged)\n *\n * - `\"prefer-source\"` — for conflicting files, snapshot the local content via\n * page-versioning (gotcha #54: snapshot before overwrite) then overwrite\n * with the archive content.\n *\n * - `\"prefer-local\"` — for conflicting files, keep the local content; the\n * archive entry is skipped.\n */\nexport type MergeCapsuleConflictMode =\n | \"skip-conflicts\"\n | \"prefer-source\"\n | \"prefer-local\";\n\n/**\n * Options accepted by {@link mergeCapsule}.\n *\n * `sourceArchive` — absolute or cwd-relative path to a `.capsule.json.gz`\n * archive produced by `exportCapsule`. Must be a V2 bundle.\n *\n * `targetRoot` — absolute or cwd-relative path to the memory directory that\n * receives the merged records. Must be an existing, non-symlink directory.\n *\n * `conflictMode` — see {@link MergeCapsuleConflictMode}. Defaults to\n * `\"skip-conflicts\"`.\n *\n * `versioning` — optional page-versioning config forwarded to\n * {@link createVersion} in `\"prefer-source\"` mode. When omitted or disabled,\n * overwrites proceed without snapshotting (not recommended for production).\n *\n * `log` — optional logger forwarded to {@link createVersion}.\n */\nexport interface MergeCapsuleOptions {\n sourceArchive: string;\n targetRoot: string;\n conflictMode?: MergeCapsuleConflictMode;\n versioning?: VersioningConfig;\n log?: VersioningLogger;\n}\n\nexport interface MergeCapsuleWrittenRecord {\n /** Capsule-relative posix path. */\n sourcePath: string;\n /** Memory-dir-relative posix path written on disk. */\n targetPath: string;\n /** Whether a page-versioning snapshot was taken before overwriting. */\n snapshotted: boolean;\n}\n\nexport interface MergeCapsuleSkippedRecord {\n /** Capsule-relative posix path. */\n path: string;\n /**\n * Why the archive entry was not written.\n *\n * `\"conflict\"` — the entry existed locally with different content and the\n * active mode did not resolve the conflict with a write (`\"skip-conflicts\"` /\n * `\"prefer-local\"`).\n *\n * `\"identical\"` — the entry's content hash matches what is already on disk;\n * no write is needed.\n */\n reason: \"conflict\" | \"identical\";\n}\n\nexport interface MergeCapsuleConflictRecord {\n /** Capsule-relative posix path of the conflicting entry. */\n path: string;\n /** SHA-256 of the archive's copy. */\n archiveSha256: string;\n /** SHA-256 of the local copy. */\n localSha256: string;\n}\n\nexport interface MergeCapsuleResult {\n /** Records that were written to the target directory. */\n merged: MergeCapsuleWrittenRecord[];\n /**\n * Records that were NOT written (conflict skipped, or byte-identical).\n * Includes conflicts that were resolved by `\"prefer-local\"`.\n */\n skipped: MergeCapsuleSkippedRecord[];\n /**\n * Metadata about every detected conflict, regardless of which mode resolved\n * it. Callers can use this to report \"N conflicts encountered; M overwritten\".\n */\n conflicts: MergeCapsuleConflictRecord[];\n /** The manifest decoded from the archive. */\n manifest: ExportManifestV2;\n}\n\n// ---------------------------------------------------------------------------\n// Main entry point\n// ---------------------------------------------------------------------------\n\n/**\n * Merge a V2 capsule archive into an existing memory directory using\n * three-way conflict semantics.\n *\n * Sequence:\n * 1. Read + gunzip + JSON.parse the archive.\n * 2. Validate through `parseExportBundle` (V1 rejected).\n * 3. Verify every record's content sha256 against the manifest.\n * Any mismatch aborts BEFORE any file is written (gotcha #25).\n * 4. Classify each record as: new (no local copy), identical (same hash),\n * or conflicting (different hash).\n * 5. Apply the selected {@link MergeCapsuleConflictMode} to conflicting\n * entries; always write new entries; always skip identical entries.\n *\n * Determinism: `merged`, `skipped`, and `conflicts` are all returned sorted\n * by `path`/`sourcePath` so callers get stable output regardless of bundle\n * order.\n */\nexport async function mergeCapsule(\n opts: MergeCapsuleOptions,\n): Promise<MergeCapsuleResult> {\n const archiveAbs = path.resolve(opts.sourceArchive);\n const rootAbs = path.resolve(opts.targetRoot);\n\n await assertIsDirectoryNotSymlink(rootAbs, \"mergeCapsule\", \"targetRoot\");\n\n const conflictMode: MergeCapsuleConflictMode =\n opts.conflictMode ?? \"skip-conflicts\";\n\n // Rule 51: reject invalid conflictMode values up-front before any I/O.\n if (\n conflictMode !== \"skip-conflicts\" &&\n conflictMode !== \"prefer-source\" &&\n conflictMode !== \"prefer-local\"\n ) {\n throw new Error(\n `mergeCapsule: unknown conflictMode ${JSON.stringify(conflictMode)}; ` +\n `expected \"skip-conflicts\", \"prefer-source\", or \"prefer-local\"`,\n );\n }\n\n // ---------------------------------------------------------------------------\n // Parse + validate archive\n // ---------------------------------------------------------------------------\n\n const raw = await readFile(archiveAbs);\n let json: string;\n try {\n json = gunzipSync(raw).toString(\"utf-8\");\n } catch (cause) {\n throw new Error(\n `mergeCapsule: archive is not a valid gzip file: ${archiveAbs}`,\n { cause: cause as Error },\n );\n }\n\n let parsedJson: unknown;\n try {\n parsedJson = JSON.parse(json);\n } catch (cause) {\n throw new Error(\n `mergeCapsule: archive is not valid JSON after gunzip: ${archiveAbs}`,\n { cause: cause as Error },\n );\n }\n\n const parsed = parseExportBundle(parsedJson);\n if (parsed.capsuleVersion !== 2) {\n throw new Error(\n \"mergeCapsule: archive is V1; only V2 capsule archives are supported\",\n );\n }\n\n const bundle = parsed.bundle as {\n manifest: ExportManifestV2;\n records: ExportMemoryRecordV1[];\n };\n const manifest = bundle.manifest;\n const capsule = manifest.capsule;\n\n // Build path → manifest entry index for O(1) checksum lookup.\n const manifestIndex = new Map<string, ExportManifestV2[\"files\"][number]>();\n for (const f of manifest.files) {\n manifestIndex.set(f.path, f);\n }\n if (manifestIndex.size !== manifest.files.length) {\n throw new Error(\"mergeCapsule: manifest contains duplicate file paths\");\n }\n\n const recordPaths = new Set<string>();\n for (const rec of bundle.records) {\n if (recordPaths.has(rec.path)) {\n throw new Error(\n `mergeCapsule: bundle contains duplicate record path: ${rec.path}`,\n );\n }\n recordPaths.add(rec.path);\n }\n\n // ---------------------------------------------------------------------------\n // Phase 1: verify checksums + validate paths before ANY filesystem mutation.\n // (gotcha #25: don't destroy old state before confirming new state succeeds)\n // ---------------------------------------------------------------------------\n\n const rootReal = await realpath(rootAbs).catch(() => rootAbs);\n\n // Tracks normalized, case-folded target paths seen so far in phase 1. Maps\n // targetAbs.toLowerCase() → first source path so the collision error can name\n // both offending entries. Two manifest entries whose computed target paths\n // normalise to the same absolute path (e.g. `subdir/file.md` and\n // `subdir/./file.md`, or differing case on case-insensitive filesystems such\n // as macOS and Windows) would both refer to the same inode. In\n // `skip-conflicts`/`prefer-local` modes one entry would be misclassified as a\n // local conflict against the OTHER entry's just-written content; in\n // `prefer-source` the second entry would silently overwrite the first. We\n // reject the import up-front before any write (Codex P2 thread on PR #748,\n // mirroring `capsule-import.ts`).\n const seenTargetPaths = new Map<string, string>();\n\n for (const rec of bundle.records) {\n // Checksum validation.\n const entry = manifestIndex.get(rec.path);\n if (!entry) {\n throw new Error(\n `mergeCapsule: archive checksum mismatch (record without manifest entry: ${rec.path})`,\n );\n }\n const { sha256, bytes } = sha256String(rec.content);\n if (sha256 !== entry.sha256 || bytes !== entry.bytes) {\n throw new Error(\n `mergeCapsule: archive checksum mismatch for ${rec.path}: ` +\n `expected sha256=${entry.sha256} bytes=${entry.bytes}, ` +\n `got sha256=${sha256} bytes=${bytes}`,\n );\n }\n\n // Path-traversal validation (mirrors capsule-import.ts).\n if (rec.path.includes(\"\\\\\")) {\n throw new Error(\n `mergeCapsule: record path contains backslash separators (Windows-style paths are not allowed): ${rec.path}`,\n );\n }\n const posixNormalized = path.posix.normalize(rec.path);\n if (\n rec.path.startsWith(\"/\") ||\n rec.path.split(\"/\").some((seg) => seg === \"..\") ||\n posixNormalized.startsWith(\"..\") ||\n posixNormalized.startsWith(\"/\")\n ) {\n throw new Error(\n `mergeCapsule: record path escapes target root: ${rec.path}`,\n );\n }\n\n // Lexical root containment check.\n const targetAbs = path.join(rootReal, fromPosixRelPath(rec.path));\n if (!isPathInsideRoot(rootReal, targetAbs)) {\n throw new Error(\n `mergeCapsule: record path escapes target root: ${rec.path}`,\n );\n }\n\n // Symlink-aware containment check (shared helper from fs-utils).\n await assertRealpathInsideRoot(rootReal, targetAbs, rec.path, \"mergeCapsule\");\n\n // Target-file symlink guard: if the target already exists as a symlink,\n // reject — writes through symlinks can redirect to unexpected locations.\n const targetLstat = await lstat(targetAbs).catch(() => null);\n if (targetLstat !== null && targetLstat.isSymbolicLink()) {\n throw new Error(\n `mergeCapsule: record target is a symlink and cannot be written to safely: ${rec.path}`,\n );\n }\n\n // Duplicate normalized target path detection (Codex P2 #748, mirrors\n // capsule-import.ts). `path.join` already normalises `.` segments\n // (e.g. `subdir/./file.md` → `subdir/file.md`). On case-insensitive\n // filesystems (macOS default, Windows), two paths that differ only in case\n // would resolve to the same inode. We fold the dedup key to lowercase so\n // that `subdir/File.md` and `subdir/file.md` are detected as duplicates\n // before any write occurs. This is intentionally unconditional: the cost\n // of an extra `.toLowerCase()` on case-sensitive filesystems is negligible,\n // and a defensive lowercase is far simpler than probing filesystem\n // case-sensitivity at runtime. Without this guard, prefer-source mode\n // would silently overwrite one entry with the other, and skip-conflicts /\n // prefer-local would misclassify the second entry as a local conflict\n // against the first entry's freshly written content.\n const dedupKey = targetAbs.toLowerCase();\n const firstSourcePath = seenTargetPaths.get(dedupKey);\n if (firstSourcePath !== undefined) {\n throw new Error(\n `mergeCapsule: manifest contains two entries that resolve to the same target path: ` +\n `\"${firstSourcePath}\" and \"${rec.path}\" both map to \"${rec.path}\"`,\n );\n }\n seenTargetPaths.set(dedupKey, rec.path);\n }\n\n // Detect manifest-only entries (missing record). Treat as corruption.\n for (const f of manifest.files) {\n if (!recordPaths.has(f.path)) {\n throw new Error(\n `mergeCapsule: archive checksum mismatch (manifest entry without record: ${f.path})`,\n );\n }\n }\n\n // ---------------------------------------------------------------------------\n // Phase 2: classify records and apply conflict mode.\n // ---------------------------------------------------------------------------\n\n const merged: MergeCapsuleWrittenRecord[] = [];\n const skipped: MergeCapsuleSkippedRecord[] = [];\n const conflicts: MergeCapsuleConflictRecord[] = [];\n // Same write-boundary rule as capsule-import (issue #2213): records land\n // with their entityRef resolved through the target's migration journal,\n // read through the identity-keyed cache PER RECORD so a peer migration\n // completing mid-merge is picked up for every record written after it.\n const journalStateDir = path.join(rootReal, \"state\");\n const historicalIdCache = new HistoricalEntityCanonicalIdCache();\n // Entity pages in THIS capsule can re-establish collisions the target's\n // journal already resolved (Codex P1): once the next migration parks the\n // mapping, a memory canonicalized onto the canonical claimant is\n // permanently misattributed. Memories whose ref targets a capsule-supplied\n // entity id merge byte-faithful behind the reconcile marker instead.\n const capsuleEntityIds = new Set(\n bundle.records\n .filter((record) =>\n classifyEntityRefWritePath(rootReal, path.join(rootReal, fromPosixRelPath(record.path))) === \"entity\")\n .map((record) => path.basename(record.path, \".md\")),\n );\n // Write a record with its entityRef resolved AT the write, then repair if\n // the journal moved across the write itself — a parked mapping cannot be\n // fixed after the fact by the reconcile pass (issue #2213). Only memory-tier\n // records canonicalize; entities/ pages carry relationship TARGETS only\n // rewriteRelationshipTargets understands, so they merge byte-faithful with\n // a reconcile marker; everything else merges losslessly. The corpus bump\n // lands AFTER the repair so a warm cache rescan never captures pre-repair\n // bytes.\n // The reconcile marker is published ONCE, after every record landed\n // (Codex P1, round 21): a per-record marker could be consumed by a peer\n // between a legacy-preserving memory write and its colliding entity page,\n // canonicalizing the memory onto the wrong claimant irreversibly.\n let reconcileNeeded = false;\n const writeCanonicalRecord = async (targetAbs: string, rawContent: string): Promise<void> => {\n const kind = classifyEntityRefWritePath(rootReal, targetAbs);\n const rawRef = kind === \"memory\" ? readEntityRefFromFrontmatter(rawContent) : null;\n if (kind === \"memory\" && rawRef !== null && capsuleEntityIds.has(rawRef)) {\n // Ref targets a capsule-supplied entity page (potential collision\n // claimant): keep the legacy bytes; the deferred marker lets the\n // migration settle the collision and rewrite per its verdict (Codex P1).\n await writeFile(targetAbs, rawContent, \"utf-8\");\n reconcileNeeded = true;\n bumpMemoryCorpusVersionForDir(rootReal); // per-write bump (Cursor Medium, #1902)\n return;\n }\n if (kind !== \"memory\") {\n await writeFile(targetAbs, rawContent, \"utf-8\");\n if (kind === \"entity\") {\n reconcileNeeded = true;\n }\n bumpMemoryCorpusVersionForDir(rootReal); // per-write bump (Cursor Medium, #1902)\n return;\n }\n const idsAtWrite = historicalIdCache.get(journalStateDir);\n const written = canonicalizeEntityRefFrontmatter(rawContent, idsAtWrite);\n // Snapshot the pre-write bytes: a repair failure after the write must\n // restore them (or remove a newly created target) before propagating —\n // the merge reports failure, so disk must return to its pre-write state\n // and warm caches stay consistent (AGENTS.md §14).\n const originalBytes = await readLocalFile(targetAbs);\n await writeFile(targetAbs, written, \"utf-8\");\n try {\n await repairContentAfterJournalMove({\n stateDir: journalStateDir,\n cache: historicalIdCache,\n idsAtWrite,\n rawContent,\n lastWritten: written,\n rewrite: (content) => writeFile(targetAbs, content, \"utf-8\"),\n });\n } catch (err) {\n if (originalBytes === null) {\n await unlink(targetAbs).catch(() => undefined);\n } else {\n await writeFile(targetAbs, originalBytes, \"utf-8\").catch(() => undefined);\n }\n throw err;\n }\n bumpMemoryCorpusVersionForDir(rootReal); // per-write bump (Cursor Medium, #1902)\n };\n\n // Sort by source path for deterministic output (mirrors capsule-import.ts).\n const sortedRecords = [...bundle.records].sort((a, b) =>\n a.path.localeCompare(b.path),\n );\n\n for (const rec of sortedRecords) {\n const targetAbs = path.join(rootReal, fromPosixRelPath(rec.path));\n const entry = manifestIndex.get(rec.path)!; // validated above\n\n const localContent = await readLocalFile(targetAbs);\n\n if (localContent === null) {\n // No local copy — always write regardless of mode. Resolve at the write\n // itself and verify the journal afterwards: a peer migration completing\n // during any of these awaits (or the write) would otherwise strand the\n // reference — capsule writes bump only the corpus version, which the\n // migration fingerprint deliberately ignores.\n await mkdir(path.dirname(targetAbs), { recursive: true });\n await writeCanonicalRecord(targetAbs, rec.content);\n merged.push({ sourcePath: rec.path, targetPath: rec.path, snapshotted: false });\n continue;\n }\n\n // Local file exists. A local copy already holding the CANONICALIZED form\n // (computed AFTER the local read, so a journal published during that\n // await is reflected) is done. A local copy matching the RAW archive\n // bytes while a mapping applies is UPGRADED in place — skipping would\n // leave the legacy entityRef on disk forever, since corpus bumps no\n // longer trigger migration rewrites (issue #2213).\n const idsAtCompare = historicalIdCache.get(journalStateDir);\n const compareRef = readEntityRefFromFrontmatter(rec.content);\n const canonicalContent =\n classifyEntityRefWritePath(rootReal, targetAbs) === \"memory\"\n && !(compareRef !== null && capsuleEntityIds.has(compareRef))\n ? canonicalizeEntityRefFrontmatter(rec.content, idsAtCompare)\n : rec.content;\n const { sha256: localSha256 } = sha256String(localContent);\n const canonicalSha256 =\n canonicalContent === rec.content ? entry.sha256 : sha256String(canonicalContent).sha256;\n\n // The identical verdict is only valid for the snapshot it was computed\n // under (Codex P1): a mapping parked/removed mid-compare can make the\n // local copy's formerly-canonical ref stale with nothing left to repair\n // it. A moved journal falls through to the write path, which resolves at\n // the write and repairs after it.\n if (localSha256 === canonicalSha256 && historicalIdCache.get(journalStateDir) === idsAtCompare) {\n skipped.push({ path: rec.path, reason: \"identical\" });\n continue;\n }\n if (localSha256 === canonicalSha256 || localSha256 === entry.sha256) {\n await writeCanonicalRecord(targetAbs, rec.content);\n merged.push({ sourcePath: rec.path, targetPath: rec.path, snapshotted: false });\n continue;\n }\n\n // Content differs → conflict.\n const { sha256: archiveSha256 } = sha256String(rec.content);\n conflicts.push({\n path: rec.path,\n archiveSha256,\n localSha256,\n });\n\n if (conflictMode === \"skip-conflicts\" || conflictMode === \"prefer-local\") {\n // Keep local copy, skip archive entry.\n skipped.push({ path: rec.path, reason: \"conflict\" });\n continue;\n }\n\n // conflictMode === \"prefer-source\": snapshot local then overwrite.\n let snapshotted = false;\n if (opts.versioning && opts.versioning.enabled) {\n // Gotcha #54: snapshot BEFORE overwriting.\n await createVersion(\n targetAbs,\n localContent,\n \"manual\",\n opts.versioning,\n opts.log,\n `capsule-merge: ${capsule.id}`,\n rootReal,\n );\n snapshotted = true;\n }\n\n // Same write-time re-resolve + post-write repair as above — the\n // snapshot/read awaits give a peer migration a real window.\n await writeCanonicalRecord(targetAbs, rec.content);\n merged.push({ sourcePath: rec.path, targetPath: rec.path, snapshotted });\n }\n\n // Every record — including every collision claimant entity page — is on\n // disk; NOW the reconcile pass can settle collisions safely.\n if (reconcileNeeded) {\n await requestEntityCanonicalIdReconcile(journalStateDir);\n }\n\n // Sort output lists for determinism.\n merged.sort((a, b) => a.sourcePath.localeCompare(b.sourcePath));\n skipped.sort((a, b) => a.path.localeCompare(b.path));\n conflicts.sort((a, b) => a.path.localeCompare(b.path));\n\n // Per-write corpus bumps happen inside the loop above (Cursor Medium, #1902):\n // a concurrent readAllMemories during the merge rescans and never serves the\n // pre-merge corpus mid-batch.\n\n return { merged, skipped, conflicts, manifest };\n}\n\n// ---------------------------------------------------------------------------\n// Private helpers\n// ---------------------------------------------------------------------------\n\nasync function readLocalFile(absPath: string): Promise<string | null> {\n const st = await stat(absPath).catch(() => null);\n if (!st || !st.isFile()) return null;\n return readFile(absPath, \"utf-8\");\n}\n\n// Re-export CapsuleBlock so callers don't need a deep import from types.ts.\nexport type { CapsuleBlock };\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,OAAO,OAAO,UAAU,UAAU,MAAM,QAAQ,iBAAiB;AAC1E,OAAO,UAAU;AACjB,SAAS,kBAAkB;AAiK3B,eAAsB,aACpB,MAC6B;AAC7B,QAAM,aAAa,KAAK,QAAQ,KAAK,aAAa;AAClD,QAAM,UAAU,KAAK,QAAQ,KAAK,UAAU;AAE5C,QAAM,4BAA4B,SAAS,gBAAgB,YAAY;AAEvE,QAAM,eACJ,KAAK,gBAAgB;AAGvB,MACE,iBAAiB,oBACjB,iBAAiB,mBACjB,iBAAiB,gBACjB;AACA,UAAM,IAAI;AAAA,MACR,sCAAsC,KAAK,UAAU,YAAY,CAAC;AAAA,IAEpE;AAAA,EACF;AAMA,QAAM,MAAM,MAAM,SAAS,UAAU;AACrC,MAAI;AACJ,MAAI;AACF,WAAO,WAAW,GAAG,EAAE,SAAS,OAAO;AAAA,EACzC,SAAS,OAAO;AACd,UAAM,IAAI;AAAA,MACR,mDAAmD,UAAU;AAAA,MAC7D,EAAE,MAAsB;AAAA,IAC1B;AAAA,EACF;AAEA,MAAI;AACJ,MAAI;AACF,iBAAa,KAAK,MAAM,IAAI;AAAA,EAC9B,SAAS,OAAO;AACd,UAAM,IAAI;AAAA,MACR,yDAAyD,UAAU;AAAA,MACnE,EAAE,MAAsB;AAAA,IAC1B;AAAA,EACF;AAEA,QAAM,SAAS,kBAAkB,UAAU;AAC3C,MAAI,OAAO,mBAAmB,GAAG;AAC/B,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AAE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ACV;AAAA,MACA;AAAA,IACF,CAAC;AAED,QAAI,iBAAiB,oBAAoB,iBAAiB,gBAAgB;AAExE,cAAQ,KAAK,EAAE,MAAM,IAAI,MAAM,QAAQ,WAAW,CAAC;AACnD;AAAA,IACF;AAGA,QAAI,cAAc;AAClB,QAAI,KAAK,cAAc,KAAK,WAAW,SAAS;AAE9C,YAAM;AAAA,QACJ;AAAA,QACA;AAAA,QACA;AAAA,QACA,KAAK;AAAA,QACL,KAAK;AAAA,QACL,kBAAkB,QAAQ,EAAE;AAAA,QAC5B;AAAA,MACF;AACA,oBAAc;AAAA,IAChB;AAIA,UAAM,qBAAqB,WAAW,IAAI,OAAO;AACjD,WAAO,KAAK,EAAE,YAAY,IAAI,MAAM,YAAY,IAAI,MAAM,YAAY,CAAC;AAAA,EACzE;AAIA,MAAI,iBAAiB;AACnB,UAAM,kCAAkC,eAAe;AAAA,EACzD;AAGA,SAAO,KAAK,CAAC,GAAG,MAAM,EAAE,WAAW,cAAc,EAAE,UAAU,CAAC;AAC9D,UAAQ,KAAK,CAAC,GAAG,MAAM,EAAE,KAAK,cAAc,EAAE,IAAI,CAAC;AACnD,YAAU,KAAK,CAAC,GAAG,MAAM,EAAE,KAAK,cAAc,EAAE,IAAI,CAAC;AAMrD,SAAO,EAAE,QAAQ,SAAS,WAAW,SAAS;AAChD;AAMA,eAAe,cAAc,SAAyC;AACpE,QAAM,KAAK,MAAM,KAAK,OAAO,EAAE,MAAM,MAAM,IAAI;AAC/C,MAAI,CAAC,MAAM,CAAC,GAAG,OAAO,EAAG,QAAO;AAChC,SAAO,SAAS,SAAS,OAAO;AAClC;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/transfer/capsule-import.ts"],"sourcesContent":["import { lstat, mkdir, readFile, realpath, stat, unlink, writeFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { createHash, randomUUID } from \"node:crypto\";\nimport { gunzipSync } from \"node:zlib\";\nimport { bumpMemoryCorpusVersionForDir } from \"../memory-corpus-version.js\";\nimport {\n HistoricalEntityCanonicalIdCache,\n readEntityRefFromFrontmatter,\n canonicalizeEntityRefFrontmatter,\n classifyEntityRefWritePath,\n repairContentAfterJournalMove,\n requestEntityCanonicalIdReconcile,\n} from \"../storage/entity-canonical-id-references.js\";\nimport {\n createVersion,\n type VersioningConfig,\n type VersioningLogger,\n} from \"../page-versioning.js\";\nimport {\n assertIsDirectoryNotSymlink,\n assertRealpathInsideRoot,\n fromPosixRelPath,\n isPathInsideRoot,\n sha256String,\n} from \"./fs-utils.js\";\nimport {\n parseExportBundle,\n type CapsuleBlock,\n type ExportManifestV2,\n type ExportMemoryRecordV1,\n} from \"./types.js\";\nimport { isEncryptedCapsuleFile, decryptCapsuleFileInMemory } from \"./capsule-crypto.js\";\n\n/**\n * Conflict-resolution mode for {@link importCapsule}. Inverse of the\n * `mode` selector in PR 4/6's CLI surface.\n *\n * - `\"skip\"` (default) — when a target file already exists at the same\n * relative path, leave it untouched. The corresponding record is reported\n * via {@link ImportCapsuleResult.skipped}.\n * - `\"overwrite\"` — when a target file exists, snapshot the prior content\n * via {@link createVersion} (gotcha #54: write-before-delete; gotcha #25:\n * don't destroy old state until new state is confirmed), then write the\n * incoming content. The snapshot's `note` includes the source capsule id.\n * - `\"fork\"` — never overwrite. Every record is rebased under\n * `forks/<capsule-id>/<original-path>` and any YAML-frontmatter `id:`\n * field is rewritten to a new fork-scoped value. The original tree is\n * not touched.\n *\n * The mode is selected once per call and applied uniformly to every record\n * in the bundle. Mixed-mode imports are not supported by design — that\n * would let a single corrupted manifest silently land partial state.\n */\nexport type ImportCapsuleMode = \"skip\" | \"overwrite\" | \"fork\";\n\n/**\n * Options accepted by {@link importCapsule}.\n *\n * `archivePath` — absolute or cwd-relative path to a `.capsule.json.gz`\n * archive produced by `exportCapsule`. The archive must contain a V2\n * bundle (`schemaVersion: 2`); V1 archives are rejected.\n *\n * `root` — absolute or cwd-relative path to the memory directory that\n * will receive the records. Must be an existing directory.\n *\n * `mode` — see {@link ImportCapsuleMode}. Defaults to `\"skip\"`.\n *\n * `versioning` — optional page-versioning config used by `mode: \"overwrite\"`\n * to snapshot prior content before replacing it. Snapshots are skipped when\n * not provided or when `enabled === false`. Tests pass an enabled config\n * to assert snapshot creation; production callers thread the\n * orchestrator's resolved versioning config.\n *\n * `log` — optional logger forwarded to {@link createVersion}.\n *\n * `now` — optional clock override (ms epoch) used to derive deterministic\n * fork ids in tests. Production callers omit this.\n */\nexport interface ImportCapsuleOptions {\n archivePath: string;\n root: string;\n mode?: ImportCapsuleMode;\n versioning?: VersioningConfig;\n log?: VersioningLogger;\n now?: number;\n /**\n * Memory directory whose secure-store keyring is used when the archive is\n * encrypted. Required when `archivePath` ends with `.enc` or when the file\n * starts with the REMNIC-ENC magic header. If `memoryDir` is omitted and the\n * archive turns out to be encrypted, `importCapsule` throws a clear error\n * rather than silently failing.\n *\n * When provided and the archive is NOT encrypted, the value is ignored.\n */\n memoryDir?: string;\n /**\n * Original secure-store passphrase for encrypted format-v2 archives. When\n * supplied, the importer derives the archive key from the embedded KDF\n * header, enabling restore without the source machine's unlocked keyring.\n */\n passphrase?: string;\n}\n\nexport interface ImportCapsuleSkippedRecord {\n /** Original record path (capsule-relative, posix). */\n path: string;\n /**\n * Why this record was not written.\n *\n * `\"exists\"` — the target path already existed and the mode was `\"skip\"`,\n * OR the computed fork path already existed in fork mode.\n *\n * `\"checksum_mismatch\"` is intentionally absent: a checksum failure aborts\n * the import entirely (fail-closed) rather than skipping the offending\n * record, so no `ImportCapsuleSkippedRecord` is ever produced for it.\n */\n reason: \"exists\";\n}\n\nexport interface ImportCapsuleImportedRecord {\n /** Capsule-relative posix path the record carried. */\n sourcePath: string;\n /** Memory-dir-relative posix path the file was written to. */\n targetPath: string;\n /** Whether a prior version snapshot was taken (overwrite-mode only). */\n snapshotted: boolean;\n /** Whether the frontmatter `id:` field was rewritten (fork-mode only). */\n rewroteId: boolean;\n}\n\nexport interface ImportCapsuleResult {\n /** Records that landed on disk. */\n imported: ImportCapsuleImportedRecord[];\n /** Records that were not written. */\n skipped: ImportCapsuleSkippedRecord[];\n /** The manifest decoded from the archive. */\n manifest: ExportManifestV2;\n}\n\n/**\n * Pure async function that imports a capsule archive into a memory\n * directory. Inverse of {@link import(\"./capsule-export.js\").exportCapsule}.\n *\n * Sequence:\n * 1. Read + gunzip + JSON.parse the archive.\n * 2. Validate the bundle through `parseExportBundle` (V1 rejected).\n * 3. Verify each record's content sha256 against the manifest entry.\n * Any mismatch aborts the import BEFORE any file is written —\n * partial-write recovery would require a full rollback we cannot\n * offer cheaply, so we fail closed (gotcha #25).\n * 4. Apply the selected {@link ImportCapsuleMode} to every record.\n *\n * Determinism guarantees:\n * - Imported records are returned sorted by `sourcePath`.\n * - Skipped records are returned sorted by `path`.\n * - Fork-mode rebases under a stable `forks/<capsule-id>/` prefix so\n * repeated fork imports of the same capsule shape land in predictable\n * locations (subsequent fork imports still skip-on-exist because the\n * target tree is computed from the source path).\n */\nexport async function importCapsule(\n opts: ImportCapsuleOptions,\n): Promise<ImportCapsuleResult> {\n const archiveAbs = path.resolve(opts.archivePath);\n const rootAbs = path.resolve(opts.root);\n await assertIsDirectoryNotSymlink(rootAbs, \"importCapsule\", \"root\");\n\n const mode: ImportCapsuleMode = opts.mode ?? \"skip\";\n // Reject unknown mode values up-front (rule 51). TypeScript callers get a\n // compile-time check via the union type; JS/CLI callers get a runtime error\n // here before any write begins — not a silent destructive fallback.\n if (mode !== \"skip\" && mode !== \"overwrite\" && mode !== \"fork\") {\n throw new Error(\n `importCapsule: unknown mode ${JSON.stringify(mode)}; expected \"skip\", \"overwrite\", or \"fork\"`,\n );\n }\n\n // Auto-detect encrypted archives. If the file ends with `.enc` or starts\n // with the REMNIC-ENC magic header, decrypt it first before gunzip+parse.\n // Rule 48: default is \"not encrypted\"; we only attempt decryption when the\n // header is definitively present, never on ambiguous content.\n const encrypted = await isEncryptedCapsuleFile(archiveAbs);\n let raw: Buffer;\n if (encrypted) {\n if (!opts.memoryDir && !opts.passphrase) {\n throw new Error(\n `importCapsule: archive is encrypted but 'memoryDir' was not provided. ` +\n `Pass the memory directory so the secure-store key can be retrieved, ` +\n `provide the original passphrase for a format-v2 archive restore, ` +\n `or run \\`remnic secure-store unlock\\` before importing.`,\n );\n }\n raw = await decryptCapsuleFileInMemory(archiveAbs, opts.memoryDir, {\n passphrase: opts.passphrase,\n });\n } else {\n raw = await readFile(archiveAbs);\n }\n const json = gunzipSync(raw).toString(\"utf-8\");\n let parsedJson: unknown;\n try {\n parsedJson = JSON.parse(json);\n } catch (cause) {\n throw new Error(\n `importCapsule: archive is not valid JSON after gunzip: ${archiveAbs}`,\n { cause: cause as Error },\n );\n }\n\n const parsed = parseExportBundle(parsedJson);\n if (parsed.capsuleVersion !== 2) {\n // PR 1/6 ships a V1 reader; capsule import is V2-only by design. A V1\n // bundle does not carry a capsule block, so fork-mode (which depends on\n // `capsule.id` for the rebase prefix) cannot work. Reject up-front per\n // gotcha #51 instead of silently routing to a different code path.\n throw new Error(\n \"importCapsule: archive is V1; only V2 capsule archives are supported\",\n );\n }\n const bundle = parsed.bundle as { manifest: ExportManifestV2; records: ExportMemoryRecordV1[] };\n const manifest = bundle.manifest;\n const capsule = manifest.capsule;\n\n // Build a path → manifest-entry index for O(1) checksum lookup. The\n // manifest is the source of truth; records-without-manifest-entries and\n // manifest-entries-without-records are both treated as corruption.\n const manifestIndex = new Map<string, ExportManifestV2[\"files\"][number]>();\n for (const f of manifest.files) {\n manifestIndex.set(f.path, f);\n }\n if (manifestIndex.size !== manifest.files.length) {\n throw new Error(\n \"importCapsule: manifest contains duplicate file paths\",\n );\n }\n const recordPaths = new Set<string>();\n for (const rec of bundle.records) {\n if (recordPaths.has(rec.path)) {\n throw new Error(\n `importCapsule: bundle contains duplicate record path: ${rec.path}`,\n );\n }\n recordPaths.add(rec.path);\n }\n\n // Phase 1: verify every record matches its manifest entry AND validate all\n // target paths before any filesystem mutation. We do both in a single pass\n // so a corrupted or malicious archive cannot leave the memory dir partially\n // written (fail-closed per gotcha #25).\n //\n // The real root is resolved once via realpath so the subsequent per-record\n // inside-root checks are symlink-aware: a record path like `facts/a.md`\n // cannot write outside the intended sandbox via a symlinked subdirectory\n // (Codex P1 feedback). If realpath fails (root does not exist) the earlier\n // assertIsDirectoryNotSymlink call already threw, so this should always succeed.\n const rootReal = await realpath(rootAbs).catch(() => rootAbs);\n\n // Tracks normalized, case-folded target paths seen so far in phase 1. Maps\n // targetAbs.toLowerCase() → first source path so the collision error can name\n // both offending entries. Two manifest entries whose computed target paths\n // normalize to the same absolute path (e.g. `subdir/file.md` and\n // `subdir/./file.md`, or differing case on case-insensitive filesystems such\n // as macOS and Windows) would both try to write the same inode — the second\n // would silently overwrite the first. We reject the import up-front before\n // any write (Codex P2 thread on PR #741, line 283).\n const seenTargetPaths = new Map<string, string>();\n\n for (const rec of bundle.records) {\n // Checksum validation.\n const entry = manifestIndex.get(rec.path);\n if (!entry) {\n throw new Error(\n `importCapsule: archive checksum mismatch (record without manifest entry: ${rec.path})`,\n );\n }\n const { sha256, bytes } = sha256String(rec.content);\n if (sha256 !== entry.sha256 || bytes !== entry.bytes) {\n throw new Error(\n `importCapsule: archive checksum mismatch for ${rec.path}: ` +\n `expected sha256=${entry.sha256} bytes=${entry.bytes}, ` +\n `got sha256=${sha256} bytes=${bytes}`,\n );\n }\n\n // Source path validation: reject any record whose posix source path\n // contains a `..` segment, an absolute prefix, or any component that would\n // let fork-mode bypass its isolation invariant. This check runs before\n // `computeTargetPath` so that fork mode's `forks/<id>/` rebase cannot be\n // bypassed by a path like `../../profile.md` (which `path.join` would\n // silently collapse, landing the file inside root but outside the fork\n // prefix — Cursor medium thread #741). Rejecting `..` up-front is simpler\n // and more robust than normalising after the fact.\n //\n // Extended guard (Codex P1 #741 round 5): also reject paths containing\n // backslash separators (`\\`), which are Windows path separators. On Windows\n // a path like `..\\\\escape.md` or `subdir\\\\..\\\\..\\\\escape.md` would resolve\n // to a parent traversal but would bypass a purely posix-split check.\n // Additionally, after posix-normalizing the path we re-check for a leading\n // `..` or `/` — this catches edge-cases such as `subdir/../..` where the\n // individual split segments are not `..` but the normalized result is.\n if (rec.path.includes(\"\\\\\")) {\n throw new Error(\n `importCapsule: record path contains backslash separators (Windows-style paths are not allowed): ${rec.path}`,\n );\n }\n const posixNormalized = path.posix.normalize(rec.path);\n if (\n rec.path.startsWith(\"/\") ||\n rec.path.split(\"/\").some((seg) => seg === \"..\") ||\n posixNormalized.startsWith(\"..\") ||\n posixNormalized.startsWith(\"/\")\n ) {\n throw new Error(\n `importCapsule: record path escapes target root: ${rec.path}`,\n );\n }\n\n // Path-traversal validation (moved here from phase 2 per Cursor feedback:\n // the traversal check must run before ANY write so a malicious archive\n // with an escaping path that sorts last cannot land partial writes).\n //\n // We build targetAbs relative to the real-resolved root (rootReal) so\n // that the inside-root check is symlink-aware: if `rootReal !== rootAbs`\n // (the import root is itself behind a symlink), we still compare against\n // the canonical path (Codex P1).\n const targetRel = computeTargetPath(rec.path, mode, capsule.id);\n const targetAbs = path.join(rootReal, fromPosixRelPath(targetRel));\n if (!isPathInsideRoot(rootReal, targetAbs)) {\n throw new Error(\n `importCapsule: record path escapes target root: ${rec.path}`,\n );\n }\n\n // Symlink-aware containment check (Cursor thread #741 line 247/264).\n // The lexical check above handles `..`-traversal but cannot detect\n // symlinked subdirectories that point outside the root. We resolve the\n // nearest existing ancestor of the target via realpath to catch symlinks\n // anywhere in the path components. If any resolved prefix escapes rootReal,\n // the import is rejected before any write. This applies to ALL modes,\n // including fork mode whose rebase prefix may itself traverse a symlink.\n await assertRealpathInsideRoot(rootReal, targetAbs, rec.path, \"importCapsule\");\n\n // Target-file symlink check (Codex P1 #741 round 4, line 260).\n // `assertRealpathInsideRoot` resolves the nearest existing *ancestor* to\n // catch symlinked parent directories, but if the TARGET FILE itself already\n // exists and is a symlink, that check passes (the parent is real) while the\n // write would silently follow the symlink to a path outside root. We\n // therefore lstat the target directly: if it exists and is a symlink we\n // reject the record up-front. For new files the parent-canonicalization\n // performed above is sufficient; no realpath of a non-existent file is\n // needed.\n const targetLstat = await lstat(targetAbs).catch(() => null);\n if (targetLstat !== null && targetLstat.isSymbolicLink()) {\n throw new Error(\n `importCapsule: record target is a symlink and cannot be written to safely: ${rec.path}`,\n );\n }\n\n // Duplicate normalized target path detection (Codex P2 #741, line 283).\n // `path.join` already normalises `.` segments (e.g. `subdir/./file.md` →\n // `subdir/file.md`). On case-insensitive filesystems (macOS default,\n // Windows), two paths that differ only in case would resolve to the same\n // inode. We fold the dedup key to lowercase so that `subdir/File.md` and\n // `subdir/file.md` are detected as duplicates before any write occurs.\n // This is intentionally unconditional: the cost of an extra `.toLowerCase()`\n // on case-sensitive filesystems is negligible, and a defensive lowercase\n // is far simpler than probing filesystem case-sensitivity at runtime.\n const dedupKey = targetAbs.toLowerCase();\n const firstSourcePath = seenTargetPaths.get(dedupKey);\n if (firstSourcePath !== undefined) {\n throw new Error(\n `importCapsule: manifest contains two entries that resolve to the same target path: ` +\n `\"${firstSourcePath}\" and \"${rec.path}\" both map to \"${targetRel}\"`,\n );\n }\n seenTargetPaths.set(dedupKey, rec.path);\n }\n // Detect manifest-only entries (missing record). Treat as corruption.\n for (const f of manifest.files) {\n if (!recordPaths.has(f.path)) {\n throw new Error(\n `importCapsule: archive checksum mismatch (manifest entry without record: ${f.path})`,\n );\n }\n }\n\n // Phase 2: apply the mode. All records were validated in phase 1; we now\n // write to disk. Per-record errors propagate; each individual write is\n // atomic (mkdir + writeFile pair).\n const imported: ImportCapsuleImportedRecord[] = [];\n const skipped: ImportCapsuleSkippedRecord[] = [];\n // The target's completed migration journal is a write boundary here too\n // (issue #2213): a capsule can carry pre-migration memories whose entityRef\n // the target already renamed, and no recurring reconciliation pass exists\n // to absorb a stale ref after the fact. Read through the identity-keyed\n // cache PER RECORD so a peer migration completing mid-import is picked up\n // for every record written after it (one lstat per record).\n const journalStateDir = path.join(rootReal, \"state\");\n const historicalIdCache = new HistoricalEntityCanonicalIdCache();\n // Entity pages in THIS capsule can re-establish collisions the target's\n // journal already resolved (Codex P1): once the next migration parks the\n // mapping, a memory canonicalized onto the canonical claimant is\n // permanently misattributed. Memories whose ref targets a capsule-supplied\n // entity id import byte-faithful behind the reconcile marker instead; the\n // migration settles the collision and rewrites references per its verdict.\n const capsuleEntityIds = new Set(\n bundle.records\n .map((record) => computeTargetPath(record.path, mode, capsule.id))\n .filter((rel) => classifyEntityRefWritePath(rootReal, path.join(rootReal, fromPosixRelPath(rel))) === \"entity\")\n .map((rel) => path.basename(rel, \".md\")),\n );\n\n // Sort by source path so the imported/skipped lists are deterministic\n // regardless of bundle order. (`exportCapsule` already sorts; we re-sort\n // defensively in case a hand-edited archive ships records in another order.)\n const sortedRecords = [...bundle.records].sort((a, b) =>\n a.path.localeCompare(b.path),\n );\n\n // The reconcile marker is published ONCE, after every record landed\n // (Codex P1, round 21): a per-record marker could be consumed by a peer\n // between a legacy-preserving memory write and its colliding entity page,\n // canonicalizing the memory onto the wrong claimant irreversibly.\n let reconcileNeeded = false;\n for (const rec of sortedRecords) {\n const targetRel = computeTargetPath(rec.path, mode, capsule.id);\n // Use rootReal (realpath-resolved) to stay consistent with phase 1's\n // traversal validation and avoid writing through stale symlinks.\n const targetAbs = path.join(rootReal, fromPosixRelPath(targetRel));\n\n const exists = await fileExistsAt(targetAbs);\n\n // Skip logic applies to both `skip` mode (explicit) and `fork` mode\n // (Cursor medium: fork mode must also be skip-on-exist for the computed\n // fork path, because production imports generate non-deterministic IDs —\n // so re-importing the same capsule should not overwrite user edits in the\n // fork tree or silently change file identities by generating new IDs).\n if ((mode === \"skip\" || mode === \"fork\") && exists) {\n skipped.push({ path: rec.path, reason: \"exists\" });\n continue;\n }\n\n let snapshotted = false;\n if (mode === \"overwrite\" && exists) {\n // Gotcha #54: snapshot BEFORE overwriting. If snapshot creation fails\n // we abort this record's import rather than silently destroying\n // history. The page-versioning module is responsible for atomic\n // sidecar writes; we just call it.\n if (opts.versioning && opts.versioning.enabled) {\n const prior = await readFile(targetAbs, \"utf-8\").catch(() => \"\");\n await createVersion(\n targetAbs,\n prior,\n \"manual\",\n opts.versioning,\n opts.log,\n `capsule-import: ${capsule.id}`,\n rootReal,\n );\n snapshotted = true;\n }\n }\n\n let contentToWrite = rec.content;\n let rewroteId = false;\n if (mode === \"fork\") {\n const forked = rewriteFrontmatterIdForFork(contentToWrite, capsule.id, opts.now);\n contentToWrite = forked.content;\n rewroteId = forked.rewrote;\n }\n\n await mkdir(path.dirname(targetAbs), { recursive: true });\n // Resolve at the write itself (mirrors capsule-merge): a peer migration\n // can complete during the snapshot/mkdir awaits, and capsule writes bump\n // only the corpus version, which the migration fingerprint ignores. The\n // post-write REPAIR re-canonicalizes and rewrites when the journal moved\n // across the write itself (a parked mapping cannot be fixed after the\n // fact by the reconcile pass). Only memory-tier records canonicalize;\n // entities/ pages carry relationship TARGETS only\n // rewriteRelationshipTargets understands, so they import byte-faithful\n // with a reconcile marker; everything else imports losslessly.\n const targetKind = classifyEntityRefWritePath(rootReal, targetAbs);\n const rawRef = targetKind === \"memory\" ? readEntityRefFromFrontmatter(contentToWrite) : null;\n if (targetKind === \"memory\" && rawRef !== null && capsuleEntityIds.has(rawRef)) {\n // Ref targets a capsule-supplied entity page (potential collision\n // claimant): keep the legacy bytes; the DEFERRED marker below lets the\n // migration settle the collision and rewrite per its verdict (Codex P1).\n await writeFile(targetAbs, contentToWrite, \"utf-8\");\n reconcileNeeded = true;\n } else if (targetKind === \"memory\") {\n const idsAtWrite = historicalIdCache.get(journalStateDir);\n const rawRecord = contentToWrite;\n contentToWrite = canonicalizeEntityRefFrontmatter(rawRecord, idsAtWrite);\n // Snapshot the pre-write bytes: a repair failure after the write must\n // restore them (or remove a newly created target), or the import\n // reports failure while an overwrite already destroyed the prior state\n // and the skipped corpus bump leaves warm caches stale (AGENTS.md §14).\n const originalBytes = await readFile(targetAbs, \"utf-8\").catch(() => null);\n await writeFile(targetAbs, contentToWrite, \"utf-8\");\n try {\n await repairContentAfterJournalMove({\n stateDir: journalStateDir,\n cache: historicalIdCache,\n idsAtWrite,\n rawContent: rawRecord,\n lastWritten: contentToWrite,\n rewrite: (content) => writeFile(targetAbs, content, \"utf-8\"),\n });\n } catch (err) {\n if (originalBytes === null) {\n await unlink(targetAbs).catch(() => undefined);\n } else {\n await writeFile(targetAbs, originalBytes, \"utf-8\").catch(() => undefined);\n }\n throw err;\n }\n } else {\n await writeFile(targetAbs, contentToWrite, \"utf-8\");\n if (targetKind === \"entity\") {\n reconcileNeeded = true;\n }\n }\n // Bump the corpus sentinel per write (Cursor Medium, #1902): a concurrent\n // readAllMemories during the import must rescan and see records already on\n // disk, never the pre-import corpus, mid-batch.\n bumpMemoryCorpusVersionForDir(rootReal);\n imported.push({\n sourcePath: rec.path,\n targetPath: targetRel,\n snapshotted,\n rewroteId,\n });\n }\n\n // Every record — including every collision claimant entity page — is on\n // disk; NOW the reconcile pass can settle collisions safely.\n if (reconcileNeeded) {\n await requestEntityCanonicalIdReconcile(journalStateDir);\n }\n\n // Sort skipped for stable output (see comment above).\n skipped.sort((a, b) => a.path.localeCompare(b.path));\n\n // Per-record corpus bumps happen inside the loop above (Cursor Medium,\n // #1902); no after-batch bump needed here.\n\n return { imported, skipped, manifest };\n}\n\n// ---------------------------------------------------------------------------\n// Path helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Compute the destination relative path for a record under the chosen\n * mode.\n *\n * - `skip` / `overwrite` — identity: the record's posix path is used as-is.\n * - `fork` — rebased under `forks/<capsule-id>/<original-path>` so the\n * original tree is never modified.\n */\nfunction computeTargetPath(\n sourcePosix: string,\n mode: ImportCapsuleMode,\n capsuleId: string,\n): string {\n if (mode === \"fork\") return `forks/${capsuleId}/${sourcePosix}`;\n return sourcePosix;\n}\n\nasync function fileExistsAt(absPath: string): Promise<boolean> {\n const st = await stat(absPath).catch(() => null);\n return st !== null && st.isFile();\n}\n\n// ---------------------------------------------------------------------------\n// Fork-mode id rewriting\n// ---------------------------------------------------------------------------\n\n/**\n * Rewrite a YAML-frontmatter `id:` field to a fork-scoped value.\n *\n * Strategy: we deliberately do NOT parse the entire YAML — memory files\n * use a deterministic top-of-file frontmatter delimited by `---` lines,\n * and the orchestrator's `parseFrontmatter` reads `id` as a top-level\n * key with a single-line scalar value. We mirror that contract:\n *\n * - Detect a leading `---\\n` … `\\n---` block at the top of the file.\n * - Within that block, locate the first `id:` line that is not nested\n * under another key (cheap heuristic: line starts at column 0).\n * - Replace its value with a new fork-id derived from `capsuleId` and\n * a short random suffix (or {@link opts.now} when provided for tests).\n *\n * Files without a frontmatter block, or without an `id:` key inside one,\n * are returned unchanged with `rewrote: false`. This keeps non-memory\n * artifacts (READMEs, transcripts) byte-identical to the source.\n */\nfunction rewriteFrontmatterIdForFork(\n content: string,\n capsuleId: string,\n now: number | undefined,\n): { content: string; rewrote: boolean } {\n // Detect the dominant line ending in the file so we can preserve it when\n // rebuilding the frontmatter delimiters. Splitting/joining on `\\n` silently\n // drops `\\r` from CRLF files, changing the byte content (Cursor thread #741\n // line 467). We detect the ending of the very first line (the opening `---`)\n // and use that as the canonical separator for the reconstructed delimiters.\n // All three cases are covered: CRLF (\\r\\n), LF (\\n), and bare CR (\\r).\n const crlfMatch = /^---(\\r\\n|\\r|\\n)/.exec(content);\n // Fall back to LF if the file starts with `---` but has no newline (EOF).\n const eol = crlfMatch ? crlfMatch[1] : \"\\n\";\n\n // Frontmatter block detection: `---` on its own line at the very start,\n // followed by content, followed by `---` on its own line. The closing\n // delimiter must be at column 0. We capture the trailing terminator\n // (`\\r?\\n` or end-of-string) as a separate group so we can re-emit it\n // verbatim, preserving CRLF/LF/EOF shape from the original file.\n const fmMatch = /^---\\r?\\n([\\s\\S]*?)\\r?\\n---(\\r?\\n|$)/.exec(content);\n if (!fmMatch) return { content, rewrote: false };\n const fmBody = fmMatch[1];\n const fmTrailer = fmMatch[2];\n const fmStart = fmMatch.index;\n const fmEnd = fmStart + fmMatch[0].length;\n\n // Find a top-level `id:` line. Top-level means the line begins at\n // column 0 inside the frontmatter body (no leading whitespace) and the\n // key is exactly `id`. We deliberately accept `id:` and `id : ` shapes\n // but reject `nested_id:` to avoid touching unrelated keys.\n const idLineRe = /^id:[ \\t]*([^\\r\\n]*)$/m;\n const idMatch = idLineRe.exec(fmBody);\n if (!idMatch) return { content, rewrote: false };\n\n const newId = mintForkId(capsuleId, idMatch[1]?.trim() ?? \"\", now);\n const replacedBody = fmBody.replace(idLineRe, `id: ${newId}`);\n // Reconstruct the file: original prefix (always empty here, fmStart === 0\n // by the `^` anchor) + frontmatter delimiters around the rewritten body.\n // Use the detected `eol` for the opening/closing `---` lines so that CRLF\n // files remain CRLF and LF files remain LF, preserving byte-content fidelity\n // (Cursor thread #741 line 467). The captured `fmTrailer` (the newline\n // immediately after the closing `---`, or end-of-string) is re-emitted\n // verbatim so the byte immediately after the closing fence is unchanged.\n const prefix = content.slice(0, fmStart);\n const tail = content.slice(fmEnd);\n const rebuilt = `${prefix}---${eol}${replacedBody}${eol}---${fmTrailer}${tail}`;\n return { content: rebuilt, rewrote: true };\n}\n\n/**\n * Derive a deterministic-when-`now`-is-set fork id from the capsule id and\n * the original record id. Production callers omit `now` and get a UUID\n * suffix; tests pass `now` for byte-stable assertions.\n */\nfunction mintForkId(capsuleId: string, originalId: string, now: number | undefined): string {\n const base = originalId.length > 0 ? originalId : \"fork\";\n if (now === undefined) {\n const suffix = randomUUID().slice(0, 8);\n return `${base}-fork-${capsuleId}-${suffix}`;\n }\n // Deterministic suffix: short hash of (capsuleId, originalId, now). Using\n // sha256 over a sorted-key serialization (gotcha #38) so the suffix does\n // not depend on Object.entries order.\n const payload = JSON.stringify({ c: capsuleId, i: originalId, n: now });\n const suffix = createHash(\"sha256\").update(payload, \"utf-8\").digest(\"hex\").slice(0, 8);\n return `${base}-fork-${capsuleId}-${suffix}`;\n}\n\n// Note: `CapsuleBlock` is re-exported here purely so callers that want to\n// inspect the manifest block don't have to deep-import from `./types.js`.\nexport type { Capsule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AAAA,EAC5C;AAIA,QAAM,UAAU,KAAK,UAAU,EAAE,GAAG,WAAW,GAAG,YAAY,GAAG,IAAI,CAAC;AACtE,QAAM,SAAS,WAAW,QAAQ,EAAE,OAAO,SAAS,OAAO,EAAE,OAAO,KAAK,EAAE,MAAM,GAAG,CAAC;AACrF,SAAO,GAAG,IAAI,SAAS,SAAS,IAAI,MAAM;AAC5C;","names":["suffix"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/recall-explain-renderer.ts","../src/recall-xray-renderer.ts"],"sourcesContent":["/**\n * Renderers for RecallTierExplain (issue #518).\n *\n * Pure functions that format a `LastRecallSnapshot` and its\n * optional `tierExplain` field for human text and machine JSON\n * consumption. CLI / HTTP / MCP surfaces consume these — they do\n * not format explain output themselves, so rendering is tested in\n * one place.\n */\n\nimport type { LastRecallSnapshot } from \"./recall-state.js\";\nimport type { RecallTierExplain } from \"./types.js\";\nimport { isRetrievalTier } from \"./retrieval-tiers.js\";\nimport type {\n RecallXraySnapshot,\n RecallFilterTrace,\n RecallXrayResult,\n} from \"./recall-xray.js\";\nimport { renderXrayMarkdown } from \"./recall-xray-renderer.js\";\n\nfunction sanitizeString(v: unknown): string | null {\n return typeof v === \"string\" && v.length > 0 ? v : null;\n}\n\nfunction sanitizeFiniteNumber(v: unknown): number | null {\n return typeof v === \"number\" && Number.isFinite(v) ? v : null;\n}\n\n/**\n * `text` and `json` are the original formats (backwards-compatible\n * since issue #518). `markdown` was added in issue #570 PR 7 and\n * delegates to the shared X-ray renderer so the three observability\n * surfaces stay in lock-step (CLAUDE.md rule 22).\n */\nexport type RecallExplainFormat = \"text\" | \"json\" | \"markdown\";\n\nexport interface RecallExplainJsonPayload {\n hasExplain: boolean;\n snapshotFound: boolean;\n sessionKey: string | null;\n recordedAt: string | null;\n namespace: string | null;\n memoryIds: string[];\n source: string | null;\n sourcesUsed: string[] | null;\n latencyMs: number | null;\n tierExplain: RecallTierExplain | null;\n}\n\nfunction normalizeTierExplain(value: unknown): RecallTierExplain | null {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return null;\n const raw = value as Record<string, unknown>;\n const filteredBy = Array.isArray(raw.filteredBy)\n ? raw.filteredBy.filter((x): x is string => typeof x === \"string\")\n : [];\n const sourceAnchors = Array.isArray(raw.sourceAnchors)\n ? raw.sourceAnchors\n .filter(\n (a): a is { path: string; lineRange?: unknown } =>\n !!a && typeof a === \"object\" && typeof (a as { path?: unknown }).path === \"string\",\n )\n .map((a) => {\n const lr = (a as { lineRange?: unknown }).lineRange;\n const lineRange =\n Array.isArray(lr) &&\n lr.length === 2 &&\n Number.isFinite(lr[0]) &&\n Number.isFinite(lr[1])\n ? ([lr[0] as number, lr[1] as number] as [number, number])\n : undefined;\n return lineRange\n ? { path: (a as { path: string }).path, lineRange }\n : { path: (a as { path: string }).path };\n })\n : undefined;\n return {\n tier: isRetrievalTier(raw.tier) ? raw.tier : \"hybrid\",\n tierReason: typeof raw.tierReason === \"string\" ? raw.tierReason : \"\",\n filteredBy,\n candidatesConsidered: sanitizeFiniteNumber(raw.candidatesConsidered) ?? 0,\n latencyMs: sanitizeFiniteNumber(raw.latencyMs) ?? 0,\n ...(sourceAnchors !== undefined ? { sourceAnchors } : {}),\n };\n}\n\nexport function toRecallExplainJson(\n snapshot: LastRecallSnapshot | null,\n): RecallExplainJsonPayload {\n if (!snapshot) {\n return {\n hasExplain: false,\n snapshotFound: false,\n sessionKey: null,\n recordedAt: null,\n namespace: null,\n memoryIds: [],\n source: null,\n sourcesUsed: null,\n latencyMs: null,\n tierExplain: null,\n };\n }\n const normalizedExplain = normalizeTierExplain(snapshot.tierExplain);\n return {\n hasExplain: normalizedExplain !== null,\n snapshotFound: true,\n sessionKey: sanitizeString(snapshot.sessionKey),\n recordedAt: sanitizeString(snapshot.recordedAt),\n namespace: sanitizeString(snapshot.namespace),\n memoryIds: Array.isArray(snapshot.memoryIds)\n ? snapshot.memoryIds.filter((x): x is string => typeof x === \"string\")\n : [],\n source: sanitizeString(snapshot.source),\n sourcesUsed: Array.isArray(snapshot.sourcesUsed)\n ? snapshot.sourcesUsed.filter((x): x is string => typeof x === \"string\")\n : null,\n latencyMs: sanitizeFiniteNumber(snapshot.latencyMs),\n tierExplain: normalizedExplain,\n };\n}\n\n/**\n * Render the shared \"--- tier explain ---\" text block used by both the\n * recall-explain surface and the Recall X-ray surface. Callers provide\n * the normalized `RecallTierExplain` (or `null` for the\n * not-populated/disabled case) so the block stays character-for-character\n * identical across surfaces (CLAUDE.md rule 22). The returned strings do\n * NOT include leading blank lines or headers — callers own that framing.\n */\nexport function renderTierExplainTextLines(\n tierExplain: RecallTierExplain | null,\n): string[] {\n const lines: string[] = [];\n if (!tierExplain) {\n lines.push(\n \"(not populated — direct-answer tier disabled or did not fire)\",\n );\n return lines;\n }\n lines.push(`tier: ${tierExplain.tier}`);\n lines.push(`reason: ${tierExplain.tierReason}`);\n lines.push(`candidates-considered: ${tierExplain.candidatesConsidered}`);\n lines.push(`latency-ms: ${tierExplain.latencyMs}`);\n if (tierExplain.filteredBy.length > 0) {\n lines.push(`filtered-by: ${tierExplain.filteredBy.join(\", \")}`);\n } else {\n lines.push(\"filtered-by: (none)\");\n }\n if (tierExplain.sourceAnchors && tierExplain.sourceAnchors.length > 0) {\n lines.push(\"source-anchors:\");\n for (const anchor of tierExplain.sourceAnchors) {\n const range = anchor.lineRange\n ? `:${anchor.lineRange[0]}-${anchor.lineRange[1]}`\n : \"\";\n lines.push(` - ${anchor.path}${range}`);\n }\n }\n return lines;\n}\n\nexport function toRecallExplainText(\n snapshot: LastRecallSnapshot | null,\n): string {\n const lines: string[] = [\"=== Recall Explain ===\"];\n\n if (!snapshot) {\n lines.push(\"No recall snapshot recorded yet.\");\n return lines.join(\"\\n\");\n }\n\n const sessionKey = sanitizeString(snapshot.sessionKey);\n const recordedAt = sanitizeString(snapshot.recordedAt);\n const namespace = sanitizeString(snapshot.namespace);\n const source = sanitizeString(snapshot.source);\n lines.push(`session: ${sessionKey ?? \"(unknown)\"}`);\n lines.push(`recorded: ${recordedAt ?? \"(unknown)\"}`);\n if (namespace) lines.push(`namespace: ${namespace}`);\n if (source) lines.push(`source: ${source}`);\n const sourcesUsed = Array.isArray(snapshot.sourcesUsed)\n ? snapshot.sourcesUsed.filter((x): x is string => typeof x === \"string\")\n : [];\n if (sourcesUsed.length > 0) {\n lines.push(`sources-used: ${sourcesUsed.join(\", \")}`);\n }\n const latencyMs = sanitizeFiniteNumber(snapshot.latencyMs);\n if (latencyMs !== null) {\n lines.push(`latency-ms: ${latencyMs}`);\n }\n const memoryIds = Array.isArray(snapshot.memoryIds)\n ? snapshot.memoryIds.filter((x): x is string => typeof x === \"string\")\n : [];\n if (memoryIds.length > 0) {\n lines.push(`memories: ${memoryIds.join(\", \")}`);\n }\n\n const ex = normalizeTierExplain(snapshot.tierExplain);\n if (!ex) {\n lines.push(\"\");\n lines.push(\n \"tier-explain: (not populated — direct-answer tier disabled or did not fire)\",\n );\n return lines.join(\"\\n\");\n }\n\n lines.push(\"\");\n lines.push(\"--- tier explain ---\");\n for (const line of renderTierExplainTextLines(ex)) {\n lines.push(line);\n }\n return lines.join(\"\\n\");\n}\n\n/**\n * Adapter: convert a `LastRecallSnapshot` into a best-effort\n * `RecallXraySnapshot` so the markdown renderer can produce a\n * consistent, richly-formatted document for callers that have asked\n * for `markdown` format. The LastRecallSnapshot and the X-ray\n * snapshot share session/namespace/memoryIds; additional X-ray-only\n * fields (filters, score decomposition, graph path, audit id) are\n * left empty because the legacy snapshot doesn't carry them. The\n * renderer handles missing fields gracefully.\n */\n/**\n * Strip backticks, pipes, and newlines from a host-provided value so it\n * cannot escape its enclosing markdown code span, break the surrounding\n * table row, or inject extra rows when it lands in\n * `renderXrayMarkdown`. Applied at the adapter boundary because\n * `LastRecallSnapshot` is hydrated from on-disk JSON without schema\n * validation (codex P2 review on #605).\n *\n * Accepts `unknown` so non-string truthy values (numbers, objects,\n * booleans, arrays) coming from a corrupted snapshot are coerced to\n * the empty string rather than crashing on `.replace(...)`. Callers\n * should treat an empty return as \"drop this field.\"\n */\nfunction sanitizeForMarkdownInline(value: unknown): string {\n if (typeof value !== \"string\") return \"\";\n return value.replace(/[`|\\r\\n]/g, \" \").trim();\n}\n\n/**\n * Map the legacy `LastRecallSnapshot.source` field to the\n * `RecallXrayServedBy` union used by the unified x-ray renderer.\n * Mirrors the `mapRecallSourceToXrayServedBy` helper inside\n * `orchestrator.ts` (which is private). Keep the two in sync when a\n * new source lands — unknown values collapse to `\"hybrid\"` to preserve\n * backwards compatibility with older on-disk snapshots.\n */\nfunction mapLegacySourceToServedBy(\n source: unknown,\n): \"hybrid\" | \"recent-scan\" {\n if (source === \"recent_scan\") return \"recent-scan\";\n return \"hybrid\";\n}\n\nexport function toRecallXraySnapshotFromLegacy(\n snapshot: LastRecallSnapshot | null,\n): RecallXraySnapshot | null {\n if (!snapshot) return null;\n const capturedAt = (() => {\n if (typeof snapshot.recordedAt !== \"string\") return 0;\n const ms = Date.parse(snapshot.recordedAt);\n return Number.isFinite(ms) && ms >= 0 ? ms : 0;\n })();\n const memoryIds = Array.isArray(snapshot.memoryIds)\n ? snapshot.memoryIds.filter((x): x is string => typeof x === \"string\")\n : [];\n // Codex P2 + Cursor Medium on #605: every converted result used to\n // be stamped with `servedBy: \"hybrid\"`, misattributing legacy\n // snapshots that came from `recent_scan` (or any future source).\n // Propagate the recorded `source` so markdown `recall-explain`\n // output matches the `served-by=` string the native x-ray capture\n // would emit for the same recall.\n const servedBy = mapLegacySourceToServedBy(snapshot.source);\n const results: RecallXrayResult[] = memoryIds.map((memoryId) => ({\n memoryId,\n path: \"\",\n servedBy,\n scoreDecomposition: { final: 0 },\n admittedBy: [],\n }));\n const filters: RecallFilterTrace[] = [];\n return {\n schemaVersion: \"1\",\n // `LastRecallSnapshot` does not preserve the original query text;\n // synthesize a placeholder so the renderer has a non-empty\n // string to print. `queryHash` + `queryLen` stay in the JSON\n // payload via `toRecallExplainJson` for callers that need them.\n query:\n snapshot.queryHash\n ? `(legacy explain; queryHash=${snapshot.queryHash})`\n : \"(legacy explain)\",\n // `snapshotId` is synthesized here; `sessionKey` is already\n // sanitized before it reaches the ID because we re-use the\n // sanitized string below.\n snapshotId: `legacy-${sanitizeForMarkdownInline(snapshot.sessionKey ?? \"unknown\") || \"unknown\"}-${capturedAt}`,\n capturedAt,\n // Run the raw on-disk value through the same normalizer the text\n // and JSON paths use so the markdown adapter cannot render\n // unvalidated tier-explain payloads (cursor / codex review on\n // #605). A malformed tierExplain is dropped to null, matching the\n // behavior of the non-markdown surfaces.\n tierExplain: normalizeTierExplain(snapshot.tierExplain) ?? null,\n results,\n filters,\n budget: { chars: 0, used: 0 },\n // Sanitize legacy session metadata at the adapter boundary so a\n // malformed on-disk value (containing backticks, pipes, or\n // newlines) cannot break the enclosing markdown table when\n // `renderXrayMarkdown` prints it in a raw code-span cell (codex P2\n // review on #605).\n ...(snapshot.sessionKey\n ? (() => {\n const clean = sanitizeForMarkdownInline(snapshot.sessionKey);\n return clean ? { sessionKey: clean } : {};\n })()\n : {}),\n ...(snapshot.namespace\n ? (() => {\n const clean = sanitizeForMarkdownInline(snapshot.namespace);\n return clean ? { namespace: clean } : {};\n })()\n : {}),\n };\n}\n\nexport function renderRecallExplain(\n snapshot: LastRecallSnapshot | null,\n format: RecallExplainFormat,\n): string {\n if (format === \"json\") {\n return JSON.stringify(toRecallExplainJson(snapshot), null, 2);\n }\n if (format === \"markdown\") {\n // Delegate to the shared X-ray renderer so CLI / HTTP / MCP\n // markdown output all share one implementation (CLAUDE.md rule\n // 22). The JSON and text paths remain byte-for-byte\n // backwards-compatible with pre-#570 behavior.\n return renderXrayMarkdown(toRecallXraySnapshotFromLegacy(snapshot));\n }\n return toRecallExplainText(snapshot);\n}\n\nexport function parseRecallExplainFormat(value: unknown): RecallExplainFormat {\n if (value === undefined || value === null) return \"text\";\n if (typeof value !== \"string\") {\n throw new Error(\n `--format expects \"text\", \"json\", or \"markdown\", got ${typeof value}`,\n );\n }\n const v = value.trim().toLowerCase();\n if (v === \"text\" || v === \"json\" || v === \"markdown\") return v;\n throw new Error(\n `--format expects \"text\", \"json\", or \"markdown\", got ${JSON.stringify(value)}`,\n );\n}\n","/**\n * Unified Recall X-ray renderer (issue #570, PR 2).\n *\n * Pure functions that format a `RecallXraySnapshot` for human text,\n * GitHub-flavored markdown, and machine JSON consumption. CLI / HTTP\n * / MCP surfaces all call into this module — they do NOT format X-ray\n * output themselves, so rendering is tested in one place (CLAUDE.md\n * rule 22).\n *\n * Scope for PR 2 (this slice):\n * - Pure rendering. No IO, no transport, no capture.\n * - `renderXray(snapshot, format)` with format ∈\n * `{\"json\", \"text\", \"markdown\"}`.\n * - `parseXrayFormat(value)` — input validator that rejects unknown\n * formats with a listed-options error (CLAUDE.md rule 51).\n * - Golden-file-style tests in `recall-xray-renderer.test.ts`.\n */\n\nimport type {\n RecallFilterTrace,\n RecallXrayResult,\n RecallXraySnapshot,\n RecallXrayServedBy,\n} from \"./recall-xray.js\";\nimport { summarizeDisclosureTokens } from \"./recall-xray.js\";\nimport { renderTierExplainTextLines } from \"./recall-explain-renderer.js\";\nimport { summarizeRetrievedMemoryProvenance } from \"./memory-provenance.js\";\n\nexport type RecallXrayFormat = \"json\" | \"text\" | \"markdown\";\n\nexport const RECALL_XRAY_FORMATS: readonly RecallXrayFormat[] = [\n \"json\",\n \"text\",\n \"markdown\",\n] as const;\n\n/**\n * Validate and coerce a user-provided `--format` / `format` argument to\n * `RecallXrayFormat`. Unknown values throw an error listing valid\n * options (CLAUDE.md rule 51). `undefined`/`null` defaults to `\"text\"`.\n */\nexport function parseXrayFormat(value: unknown): RecallXrayFormat {\n if (value === undefined || value === null) return \"text\";\n if (typeof value !== \"string\") {\n throw new Error(\n `--format expects one of ${RECALL_XRAY_FORMATS.join(\", \")}; got ${typeof value}`,\n );\n }\n const v = value.trim().toLowerCase();\n if (v === \"json\" || v === \"text\" || v === \"markdown\") return v;\n throw new Error(\n `--format expects one of ${RECALL_XRAY_FORMATS.join(\", \")}; got ${JSON.stringify(value)}`,\n );\n}\n\n/**\n * Top-level dispatcher. CLI / HTTP / MCP callers should always route\n * through this function so the three formats stay in lock-step.\n */\nexport function renderXray(\n snapshot: RecallXraySnapshot | null,\n format: RecallXrayFormat,\n): string {\n if (format === \"json\") return renderXrayJson(snapshot);\n if (format === \"markdown\") return renderXrayMarkdown(snapshot);\n return renderXrayText(snapshot);\n}\n\n// ─── JSON ─────────────────────────────────────────────────────────────────\n\n/**\n * Deterministic JSON encoding of an X-ray snapshot. Returns a stable\n * v1 envelope when the snapshot is absent so consumers can pattern-match\n * on `snapshotFound` rather than distinguishing `null` vs `{}`.\n */\nexport function renderXrayJson(snapshot: RecallXraySnapshot | null): string {\n if (!snapshot) {\n return JSON.stringify(\n { schemaVersion: \"1\", snapshotFound: false },\n null,\n 2,\n );\n }\n // `snapshotFound` is injected *before* the rest so downstream JSON\n // consumers see it near the top of the document.\n return JSON.stringify(\n { snapshotFound: true, ...snapshot },\n null,\n 2,\n );\n}\n\n// ─── Text ─────────────────────────────────────────────────────────────────\n\nexport function renderXrayText(snapshot: RecallXraySnapshot | null): string {\n const lines: string[] = [\"=== Recall X-ray ===\"];\n if (!snapshot) {\n lines.push(\"No X-ray snapshot captured.\");\n return lines.join(\"\\n\");\n }\n\n lines.push(`query: ${snapshot.query}`);\n lines.push(`snapshot-id: ${snapshot.snapshotId}`);\n lines.push(`captured-at: ${formatCapturedAt(snapshot.capturedAt)}`);\n if (snapshot.sessionKey) lines.push(`session: ${snapshot.sessionKey}`);\n if (snapshot.namespace) lines.push(`namespace: ${snapshot.namespace}`);\n if (snapshot.traceId) lines.push(`trace-id: ${snapshot.traceId}`);\n lines.push(\n `budget: ${snapshot.budget.used} / ${snapshot.budget.chars} chars`,\n );\n\n lines.push(\"\");\n lines.push(\"--- filters ---\");\n if (snapshot.filters.length === 0) {\n lines.push(\"(no filter traces recorded)\");\n } else {\n for (const f of snapshot.filters) {\n lines.push(renderFilterTextLine(f));\n }\n }\n\n lines.push(\"\");\n lines.push(\"--- results ---\");\n if (snapshot.results.length === 0) {\n lines.push(\"(no results admitted)\");\n } else {\n snapshot.results.forEach((result, idx) => {\n for (const line of renderResultTextLines(result, idx + 1)) {\n lines.push(line);\n }\n });\n }\n\n lines.push(\"\");\n lines.push(\"--- tier explain ---\");\n for (const line of renderTierExplainTextLines(snapshot.tierExplain ?? null)) {\n lines.push(line);\n }\n\n return lines.join(\"\\n\");\n}\n\nfunction renderFilterTextLine(f: RecallFilterTrace): string {\n const base = `- ${f.name}: ${f.admitted}/${f.considered} admitted`;\n return f.reason ? `${base} (${f.reason})` : base;\n}\n\nfunction renderResultTextLines(\n result: RecallXrayResult,\n rank: number,\n): string[] {\n const lines: string[] = [];\n lines.push(`[${rank}] ${result.memoryId} — ${servedByLabel(result.servedBy)}`);\n if (result.path) lines.push(` path: ${result.path}`);\n lines.push(` score: ${renderScoreDecomposition(result)}`);\n if (result.provenance) {\n lines.push(\n ` provenance: ${summarizeRetrievedMemoryProvenance(result.provenance)}`,\n );\n lines.push(` retrieval-reason: ${result.provenance.retrievalReason}`);\n if (result.provenance.userContextScopes.length > 0) {\n lines.push(\n ` context-scopes: ${result.provenance.userContextScopes.join(\", \")}`,\n );\n }\n if (\n result.provenance.safety !== \"safe\" ||\n result.provenance.safetyReasons.length > 0\n ) {\n const reasonSuffix =\n result.provenance.safetyReasons.length > 0\n ? ` (${result.provenance.safetyReasons.join(\", \")})`\n : \"\";\n lines.push(` safety: ${result.provenance.safety}${reasonSuffix}`);\n }\n }\n if (result.sourceSpan) {\n const q = truncateForXray(result.sourceSpan.quote, 120);\n lines.push(\n ` source: \"${q}\" (observed ${result.sourceSpan.observedAt}) [${result.sourceSpan.provenance}]`,\n );\n }\n if (result.admittedBy.length > 0) {\n lines.push(` admitted-by: ${result.admittedBy.join(\", \")}`);\n }\n if (result.rejectedBy) {\n lines.push(` rejected-by: ${result.rejectedBy}`);\n }\n if (result.graphPath && result.graphPath.length > 0) {\n lines.push(` graph-path: ${result.graphPath.join(\" -> \")}`);\n // Issue #681 PR 3/3 — surface per-edge confidence inline so\n // operators can attribute floor-pruning / PageRank ranking\n // decisions to specific edges. Skipped when no confidences were\n // recorded (legacy snapshot or single-node path).\n if (\n result.graphEdgeConfidences &&\n result.graphEdgeConfidences.length > 0\n ) {\n lines.push(\n ` edge-confidences: ${result.graphEdgeConfidences\n .map((c) => c.toFixed(2))\n .join(\", \")}`,\n );\n }\n }\n if (result.auditEntryId) {\n lines.push(` audit-entry: ${result.auditEntryId}`);\n }\n return lines;\n}\n\n// ─── Markdown ─────────────────────────────────────────────────────────────\n\nexport function renderXrayMarkdown(\n snapshot: RecallXraySnapshot | null,\n): string {\n const lines: string[] = [\"# Recall X-ray\"];\n if (!snapshot) {\n lines.push(\"\");\n lines.push(\"_No X-ray snapshot captured._\");\n return lines.join(\"\\n\");\n }\n\n lines.push(\"\");\n lines.push(`**Query:** ${mdInlineCode(snapshot.query)}`);\n lines.push(\"\");\n lines.push(\"| Field | Value |\");\n lines.push(\"| --- | --- |\");\n lines.push(`| Snapshot ID | \\`${snapshot.snapshotId}\\` |`);\n lines.push(`| Captured at | ${formatCapturedAt(snapshot.capturedAt)} |`);\n if (snapshot.sessionKey) {\n lines.push(`| Session | \\`${snapshot.sessionKey}\\` |`);\n }\n if (snapshot.namespace) {\n lines.push(`| Namespace | \\`${snapshot.namespace}\\` |`);\n }\n if (snapshot.traceId) {\n lines.push(`| Trace ID | \\`${snapshot.traceId}\\` |`);\n }\n lines.push(\n `| Budget | ${snapshot.budget.used} / ${snapshot.budget.chars} chars |`,\n );\n\n lines.push(\"\");\n lines.push(\"## Filters\");\n if (snapshot.filters.length === 0) {\n lines.push(\"\");\n lines.push(\"_No filter traces recorded._\");\n } else {\n lines.push(\"\");\n lines.push(\"| Filter | Considered | Admitted | Reason |\");\n lines.push(\"| --- | ---: | ---: | --- |\");\n for (const f of snapshot.filters) {\n const reason = f.reason ? mdEscape(f.reason) : \"\";\n lines.push(`| ${mdEscape(f.name)} | ${f.considered} | ${f.admitted} | ${reason} |`);\n }\n }\n\n lines.push(\"\");\n lines.push(\"## Results\");\n if (snapshot.results.length === 0) {\n lines.push(\"\");\n lines.push(\"_No results admitted._\");\n } else {\n snapshot.results.forEach((result, idx) => {\n for (const line of renderResultMarkdownLines(result, idx + 1)) {\n lines.push(line);\n }\n });\n\n // Per-disclosure token-spend summary (issue #677 PR 3/4). Only\n // emitted when at least one result carries a disclosure level so\n // we don't pollute the snapshot for callers who haven't wired the\n // depth knob through. Counts and tokens default to 0 for buckets\n // with no contributions.\n const summary = summarizeDisclosureTokens(snapshot.results);\n const hasAnyDisclosure =\n summary.chunk.count + summary.section.count + summary.raw.count > 0;\n if (hasAnyDisclosure) {\n lines.push(\"\");\n lines.push(\"### Token spend by disclosure\");\n lines.push(\"\");\n lines.push(\"| Disclosure | Results | Estimated tokens |\");\n lines.push(\"| --- | ---: | ---: |\");\n lines.push(\n `| chunk | ${summary.chunk.count} | ${summary.chunk.estimatedTokens} |`,\n );\n lines.push(\n `| section | ${summary.section.count} | ${summary.section.estimatedTokens} |`,\n );\n lines.push(\n `| raw | ${summary.raw.count} | ${summary.raw.estimatedTokens} |`,\n );\n if (summary.unspecified.count > 0) {\n lines.push(\n `| _(unspecified)_ | ${summary.unspecified.count} | ${summary.unspecified.estimatedTokens} |`,\n );\n }\n }\n }\n\n lines.push(\"\");\n lines.push(\"## Tier Explain\");\n if (!snapshot.tierExplain) {\n lines.push(\"\");\n lines.push(\n \"_Not populated — direct-answer tier disabled or did not fire._\",\n );\n } else {\n const te = snapshot.tierExplain;\n lines.push(\"\");\n lines.push(\"| Field | Value |\");\n lines.push(\"| --- | --- |\");\n lines.push(`| Tier | \\`${te.tier}\\` |`);\n lines.push(`| Reason | ${mdEscape(te.tierReason)} |`);\n lines.push(`| Candidates considered | ${te.candidatesConsidered} |`);\n lines.push(`| Latency (ms) | ${te.latencyMs} |`);\n lines.push(\n `| Filtered by | ${\n te.filteredBy.length > 0\n ? te.filteredBy.map(mdInlineCode).join(\", \")\n : \"_(none)_\"\n } |`,\n );\n if (te.sourceAnchors && te.sourceAnchors.length > 0) {\n lines.push(\"\");\n lines.push(\"**Source anchors:**\");\n for (const anchor of te.sourceAnchors) {\n const range = anchor.lineRange\n ? `:${anchor.lineRange[0]}-${anchor.lineRange[1]}`\n : \"\";\n lines.push(`- \\`${anchor.path}${range}\\``);\n }\n }\n }\n\n return lines.join(\"\\n\");\n}\n\nfunction renderResultMarkdownLines(\n result: RecallXrayResult,\n rank: number,\n): string[] {\n const lines: string[] = [];\n lines.push(\"\");\n lines.push(\n `### ${rank}. \\`${result.memoryId}\\` — ${servedByLabel(result.servedBy)}`,\n );\n if (result.path) {\n lines.push(\"\");\n lines.push(`- **Path:** \\`${result.path}\\``);\n } else {\n lines.push(\"\");\n }\n lines.push(`- **Score:** ${renderScoreDecomposition(result)}`);\n if (result.provenance) {\n lines.push(\n `- **Provenance:** ${mdEscape(summarizeRetrievedMemoryProvenance(result.provenance))}`,\n );\n lines.push(\n `- **Retrieval reason:** ${mdInlineCode(result.provenance.retrievalReason)}`,\n );\n if (result.provenance.userContextScopes.length > 0) {\n lines.push(\n `- **Context scopes:** ${result.provenance.userContextScopes\n .map(mdInlineCode)\n .join(\", \")}`,\n );\n }\n if (\n result.provenance.safety !== \"safe\" ||\n result.provenance.safetyReasons.length > 0\n ) {\n const reasonSuffix =\n result.provenance.safetyReasons.length > 0\n ? ` (${result.provenance.safetyReasons.map(mdInlineCode).join(\", \")})`\n : \"\";\n lines.push(\n `- **Safety:** ${mdInlineCode(result.provenance.safety)}${reasonSuffix}`,\n );\n }\n }\n if (result.sourceSpan) {\n const q = truncateForXray(result.sourceSpan.quote, 120);\n lines.push(\n `- **Source:** \"${mdEscape(q)}\" (${mdInlineCode(result.sourceSpan.observedAt)}) \\u2014 ${result.sourceSpan.provenance}`,\n );\n }\n if (result.admittedBy.length > 0) {\n lines.push(\n `- **Admitted by:** ${result.admittedBy.map(mdInlineCode).join(\", \")}`,\n );\n }\n if (result.rejectedBy) {\n lines.push(`- **Rejected by:** ${mdInlineCode(result.rejectedBy)}`);\n }\n if (result.graphPath && result.graphPath.length > 0) {\n lines.push(\n `- **Graph path:** ${result.graphPath\n .map(mdInlineCode)\n .join(\" → \")}`,\n );\n // Issue #681 PR 3/3 — render per-edge confidences as a parallel\n // markdown line so operators can correlate them with the path\n // arrows above. Skipped when no confidences were recorded.\n if (\n result.graphEdgeConfidences &&\n result.graphEdgeConfidences.length > 0\n ) {\n lines.push(\n `- **Edge confidences:** ${result.graphEdgeConfidences\n .map((c) => mdInlineCode(c.toFixed(2)))\n .join(\", \")}`,\n );\n }\n }\n if (result.auditEntryId) {\n lines.push(`- **Audit entry:** \\`${result.auditEntryId}\\``);\n }\n if (result.disclosure !== undefined) {\n const tokenLine =\n typeof result.estimatedTokens === \"number\"\n ? ` (~${result.estimatedTokens} tokens)`\n : \"\";\n lines.push(`- **Disclosure:** \\`${result.disclosure}\\`${tokenLine}`);\n } else if (typeof result.estimatedTokens === \"number\") {\n // Disclosure unspecified but tokens recorded — still surface the\n // budget so the operator can attribute spend.\n lines.push(`- **Estimated tokens:** ${result.estimatedTokens}`);\n }\n return lines;\n}\n\n// ─── Shared helpers ───────────────────────────────────────────────────────\n\nfunction servedByLabel(servedBy: RecallXrayServedBy): string {\n return `served-by=${servedBy}`;\n}\n\nfunction renderScoreDecomposition(result: RecallXrayResult): string {\n const parts: string[] = [`final=${formatScore(result.scoreDecomposition.final)}`];\n const s = result.scoreDecomposition;\n if (s.vector !== undefined) parts.push(`vector=${formatScore(s.vector)}`);\n if (s.bm25 !== undefined) parts.push(`bm25=${formatScore(s.bm25)}`);\n if (s.importance !== undefined) {\n parts.push(`importance=${formatScore(s.importance)}`);\n }\n if (s.mmrPenalty !== undefined) {\n parts.push(`mmr_penalty=${formatScore(s.mmrPenalty)}`);\n }\n if (s.tierPrior !== undefined) {\n parts.push(`tier_prior=${formatScore(s.tierPrior)}`);\n }\n if (s.reinforcementBoost !== undefined && s.reinforcementBoost > 0) {\n parts.push(`reinforcement_boost=${formatScore(s.reinforcementBoost)}`);\n }\n return parts.join(\" \");\n}\n\nfunction formatScore(value: number): string {\n // Deterministic 4-decimal formatting keeps golden files stable\n // without printing spurious trailing zeros via toString().\n if (!Number.isFinite(value)) return \"0.0000\";\n return value.toFixed(4);\n}\n\nfunction formatCapturedAt(ts: number): string {\n if (!Number.isFinite(ts) || ts < 0) return \"(unknown)\";\n // `new Date(n).toISOString()` throws a RangeError for finite numbers\n // outside the valid Date range (roughly |n| > 8.64e15). That case\n // can surface when snapshots are corrupted or captured with a\n // custom clock, so coerce it to the same \"(unknown)\" fallback\n // rather than crashing the renderer.\n try {\n return new Date(ts).toISOString();\n } catch {\n return \"(unknown)\";\n }\n}\n\nfunction mdEscape(value: string): string {\n // Pipe is the only character that breaks GFM table rendering; escape\n // backslash first so we do not re-escape the escape character.\n return value.replace(/\\\\/g, \"\\\\\\\\\").replace(/\\|/g, \"\\\\|\");\n}\n\n/**\n * Truncate a quote for X-ray display (issue #1575 PR 3). Collapses internal\n * whitespace runs (including newlines/carriage returns) to single spaces so\n * a multi-line source excerpt cannot split what is meant to be a single X-ray\n * row, then caps at `maxChars` on a word boundary with an ellipsis marker.\n * The JSON \\`sourceSpan.quote\\` stays verbatim — this is display-only.\n */\nfunction truncateForXray(text: string, maxChars: number): string {\n const collapsed = text.replace(/\\s+/g, \" \").trim();\n if (collapsed.length <= maxChars) return collapsed;\n const slice = collapsed.slice(0, maxChars);\n const lastSpace = slice.lastIndexOf(\" \");\n const cut = lastSpace > Math.floor(maxChars * 0.5) ? slice.slice(0, lastSpace) : slice;\n return `${cut}\\u2026`;\n}\n\nfunction mdInlineCode(value: string): string {\n if (value.length === 0) return \"``\";\n // Use exactly enough backticks to unambiguously wrap content that\n // itself contains backticks (GFM rule).\n const longestRun = /`+/g;\n let maxLen = 0;\n for (const match of value.matchAll(longestRun)) {\n if (match[0].length > maxLen) maxLen = match[0].length;\n }\n const fence = \"`\".repeat(maxLen + 1);\n const pad = value.startsWith(\"`\") || value.endsWith(\"`\") ? \" \" : \"\";\n return `${fence}${pad}${value}${pad}${fence}`;\n}\n"],"mappings":";;;;;;;;;;;AAoBA,SAAS,eAAe,GAA2B;AACjD,SAAO,OAAO,MAAM,YAAY,EAAE,SAAS,IAAI,IAAI;AACrD;AAEA,SAAS,qBAAqB,GAA2B;AACvD,SAAO,OAAO,MAAM,YAAY,OAAO,SAAS,CAAC,IAAI,IAAI;AAC3D;AAuBA,SAAS,qBAAqB,OAA0C;AACtE,MAAI,CAAC,SAAS,OAAO,UAAU,YAAY,MAAM,QAAQ,KAAK,EAAG,QAAO;AACxE,QAAM,MAAM;AACZ,QAAM,aAAa,MAAM,QAAQ,IAAI,UAAU,IAC3C,IAAI,WAAW,OAAO,CAAC,MAAmB,OAAO,MAAM,QAAQ,IAC/D,CAAC;AACL,QAAM,gBAAgB,MAAM,QAAQ,IAAI,aAAa,IACjD,IAAI,cACD;AAAA,IACC,CAAC,MACC,CAAC,CAAC,KAAK,OAAO,MAAM,YAAY,OAAQ,EAAyB,SAAS;AAAA,EAC9E,EACC,IAAI,CAAC,MAAM;AACV,UAAM,KAAM,EAA8B;AAC1C,UAAM,YACJ,MAAM,QAAQ,EAAE,KAChB,GAAG,WAAW,KACd,OAAO,SAAS,GAAG,CAAC,CAAC,KACrB,OAAO,SAAS,GAAG,CAAC,CAAC,IAChB,CAAC,GAAG,CAAC,GAAa,GAAG,CAAC,CAAW,IAClC;AACN,WAAO,YACH,EAAE,MAAO,EAAuB,MAAM,UAAU,IAChD,EAAE,MAAO,EAAuB,KAAK;AAAA,EAC3C,CAAC,IACH;AACJ,SAAO;AAAA,IACL,MAAM,gBAAgB,IAAI,IAAI,IAAI,IAAI,OAAO;AAAA,IAC7C,YAAY,OAAO,IAAI,eAAe,WAAW,IAAI,aAAa;AAAA,IAClE;AAAA,IACA,sBAAsB,qBAAqB,IAAI,oBAAoB,KAAK;AAAA,I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AAG,KAAK,GAAG,GAAG,GAAG,KAAK;AAC7C;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/storage/entity-canonical-id-references.ts","../src/storage/entity-canonical-id-lock.ts"],"sourcesContent":["/**\n * Write-boundary surface of the entity canonical-id migration (issue #2213).\n *\n * The migration itself (entity-canonical-id-migration.ts) renames legacy\n * entity files and rewrites references ONCE, to convergence, then retires.\n * Everything here exists so nothing can re-introduce a legacy reference\n * afterwards without the migration having to rescan the corpus:\n *\n * - store-mediated writes canonicalize the caller-supplied `entityRef`\n * ({@link canonicalizeEntityRefOption});\n * - bulk writers that persist raw record bytes (capsule import/merge)\n * canonicalize the frontmatter line ({@link canonicalizeEntityRefFrontmatter});\n * - raw-byte writers that CANNOT parse what they write (offline sync,\n * consolidation-undo, governance restores) request one bounded\n * reconciliation pass instead ({@link requestEntityCanonicalIdReconcile}).\n */\nimport path from \"node:path\";\nimport {\n closeSync,\n constants,\n fstatSync,\n lstatSync,\n realpathSync,\n openSync,\n readFileSync,\n renameSync,\n rmSync,\n writeFileSync,\n} from \"node:fs\";\nimport { randomUUID } from \"node:crypto\";\nimport { log } from \"../logger.js\";\nimport { isErrnoCode } from \"../utils/errno.js\";\nimport { RECALL_FALLBACK_DIRS } from \"../utils/category-dir.js\";\nimport { withEntityCanonicalMutationLock } from \"./entity-canonical-id-lock.js\";\nimport { normalizeSupersessionKey } from \"../temporal-supersession.js\";\n\nexport const ENTITY_CANONICAL_ID_MIGRATION_FILE = \"entity-canonical-id-migration-v1.json\";\n\n/**\n * Parse a journal document into a mapping table. A document without a valid\n * `mappings` object is a LEGITIMATELY empty table; an unreadable/unparsable\n * document THROWS so callers can distinguish \"empty\" from \"failed\".\n */\nfunction parseJournalMappings(raw: string): Readonly<Record<string, string>> {\n const parsed: unknown = JSON.parse(raw);\n if (!parsed || typeof parsed !== \"object\" || Array.isArray(parsed) || !(\"mappings\" in parsed)) return {};\n const mappings = parsed.mappings;\n if (!mappings || typeof mappings !== \"object\" || Array.isArray(mappings)) return {};\n // Null prototype: journal-supplied ids like `constructor` must be own\n // entries, never collide with Object.prototype (Codex P2, round 20).\n const cleaned: Record<string, string> = Object.create(null) as Record<string, string>;\n for (const [legacyId, canonicalId] of Object.entries(mappings)) {\n if (legacyId.length > 0 && typeof canonicalId === \"string\" && canonicalId.length > 0) {\n cleaned[legacyId] = canonicalId;\n }\n }\n return cleaned;\n}\n\ntype JournalRead =\n | { kind: \"ok\"; raw: string; key: string }\n | { kind: \"missing\" }\n | { kind: \"refused\" }\n | { kind: \"error\" };\n\n/**\n * Open the journal WITHOUT following symlinks and read content + identity\n * from the same opened inode (repo rule: reject symlink traversal from\n * memory directories). O_NOFOLLOW makes the open refuse a symlinked FINAL\n * component (ELOOP); the parent `state/` directory is verified AFTER the\n * open, together with a path↔fd identity pairing, so a parent swapped\n * around the open cannot hold: a swap still in place fails the parent\n * lstat, and a swap reverted fails the dev/ino pairing against the real\n * journal. Platforms without O_NOFOLLOW get the same post-open checks.\n */\nfunction readJournalFileNoFollow(statePath: string): JournalRead {\n let fd: number;\n try {\n fd = openSync(statePath, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));\n } catch (error) {\n if (isErrnoCode(error, \"ENOENT\")) return { kind: \"missing\" };\n if (isErrnoCode(error, \"ELOOP\")) return { kind: \"refused\" };\n return { kind: \"error\" };\n }\n try {\n const s = fstatSync(fd);\n if (!s.isFile()) return { kind: \"refused\" };\n const parent = lstatSync(path.dirname(statePath));\n if (parent.isSymbolicLink() || !parent.isDirectory()) return { kind: \"refused\" };\n const l = lstatSync(statePath);\n if (l.isSymbolicLink() || l.dev !== s.dev || l.ino !== s.ino) return { kind: \"refused\" };\n return {\n kind: \"ok\",\n raw: readFileSync(fd, \"utf-8\"),\n key: `${s.dev}:${s.ino}:${s.mtimeMs}:${s.ctimeMs}:${s.size}`,\n };\n } catch {\n return { kind: \"error\" };\n } finally {\n closeSync(fd);\n }\n}\n\nexport function loadHistoricalEntityCanonicalIds(stateDir: string): Readonly<Record<string, string>> {\n const result = readJournalFileNoFollow(path.join(stateDir, ENTITY_CANONICAL_ID_MIGRATION_FILE));\n if (result.kind !== \"ok\") return {};\n try {\n return parseJournalMappings(result.raw);\n } catch {\n return {};\n }\n}\n\n/**\n * Append a tombstone with its identity canonicalized against the CURRENT\n * journal, then recheck: a peer publishing a mapping inside the\n * resolve-to-append window would leave the guard under the legacy id while\n * lookups canonicalize. Each identity change appends the replacement FIRST\n * (AGENTS.md §14 — the retired fact must never be without an active guard),\n * then revokes the superseded one — a park makes the prior canonical\n * claimant a distinct entity, and a stale keyed guard under it would\n * suppress that entity's facts. When the journal will not settle, one final\n * replacement runs under the entity MUTATION lock (parks publish under it).\n */\nexport async function appendCanonicalizedTombstone(\n stateDir: string,\n input: { entityRef?: string; supersessionKey?: string },\n currentIds: () => Readonly<Record<string, string>>,\n append: (identity: TombstoneIdentity) => Promise<string | null>,\n revoke: (tombstoneId: string) => Promise<unknown>,\n label: string,\n): Promise<string | null> {\n let refIds = currentIds();\n let identity = canonicalizeTombstoneIdentity(input.entityRef, input.supersessionKey, refIds);\n let result = await append(identity);\n const replaceIfChanged = async (next: TombstoneIdentity): Promise<boolean> => {\n if (next.entityRef === identity.entityRef && next.supersessionKey === identity.supersessionKey) {\n return false;\n }\n identity = next;\n const superseded = result;\n result = await append(next);\n if (superseded !== null) {\n try {\n await revoke(superseded);\n } catch (err) {\n log.warn(`failed to revoke superseded tombstone ${superseded} for ${label}: ${err}`);\n }\n }\n return true;\n };\n for (let attempt = 0; attempt < 3; attempt += 1) {\n const fresh = currentIds();\n if (fresh === refIds) return result;\n refIds = fresh;\n if (!(await replaceIfChanged(canonicalizeTombstoneIdentity(input.entityRef, input.supersessionKey, fresh)))) {\n return result;\n }\n }\n await withEntityCanonicalMutationLock(stateDir, async () => {\n await replaceIfChanged(canonicalizeTombstoneIdentity(input.entityRef, input.supersessionKey, currentIds()));\n });\n return result;\n}\n\n/**\n * Journal mapping table keyed by the journal FILE's identity, so a long-lived\n * StorageManager never canonicalizes against a stale snapshot after ANY other\n * writer changes the journal — a peer process completing a migration, or\n * `pruneBlocked()` parking a contested mapping (which rewrites the journal\n * without bumping any shared version). `writeState` publishes via\n * temp-file-plus-rename, so every journal write swaps the inode and the key\n * always moves — the identity is taken from the fstat of the SAME opened\n * inode the content is read from (no stat→read window). Reload cost is one\n * open per lookup and one journal parse per actual change.\n *\n * Failure semantics: last-known data is served ONLY for the SAME state dir\n * (module-level instances can face several stores — another store's table\n * must never leak in), and a failed read/parse never commits the journal's\n * identity, so the next lookup retries instead of caching an empty table\n * under a valid key.\n */\nexport class HistoricalEntityCanonicalIdCache {\n private mappings: Readonly<Record<string, string>> = {};\n private key: string | null = null;\n private stateDir: string | null = null;\n\n get(stateDir: string): Readonly<Record<string, string>> {\n const lastKnown = this.stateDir === stateDir ? this.mappings : {};\n const result = readJournalFileNoFollow(path.join(stateDir, ENTITY_CANONICAL_ID_MIGRATION_FILE));\n if (result.kind === \"refused\") {\n // Symlinked/non-regular journal: never follow it, never adopt its\n // identity — serve this store's last-known table. If it later becomes\n // a regular file its identity differs from the stored key and reloads.\n log.warn(\"ignoring non-regular entity canonical-id journal (symlink refused)\");\n return lastKnown;\n }\n if (result.kind === \"error\") {\n // A TRANSIENT open/read failure (EACCES/EIO) must not dump a valid\n // table for {}: a write during the outage would skip canonicalization\n // AND its post-write identity check would compare equal. Serve this\n // store's last-known table; only a genuine ENOENT means \"no journal\".\n return lastKnown;\n }\n const key = result.kind === \"missing\" ? \"missing\" : result.key;\n if (key !== this.key || stateDir !== this.stateDir) {\n let table: Readonly<Record<string, string>> = {};\n if (result.kind === \"ok\") {\n try {\n table = parseJournalMappings(result.raw);\n } catch {\n // Parse failed under a VALID identity: do not commit the key —\n // the next lookup retries instead of pinning an empty table.\n return lastKnown;\n }\n }\n this.mappings = table;\n this.key = key;\n this.stateDir = stateDir;\n }\n return this.mappings;\n }\n}\n\nexport function resolveHistoricalEntityCanonicalId(\n normalized: string,\n mappings: Readonly<Record<string, string>>,\n): string {\n let current = normalized;\n const seen = new Set<string>();\n while (!seen.has(current)) {\n seen.add(current);\n // Own properties only: an unmapped id like `constructor` must not read\n // Object.prototype and return a function (Codex P2, round 20).\n const next = Object.hasOwn(mappings, current) ? mappings[current] : undefined;\n if (!next || next === current) break;\n current = next;\n }\n return current;\n}\n\n/**\n * Canonicalize the `entityRef` a memory-write caller supplied (issue #2213).\n *\n * Extraction and capture callers pass whatever id the LLM or user produced,\n * which can name a legacy id this migration already renamed. Resolving at the\n * WRITE boundary means store-mediated writes can never re-introduce legacy\n * references — which is what let the completed migration retire its recurring\n * full-corpus reference rewrite. It also keeps write-time tombstone lookups on\n * the same id space as migrated tombstones. Unknown ids pass through verbatim.\n */\nexport function canonicalizeEntityRefOption<T extends { entityRef?: string }>(\n options: T,\n mappings: Readonly<Record<string, string>>,\n): T {\n // Non-strings (absent, or a JS caller's null/junk) pass through untouched:\n // this boundary canonicalizes ids, it does not take over input validation\n // the write path never performed — serialization already drops falsy refs.\n if (typeof options.entityRef !== \"string\") return options;\n return { ...options, entityRef: resolveHistoricalEntityCanonicalId(options.entityRef, mappings) };\n}\n\n/**\n * Canonicalize the effective `entityRef:` line inside a raw memory record's\n * leading frontmatter block (issue #2213). Bulk writers that persist record\n * bytes verbatim — capsule import/merge — are a write boundary too: a capsule\n * can carry pre-migration memories whose refs the target's completed journal\n * already renamed, and no later reconciliation pass exists to absorb them.\n *\n * Line selection mirrors the frontmatter parser and the migration's own\n * serializer: the LAST `entityRef` key wins (indentation tolerated), its\n * indent is preserved, and CRLF records keep their line endings. The closing\n * delimiter must be a standalone `---` line. Non-frontmatter content, records\n * without an `entityRef` line, and ids the journal does not map all pass\n * through byte-identical.\n */\nexport function canonicalizeEntityRefFrontmatter(\n content: string,\n mappings: Readonly<Record<string, string>>,\n): string {\n if (Object.keys(mappings).length === 0) return content;\n const loc = locateEntityRefLine(content);\n if (loc === null) return content;\n const canonical = resolveHistoricalEntityCanonicalId(loc.value, mappings);\n if (canonical === loc.value) return content;\n const line = loc.lines[loc.index]!;\n const indent = /^\\s*/.exec(line)?.[0] ?? \"\";\n loc.lines[loc.index] = `${indent}entityRef: ${canonical}${line.endsWith(\"\\r\") ? \"\\r\" : \"\"}`;\n return loc.lines.join(\"\\n\") + content.slice(loc.closeIndex);\n}\n\n/** The raw `entityRef` value in a record's leading frontmatter, or null. */\nexport function readEntityRefFromFrontmatter(content: string): string | null {\n return locateEntityRefLine(content)?.value ?? null;\n}\n\nfunction locateEntityRefLine(\n content: string,\n): { lines: string[]; index: number; value: string; closeIndex: number } | null {\n if (!/^---\\r?\\n/.test(content)) return null;\n const close = /\\r?\\n---(?:\\r?\\n|$)/g;\n close.lastIndex = content.indexOf(\"\\n\") + 1;\n const closeMatch = close.exec(content);\n if (!closeMatch) return null;\n const lines = content.slice(0, closeMatch.index).split(\"\\n\");\n let index = -1;\n for (let i = 1; i < lines.length; i += 1) {\n if (/^\\s*entityRef\\s*:/.test(lines[i] ?? \"\")) index = i;\n }\n if (index === -1) return null;\n const line = lines[index]!;\n const value = line.slice(line.indexOf(\":\") + 1).replace(/\\r$/, \"\").trim();\n if (value.length === 0) return null;\n return { lines, index, value, closeIndex: closeMatch.index };\n}\n\n/**\n * Reconcile-pending marker (issue #2213). Raw-byte memory writers that CANNOT\n * canonicalize inline — offline-sync file replication (opaque, possibly\n * encrypted buffers), consolidation-undo restores, governance-run restores —\n * touch this marker instead. The next migration invocation honors it by\n * running ONE bounded reference-reconciliation pass over the completed\n * journal's retained mappings, then clears it. This replaces the retired\n * every-run corpus rewrite with a signal that fires only when a raw writer\n * actually landed unvetted bytes.\n */\nexport const ENTITY_CANONICAL_ID_RECONCILE_MARKER = \"entity-canonical-id-reconcile.pending\";\n/** The generation a migration run renamed aside for consumption; a crash can strand it. */\nexport const ENTITY_CANONICAL_ID_RECONCILE_CONSUMING_MARKER = `${ENTITY_CANONICAL_ID_RECONCILE_MARKER}.consuming`;\n\nexport function requestEntityCanonicalIdReconcileSync(stateDir: string): void {\n const markerPath = path.join(stateDir, ENTITY_CANONICAL_ID_RECONCILE_MARKER);\n const temporary = `${markerPath}.${process.pid}.${randomUUID()}.tmp`;\n try {\n // Never write THROUGH a symlinked marker OR a symlinked state dir (repo\n // rule: reject symlink traversal from memory directories). The parent is\n // lstat-verified as a real directory — direct restore/import callers can\n // reach this helper without validateRoots() — and temp-file-plus-rename\n // handles the final component: rename() replaces a planted link ITSELF\n // rather than following it, with no O_NOFOLLOW dependency.\n const parent = lstatSync(stateDir);\n if (parent.isSymbolicLink() || !parent.isDirectory()) {\n log.warn(`refusing to write entity canonical-id reconcile marker: ${stateDir} is not a real directory`);\n return;\n }\n const parentRealPath = realpathSync(stateDir);\n writeFileSync(temporary, `${new Date().toISOString()}\\n`, { mode: 0o600 });\n // Revalidate the parent between the temp write and publication (Codex\n // P2, round 20): a state-dir swapped for a symlink after the check above\n // would have landed the temp file through the link. Node has no openat,\n // so the residual window is the realpath→rename gap — this recheck\n // reduces check-then-use to the platform primitive's own atomicity.\n const recheck = lstatSync(stateDir);\n if (recheck.isSymbolicLink() || !recheck.isDirectory() || realpathSync(stateDir) !== parentRealPath) {\n rmSync(temporary, { force: true });\n log.warn(`refusing to publish entity canonical-id reconcile marker: ${stateDir} changed during write`);\n return;\n }\n renameSync(temporary, markerPath);\n } catch (error) {\n rmSync(temporary, { force: true });\n // Best effort by design: a marker failure must not fail the restore/sync\n // that requested it (AGENTS.md §4). The reference stays legacy-but-readable\n // until the next mapping change.\n log.warn(`could not request entity canonical-id reconcile: ${error}`);\n }\n}\n\nexport async function requestEntityCanonicalIdReconcile(stateDir: string): Promise<void> {\n requestEntityCanonicalIdReconcileSync(stateDir);\n}\n\n/**\n * Post-persist TOCTOU guard (issue #2213). A writer resolves `entityRef`\n * against one journal generation, then awaits (snapshots, locks, fsyncs)\n * before its bytes land — a peer migration can publish AND finish its final\n * reference scan inside that window, leaving the just-written file behind.\n * Callers pass the mapping table captured at resolve time plus a fresh cache\n * read taken AFTER the write: the cache returns the identical object while\n * the journal file is unchanged, so an identity mismatch means the journal\n * moved mid-write and one bounded reconcile pass is requested.\n */\nexport function reconcileIfJournalMovedSync(\n stateDir: string,\n idsAtResolve: Readonly<Record<string, string>>,\n idsAfterWrite: Readonly<Record<string, string>>,\n): void {\n if (idsAtResolve === idsAfterWrite) return;\n requestEntityCanonicalIdReconcileSync(stateDir);\n}\n\nexport async function reconcileIfJournalMoved(\n stateDir: string,\n idsAtResolve: Readonly<Record<string, string>>,\n idsAfterWrite: Readonly<Record<string, string>>,\n): Promise<void> {\n reconcileIfJournalMovedSync(stateDir, idsAtResolve, idsAfterWrite);\n}\n\n/**\n * Classify a raw write target for entity-reference handling (issue #2213):\n * - `\"memory\"` — hot recall / cold / archive record whose FRONTMATTER\n * `entityRef` the writer must canonicalize at the write (and repair after).\n * - `\"entity\"` — an `entities/` page. Its migrated surface is relationship\n * TARGETS in the body, which only `rewriteRelationshipTargets` understands;\n * raw writers persist bytes faithfully and request the bounded reconcile\n * pass instead of attempting a frontmatter rewrite.\n * - `\"outside\"` — transcripts, profiles, runtime state, and every other file\n * outside the migration's scan scope: write byte-identical, no marker.\n */\nexport type EntityRefWritePathKind = \"memory\" | \"entity\" | \"outside\";\n\nexport function classifyEntityRefWritePath(baseDir: string, filePath: string): EntityRefWritePathKind {\n if (!filePath.endsWith(\".md\")) return \"outside\";\n const rel = path.relative(baseDir, filePath);\n if (rel.startsWith(\"..\") || path.isAbsolute(rel)) return \"outside\";\n const top = rel.split(path.sep)[0] ?? \"\";\n if (top === \"entities\") return \"entity\";\n return RECALL_FALLBACK_DIRS.includes(top) || top === \"cold\" || top === \"archive\" ? \"memory\" : \"outside\";\n}\n\n/** True when `filePath` is in the migration's scan scope at all. */\nexport function pathMayCarryEntityRefs(baseDir: string, filePath: string): boolean {\n return classifyEntityRefWritePath(baseDir, filePath) !== \"outside\";\n}\n\n/**\n * Canonicalize a tombstone's identity fields at the append chokepoint\n * (issue #2213): emitters (forget, temporal supersession, pattern\n * reinforcement, supersede) build inputs from records that may have been\n * read before a peer migration completed. The supersession key embeds the\n * NORMALIZED entity segment (`entity::attr`), so it is re-prefixed when the\n * ref moved — otherwise the keyed guard lands in the legacy id space while\n * write-time lookups canonicalize, and a paraphrase resurrects.\n */\nexport interface TombstoneIdentity {\n entityRef: string | undefined;\n supersessionKey: string | undefined;\n}\n\nexport function canonicalizeTombstoneIdentity(\n entityRef: string | undefined,\n supersessionKey: string | undefined,\n refIds: Readonly<Record<string, string>>,\n): TombstoneIdentity {\n if (typeof entityRef !== \"string\") return { entityRef, supersessionKey };\n const canonical = resolveHistoricalEntityCanonicalId(entityRef, refIds);\n if (canonical === entityRef) return { entityRef, supersessionKey };\n if (supersessionKey) {\n const stalePrefix = `${normalizeSupersessionKey(entityRef)}::`;\n if (supersessionKey.startsWith(stalePrefix)) {\n supersessionKey = `${normalizeSupersessionKey(canonical)}::${supersessionKey.slice(stalePrefix.length)}`;\n }\n }\n return { entityRef: canonical, supersessionKey };\n}\n\n/**\n * Post-persist repair (issue #2213): when the journal moved across a persist,\n * re-resolve the caller's ORIGINAL ref against the fresh table and rewrite\n * the file in place (bounded). When the journal will not settle, take the\n * entity MUTATION lock — parks/removals (the direction the reconcile pass\n * cannot repair, because the removed mapping is gone from the table) publish\n * under it — settle once, then request the marker for additive moves only.\n */\nexport async function repairEntityRefAfterJournalMove(options: {\n stateDir: string;\n currentIds: () => Readonly<Record<string, string>>;\n idsAtResolve: Readonly<Record<string, string>>;\n rawRef: string;\n frontmatter: { entityRef?: string };\n rewrite: () => Promise<void>;\n}): Promise<void> {\n let refIds = options.idsAtResolve;\n for (let attempt = 0; attempt < 3; attempt += 1) {\n const fresh = options.currentIds();\n if (fresh === refIds) return;\n refIds = fresh;\n const desired = resolveHistoricalEntityCanonicalId(options.rawRef, fresh);\n if (desired === options.frontmatter.entityRef) return;\n options.frontmatter.entityRef = desired;\n await options.rewrite();\n }\n await withEntityCanonicalMutationLock(options.stateDir, async () => {\n const desired = resolveHistoricalEntityCanonicalId(options.rawRef, options.currentIds());\n if (desired !== options.frontmatter.entityRef) {\n options.frontmatter.entityRef = desired;\n await options.rewrite();\n }\n });\n await requestEntityCanonicalIdReconcile(options.stateDir);\n}\n\n/**\n * Content-form counterpart of {@link repairEntityRefAfterJournalMove} for\n * async writers that persist raw record bytes (capsule import/merge,\n * binary-lifecycle redirects): same bounded loop, same locked settle.\n */\nexport async function repairContentAfterJournalMove(options: {\n stateDir: string;\n cache: HistoricalEntityCanonicalIdCache;\n idsAtWrite: Readonly<Record<string, string>>;\n rawContent: string;\n lastWritten: string;\n rewrite: (content: string) => Promise<void>;\n}): Promise<void> {\n let refIds = options.idsAtWrite;\n let written = options.lastWritten;\n for (let attempt = 0; attempt < 3; attempt += 1) {\n const fresh = options.cache.get(options.stateDir);\n if (fresh === refIds) return;\n refIds = fresh;\n const desired = canonicalizeEntityRefFrontmatter(options.rawContent, fresh);\n if (desired === written) return;\n written = desired;\n await options.rewrite(desired);\n }\n await withEntityCanonicalMutationLock(options.stateDir, async () => {\n const desired = canonicalizeEntityRefFrontmatter(options.rawContent, options.cache.get(options.stateDir));\n if (desired !== written) {\n written = desired;\n await options.rewrite(desired);\n }\n });\n await requestEntityCanonicalIdReconcile(options.stateDir);\n}\n\n/**\n * Sync variant (space promotion, curation, review actions). Sync callers\n * cannot take the async mutation lock, so exhaustion surfaces a retryable\n * error after requesting the marker — a silent return could leave the bytes\n * on a parked canonical claimant the reconcile pass cannot restore.\n */\nexport function repairContentAfterJournalMoveSync(options: {\n stateDir: string;\n cache: HistoricalEntityCanonicalIdCache;\n idsAtWrite: Readonly<Record<string, string>>;\n rawContent: string;\n lastWritten: string;\n rewrite: (content: string) => void;\n}): void {\n let refIds = options.idsAtWrite;\n let written = options.lastWritten;\n for (let attempt = 0; attempt < 3; attempt += 1) {\n const fresh = options.cache.get(options.stateDir);\n if (fresh === refIds) return;\n refIds = fresh;\n const desired = canonicalizeEntityRefFrontmatter(options.rawContent, fresh);\n if (desired === written) return;\n written = desired;\n options.rewrite(desired);\n }\n requestEntityCanonicalIdReconcileSync(options.stateDir);\n throw new Error(\n \"entity canonical-id journal kept changing during post-write repair; retry the write\",\n );\n}\n","/**\n * Entity canonical-id MUTATION lock (issue #2213).\n *\n * Serializes every writer whose correctness depends on the canonical-id\n * journal not moving mid-write: entity file mutations (entity-store),\n * per-pair file migration and journal pruning (entity-canonical-id-migration),\n * and the final settle attempt of the post-persist repair helpers\n * (entity-canonical-id-references). Lives in its own module so the reference\n * helpers can take the lock without importing the migration module, which\n * itself imports the reference helpers.\n */\nimport path from \"node:path\";\nimport { withHeldFileLock } from \"../utils/serialize-mutations.js\";\n\nconst ENTITY_CANONICAL_ID_MUTATION_LOCK_STALE_MS = 60_000;\nconst ENTITY_CANONICAL_ID_MUTATION_LOCK_MAX_WAIT_MS = 300_000;\n\nexport async function withEntityCanonicalMutationLock<T>(\n stateDir: string,\n task: (refreshLock: () => Promise<boolean>) => Promise<T>,\n): Promise<T> {\n return withHeldFileLock(\n path.join(stateDir, \"entity-canonical-id-mutation.lock\"),\n {\n staleMs: ENTITY_CANONICAL_ID_MUTATION_LOCK_STALE_MS,\n maxWaitMs: ENTITY_CANONICAL_ID_MUTATION_LOCK_MAX_WAIT_MS,\n },\n async (acquired, lock) => {\n if (!acquired) throw new Error(\"Timed out waiting for entity mutation lock.\");\n return task(() => lock.refresh());\n },\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAgBA,OAAOA,WAAU;AACjB;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,kBAAkB;;;AClB3B,OAAO,UAAU;AAGjB,IAAM,6CAA6C;AACnD,IAAM,gDAAgD;AAEtD,eAAsB,gCACpB,UACA,MACY;AACZ,SAAO;AAAA,IACL,KAAK,KAAK,UAAU,mCAAmC;AAAA,IAC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Q,QAAQ;AAAA,IACxB;AAAA,EACF,CAAC;AACD,QAAM,kCAAkC,QAAQ,QAAQ;AAC1D;AAOA,eAAsB,8BAA8B,SAOlC;AAChB,MAAI,SAAS,QAAQ;AACrB,MAAI,UAAU,QAAQ;AACtB,WAAS,UAAU,GAAG,UAAU,GAAG,WAAW,GAAG;AAC/C,UAAM,QAAQ,QAAQ,MAAM,IAAI,QAAQ,QAAQ;AAChD,QAAI,UAAU,OAAQ;AACtB,aAAS;AACT,UAAM,UAAU,iCAAiC,QAAQ,YAAY,KAAK;AAC1E,QAAI,YAAY,QAAS;AACzB,cAAU;AACV,UAAM,QAAQ,QAAQ,OAAO;AAAA,EAC/B;AACA,QAAM,gCAAgC,QAAQ,UAAU,YAAY;AAClE,UAAM,UAAU,iCAAiC,QAAQ,YAAY,QAAQ,MAAM,IAAI,QAAQ,QAAQ,CAAC;AACxG,QAAI,YAAY,SAAS;AACvB,gBAAU;AACV,YAAM,QAAQ,QAAQ,OAAO;AAAA,IAC/B;AAAA,EACF,CAAC;AACD,QAAM,kCAAkC,QAAQ,QAAQ;AAC1D;AAQO,SAAS,kCAAkC,SAOzC;AACP,MAAI,SAAS,QAAQ;AACrB,MAAI,UAAU,QAAQ;AACtB,WAAS,UAAU,GAAG,UAAU,GAAG,WAAW,GAAG;AAC/C,UAAM,QAAQ,QAAQ,MAAM,IAAI,QAAQ,QAAQ;AAChD,QAAI,UAAU,OAAQ;AACtB,aAAS;AACT,UAAM,UAAU,iCAAiC,QAAQ,YAAY,KAAK;AAC1E,QAAI,YAAY,QAAS;AACzB,cAAU;AACV,YAAQ,QAAQ,OAAO;AAAA,EACzB;AACA,wCAAsC,QAAQ,QAAQ;AACtD,QAAM,IAAI;AAAA,IACR;AAAA,EACF;AACF;","names":["path","path","path","path"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/mcp-read-only-tools.ts"],"sourcesContent":["/**\n * Conservative allowlist of canonical MCP tool suffixes that are\n * unambiguously read-only. Tools in this set are tagged with\n * `annotations: { readOnlyHint: true }` so ChatGPT (and other MCP\n * clients that honor the hint) can skip per-call confirmation.\n *\n * The list is suffix-based so it covers both the `remnic.*` and\n * `engram.*` naming forms. Anything not on it stays unannotated:\n * uncertainty is resolved as \"might mutate\".\n *\n * Excluded by construction: anything that writes, runs a pipeline,\n * flushes, applies, records, imports, or destructively deletes.\n */\nexport const MCP_READ_ONLY_TOOL_SUFFIXES: Readonly<Record<string, true>> = {\n recall: true,\n recall_explain: true,\n recall_tier_explain: true,\n recall_xray: true,\n briefing: true,\n wearables_status: true,\n transcript_day: true,\n transcript_search: true,\n transcript_memories: true,\n meetings_list: true,\n meetings_get: true,\n action_confidence: true,\n capsule_list: true,\n procedural_stats: true,\n memory_get: true,\n memory_timeline: true,\n entity_get: true,\n review_queue_list: true,\n lcm_search: true,\n continuity_incident_list: true,\n identity_anchor_get: true,\n memory_identity: true,\n memory_search: true,\n memory_profile: true,\n memory_entities_list: true,\n memory_questions: true,\n memory_last_recall: true,\n memory_intent_debug: true,\n memory_qmd_debug: true,\n memory_graph_explain: true,\n graph_snapshot: true,\n review_list: true,\n profiling_report: true,\n peer_list: true,\n peer_get: true,\n peer_profile_get: true,\n console_state: true,\n dreams_status: true,\n codegraph_list_projects: true,\n codegraph_index_status: true,\n codegraph_search_graph: true,\n codegraph_trace_path: true,\n codegraph_detect_changes: true,\n codegraph_query_graph: true,\n codegraph_get_schema: true,\n codegraph_get_snippet: true,\n codegraph_get_architecture: true,\n codegraph_search_code: true,\n};\n"],"mappings":";AAaO,IAAM,8BAA8D;AAAA,EACzE,QAAQ;AAAA,EACR,gBAAgB;AAAA,EAChB,qBAAqB;AAAA,EACrB,aAAa;AAAA,EACb,UAAU;AAAA,EACV,kBAAkB;AAAA,EAClB,gBAAgB;AAAA,EAChB,mBAAmB;AAAA,EACnB,qBAAqB;AAAA,EACrB,eAAe;AAAA,EACf,cAAc;AAAA,EACd,mBAAmB;AAAA,EACnB,cAAc;AAAA,EACd,kBAAkB;AAAA,EAClB,YAAY;AAAA,EACZ,iBAAiB;AAAA,EACjB,YAAY;AAAA,EACZ,mBAAmB;AAAA,EACnB,YAAY;AAAA,EACZ,0BAA0B;AAAA,EAC1B,qBAAqB;AAAA,EACrB,iBAAiB;AAAA,EACjB,eAAe;AAAA,EACf,gBAAgB;AAAA,EAChB,sBAAsB;AAAA,EACtB,kBAAkB;AAAA,EAClB,oBAAoB;AAAA,EACpB,qBAAqB;AAAA,EACrB,kBAAkB;AAAA,EAClB,sBAAsB;AAAA,EACtB,gBAAgB;AAAA,EAChB,aAAa;AAAA,EACb,kBAAkB;AAAA,EAClB,WAAW;AAAA,EACX,UAAU;AAAA,EACV,kBAAkB;AAAA,EAClB,eAAe;AAAA,EACf,eAAe;AAAA,EACf,yBAAyB;AAAA,EACzB,wBAAwB;AAAA,EACxB,wBAAwB;AAAA,EACxB,sBAAsB;AAAA,EACtB,0BAA0B;AAAA,EAC1B,uBAAuB;AAAA,EACvB,sBAAsB;AAAA,EACtB,uBAAuB;AAAA,EACvB,4BAA4B;AAAA,EAC5B,uBAAuB;AACzB;","names":[]}
|